code:
from collections import deque
def find_minimal_length_subarr(arr, k):
   # assume k is positive
   sumBefore = [0]
   for x in arr: sumBefore.append(sumBefore[-1] + x)
   bestStart = -1
   bestEnd = len(arr)
   startPoints = deque()
   start = 0
   for end in range(len(arr)):
      totalToEnd = sumBefore[end+1]
      while startPoints and totalToEnd - sumBefore[startPoints[0]] >= k: # adjust start
         start = startPoints.popleft()
      if totalToEnd - sumBefore[start] >= k and end-start < bestEnd-bestStart:
         bestStart,bestEnd = start,end
      while startPoints and totalToEnd <= sumBefore[startPoints[-1]]: # remove bad candidates
         startPoints.pop()
      startPoints.append(end+1) # end+1 is a new candidate
   return (bestStart,bestEnd)

rawDescription: Finding a minimal subarray of n integers of sum >= k in linear time


code:
import pyopencl as cl
import numpy as np

def findDistances_cl(imageSize, points):
    #Boilerplate opencl code
    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    f = open('nn.cl', 'r')
    fstr = "".join(f.readlines())
    program = cl.Program(ctx, fstr).build()

    #Creating buffers for the opencl kernel
    mf = cl.mem_flags
    img = np.empty(imageSize, dtype=np.float32)
    x_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.USE_HOST_PTR, hostbuf=points[:,0].astype(np.float32))
    y_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.USE_HOST_PTR, hostbuf=points[:,1].astype(np.float32))
    n_points = cl.Buffer(ctx, mf.READ_ONLY | mf.USE_HOST_PTR, hostbuf=np.array([len(points)],dtype=np.int))
    img_buf = cl.Buffer(ctx, mf.WRITE_ONLY, img.nbytes)

    #Run the kernel
    exec_evt = program.nn(queue, img.shape, None, img_buf, x_buf, y_buf, n_points)
    exec_evt.wait()
    #read back the result
    cl.enqueue_read_buffer(queue, img_buf, img).wait()

    return img

rawDescription: Producing a nearest neighbour distance map for a set of points


code:
from guppy import hpy
import networkx as nx

h = hpy()

num_nodes = 1000
num_edges = 5000
G = nx.gnm_random_graph(num_nodes, num_edges)

x = h.heap()
print(x.size)

rawDescription: Simple way to get current memory usage from Guppy


code:
indexes = np.argsort(eigenvalues)[::-1]
eigval = eigenvalues[indexes]
eigvec = eigenvectors[:,indexes]

rawDescription: Principal Component Analysis in Python: Analytical Mistake


code:
B = "This Is A String With A /Linux/Path and /Another/Linux/Path"
get_paths(B)

rawDescription: Extract path like strings from string

description: Extract path like strings from string


code:
def move(self):
    if(self.x > 500):
        self.x = 0
    self.x += 1

rawDescription: How to continuously move an image in Pygame

description: Continuously move an image in Pygame


rawDescription: use custom html writer in sphinx

description: Use custom html writer in sphinx


code:
with open("data.txt") as file:
    lines = file.read().split("\n")

#remove header line.
lines = lines[1:]

entries = {}

#create an entry for each child node.
for line in lines:
    name, level, child, size = line.split()
    entries[child] = {"name": child, "size": int(size), "children": []}

#we now have an entry for all nodes that are a child of another node.
#but not for the topmost parent node, so we'll make one for it now.
parents  = set(line.split()[0] for line in lines)
children = set(line.split()[2] for line in lines)
top_parent = (parents - children).pop()
#(just guess the size, since it isn't supplied in the file)
entries[top_parent] = {"name": top_parent, "size": 5000, "children": []}

#hook up each entry to its children
for line in lines:
    name, level, child, size = line.split()
    entries[name]["children"].append(entries[child])

#the nested structure is ready to use!
structure = entries[top_parent]

#display the beautiful result
import pprint
pprint.pprint(structure)

rawDescription: Convert a flat tab-delimited file into Json nested structure


rawDescription: Plot points with different colors in a matplotlib animation


rawDescription: Assign value to an individual cell in a two dimensional python array


code:
delim = '\t'*9
data = [ x.split(delim) for x in fobj ]

rawDescription: python 2.4 sorting a text file by specific column

description: Python 2.4 sorting a text file by specific column


code:
for i in date_list:
    data[i+"InDays"] = data[i].apply(lambda x: (current_date - x).days if x is not pd.NaT else x)

rawDescription: pandas error creating TimeDeltas from Datetime operation

description: Pandas error creating TimeDeltas from Datetime operation


code:
import subprocess

script = subprocess.Popen(['script.sh'], stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE, shell=True)

rawDescription: Provide called shell script with input in Python


code:
@app.route('/')
def hello_world():
    return "Hello World!"

rawDescription: Context locals - how do they make local context variables global?


code:
import operator as ops
import time
import random

NUM_QUESTIONS = 10
OPERANDS = list(range(2, 12))
OPERATORS = {'+': ops.add, '-': ops.sub, '*': ops.mul}

def getInteger(prompt, errormsg='Please input an integer'):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print(errormsg)

def main():
    question = score = 0

    name = input('What is your full name? ')
    print('Hello {}, welcome to The Arithmetic Quiz'.format(name))
    time.sleep(2)

    for _ in range(NUM_QUESTIONS):
        operand1 = random.choice(OPERANDS)
        operand2 = random.choice(OPERANDS)
        operator = random.choice(list(OPERATORS))

        user_answer = getInteger('{} {} {} '.format(operand1, operator, operand2))
        expected_answer = OPERATORS[operator](operand1, operand2)
        if user_answer == expected_answer:
            print('This is correct!')
            score += 1
        else:
            print('This is incorrect!')
        time.sleep(2)

if __name__ == '__main__':
    main()

rawDescription: Python: how to make python calculate a sum to make sure an input is correct?


code:
with open('output.fna', 'w') as output_fh:
    for seq in skbio.io.read('seqs.fna', format='fasta'):
        if seq.metadata['id'] in ['47P50SDHBQ1PA_0', '4OZ9UI889OL5V_1', '2EC8VWHQD1LW5_2']:
            seq.write(output_fh)

rawDescription: Write multiple fasta entries using scikit-bio write


code:
def upload_keys(**kwargs):
    add_action(UploadSsh, kwargs)

def remote_action(**kwargs):
    add_action(RemoteAction, kwargs)

rawDescription: Options to do a "mini-dsl" with Python?

description: Options to do a "mini-dsl" with Python


rawDescription: Using the Image.point() method in PIL to manipulate pixel data


rawDescription: Running bunch of python methods on a single piece of data


code:
from lxml import etree
with open(u'/path/to/my_evernote_file.enex', 'rb') as src_file:
    my_xml_file = src_file.read()
root = etree.fromstring(my_xml_file)

rawDescription: Extracting each instance of a group of tags from an xml file and Parsing as a Column


code:
your_search_query = 'super very news'

qset = Q()
for term in your_search_query.split():
    qset |= Q(name__contains=term)

matching_results = YourModel.objects.filter(qset)

rawDescription: How to match string with database fields in Django?

description: Match string with database fields in Django


code: weight1 = weight1.replace(",", ".")

rawDescription: python 3 directed graph with labels from file

description: Python 3 directed graph with labels from file


code: df.apply(lambda x: x['sent'] + np.timedelta64(x['tz_offset'], 's'), axis=1)

rawDescription: How to add x seconds to a Python datetime64[ns] field?

description: Add x seconds to a Python datetime64[ns] field


code:
class MyTextInput(TextInput):
    def __init__(self, error_class=u'has_errors'):
        super(MyTextInput, self).__init__()
        self.error_class = error_class

    def __call__(self, field, **kwargs):
        if field.errors:
            c = kwargs.pop('class', '') or kwargs.pop('class_', '')
            kwargs['class'] = u'%s %s' % (self.error_class, c)
        return super(MyTextInput, self).__call__(field, **kwargs)

rawDescription: How to get red borders when a field is invalid using WTForms with GAE and Jinja2?

description: Get red borders when a field is invalid using WTForms with GAE and Jinja2


code: self.filterActive = False

rawDescription: How to select QTableView index or row from inside of Model

description: Select QTableView index or row from inside of Model


code:
import datetime
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

query = ("SELECT first_name, last_name, hire_date FROM employees "
         "WHERE hire_date BETWEEN %s AND %s")

hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)

cursor.execute(query, (hire_start, hire_end))

for (first_name, last_name, hire_date) in cursor:
  print("{}, {} was hired on {:%d %b %Y}".format(
    last_name, first_name, hire_date))

cursor.close()
cnx.close()

rawDescription: I am creating a dictionary in python

description: I am creating a dictionary in python


code: [s for s in list1 if len(s) == 3]

rawDescription: Get string of certain length out of a list


rawDescription: Matplotlib Xticklabels not working

description: Matplotlib Xticklabels not working


rawDescription: How to maintain state in Python without classes?

description: Maintain state in Python without classes


code:
import urllib2, urllib2_ssl

opener = urllib2.build_opener(urllib2_ssl.HTTPSHandler(ca_certs='ca.pem'))
xml = opener.open('https://example.com/').read()

rawDescription: urllib2/pycurl in Django: Fetch XML, check HTTP status, check HTTPS connection

description: Urllib2/pycurl in Django: Fetch XML, check HTTP status, check HTTPS connection


code:
from itertools import chain, repeat, izip

a_2_generator = chain.from_iterable(repeat(i, int(round(j * 10))) for i, j in izip(a, c))
b_2_generator = chain.from_iterable(repeat(i, int(round(j * 10))) for i, j in izip(b, c))

rawDescription: Generate repeated elements in a list based on elements of another list


code:
t - t2
dt = t - t2
dt1 = datetime.timedelta(0, 28800) #08:00 hrs
dt2 = datetime.timedelta(0, 68400) #08:00 hrs
dt > dt1
dt2 > dt > dt1

rawDescription: Check if a timestamp string is within a time range


code:
for chunk in iter(partial(f.read, 8192), b''):
    process(chunk)

rawDescription: Process large data in python

description: Process large data in python


code:
#!/usr/bin/env python
from datetime import datetime
import tzlocal  # pip install tzlocal

local_time = datetime.now(tzlocal.get_localzone())
print(local_time.strftime('%Y-%m-%d %H:%M:%S%z (%Z)'))
# -> 2016-01-12 08:12:51+0100 (CET)

rawDescription: Equivalent of GNU coreutils /bin/date output with Python2 (timezone)


code:
class IterWatch(object):
    def __init__(self, it):
        self.iter = iter(it)
        self._pending = []
    @property
    def pending(self):
        try:
            if not self._pending:
                # will raise StopIteration if exhausted
                self._pending.append(next(self.iter))
        except StopIteration:
            pass # swallow this
        return self._pending
    def next(self):
        try:
            return self.pending.pop(0)
        except IndexError:
            raise StopIteration
    __next__ = next # for Py3
    def __iter__(self): return self
    def __nonzero__(self):
        # returns True if we have data.
        return not not self.pending
        # or maybe bool(self.pending)
    __bool__ = __nonzero__ # for Py3

rawDescription: Check if a generator really generate something in one line


code: text = "'%s'" % text

rawDescription: python SQL Variables in SELECT /WHERE

description: Python SQL Variables in SELECT /WHERE


code: ÄÜ

rawDescription: Python 2.7 Correct syntax to re.match accented characters in a Unicode string?


code: blog = Blog(title="title", body="body", author=user.key)

rawDescription: Assigning an author to an entity during its creation


code:
import os
import signal
def kill_child():
    if child_pid is None:
        pass
    else:
        os.kill(child_pid, signal.SIGTERM)

import atexit
atexit.register(kill_child)

rawDescription: How to kill a python child process created with subprocess.check_output() when the parent dies?

description: Kill a python child process created with subprocess.check_output() when the parent dies


code:
# Loop until the original tweet
while True:
    print(last_tweet.text)
    prev_tweet = api.get_status(last_tweet.in_reply_to_status_id_str)
    last_tweet = prev_tweet
    if not last_tweet.in_reply_to_status_id_str:
        break

rawDescription: Tweepy Twitter get all tweet replies of particular user


code:
a = ["a","b","a","c","b","a"]
d = {x:i for i, x in enumerate(set(a))}
[d[item] for item in a]

rawDescription: Enumerate unique strings in list

description: Enumerate unique strings in list


code:
Parameters = collections.OrderedDict()
Parameters = {"current": '50mA', "voltage": '230', "resistance": '40 ohms'}

rawDescription: How to retain the order of items in dictionary?

description: Retain the order of items in dictionary


code:
from django.db.models import FileField
from django.db.models.fields.files import FieldFile

from .storage import PastebinStorage
from .form_field import PastebinFormField

default_storage = PastebinStorage()

# This custom FieldFile implementation is an optional optimization.
class PastebinContentCachingFieldFile(FieldFile):
    def cached_get_pastebin_content(self):
        cached = getattr(self, '_cached_pastebin_content', None)
        if cached and cached[0] == self.name:
            return cached[1]
        with self.storage.open(self.name) as f:
            content = f.read()
        setattr(self, '_cached_pastebin_content', (self.name, content))
        return content

class PastebinModelField(FileField):
    attr_class = PastebinContentCachingFieldFile

    def __init__(self, verbose_name=None, name=None, storage=None, **kwargs):
        storage = storage or default_storage
        super(PastebinModelField, self).__init__(verbose_name, name, storage=storage, **kwargs)

    def formfield(self, **kwargs):
        defaults = {'form_class': PastebinFormField}
        defaults.update(kwargs)
        return super(PastebinModelField, self).formfield(**defaults)

rawDescription: Passing an input to a service and saving the result to DB in Django


code:
with open("example.html") as of:
    of.write("
")
    for index, row in enumerate(data):
        if index == 0:
             of.write("")
        else:
             of.write("
")
        for cell in row:
             of.write("" + cell + "	")
        if index == 0:
             of.write("	")
        else:
             of.write("
")
    of.write("
")

rawDescription: Creating publication quality tables in python


code: lines_list = [line.strip() for line in lines_list]

rawDescription: Python: list items are not changed in for loop


code:
var1 = 5
var2 = -190
{k: [v, v/var1, v/var1+var2] for k, v in band1.iteritems()}

rawDescription: adding arithmetic values to dictionary?

description: Adding arithmetic values to dictionary


rawDescription: turn string to array python

description: Turn string to array python


code:
a
[i.split("{}") for i in "{}".join(a).split("\n")]

rawDescription: How do I split a list into a list of lists on a specific character in the elements?

description: Split a list into a list of lists on a specific character in the elements


rawDescription: Average of a vector of numbers or a list of numbers in Python


code: results = set.union(set(), *[foo(node) for node in nodes])

rawDescription: Python create union of results from function applied to elements in a set


code:
from itertools import chain, izip
any(x == y for x, y in izip(chain([list2[-1]], list2), list2))

rawDescription: How to check if any tuple same as previsious or next

description: Check if any tuple same as previsious or next


code:
import Tkinter as Tk
root = Tk.Tk()
f = Tk.Frame(root)
f.grid(row=0,column=0)
#place buttons on the *frame*
b1 = Tk.Button(f,text="Button1")
b1.grid(row=0,column=0)
b2 = Tk.Button(f,text="Button2")
b2.grid(row=0,column=1)

big_widget = Tk.Canvas(root)
big_widget.grid(row=1,column=0)  #don't need columnspan any more.

rawDescription: What is a better Tkinter geometry manager than .grid()


code: d = dict(Index1=[], Index2=[])

rawDescription: Python lists indexes

description: Python lists indexes


rawDescription: split url by python

description: Split url by python


code:
from nltk.chunk.util import tagstr2tree
from nltk import word_tokenize, pos_tag
text = "Let the sizes be denoted by $s(n)$ and $t(n)$ respectively."
tagged_text = pos_tag(text.split())
tagged_text_string = " ".join(["{}/{}".format(word,pos) for word, pos in tagged_text])
tagstr2tree(tagged_text_string)

rawDescription: chunk NP and VP using nltk

description: Chunk NP and VP using nltk


code: fidzavg.write("%g\t%g\n" % (stepval*filenum, float(value)))

rawDescription: Writing tabs in a specific way (Not from lists) in python


rawDescription: update matplotlib plot

description: Update matplotlib plot


code: X,Y = np.meshgrid(N,M[::-1])

rawDescription: Repeating rows and columns in Python

description: Repeating rows and columns in Python


code:
import sys

file_paths = sys.argv[1:]
for p in file_paths:
    print(p)

rawDescription: Python drag and drop, get filenames

description: Python drag and drop, get filenames


code:
cm = CoffeeMachine()
cm.state
cm.ground_beans()
cm.state
cm.ground_beans()
cm.heat_water()
cm.pump_water()
cm.state

rawDescription: Implementing a state machine with decorators


code:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5, 100)
cmap = plt.get_cmap('jet_r')
N = 20
for i, n in enumerate(np.linspace(2.0, 0, N)):
    y = np.sin(x)*x**n
    color = cmap(float(i)/N)
    lw = 2.5 if i==0 else 1
    # zorder controls the order in which the lines are drawn.
    # The line with the highest zorder lies on top.
    plt.plot(x, y, c=color, lw=lw, zorder=-i)
plt.show()

rawDescription: Pyplot / matplotlib line plot - same color


code:
float_array = array('d', [1, 1.2, 0.34, 9.8, 0.13, 1.1, 0.88, 72])
s = float_array.tostring()
new_float_array = array('f')
new_float_array.fromstring(s)
new_float_array

rawDescription: Convert a float array into little/big endian


code:
li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
    for i, j in enumerate(lst):
        if isinstance(j, list):
            for item in to_int(j, path+[i]): yield item
        else:
            yield int(j), path+[i]

for item in to_int(li):
    print (item)

rawDescription: Working on multilevel list (2)

description: Working on multilevel list (2)


rawDescription: python : How can I replace complex number to -1?

description: Python : How can I replace complex number to -1


code:
from PyQt4 import QtCore, QtGui
import time

class Dialog(QtGui.QDialog):
    value = 0.001
    def __init__(self, parent=None):
        QtGui.QDialog .__init__(self, parent)
        mainLayout = QtGui.QVBoxLayout()

        self.lineedit = QtGui.QLineEdit()
        self.setValues()
        mainLayout.addWidget(self.lineedit)
        button = QtGui.QPushButton('Calculate')
        button.clicked.connect(self.buttonClicked)
        mainLayout.addWidget(button)
        self.setLayout(mainLayout)

    def setValues(self):
        self.lineedit.setText('progress %s'%self.value)
        palette = self.lineedit.palette()
        QRectF = QtCore.QRectF(self.lineedit.rect())
        gradient = QtGui.QLinearGradient(QRectF.topLeft(), QRectF.topRight())
        gradient.setColorAt(self.value-0.001, QtGui.QColor('#f99e41'))
        gradient.setColorAt(self.value, QtGui.QColor('#ffffff'))
        gradient.setColorAt(self.value+0.001, QtGui.QColor('#ffffff'))
        palette.setBrush(QtGui.QPalette.Base, QtGui.QBrush(gradient))
        self.lineedit.setPalette(palette)

    def buttonClicked(self):
        if self.value >0.9:
            self.value = 0.001
        else:
            self.value=self.value+0.1

        self.setValues()
        time.sleep(1)

if __name__ == '__main__':
    app = QtGui.QApplication([])
    window = Dialog()
    window.resize(300, 50)
    window.show()
    app.exec_()

rawDescription: How to turn QLineEdit background into a Progress Bar

description: Turn QLineEdit background into a Progress Bar


rawDescription: Python - list of same columns / rows from matrix


code:
df.index=df.dt
df=df.ix[time1.date():time2]['count'].reset_index() # filter times and remove date index
df.groupby(by=['loc','dt']).sum().groupby(level=[0]).cumsum()

rawDescription: Python Pandas cumulative column between datetime ranges


code: import random

rawDescription: Python dictionary random key print

description: Python dictionary random key print


rawDescription: Summing several equal size matrices by elements


code:
from django.contrib.auth.models import User
from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=10)

class UserBook(models.Model):
    user = models.OneToOneField(User)
    purchasedBooks = models.ManyToManyField(Book)

rawDescription: Django manage.py sqlclear omit some tables


code:
ax.set_xticks(np.arange(0, 10, 0.5))
ax.set_xticklabels(np.arange(0, 10, 0.5))
# This second line is kind of redundant but it's useful if you want
# to format the ticks different than just plain floats.

rawDescription: Python Pyplot: How to scale x-axis independant from number of list-elements?


code:
something = 'something'

for i in xrange(1000000):
    if something == 'this':
        the_thing = 1
    elif something == 'that':
        the_thing = 2
    elif something == 'there':
        the_thing = 3
    else:
        the_thing = 4

rawDescription: Most efficient way of making an if-elif-elif-else statement when the else is done the most?


code:
url_response = urllib2.urlopen(url) ## return a http.response object
xml_content = url_response.read() ## read the content

rawDescription: Accessing online xml with python

description: Accessing online xml with python


code:
from random import choice

... # Initialize graph

random_edge = choice(g.edges())

rawDescription: Getting the nodes at the end of an edge g.edge_iter


code:
#!/usr/bin/env python
"""Show messages in two new console windows simultaneously."""
import sys
import platform
from subprocess import Popen

messages = 'This is Console1', 'This is Console2'

# define a command that starts new terminal
if platform.system() == "Windows":
    new_window_command = "cmd.exe /c start".split()
else:  #XXX this can be made more portable
    new_window_command = "x-terminal-emulator -e".split()

# open new consoles, display messages
echo = [sys.executable, "-c",
        "import sys; print(sys.argv[1]); input('Press Enter..')"]
processes = [Popen(new_window_command + echo + [msg])  for msg in messages]

# wait for the windows to be closed
for proc in processes:
    proc.wait()

rawDescription: How can I open two consoles from a single script

description: Open two consoles from a single script


rawDescription: How to print every 5 characters in a sequence of 'X' characters?

description: Print every 5 characters in a sequence of 'X' characters


code:
list_of_games = session.query(Game_Table)
list_of_games.all()
list_of_games.filter(name=="stuff").all()

rawDescription: SQLAlchemy Query Possible?

description: SQLAlchemy Query Possible


code: #!/usr/bin/python

rawDescription: How to make a Python script an executable program

description: Make a Python script an executable program


code:
from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.scrollview import ScrollView
Builder.load_string('''
<ScrollLabel>:
    Label:
        size_hint_y:None
        text_size:self.width,None
        text:'l or emi psum '*1000
        height:self.texture_size[1]
''')
class ScrollLabel(ScrollView):pass
runTouchApp(ScrollLabel())

rawDescription: Change the label size depending on the text


code: matching = (l for l, b in zip(L, B) if l > float(b * 1.1))

rawDescription: to check a condition for all the items in two list in python

description: To check a condition for all the items in two list in python


rawDescription: Escape sequence in python

description: Escape sequence in python


code: #include raw "prod.env"

rawDescription: Python Cheetah - Specify name/value pairs for templating


code:
import time
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get("http://goldprice.org/gold-price-canada.html")
while True:
    print(driver.find_element_by_id("gpotickerLeftCAD_price").text)
    time.sleep(1)

rawDescription: Having issues with Python xpath scraping


rawDescription: Rounding a number in python but keeping ending zeros


code:
class Node (db.Model):

    def get_path (self, field):

        @cache.version (key=[self.uuid, 'path', field])
        def cached_path (self, field):

            if self.root:
                return self.root.get_path (field) + [getattr (self, field)]
            else:
                return [getattr (self, field)]

        if field == 'uuid':
            return cached_path (self, field)
        else:
            return cached_path.uncached (self, field)

    @hybrid_property
    def name_path (self):
        return os.path.sep.join (self.get_path (field='name'))

    @name_path.expression
    def name_path (cls):
        return NamePathColumn (cls)

rawDescription: SQLAlchemy: Recursive hybrid property in a tree node


code: help(divmod)

rawDescription: Splitting a 2 digit number into 10's and 1's in python


code: merged[merged.SICcode == 'Aux']

rawDescription: Pandas: dataframes won't merge

description: Pandas: dataframes won't merge


rawDescription: How to split a byte string into separate bytes in python

description: Split a byte string into separate bytes in python


code:
['Princess Maria Amelia of Brazil (1831\x961853)']

['was the daughter of Dom Pedro I,', "founder of Brazil's independence and its first emperor,"]

['and Amelie of Leuchtenberg.']

["The only child from her father's second marriage,", 'Maria Amelia was born in France', "following Pedro I's 1831 abdication in favor of his son Dom Pedro II."]

['Before Maria Amelia was a month old, Pedro I left for Portugal', 'to restore its crown to his eldest daughter Dona Maria II.', "He defeated his brother Miguel I (who had usurped Maria II's throne),", 'only to die a few months later of tuberculosis.']

[['2', '3'], ['5', '6', '7', '8'], ['11']]

rawDescription: Split lines into paragraphs

description: Split lines into paragraphs


rawDescription: NLTK WordNet verb hierarchy

description: NLTK WordNet verb hierarchy


code: profile.run('runCombinationCheckingMethod(triadicIteractionGranular, [], {"signsQty" : 15})')

rawDescription: Why is triadic iteration 2 times slower than the recursion?


code:
if __name__ == '__main__':
    pool = multiprocessing.Pool()
    pool.map(worker, range(4))
    pool.close()
    pool.join()

rawDescription: Multiprocessing, how to run processes in parallel without creating zombies?


code:
class Article(models.Model):
    author_name = models.ForeignKey(Author)

class Author(models.Model):
    # ...
    def get_articles(self):
         "Returns the author published articles"
         return self.article_set.all()

rawDescription: Confused regarding ForeignKey relationship in Django


rawDescription: generate lists from 3 dimensional array

description: Generate lists from 3 dimensional array


code:
M,N,R = A.shape

p1 = np.arange(M)[:,None,None]/Lx
p2 = np.arange(N)[:,None]/Ly
p3 = np.arange(R)/Lz

out = A/(w*(p1 + p2 + p3))

rawDescription: Applying function that cares about index to every element of numpy array


rawDescription: connect to mysql server in docker

description: Connect to mysql server in docker


code: [e.get_text() for e in soup.select('.panda .cheese')]

rawDescription: How can I use BeautifulSoup to get deeply nested div values?

description: Use BeautifulSoup to get deeply nested div values


code:
import unittest

def get_highest_valued_company(input_csv):
    process[...]
    return 'highest company name'

class TestMyFunction(unittest.TestCase):
    def setUp(self):
        pass

    def test_my_csv_function(self):
        self.assertTrue(get_highest_valued_company(csv)=='name_here')

if __name__ == '__main__':
    unittest.main()

rawDescription: write unit test case in python for below algorithm

description: Write unit test case in python for below algorithm


code:
@hybrid_property
def previous_count(self):
    # the python property, queries the database and returns a count
    cls = self.__class__
    return session.query(func.count(cls.id)).filter(cls.project == self.project, cls.ts < self.ts).scalar()

@previous_count.expression
def previous_count(cls):
    # the sql property, constructs a scalar subquery with an alias
    other = aliased(cls)
    return session.query(func.count(other.id)).filter(other.project_id == cls.project_id, other.ts < cls.ts).as_scalar()

rawDescription: Using HybridProperty to count previous sibblings


code:
strs = "United Kingdom, United Kingdoms, United States, Kingdmo"
strs.split(",")

rawDescription: Inputting a list of strings Python

description: Inputting a list of strings Python


rawDescription: Pandas(Python) to_clipboard with comma decimal parameter


code: path = iter.get_selected_rows()[0]

rawDescription: Getting the row number of Gtk TreeView

description: Getting the row number of Gtk TreeView


code:
{'link': [u'#mw-navigation'], 'title': [u'navigation']}
{'link': [u'#p-search'], 'title': [u'search']}
...
{'link': [u'/wiki/Internet_forum'], 'title': [u'Internet forums']}
...

rawDescription: How to loop over a response element in Scrapy?

description: Loop over a response element in Scrapy


code:
from django.utils.safestring import mark_safe

def divgrid(content_list):
    ...
    return mark_safe(dstring)

rawDescription: Get django to render python generated html passed via context parameter?


rawDescription: Python string to dict

description: Python string to dict


rawDescription: z3 pseudo-randomly hangs while parsing through a SAT Model

description: Z3 pseudo-randomly hangs while parsing through a SAT Model


code: op, value = (lambda x, y: x+y), 0

rawDescription: How to go back to a specific line

description: Go back to a specific line


rawDescription: How to combine try/except in python into a pretty one liner?

description: Combine try/except in python into a pretty one liner


code:
from mycache import Cache

@app.route('/')
@app.route('/index')
def index():
    if not g.identity.is_authenticated():
        return render_template('homepage.html')
    else:
        login_count = Cache.get("login_count")
        if login_count == 0:
            # ...
            # Your code
            login_count += 1
            Cache.set("login_count", login_count)

rawDescription: How to execute a block of code only once in flask?

description: Execute a block of code only once in flask


code:
user = 'username'
host = 'host'
'%s@%s' % (user, host)

rawDescription: Python .join or string concatenation

description: Python .join or string concatenation


code:
d = datetime.datetime(targetYear,targetMonth,1,hour,min,sec)
d = d + datetime.timedelta(days=targetDayOfMonth-1)

rawDescription: datetime.datetime - day field out of range

description: Datetime.datetime - day field out of range


code: {{ trans.short-introduction-text }}

rawDescription: Django Application Layout: Internationalization


code:
import sys, pprint
pprint.pprint(sys.path)

rawDescription: Python 2.7: "import time" Where is python importing this time module from?


code: g.db.execute('delete from entries where id=' + id)

rawDescription: How to delete record in Sqlite

description: Delete record in Sqlite


rawDescription: Find Matches in 2 list of lists of different length


code:
method1
method2

rawDescription: Python How to list all methods/classes that have been imported into a class


code:
DateRange(datetime.date(2014,2,20), None)
DateRange(datetime.date(2014,1,1), datetime.date(2014,4,1))
DateRange.parse(':2014-2-20')
DateRange.parse('2014-2-20:2014-3-22')
daterange = DateRange.parse('2014-2-20:2014-3-2')
daterange
datetime.date(2014,1,25) in daterange
datetime.date(2014,2,20) in daterange
list(daterange)

rawDescription: Representing a Range of values as a Python Sequence Type


code:
g = MyClass()
g.bar = -5  # Negative bar!
g.baz = 3   # Odd baz!
g.quux = 2  # Non-bar/baz attribute!

rawDescription: Set a custom object attribute

description: Set a custom object attribute


code:
params = urllib.urlencode({'username': username, 'password': password})
urllib2.urlopen('http://somedomain.com/login', params)

rawDescription: How to store cookie jar to be used between functions inside class?

description: Store cookie jar to be used between functions inside class


code: node_colors = ["blue" if n in shortestPath else "red" for n in G.nodes()]

rawDescription: NetworkX color the nodes in path

description: NetworkX color the nodes in path


code:
class Item(models.Model):
    name = models.CharField(max_length = 200, blank = False)

class Player(models.Model):
    items = models.ManyToManyField(Item, through='PlayerItem')

class PlayerItem(models.Model):
    player = models.ForeignKey(Player)
    item = models.ForeignKey(Item)
    acquired = models.DateTimeField(default=datetime.datetime.now)

rawDescription: Django - How to model this correctly?

description: Django - How to model this correctly


code: print("Randy's phone # is {0[Randy][phone]}".format(people))

rawDescription: Accessing nested dictionary items in Python


code:
Pages = Pages()
Pages.index
Pages.index.selected
Pages.index.select()
Pages.index.selected
Pages.faq.select()
Pages.index.selected

rawDescription: Accessing outer class from inner python

description: Accessing outer class from inner python


code: #!/usr/bin/env python

rawDescription: How do I alias a command line command? (Mac)

description: Alias a command line command? (Mac)


rawDescription: Entering Parameters in Python

description: Entering Parameters in Python


code:
@app.task(base=DBTask, bind=True)
def do_stuff_with_db(self, conf, some_arg):
    self.conf = conf
    thing = self.session.query(Thing).filter_by(arg=some_arg).first()

rawDescription: how to setup sqlalchemy session in celery tasks with no global variable

description: Setup sqlalchemy session in celery tasks with no global variable


code:
from collections import defaultdict

races = defaultdict(int)
counties = defaultdict(int)
for row in soup.select('table.os tr')[1:]:
    cells = row.find_all("td")

    race = cells[8].text
    races[race] += 1

    county = cells[9].text
    counties[county] += 1

rawDescription: IndexError: list index out of range While Trying to Scrape Specific Columns on a Table?


rawDescription: Pad rows with no data as Na in Pandas Dataframe


code:
id(temp[1])
id(board[1])

rawDescription: Python - Function has a list as argument. How to return another list without changing the first?


code: import datetime as dt

rawDescription: Are there standard rules and practices for Date serialization between two languages or frameworks?


code:
res.resid
res.seasonal
res.trend

rawDescription: Seasonal Decomposition of Time Series by Loess with Python


code:
if True:
    while 1:
        for x in range(1):
            z = 1
        break

def function():
    print(z)

function() # prints 1

rawDescription: Why can I access a non-global variable in one module from another in python?


code: ndb.Query(kind=clss, filters=...)

rawDescription: How To Use NDB Query Without Knowing Class Name


code:
result_list = []
for j in some_list:
    result_list.append(method(j))
sums = tuple(sum(grouped) for grouped in zip(*result_list))

rawDescription: Most pythonic way to 'or' tuples?

description: Most pythonic way to 'or' tuples


code:
if convert_to_bool(your_byte_string):
    # here I'm just printing it but you should use the dumped string as a json response
    print(json.dumps('The field is true!'))
else:
    print(json.dumps('Unfortunately the field is false.'))

rawDescription: Jsonifying bits from MySQLdb in Python

description: Jsonifying bits from MySQLdb in Python


code:
from bottle import mako_template as template

def func():
    ...
    return template('mytemplate.mako')

rawDescription: Set Mako as the default template renderer in Bottle.py


code:
f = open("/dev/random","rb")
rnd_str = f.read(4)

rawDescription: Best seed for parallel process

description: Best seed for parallel process


code:
import xlrd
from xlutils.copy import copy as xlcopy

read_book = xlrd.open_workbook('filepath/to/file.xlsx')
read_sheet = read_book.sheet_by_index(0)
write_book = xlcopy(read_book)
write_sheet = write_book.get_sheet(0)

rawDescription: How to collapse rows in excel using python?

description: Collapse rows in excel using python


code:
def clean(lst):
    if lst.count(lst[0]) == len(lst):
        return [lst[0]]
    else:
        return lst

rawDescription: remove duplicate list elements

description: Remove duplicate list elements


code:
id_vars
val_vars
mlt
mlt[['prov', 'value']].reset_index()
# set original index for joining in future
new['idx'] = new['index']%len(df)
new
pvt = pd.pivot_table(new, index='idx', columns='prov', values='value', aggfunc='first')
pvt
rslt = df[['text','rank','date']].join(pvt)
rslt

rawDescription: Reformatting my csv file by pandas (convert set of values to columns, matching another set to corresponding values)


code:
result = []
for i in range(len(l)):
    result.extend(list(itertools.product(*l[:i+1])))
result

rawDescription: How to pull all the unique combinations from a list of lists

description: Pull all the unique combinations from a list of lists


code:
gid = [0] # list - mutable object

def incremented(gid):
    gid[0] += 1
    return gid[0]

groups[m][n] = groups[m - 1][n] or incremented(gid)

rawDescription: How to write this statement more compactly without a ++ operator?

description: Write this statement more compactly without a ++ operator


code:
coords = (u[:, None, None] * np.linspace(0, 9, 10)[None, :, None] +
          v[:, None, None] * np.linspace(0, 2.5, 10)[None, None, :])

rawDescription: Fast interpolation of regularly sampled 3D data with different intervals in x,y, and z


code:
import pandas
data = pandas.read_csv('iris.csv', header=None)

float_dat = data[data.columns[:-1]]
dmin, dmax = float_dat.min(axis=0), float_dat.max(axis=0)

data[data.columns[:-1]] = (float_dat - dmin) / (dmax - dmin)

rawDescription: Normalize/Standardize a numpy recarray

description: Normalize/Standardize a numpy recarray


code: line = line.replace('\r', '').replace('\n', '')

rawDescription: How can I print a long line in realtime in python?

description: Print a long line in realtime in python


code:
from pprint import pprint
inputlist = [{'key0': 'key0_value0', 'key1': 'key1_value0'},
 {'key0': 'key0_value1', 'key1': 'key1_value1'}]
columns = [['key_header'] + sorted(inputlist[0].keys())]  # first column
for i, entry in enumerate(inputlist):
    columns.append([i] + [entry[k] for k in columns[0][1:]])

pprint(zip(*columns))

rawDescription: Writing a CSV horizontally

description: Writing a CSV horizontally


code:
import scipy.ndimage
abs(scipy.ndimage.laplace(x)) > 0

rawDescription: Find adjacent elements in a 2D numpy grid


code:
# you could also replace np.newaxis with None for brevity (see below)
d = a[:, np.newaxis] * b[np.newaxis, :]

rawDescription: Vector-vector multiplication to create a matrix


code:
import re

alias_pattern = re.compile(r'''(?:\[(\w+)\])''')

def mapper(mat):
    func_alias = mat.group(1)
    function = function_alias_mapping.get(func_alias)
    if not function:
        raise NameError(func_alias)
    return function.__name__ + '()'

# must be defined before anything can be mapped to them
def FooFunction(): return 15
def BarFunction(): return 30
def BazFunction(): return 6

function_alias_mapping =  dict(foo=FooFunction, bar=BarFunction, baz=BazFunction)
formula = "(([foo] + [bar]) - ([baz]/2))"

converted_formula = re.sub(alias_pattern, mapper, formula)
print('converted_formula = "{}"'.format(converted_formula))

# define contexts and function in which to evalute the formula expression
global_context = dict(FooFunction=FooFunction,
                      BarFunction=BarFunction,
                      BazFunction=BazFunction)
local_context = {'__builtins__': None}

function = lambda: eval(converted_formula, global_context, local_context)
print('answer = {}'.format(function()))  # call function

rawDescription: Convert custom formula to python function


code:
import pickle
ppp = pickle.dumps(pp)

rawDescription: Use of class typenames in python

description: Use of class typenames in python


code:
arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)

rawDescription: How to add a new row to an empty numpy array

description: Add a new row to an empty numpy array


code:
output.default_factory = None
for default_date_dict in output.values():
    default_date_dict.default_factory = None

rawDescription: Merge two dictionaries with nested dictionaries into new one, summing same keys and keeping unaltered ones in Python


code:
from rootpy import stl
from rootpy.io import TemporaryFile
from rootpy.tree import Tree, TreeModel, CharArrayCol

class Model(TreeModel):
    # define the branches you want here
    # with branchname = branchvalue
    char_array = CharArrayCol(21)
    # the dictionary is compiled and cached for later
    # if not already available
    strings = stl.vector('string')

# create the tree inside a temporary file
with TemporaryFile():
    # all branches are created automatically according to your model above
    tree = Tree('tree', model=Model)

    tree.char_array = 'a' * 20
    # attemping to set char_array with a string of length 21 or longer will
    # result in a ValueError being raised.
    tree.strings.push_back('Hello')
    tree.strings.push_back('world!')
    tree.Fill()
    tree.Scan('', '', 'colsize=21')

rawDescription: Python array of strings in a ROOT TTree

description: Python array of strings in a ROOT TTree


code:
parser = argparse.ArgumentParser()
subs = parser.add_subparsers()
dpd = subs.add_parser('download-and-parse-data', aliases=['dpd'])
dpd.add_argument(...)
...

rawDescription: An easy way to set up abbreviations with argh


code:
turn = True
while turn == True:
    listboxInventory.curselection()

rawDescription: Python 3.4.2, Using listbox for an inventory


code: found in word #3

rawDescription: Efficient way to find the token (word) index after a regular expression string search


code:
from rest_framework import serializers

class Fruit(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

class FruitSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=200)

rawDescription: Rest_framework datas from list

description: Rest_framework datas from list


code:
def p_type_list_1(p):
    '''type_list : type'''
    p[0] = [p[1]]

def p_type_list_2(p):
    '''type_list : type_list COMMA type'''
    p[0] = p[1] + [p[3]]

rawDescription: PLY YACC pythonic syntax for accumulating list of comma-separated values


code:
def triup(a, b):
    c = b
    out = ""
    for i in range(1, b + 1):
        out += a * " " + c * '*' + "\n"
        c -= 2
        a += 1
        if c == -1:
            return out
    return  out

def trido(a, b):
    c = 1
    a += round((b - 1) / 2)
    out = ""
    for j in range(1, b + 1):
        out += a * " " + c * "*"  + "\n"
        c += 2
        a -= 1
        if c == b + 2:
            return out
    return out

rawDescription: Defining a rhomb by two triangles

description: Defining a rhomb by two triangles


rawDescription: How to read data table column by column from a txt in python

description: Read data table column by column from a txt in python


code:
def get_symmetric_time_window_fwd(ref_date, end_date):
  da1 = ref_date+timedelta(1)
  da2 = end_date-timedelta(1)

  if da2.weekday() >= ref_date.weekday():
    db2 = da2 - timedelta( 7 * (1+int((end_date - ref_date).days/7)))
  else:
    db2 = da2 - timedelta( 7 * (int((end_date - ref_date).days/7)))

  db1 = db2-(da2-da1)

  return da1, da2, db1, db2

rawDescription: Mirroring dates in Python

description: Mirroring dates in Python


rawDescription: how to add two numpy.array with indices or mask

description: Add two numpy.array with indices or mask


code:
import networkx as nx

deps = nx.DiGraph()
deps.add_nodes_from("abcdef")
deps.add_edges_from([("a","b"), ("c","a"), ("e","c")], is_strong=True)
deps.add_edges_from([("f","c"), ("d","c")], is_strong=False)

rawDescription: How can I implement "weak" edges with NetworkX?

description: Implement "weak" edges with NetworkX


code:
pr = Rectangle((0, 0), 1, 1, fc='r')
pg = Rectangle((0, 0), 1, 1, fc='g')
pb = Rectangle((0, 0), 1, 1, fc='b')
legend([pr, pg, pb], ['Lenovo', 'HP', 'Dell'])

rawDescription: How do I assign different dots different colors in a scatter plot made with MatPlotLib?

description: Assign different dots different colors in a scatter plot made with MatPlotLib


code:
from collections import namedtuple
a = namedtuple("person", ['name', 'income'])
a
ab = a("Dannnnno", 100)
ab
ab.name
ab.income

rawDescription: Best way to make 'n' objects with each with unique data contents?

description: Make 'n' objects with each with unique data contents


code:
from __future__ import absolute_import
import json

rawDescription: Fully Qualified name of a python module

description: Fully Qualified name of a python module


code:
from collections import Counter
c = Counter('aaaaabbbdddeeegggg')

rawDescription: A program that opens a text file, counts the number of words and reports the top N words ordered by the number of times they appear in the file?


code: unbound_mth = getattr(MyClass, "mymethodname")

rawDescription: Python: how does inspect.ismethod work?

description: Python: how does inspect.ismethod work


code:
data.sort(key=sum, reverse=True)
sorted(data, key=sum, reverse=True)

rawDescription: Python - sort lists based on their sum

description: Python - sort lists based on their sum


code:
from concurrent.futures import ProcessPoolExecutor

def thirty_second_function():
    return ["mango", "habanero", "salsa"]

def five_second_function():
    return {"beans": "8 oz", "tomato paste": "16 oz"}

if __name__ == '__main__':
    with ProcessPoolExecutor() as e:
        p1 = e.submit(thirty_second_function)
        p2 = e.submit(five_second_function)
    print(p1.result())
    print(p2.result())

rawDescription: Multiprocessing and variable return?

description: Multiprocessing and variable return


code:
from PyQt4 import QtGui, QtCore
import os

class MyQTreeView(QtGui.QTreeView):

    def __init__(self, path, parent=None):
        super(MyQTreeView, self).__init__(parent)

        ppath = os.path.dirname(path) # parent of path
        self.setFrameStyle(0)

        #---- File System Model ----

        sourceModel = QtGui.QFileSystemModel()
        sourceModel.setRootPath(ppath)

        #---- Filter Proxy Model ----

        proxyModel = MyQSortFilterProxyModel(path)
        proxyModel.setSourceModel(sourceModel)

        #---- Filter Proxy Model ----

        self.setModel(proxyModel)
        self.setHeaderHidden(True)
        self.setRootIndex(proxyModel.mapFromSource(sourceModel.index(ppath)))

        #--- Hide All Header Sections Except First ----

        header = self.header()
        for sec in range(1, header.count()):
            header.setSectionHidden(sec, True)

    def sizeHint(self):
        baseSize = super(MyQTreeView,self).sizeHint()

        #---- get model index of "path" ----
        qindx = self.rootIndex().child(0, 0)

        if self.isExpanded(qindx): # default baseSize height will be used
            pass

        else:  # shrink baseShize height to the height of the row
            baseSize.setHeight(self.rowHeight(qindx))

        return baseSize

class MyQSortFilterProxyModel(QtGui.QSortFilterProxyModel):
    def __init__(self, path, parent=None):
        super(MyQSortFilterProxyModel, self).__init__(parent)

        self.path = path

    def filterAcceptsRow(self, row, parent):

        model = self.sourceModel()
        path_dta = model.index(self.path).data()
        ppath_dta = model.index(os.path.dirname(self.path)).data()

        if parent.data() == ppath_dta:
            if parent.child(row, 0).data() == path_dta:
                return True
            else:
                return False
        else:
            return True

rawDescription: How to add QTreeView in a QTableView column

description: Add QTreeView in a QTableView column


code:
def pseudosplit(predicate, seq):
    return (tuple(g) for k,g in groupby(seq, key=lambda x: not predicate(x)) if k)

rawDescription: Analog of str.split for iterables?

description: Analog of str.split for iterables


code:
import Tkinter as tk

def timeclock():
    global m, y
    if m < 12:
        m += 1
        clock.configure(text = "Month: "+str(m)+", Year: "+str(y))
    else:
        m = 1
        y += 1
        clock.configure(text = "Month: "+str(m)+", Year: "+str(y))
    root.after(100, timeclock)

def reset():
    global m, y
    m = 0
    y = 0

root = tk.Tk()
clock = tk.Label(root, text='Clock')
clock.pack()
m = 0
y = 0
button = tk.Button(root, text='Reset clock', command=reset)
button.pack()
root.after(100, timeclock)
root.mainloop()

rawDescription: Month/Year clock ingame stopping the rest of my game


code: ", ".join("+".join(chars) for chars in [A1, B1, C1])

rawDescription: Printing strings that have chars separated by " + " and strings themselves separated by " , "


code:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

rawDescription: Refactor the first iteration for generator in python


code:
import time, sys
from IPython.display import clear_output
f, ax = plt.subplots()

for i in range(10):
  y = i/10*sin(x)
  ax.plot(x,y)
  time.sleep(0.5)
  clear_output()
  display(f)
  ax.cla() # turn this off if you'd like to "build up" plots
plt.close()

rawDescription: Animated graphs in ipython notebook

description: Animated graphs in ipython notebook


rawDescription: Numpy tensor: Tensordot over frontal slices of tensor


code:
mktemp(src)  # __main__:33
pass  # __main__:30
p=src  # __main__:34
mktemp(src)  # __main__:33
pass  # __main__:30
p=src  # __main__:34
if on: sys.settrace(_traceit)  # __main__:26
else: sys.settrace(_passit)  # __main__:27

rawDescription: Can Python be made to generate tracing similar to bash's set -x?


code:
query = """select column1 from my_table where id = :my_id"""
bind_vars = {'my_id' : 1}

db_cursor.execute(query, bind_vars)

rawDescription: Optimizing Oracle database query/fetchall


code:
def listmatrixMap(f, *matrices):
    return \
        [
            [
                f(*values)
                for c,values in enumerate(zip(*rows))
            ]
            for r,rows in enumerate(zip(*matrices))
        ]

rawDescription: Add two matrices in python

description: Add two matrices in python


code:
# Let's use random numbers to test out variety as also OP states :
box_sum
box_nb

rawDescription: Grid distribution with numpy

description: Grid distribution with numpy


rawDescription: Counting positive elements in a list with Python list comprehensions


code:
foos = Foo.query.all()
dict = FooSerializer(foos, many=True).data

rawDescription: Sqlalchemy - Foreign Value

description: Sqlalchemy - Foreign Value


code:
images = [glob.glob(pattern) for pattern in ("image_000[1-3]*",
    "image_00[10-11]*", "image_0011-[1-3]*", "image_9999*")]
images = [image for seq in images for image in seq]  # flatten the list

rawDescription: How to list an image sequence in an efficient way? Numercial sequence comparison in Python

description: List an image sequence in an efficient way? Numercial sequence comparison in Python


code:
def contact(request):
    from yourapp.models import ContactAdmin
    contacts = ContactAdmin.objects.all()

    return {
        'contacts': contact,  # Add 'contacts' to the context
    }

rawDescription: How to put variable from database into base.html template?

description: Put variable from database into base.html template


rawDescription: How to set multiple columns in a 2D numpy array without for-loop?

description: Set multiple columns in a 2D numpy array without for-loop


code:
def __recvall(self, bytes):
    """__recvall(bytes) -> data
    Receive EXACTLY the number of bytes requested from the socket.
    Blocks until the required number of bytes have been received.
    """
    data = self.recv(bytes, socket.MSG_WAITALL)
    if type(data) not in (str, unicode) or len(data) != bytes:
        raise socket.timeout('timeout')
    return data

rawDescription: How to set timeout for urllib2.OpenDirector open() method

description: Set timeout for urllib2.OpenDirector open() method


rawDescription: Using set in Python inside a loop

description: Using set in Python inside a loop


code:
d = ["'WORKSHOP'", "'KIDS'", "'EXHIBITION'", "'FANTASY'", "'FESTIVAL'"]
[i[1:-1] for i in d]
list(map(lambda x: x[1:-1], d))

rawDescription: using ast_literal_eval in python

description: Using ast_literal_eval in python


code:
from app.models import Task
task = Task.objects.all().select_related()[0]
task.project.job.job_number
from django.db import connection
len(connection.queries)
connection.queries

rawDescription: Django: How to use select_related to INNER JOIN FK's FK


code:
views.py
# Send your list of active slugs to the template

return render(request, 'category.html', {
    'active_filters': active,
    'inactive_filters': inactive,
    'slugs': slugs,
})

rawDescription: get_full_path in django model method

description: Get_full_path in django model method


code:
s = 'thumbgreenappleactiveassignmentweeklymetaphor'
print(infer_spaces(s))

rawDescription: How to split text without spaces into list of words?

description: Split text without spaces into list of words


rawDescription: Convert a text file into a list

description: Convert a text file into a list


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "[alt=\"Deals in Books\"]"))
)
element.click()

rawDescription: Python selenium didn't find css element

description: Python selenium didn't find css element


code:
blacklisted = ('foo.com', 'bar.com')
email = 'x@bar.com'
email.endswith(blacklisted)

rawDescription: Best way to filter out emails and domains in python

description: Filter out emails and domains in python


code: lines = filter(None, (line.rstrip() for line in open(filename)))

rawDescription: Python: Easiest way to ignore blank lines when reading a file


code:
outcome_cat.codes
Out[6]: array([0, 0, 1, 1], dtype=int8)

rawDescription: setting levels apriori when using factorize in Pandas to cover missing cases

description: Setting levels apriori when using factorize in Pandas to cover missing cases


code:
class ThingType(type):
    __stuff__ = ["foo", "bar", "baz"]

    @classmethod
    def __iter__(cls):
        return iter(cls.__stuff__)

class Thing(object, metaclass=ThingType):
    pass

for thing in Thing:
    print(thing)

rawDescription: Defining magic methods on classes

description: Defining magic methods on classes


code:
L=loadmat('stack32723802.mat')
L['y']

rawDescription: scipy and preserving mat file (.mat matlab data file) structure

description: Scipy and preserving mat file (.mat matlab data file) structure


code:
import json

data_obj = json.loads(json_data_string)

rawDescription: Javascript/python design assistance

description: Javascript/python design assistance


code:
import shelve

DOC1 = "The problem of Programming Communication with"
DOC2 = "Programming of Arithmetic Operations"

DOC1 = DOC1.lower()
DOC2 = DOC2.lower()

all_words = DOC1.split()
all_words.extend(DOC2.split())
all_words = set(all_words)

inverted_index = {}

def location(doc, word):
    return doc[:doc.find(word)].count(' ') + 1

for word in all_words:
    if word in DOC1:
        if word in inverted_index:
            inverted_index[word].append(('DOC1', location(DOC1, word)))
        else:
            inverted_index[word] = [('DOC1', location(DOC1, word))]
    if word in DOC2:
        if word in inverted_index:
            inverted_index[word].append(('DOC2', location(DOC2, word)))
        else:
            inverted_index[word] = [('DOC2', location(DOC2, word))]

# Saving to persistent object
inverted_index_file = shelve.open('temp.db')
inverted_index_file['1'] = inverted_index
inverted_index_file.close()

rawDescription: Writing b-tree in file using python

description: Writing b-tree in file using python


code:
import re
def get_patterns(string, re_digits=re.compile("(\d+)"), re_alpha=re.compile("(?i)([A-Z]+)")):
    """
    Takes a string and returns found groups
    of numeric and alphabetic characters.

    """
    digits = re_digits.findall(string)
    alpha = re_alpha.findall(string)
    return digits, alpha

rawDescription: compiling regexes within a frequently-called function

description: Compiling regexes within a frequently-called function


code:
def IdSet(self, value):
    if not isinstance(value, basestring):
        raise TypeError('ID must be a string.')
    self.UpdateFromKey(ndb.Key(self.__class__, value.lower()))
    if self.caseful_id is None:
        self.caseful_id = value

rawDescription: Making id case-insensitive but case-preserving in endpoints-proto-datastore


code:
root = Tk()
root.attributes('-fullscreen', True)

rawDescription: tkinter python maximize window

description: Tkinter python maximize window


code:
"""
Test module for cProfile stats

"""

import time

def wait(t):
    time.sleep(t)

wait(5)

rawDescription: Why is my code so slow?

description: Why is my code so slow


rawDescription: Extend Python list "inline"

description: Extend Python list "inline"


code: blurred = scipy.ndimage.uniform_filter(a, filtsize, output=a)

rawDescription: Using strides for an efficient moving average filter


code:
class allabolagspider(CrawlSpider):
    name="allabolagspider"
    # allowed_domains = ["byralistan.se"]
    start_urls = [
        "http://www.allabolag.se/5565794400/befattningar"
    ]

    rules = (
        Rule(LinkExtractor(allow = "http://www.allabolag.se",
                           restrict_xpaths=('//*[@id="printContent"]//a[1]'),
                           canonicalize=False),
             callback='parse_link'),
    )
    ...

rawDescription: Scrapy - can't follow links due to encoding


code: a, b = range(7), range(5, 11)

rawDescription: Compare with each other, items inside two lists, in a for loop?


code:
t = tuple(arr_invalid)
filt = list(filter(lambda x: not x.lower().startswith(t), strings))

rawDescription: Filter using lambda function python

description: Filter using lambda function python


code:
for i, value in zip(indices, values):
    seq[i] = value

rawDescription: Better to use dict of integer keys or a very long list?


rawDescription: Multiply Dense Rectangular Matrix by Sparse Matrix


code:
import pygame
pygame.init()

display = pygame.display.set_mode((100,100))

clock = pygame.time.Clock()

while True:
    pygame.event.pump()
    keypressed = pygame.key.get_pressed()

    if keypressed[pygame.K_w]:
        print("it worked")
    else:
        print("It didn't work")

    #compute how many milliseconds have passed since the previous call
    clock.tick(30)

rawDescription: Why is pygame.key.get_pressed not working as expected?


code:
a = numpy.arange(10)
b = numpy.arange(1, 11)
a
b
numpy.column_stack((a, b))
numpy.column_stack((a, b)).shape

rawDescription: Is zip() the most efficient way to combine arrays with respect to memory in numpy?


code:
datalist = [['India', 'Yes', '99%'], [['China', 'Yes', '89%'], ['Brazil', 'No', '90%']], ['Russia', 'Yes', '92%'],
            [['Germany', 'No', '97%'], ['Spain', 'No', '70%']]]

new_datalist = []
for lst in datalist:
    if isinstance(lst[0], list):
        new_datalist.extend(lst)
    else:
        new_datalist.append(lst)
datalist = new_datalist

print(datalist)

rawDescription: Python - Write list values in xlwt

description: Python - Write list values in xlwt


code: KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (1)'

rawDescription: How to slice one MultiIndex DataFrame with the MultiIndex of another

description: Slice one MultiIndex DataFrame with the MultiIndex of another


code:
from operator import methodcaller

map(methodcaller('__call__', arg), list_of_functions)

rawDescription: Apply multiple functions to the same argument in functional Python


code:
@property
def area(self):
    try:
        return self._area
    except AttributeError:
        area = pi*self.radius**2
        self._area = area
        return area

@property
def radius(self):
    return self._radius

@radius.setter
def radius(self, radius):
    try:
        del self._area
    except AttributeError:
        pass
    self._radius = radius

rawDescription: When and how often are properties calculated in python?


rawDescription: python: finding a continuous list of values, matching a condition, starting from the first element

description: Python: finding a continuous list of values, matching a condition, starting from the first element


code:
other_number = currencies[currency1]
exchange_rate = number / other_number # exchange rate BETWEEN the two currencies

rawDescription: using subroutines in python instead of if statements

description: Using subroutines in python instead of if statements


code: columns = line.split("\t")

rawDescription: read files with empty entries for certain columns

description: Read files with empty entries for certain columns


code: df[df.Change == 1].resample('D', fill_method='ffill')

rawDescription: Pandas DataFrame Repeat Value Based on a Condition


code:
from django import template
from django.utils.encoding import force_unicode

def split_by_sentence(text, word_count):
    words = force_unicode(text).strip().split(' ')
    word_count = int(word_count)
    if len(words)>word_count:
        cnt = word_count
        for word in words[word_count:]:
            cnt+=1
            if '.' in word or '?' in word or '!' in word:
                break
        if cnt>=len(words):
            cnt = word_count

        pre = ' '.join(words[:cnt])
        post = ' '.join(words[cnt:])
        return pre, post
    else:
        return text, None

register = template.Library()
@register.tag
def splitarticle(parser, token):
    try:
        tag, data, word_count = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError('splitarticle parsing error')
    return SplitArticleNode(data, word_count)

class SplitArticleNode(template.Node):
    def __init__(self, data, word_count):
        self.data = template.Variable(data)
        self.word_count = word_count
    def render(self, context):
        data = self.data.resolve(context)
        context['pre_part'], context['post_part'] = split_by_sentence(data, self.word_count)
        return ''

rawDescription: django templatetag

description: Django templatetag


rawDescription: parsing text file without splitting up multi-word names

description: Parsing text file without splitting up multi-word names


code: add_button = Button(wrapper, text="add", command=lambda:addmeter(self))

rawDescription: Calling an global function from inside a class. Python 2.7 using Tkinter


code:
def my_func(request):
    if request.user.is_authenticated():
        print (user.id) #the user is loggedin

rawDescription: login sessions for django

description: Login sessions for django


code:
from flask import request

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search')
def search():
    search = request.args.get('search')  # will be None if form wasn't submitted
    # do something with search
    return render_template('search.html', search=search)

rawDescription: Can't retrieve variable from url with Flask app after submitting search form


rawDescription: merging indexed array in Python

description: Merging indexed array in Python


rawDescription: delete items from 3 different lists

description: Delete items from 3 different lists


code:
asciiCoded = []
for i in ascii:
    if 65 <= i <= 90 or 97 <= i <= 122:  # only letters get changed
        asciiCoded.append(i+shiftValue)
    else:
        asciiCoded.append(i)

rawDescription: Selecting specific int values from list and changing them


code:
def f(x):
    return f_norec(f,x)
return memoize(f)

rawDescription: Why does Python's decorator syntax give faster memoization code than plain wrapper syntax?


code: key = next(filter(lambda lst: 'b' in lst, d.values()))

rawDescription: How to access a list containing specific item in a dictionary?

description: Access a list containing specific item in a dictionary


code: f_sorted = sorted(sa, key=first)

rawDescription: Python: how to search for a substring in a set the fast way?


code:
# Save result
# print(docx.oxml.xmlchemy.serialize_for_reading(doc_body))
doc.save('/some/path/generated_doc.docx')

rawDescription: python-docx insertion point

description: Python-docx insertion point


code:
import urllib
u = urllib.urlopen('http://stackoverflow.com')
x = u.read(1000)
len(x)
u.close()

rawDescription: Stop downloading after receiving particular amount of bytes?


code:
import numpy as np
array=np.arange(6).view([('x',np.int),('y',np.int)])
print(array)
# [(0, 1) (2, 3) (4, 5)]

print(array['x'])
# [0 2 4]

print(array['x']<3)
# [ True  True False]

print((array['x']<3).sum())
# 2

rawDescription: Function application over numpy's matrix row/column


rawDescription: How to raise an exception on the version number of a module

description: Raise an exception on the version number of a module


code:
#!/usr/bin/python3

from numpy import arange

from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap

# ======
## data:

N = 10000
data = arange(N +1)

# =================
## custom colormap:

# red-green colormap:
cdict = {'red':   [(0.0, 1.0, 1.0),  # red decreases
                   (1.0, 0.0, 0.0)],

         'green': [(0.0, 0.0, 0.0),  # green increases
                   (1.0, 1.0, 1.0)],

         'blue':  [(0.0, 0.0, 0.0),  # no blue at all
                   (1.0, 0.0, 0.0)]}

red_green_cm = LinearSegmentedColormap('RedGreen', cdict, N)

# ======
## plot:

colors = cm.get_cmap(red_green_cm, N)

fig = plt.figure()
ax = fig.add_subplot(111)

# each line is of its own color:
for i, x in enumerate(data):
    ax.plot(data, data*x, color=colors(i))

fig.savefig("red-green-cm.png")

rawDescription: Mapping range of integer values to colors in python


code: df.fillna(method='ffill', inplace=True)

rawDescription: How to replace NaNs by preceding values in pandas DataFrame?

description: Replace NaNs by preceding values in pandas DataFrame


code:
def cbk(match, nb = [0] ):
    if len(match.group())>len(nb):
        nb.append(1)
    else:
        nb[:] = nb[0:len(match.group())]
        nb[-1] += 1
    return match.group()+' '+('.'.join(map(str,nb)))

rawDescription: "Counting" with multiple regular expressions matches in Python


code:
def isPalindrome(number):
    if str(number) == reverse(number):
        return True
    else:
        return False

rawDescription: Python main function dealing with true and false


code:
array_a1 = np.array([1, 2])
array_a2 = np.array([3, 4])
array_a = np.array([array_a1, array_a2])
array_a
array_b = np.array([[5, 6], [7, 8]])
array_b
f(array_a, array_b)
np.sum(f(array_a, array_b), axis=0)

rawDescription: How to apply function of multiple matrices to each element of a list of matrices with python numpy?

description: Apply function of multiple matrices to each element of a list of matrices with python numpy


code: d = {k: dict(item for item in v if item) for k, v in enumerate(X)}

rawDescription: Converting list of lists of lists into dictionary of dictionaries (Python)


code:
sorted_lists = sorted(izip(a, b, c, d, score), reverse=True, key=lambda x: x[4])
a, b, c, d, score = [[x[i] for x in sorted_lists] for i in range(5)]

rawDescription: sorting multiple lists in python based on sorting of a single list

description: Sorting multiple lists in python based on sorting of a single list


code:
class Bar(Foo,Baz):
    pass

rawDescription: How to get an inheritance tree from AST?

description: Get an inheritance tree from AST


code: ['Lazy', 'Brown', 'Fox'] + ['Jumps', 'Over']

rawDescription: Get the indicies of a dataframe to use on a list


code:
class YourForm(Form):
    your_text_area = TextAreaField("TextArea", default="please add content")

rawDescription: WTForms-How to prepopulate a textarea field?


code:
class A(object):
    def __init__(self):
        self._defaultReportText = "hello world"

    def report(self, text=None):
        if text is None:
            text = self._defaultReportText
        return text

rawDescription: How should data attributes of a class be used as default arguments in methods of the class?


code:
sortx = np.lexsort((np.arange(len(data),0,-1), data[:,-1]))[::-1]
sorted_data = data[ sortx, : ]

order = np.lexsort((np.arange(len(data),0,-1), sorted_data[:,-1]))[::-1]
r = np.arange( len(sorted_data) )
print(order)
# [0 1 2 3 4 5 6 7]
print(r)
# [0 1 2 3 4 5 6 7]
print(np.allclose(order, r))
# True

rawDescription: numpy 1.6.1 argsort() strange behaviour?

description: Numpy 1.6.1 argsort() strange behaviour


code:
functionCall = funcNames("funcname") + "[" + dbRef("arg") + "]"
functionCall.setParseAction(EvalFunction)

rawDescription: Evaluating functions within arithmetic grammar of a DSL


code:
import pandas as pd
import numpy as np
import math

N_DATA = pd.DataFrame({'column_name':[1,2,3]})
N_DATA = pd.concat([N_DATA]*1000).reset_index(drop=True)

rchdcayf=np.exp(-N_DATA['column_name']*0.008)
print (rchdcayf)

rchdcayf1=(-N_DATA['column_name']*0.008).apply(math.exp)
print (rchdcayf1)

rawDescription: how to do math calculation on each number in a specific column in panda

description: Do math calculation on each number in a specific column in panda


code:
import re
st = "\t [[  dwarf ]]]   \n"
re.sub(r"\s*\[|\]\s*", "", st, flags=re.UNICODE).strip()

rawDescription: Add characters to Python unicode strip?

description: Add characters to Python unicode strip


code: df = pd.read_csv('D:/test.csv', header=None)

rawDescription: Split time series to find annual maximum from a data frame in Pandas


code:
import pickle
original_dict = {0: {1: 2}}
original_dict == pickle.loads((pickle.dumps(original_dict)))

rawDescription: Python: How to ensure verify the data using JSON dump/load


code: [''.join(row).strip('0').count('0') for row in matrix]

rawDescription: Find number of characters trapped in a list


code:
from matplotlib.pyplot import plot, title, xlabel, ylabel, savefig, legend
from numpy import array

values = [(3, 4, 5), (5, 8, 9), (2, 3, 5), (3, 5, 6)]
days = array([24, 25, 26, 27])

min_temp, avg_temp, max_temp = zip(*values)
temperature_with_colors_and_labels = (
    (min_temp, 'green', 'min'),
    (avg_temp, 'grey', 'avg'),
    (max_temp, 'orange', 'max'),
)

for temp, color, label in temperature_with_colors_and_labels:
    plot(days, array(temp), color=color, label=label)
title('Temperature at december (last decade)')
xlabel('Days of december')
ylabel('Temperature (Celsius)')
legend()
savefig("temperature_at_christmas.png")

rawDescription: How do I plot a list of tuples with matplotlib?

description: Plot a list of tuples with matplotlib


code:
keys = ('name', 'location', 'value')
[dict(zip(keys, values)) for values in all_values]

rawDescription: Creating an iterable of dictionaries from an iterable of tuples


code:
c.update(listA)
c

rawDescription: Comparing a list to a tuple

description: Comparing a list to a tuple


code:
dic={x:[] for x in "spam"}
[id(x) for x in dic.values()]               #unique objects
dic['s'].append(1)
dic

rawDescription: Strange Output When Iterating Over a Dict of Lists


code:
def __str__(self):
    return "\n".join([" ".join(row) for row in self.map_])

rawDescription: Python: How to return a string with a certain formatting for a nested list


rawDescription: Connect double-click event of QListView with method in PyQt4


code: df_temp = df.apply(lambda x: x.str.split('.').str[:-1].str.join('.'))

rawDescription: How to remove everything after the last occurence of a character in a Dataframe?

description: Remove everything after the last occurence of a character in a Dataframe


code:
from collections import OrderedDict

items = [(1, 3), (4, 7), (2, 4), (6, 10)]
from operator import itemgetter

d = OrderedDict(sorted(items, key=itemgetter(1), reverse=True))
print(d)
OrderedDict([(6, 10), (4, 7), (2, 4), (1, 3)])

rawDescription: storing variables in dictionary and descending order sorting

description: Storing variables in dictionary and descending order sorting


code:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

rawDescription: Two Raspberries communicating each other


code:
from collections import Counter
from itertools import chain

with open("in.txt") as f:
    prev = f.read(1)
    c = Counter()
    for ch in filter(str.isalpha, chain.from_iterable(f)):
        c[prev + ch] += 1
        prev = ch
print(c)

rawDescription: Counting Occurrences of Letter Combinations


code:
hdf5store2 = pd.HDFStore('mydata.h5')
list(hdf5store2.items())
framecopy = hdf5store2['frame']
framecopy
framecopy == frame
hdf5store2.close()

rawDescription: Converting a dataset into an HDF5 dataset


code: exec("getattr(self, settings.field)[attrib_name] = %s" % attrib_value)

rawDescription: Dynamic form requirements in Django

description: Dynamic form requirements in Django


code:
t1 = "\x00\x00\xBF\x13\xDB\x79\xC0\x00" # expected: 2012-10-04 01:00:51.759
import struct
import datetime
GPS_EPOCH = datetime.datetime(1980, 1, 6)
t1_unpacked = struct.unpack('<q', t1)[0]
t1_seconds = t1_unpacked / 52428800
t1_us = int(round((t1_unpacked % 52428800) / 52.428800, 0))
GPS_EPOCH + datetime.timedelta(seconds=t1_seconds, microseconds=t1_us)

rawDescription: Covert binary 64-bit timestamp offset from the GPS epoch to python datetime object


code:
def getOdds(p,q):
    """ returns a string of odd numbers between integers p & q """
    return ", ".join(str(p) for p in getOdds_gen_helper(p, q))

rawDescription: I don't know how to strip the end of this line


rawDescription: Convert triplets to matrix/dataframe in python


code:
def generic_regroup(values, keys):
    groups = dict()
    valkeys = [k for k in values[0] if k not in key]
    for d in values:
        key = tuple(d[k] for k in keys)
        if key in groups:
            group = groups[key]
            for k in valkeys:
                group[k] += d[k]
        else:
            groups[key] = d.copy()
    return list(groups.values())

results = generic_regroup(values, ("prod_name", "prod_hola"))

rawDescription: Python sum dict values based on keys

description: Python sum dict values based on keys


code:
#!/usr/bin/env python
r"""
>>> u"This is a tokenized sentence s\u00f3".split()
[u'This', u'is', u'a', u'tokenized', u'sentence', u's\xf3']
"""
import doctest
import re
import sys

class Py23DocChecker(doctest.OutputChecker):
    def check_output(self, want, got, optionflags):
        if sys.version_info[0] > 2:
            want = re.sub("u'(.*?)'", "'\\1'", want)
            want = re.sub('u"(.*?)"', '"\\1"', want)
        return doctest.OutputChecker.check_output(self, want, got, optionflags)

if __name__ == "__main__":
    import unittest

    suite = doctest.DocTestSuite(sys.modules['__main__'], checker=Py23DocChecker())
    sys.exit(len(unittest.TextTestRunner().run(suite).failures))

rawDescription: Doctest fails due to unicode leading u

description: Doctest fails due to unicode leading u


code:
from collections import OrderedDict

class MyModel(models.Model):
    CHOICES_DICT = OrderedDict((
        (1, 'Choice 1'),
        (2, 'Choice 2'),
    ))
    choicefield = models.IntegerField(choices=CHOICES_DICT.items())
    ...

rawDescription: Get full label name of ChoiceField in QuerySet values list


code:
string = 'abc\r\n\r\n\\\\'
string = string.replace('\r', '')
string = string.replace('\n', '')
string = string.replace('\\', '')

rawDescription: How do you remove \r and \n using re.py?

description: Remove \r and \n using re.py


code:
def my_game():
    should_continue = False
    while should_continue:
        should_continue = update_logic()
        update_graphics()

rawDescription: How do you create a new thread in python?

description: Create a new thread in python


code:
from operator import itemgetter
l.sort(key=itemgetter(1), reverse=True)
l

rawDescription: How to Sort 2 Element Tuple of Strings in Mixed Order Using key Parameter (Not cmp)


rawDescription: How to query MultiIndex index columns values in pandas

description: Query MultiIndex index columns values in pandas


code:
import dis
def g():
    yield 1
    for i in range(10):
            yield i*2

gen = g()
dis.dis(gen.gi_code)
gen.gi_frame.f_lasti ## -1 because we haven't started yet
gen.next()
gen.gi_frame.f_lasti
gen.gi_frame.f_locals
gen.next()
gen.gi_frame.f_lasti , gen.gi_frame.f_locals
gen.next()
gen.gi_frame.f_lasti , gen.gi_frame.f_locals

rawDescription: Why yield returns an iterator?

description: Why yield returns an iterator


code:
import heapq

def flatten(li):
    for el in li:
        try:    # if strings can be in list, would have to check here
            for sub in flatten(el):
                yield sub
        except TypeError:
            yield el

def find(li):
    return tuple(heapq.nsmallest(2, flatten(li))[::-1])

rawDescription: Finding the second smallest int in list of list in Python 3 with recursion


code:
a = np.load('/tmp/model.npz')
a = {key:a[key].item() for key in a}
a['0']['A']

rawDescription: Storing a dict with np.savez gives unexpected result?


code: df[df < 2.0 ].count()

rawDescription: Pandas count number of elements in each column less than x


code:
class C():
   def Bar(self):
       self.a.name()
   ...

rawDescription: Python subclasses calling parent function


code:
pos = len(lines) - 1
while pos >= 0 and len(lines[pos].strip()) == 0:
  pos -= 1
lines = lines[:pos+1]

rawDescription: Deleting blank lines with Python

description: Deleting blank lines with Python


rawDescription: XLRD doesn't seem to be finding my variable inside the file


code: lastNumber = rangeList[-1]

rawDescription: how get last number in range in python

description: How get last number in range in python


rawDescription: Add a column to the end of csv using pandas or in general python


code:
datetime.strptime(solve('1st January 2014'), "%d %B %Y")
datetime.strptime(solve('3rd March 2014'), "%d %B %Y")
datetime.strptime(solve('2nd June 2014'), "%d %B %Y")
datetime.strptime(solve('1st August 2014'), "%d %B %Y")

rawDescription: python format date days that contains st nd ..or th

description: Python format date days that contains st nd ..or th


code:
a = 'python'
b = 'python'
a is b
a = 'python!'
b = 'python!'
a is b

rawDescription: Why and where python interned strings when executing `a = 'python'` while the source code does not show that?


code:
v = (item for item in propadd if item[0]==row1[8] and harversine(custx,custy,item[2],item[3])<1500)
k = (item for item in custadd if item[0]==row1[4])
m = (item for item in numlist if re.search(r"^[0-9]+(?=\s)",row1[0]) is not None and item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group())
for gen in (v, k, m):
    l = list(gen)
    if len(l) == 1:
        row1[1] = l[0][1]
        row1[2] = l[0][2]
        break

rawDescription: Assign variable name to list in if statement python


code:
reobj = re.compile(r"""
    # Match a word that is not: 'BAD'
    \b         # Anchor to start of word.
    (?!BAD\b)  # Verify that this word is not 'BAD'
    \w+        # Ok. Safe to match non-BAD word.
    \b         # Anchor to end of word.
    """, re.VERBOSE)

rawDescription: Python regex: Reject one two-digit number and accept other two-digit numbers


code: '\tdemo with some leading  \t and trailing whitespace\n'.split(' ')

rawDescription: What happens if we split by a delimiter yet have multiple of those delimiters in a row?


code:
with open('random_sorted.csv') as csvfile:
        csv_reader = csv.reader(csvfile, delimiter=';')
        headers = next(csv_reader)
        rows = [row for row in csv_reader]

rawDescription: Selecting rows in cvs file and write them in another csv file


code:
default = object()

def fun(x, y, param1=10, param2=default):
    if param2 is default:
        param2 = param1 / 3
    # do something

rawDescription: Function with dependent preset arguments


code:
trans = """!"#$%&()*+,./:;<=>?@[\]^_`{|}~0123456789"""
d = {k: "" for k in trans}
def delUnknownChar1(s):
    return s.translate(str.maketrans(d)).lstrip("-'").rstrip("-")

rawDescription: Python: Suggestion needed to optimise runtime of filter character method


code: ['localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html']

rawDescription: How to include the toctree in the sidebar of each page

description: Include the toctree in the sidebar of each page


rawDescription: Using Python List Comprehension to match values that exist in a 2d array and simple list


code:
import inspect
inspect.isgeneratorfunction(gen)
inspect.isgeneratorfunction(func)

rawDescription: How python interpret a function as a generator


rawDescription: how to traverse a list in reverse order in python(index style-'in Range' only)

description: Traverse a list in reverse order in python(index style-'in Range' only)


code: G2 = nx.MultiGraph(top)

rawDescription: Getting top n edges in a graph networkx

description: Getting top n edges in a graph networkx


code: path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' + '"'

rawDescription: Adding a simple value to a string

description: Adding a simple value to a string


code:
import pandas as pd
from datetime import datetime

ps = pd.Series([datetime(2014, 1, 7), datetime(2014, 3, 13), datetime(2014, 6, 12)])
new = ps.apply(lambda dt: dt.replace(day=1))

rawDescription: Pandas: Change day

description: Pandas: Change day


rawDescription: wxpython controlling a widget with the id

description: Wxpython controlling a widget with the id


code:
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()

rawDescription: Moving x-axis to the top of a plot in matplotlib


rawDescription: Overlapping boxplots in python

description: Overlapping boxplots in python


code: passwords = dict([(row["service"], row["password"]) for row in cursor])

rawDescription: How to retrieve data using Python and MySQL connector

description: Retrieve data using Python and MySQL connector


rawDescription: Regex finds just once

description: Regex finds just once


rawDescription: Analysing and calculating new values in list of lists in Python3


code: lib.find_vertex(vertices, len(vertices), lower, higher)

rawDescription: A way to pass milions of items in python to C program many times in rapid succesion


code:
sentences = []
sentence = []

for word, code in data:
    if word in '.?!':
        sentences.append(sentence)
        sentence = []
    else:
        sentence.append((word, code))

rawDescription: How to stop a for-loop and make it work further?

description: Stop a for-loop and make it work further


code: yield Request(url, meta={'ftp_user': 'user', 'ftp_password': 'password'})

rawDescription: Using Scrapy to crawl a public FTP server


code:
from PythonCard import model
from PythonCard.event import KeyEvent
import PythonCard.components.textfield

import wx

class KeyPressHookEvent(KeyEvent):
    name = 'keyPressHook'
    binding = wx.EVT_CHAR_HOOK
    id = wx.wxEVT_CHAR_HOOK

# TextFieldEvents is a tuple so type juggling is needed to modify it
PythonCard.components.textfield.TextFieldEvents = tuple(
        list(PythonCard.components.textfield.TextFieldEvents) +
        [KeyPressHookEvent])

rawDescription: PythonCard not getting 'enter' KeyEvent in Windows


code: wave_date = sampling_rate * np.diff(wave_data)

rawDescription: Mapping a numpy array pairwise

description: Mapping a numpy array pairwise


code: df = df.T

rawDescription: How to turn all index rows into columns and all column headers into index

description: Turn all index rows into columns and all column headers into index


code:
for i in range(1,11):
    print ( "Welcome student #", i ,"your ticket is #" , 1000+i)

rawDescription: how to solve this in python (for and while loops)?

description: Solve this in python (for and while loops)


rawDescription: how to create a pivot nested dictionary in python

description: Create a pivot nested dictionary in python


code:
message = escape(message)
message = str(message).replace('\r\n','
').replace('\n','
')

rawDescription: How to turn a Flask Markup string into a normal string

description: Turn a Flask Markup string into a normal string


code:
response.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.response.out.write(output)

rawDescription: Jquery ajax with google app engine post method


code:
Math.log [s.abs, 1].max, 10
Math.log10 [s.abs, 1].max  # or use Math.log10 and skip passing the base

rawDescription: How do i rewrite these math python functions in ruby?

description: Rewrite these math python functions in ruby


code:
h0 = 1.1, 1, 0, 5000, 100, .5
h, hcov = curve_fit(rot_hyperbola, x, y, h0)
plt.plot(x, y, 'o', x, two_lines(x, *pw), '-', x, rot_hyperbola(x, *h), '-')
plt.legend(['data', 'piecewise linear', 'rotated hyperbola'], loc='upper left')
plt.show()

rawDescription: Fit a curve for data made up of two distinct regimes


rawDescription: NumPy: array assignment issue when using custom dtype


code:
import mmap

shm = mmap.mmap(0, 512, "Local\\Test") #You should "open" the memory map file instead of attempting to create it..
if shm:
    shm.write(bytes("5", 'UTF-8'));
    shm.write(bytes("Hello", 'UTF-8'))
    print("GOOD")

rawDescription: IPC Between Python and Win32 on Windows OS


code: red

rawDescription: OpenCV: setting all pixels of specific BGR value to another BGR value


rawDescription: set very low values to zero in numpy

description: Set very low values to zero in numpy


code:
# print 1000 random numbers
for i in range(1000):
    num = random.randint(0, 1000)
    print(num)

rawDescription: how to loop random.randint(0, 1000) to print all resuts at once line by line?

description: Loop random.randint(0, 1000) to print all resuts at once line by line


code:
from sqlalchemy.engine.default import DefaultDialect
from sqlalchemy.sql.sqltypes import String, DateTime, NullType

# python2/3 compatible.
PY3 = str is not bytes
text = str if PY3 else unicode
int_type = int if PY3 else (int, long)
str_type = str if PY3 else (str, unicode)

class StringLiteral(String):
    """Teach SA how to literalize various things."""
    def literal_processor(self, dialect):
        super_processor = super(StringLiteral, self).literal_processor(dialect)

        def process(value):
            if isinstance(value, int_type):
                return text(value)
            if not isinstance(value, str_type):
                value = text(value)
            result = super_processor(value)
            if isinstance(result, bytes):
                result = result.decode(dialect.encoding)
            return result
        return process

class LiteralDialect(DefaultDialect):
    colspecs = {
        # prevent various encoding explosions
        String: StringLiteral,
        # teach SA about how to literalize a datetime
        DateTime: StringLiteral,
        # don't format py2 long integers to NULL
        NullType: StringLiteral,
    }

def literalquery(statement):
    """NOTE: This is entirely insecure. DO NOT execute the resulting strings."""
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        statement = statement.statement
    return statement.compile(
        dialect=LiteralDialect(),
        compile_kwargs={'literal_binds': True},
    ).string

rawDescription: SQLAlchemy: print the actual query

description: SQLAlchemy: print the actual query


code:
dt = datetime.datetime.now()
dt
dt.date()

rawDescription: django convert .values_list('datetimefield') to date

description: Django convert .values_list('datetimefield') to date


code:
from collections import Counter
mystr = "AaAaaEeEiOoouuu"
a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
"the most frequent vowel is {} occurring {} times".format(a.upper(), b)

rawDescription: Count specific vowels in a sentence

description: Count specific vowels in a sentence


code:
def GetSteamAccts():
    Steamapp_Folders = [f for f in ("C:\\Program Files (x86)\\Steam\\steamapps\\",
                                    "C:\\Program Files\\Steam\\steamapps\\")
                          if os.path.isdir(f)]
    return [os.path.join(root, folder)
                    for root in Steamapp_Folders
                    for folder in os.listdir(root)
                    if os.path.isdir( os.path.join(root, folder)) ]

rawDescription: Cleaning up nested for loops in python

description: Cleaning up nested for loops in python


code:
bits = bitarray()
for i in pixels: bits.extend("{0:08b}".format(i))

rawDescription: python how to transfer between a list of integers and string of bits?

description: Python how to transfer between a list of integers and string of bits


rawDescription: Pandas cvs find date between startdate to enddate


code:
stats['health'] = stats['health'] + 1
stats['armor'] = 10

rawDescription: My game relies heavily on globals, but also gives me syntaxwarning even though the game won't work without them


code: plot(x, smoothed)

rawDescription: Smooth circular data

description: Smooth circular data


code:
from Bio import Seq
import regex as re
startP = re.compile('ATG')
nuc = input_seq.replace('\n','')
longest = (0,)
for m in startP.finditer(nuc, overlapped=True):
    if len(Seq.Seq(nuc)[m.start():].translate(to_stop=True)) > longest[0]:
        pro = Seq.Seq(nuc)[m.start():].translate(to_stop=True)
        longest = (len(pro),
                   m.start(),
                   str(pro),
                   nuc[m.start():m.start()+len(pro)*3+3])

rawDescription: Python find longest ORF in DNA sequence

description: Python find longest ORF in DNA sequence


code: lines = [['Column1', 'Column2', 'Column3', 'Column4'], ['Value1', 'Value2', 'Value3', 'Value4'], ['Value5', 'Value6', 'Value7', 'Value8']]

rawDescription: Adding a Newline Character at the End of a Line in a Column


code:
div = int(data.shape[0])
row_len_squared = int(data.shape[1]**2)

firstPossibleSumsArray = np.empty( int((div*(div-1))/2 * row_len_squared), dtype=int )

idx = 0
for row in range(div):
    for col in range(row+1,div):
        firstPossibleSumsArray[idx:idx+row_len_squared] = \
            (data[row,:,np.newaxis] + data[col]).flatten()
        idx += row_len_squared
#reapeat process for second possible sums array by replacing the range
#in the first loop from range(div) to range(div,2*div)

rawDescription: How to get list of all possible sums of n*m matrix rows

description: Get list of all possible sums of n*m matrix rows


code:
import requests
import json

jsonResponse = requests.get("https://www.kaggle.com/knockout/profiles/54836/results")
data = json.loads(jsonResponse.text)
print(data)

for eachData in data:
    print("competition name:", eachData["competition"]["title"])
    print("Rank:", eachData["rank"])
    print("competitors count:", eachData["teamCount"])

rawDescription: Python: Getting data from databound using BeatifulSoup


code:
totals = {}

for row in csv.reader(open('data.csv')):
  if row[3] == 'Sales':
    key = (row[2], row[1][:2], row[0])
    totals[key] = totals.setdefault(key, 0) + float(row[4])

rawDescription: How to aggregate column values from a CSV file in Python

description: Aggregate column values from a CSV file in Python


code: x = EqM_list(d.iterkeys())

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


code:
class B():
    def __init__(self):
        print("The awful B class!!!")

    def get_name(self):
        print("The awful B.get_name() method!!!")

class A():
    def __init__(self):
        self.b = B()

    def is_authorized(self):
        name = self.b.get_name()
        if name == 'admin':
            return True
        else:
            return False

rawDescription: How do I mock a class in a Python unit test?

description: Mock a class in a Python unit test


code:
import re
text = """\
part 1

Continue reading the main story

part 2

Continue reading the main story

part 3

Continue reading the main story

Continue reading the main story

part 4
"""

parts = re.split('Continue reading the main story', text)
print(parts)
# Ignore first and last part, test for and ignore
# empty (all whitespace) strings
innerparts = [part for part in parts[1:-1] if part.strip()]
print("".join(innerparts))

rawDescription: python regex keep lines between first and last term

description: Python regex keep lines between first and last term


code:
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
import sys

x, y, k, a = symbols('x y k a')

z2 = x**2*(k*a**1) + (k**1)*x**2 - k*a**8 + y*x*(k**2) + y*(x**2)*k**3 + x*k*a - k*a**3 + y*a**1

zc = collect(z2, a, evaluate=False)
zmod2 = Mul(zc[a], a)

rawDescription: Collecting like term of an expression in Sympy


rawDescription: find all matching words in string from URL

description: Find all matching words in string from URL


code:
from sklearn.naive_bayes import BernoulliNB
import numpy as np

nSamples = 2000
nFeatures =  30000
X = np.random.randint(2, size=(nSamples,nFeatures))
X.nbytes / 10 ** 6
Out[11]: 480.0

rawDescription: Practical limits to data size for sklearn.naive_bayes.BernoulliNB


code: ln -s /package/dir/path /project/dir/path

rawDescription: Append single package folder to sys.path


rawDescription: Elegant pythonic cumsum

description: Elegant pythonic cumsum


rawDescription: Output data from all columns in a dataframe in pandas


code: line = ax.plot(x, y)[0]

rawDescription: How do I target a list element of a MatPlotLib object that "returns a list"?

description: Target a list element of a MatPlotLib object that "returns a list"


rawDescription: how to use Pi3d to draw an array

description: Use Pi3d to draw an array


rawDescription: Index pandas series entries with integers


code:
Ac=A.tocoo()
Ac.data
Ac.row
Ac.col

rawDescription: Convert triplets to matrix/dataframe in python


code:
renormed = scipy.stats.zscore(data)
renormed.mean(), renormed.std()

rawDescription: How should the values of a list be scaled such that they meet standard deviation and mean requirements?


code:
df_container = []
for customer_id, group in grouped_data:
    group['days_since'] = (group['date'] - group['date'].shift().fillna(pd.datetime(2000,1,1))).astype('timedelta64[D]')
    df_container.append(group)

data_df = pd.concat(df_container)

rawDescription: PANDAS: merging calculated data in groupby dataframe into main dataframe


code:
#List comprehension:
pieces = [float(i) for i in pieces]

rawDescription: Map serial port data into integer

description: Map serial port data into integer


code: print(" ")

rawDescription: Python 3: Print multiple lines to one line


code:
y = numpy.roll(x, 1)
y[0] = 0

rawDescription: Shift all indices in NumPy array

description: Shift all indices in NumPy array


code:
def codeinfo():
    import sys
    f = sys._getframe(1)

    filename = f.f_code.co_filename
    classname = ''

    if 'self' in f.f_locals:
        classname = f.f_locals['self'].__class__.__name__

    funcname = f.f_code.co_name

    return "filename: %s\nclass: %s\nfunc: %s" % (filename, classname, funcname)

rawDescription: Python - get static information

description: Python - get static information


code: pd.DataFrame( np.hstack( [arr,-1*arr] ) )

rawDescription: How to return all opposite pairs in a Pandas DataFrame?

description: Return all opposite pairs in a Pandas DataFrame


code:
hdr = {'Accept': 'text/html,application/xhtml+xml,*/*'}
url = 'http://www.carnextdoor.com.au/'
req=urllib2.Request(url,headers=hdr)
html = urllib2.urlopen(req).read()

rawDescription: HTTP Error 403: Forbidden urlib2 Python 2.7


code:
dis(clsmaker.__call__)
act = maker(3)
dis(act)

rawDescription: python factory functions compared to class

description: Python factory functions compared to class


code: if df.empty: return df

rawDescription: How can I reduce the duplicated use of if and else

description: Reduce the duplicated use of if and else


code: df[df.columns - ["T1_V6"]]

rawDescription: Select everything but a list of columns from pandas dataframe


rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code:
print('private' in dir(a))
# False

rawDescription: Data Hiding in Python Class

description: Data Hiding in Python Class


code:
def simulation(rn_provider):
    sum = 0
    for i in range(10):
        sum += rn_provider()
    return sum / 10

rng1 = random.Random(0)
sum1 = simulation(rng1.random)
rng2 = random.Random(0)
sum2 = simulation(rng2.random)
print(sum1 == sum2)

rawDescription: Why do I get different results with same random seed, same computer, same program


code:
processList = [subprocess.Popen('ls') for i in range(1)]
processList

rawDescription: Use poll() on new subprocess.Popen object list


code:
def score_ngram(self, score_fn, w1, w2):
    """Returns the score for a given bigram using the given scoring
    function.  Following Church and Hanks (1990), counts are scaled by
    a factor of 1/(window_size - 1).
    """
    n_all = self.word_fd.N()
    n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0)
    if not n_ii:
        return
    n_ix = self.word_fd[w1]
    n_xi = self.word_fd[w2]
    return score_fn(n_ii, (n_ix, n_xi), n_all)

rawDescription: What is the total bigram count returned for NLTK BigramCollocationFinder?