code:
from itertools import groupby, count
from operator import itemgetter

def _sub(item):
    a, b = item
    return a - b

def consecutive(iterable, step):
    for _, g in groupby(zip(count(step=step), iterable), _sub):
        yield map(itemgetter(1), g)

a = [1, 2, 3, 5, 55, 56]

print(list(consecutive(a, 2)))

rawDescription: Finding Deltas - Difference between elements in a Python list


code:
def error(self, message):
    raise ParsingError(message)

rawDescription: Is there a way I can use mock() (or similar) to mock the date & time for a script I *invoke* from a unit test?


code:
events_table_num = 'user_events_0'
bq.Query(test2,events_table_num = events_table_num).sample()

rawDescription: Passing parameters for TABLE_QUERY in Google Cloud Datalab iPython notebook


code:
def mptt_stack(tree, node):
    if node not in tree: return
    preorder = deque()

    stack = []
    for child in reversed(tree[node]):
        stack.append([child, True])

    while stack:
        (node, first) = stack.pop()
        preorder.append(node)
        if first:
            stack.append([node, False])
            if node in tree:
                for child in reversed(tree[node]):
                    stack.append([child, True])

    return preorder

rawDescription: Stack based modified preorder tree traversal


code: attributes = re.findall('(?:@)([^\( ]*)', query)

rawDescription: Regex for finding valid sphinx fields

description: Regex for finding valid sphinx fields


code:
#!/usr/bin/env python
import subprocess
from operator import itemgetter

ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = [p for p in ps.split('\n') if p]
split_processes = [p.split() for p in processes]

rawDescription: Python sort string array with subtring

description: Python sort string array with subtring


code:
def f(n):
    if n == 0:
        return [""]
    return [a + b for a in "RL" for b in f(n-1)]

print(f(3))

rawDescription: How to decrease running time of this particular solution?

description: Decrease running time of this particular solution


code:
import pygame
from pygame.locals import *

pygame.init()
display = pygame.display.set_mode((320, 240))

background = pygame.image.load("leaves.png").convert_alpha()
mask = pygame.image.load("mask-fuzzy.png").convert_alpha()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # draw
    display.fill(Color(255, 0, 255))
    masked = background.copy()
    masked.blit(mask, (0, 0), None, pygame.BLEND_RGBA_MULT)
    display.blit(masked, (0, 0))
    pygame.display.flip()

rawDescription: Pygame - is there any way to only blit or update in a mask


code: [sub[:2] + [elem] for sub in yourlist for elem in sub[2:]]

rawDescription: how to join element in list by index?

description: Join element in list by index


code:
class LazyDict(dict):
    def __init__(self, *args, **kwargs):
        super(LazyDict, self).__init__(*args, **kwargs)
        # init a set which will keep the already loaded keys
        self._loaded = set()

    def __getitem__(self, item):
        if item in self and item not in self._loaded:
            # do the "lazy" action
            self[item] = some_function(item)
            self._loaded.add(item)
        # return the value
        return super(LazyDict, self).__getitem__(self, item)

rawDescription: Descriptor behavior when accessing a dict's key


code:
class MetaClass:
    def __init__(cls, name, bases, dictionary):
        if name is not 'Parent':
            print('Subclass created with name: %s' % name)
        super().__init__(name, bases, dictionary)

class Parent(metaclass=MetaClass):
    pass

class Subclass(Parent):
    pass

rawDescription: Is there a way to make code run when a class is derived from a particular parent class in Python?


rawDescription: How to install Python module without setup.py?

description: Install Python module without setup.py


rawDescription: How to get current date and time from GPS unsegment time in python

description: Get current date and time from GPS unsegment time in python


code: g.apply(lambda x: x.index.max() - x.index.min())

rawDescription: Calculating date_range over GroupBy object in pandas


rawDescription: Python's append() only allows unique items in a list?


code:
import dis
def unpack_or_index(t=(0, 1)):
    _, x = t
    x = t[1]

dis.dis(unpack_or_index)

rawDescription: How come unpacking is faster than accessing by index?


rawDescription: Numpy - slicing 2d row or column vector from array


code:
ob1 = A()
ob2 = A()
ob1.var += 2
ob2.var

rawDescription: How to use a variable within a class that will be independent of any objects created in python?

description: Use a variable within a class that will be independent of any objects created in python


code:
with open(filename, 'rb') as fd:
    contents = fd.read()

rawDescription: How to convert a wav file -> bytes-like object?

description: Convert a wav file -> bytes-like object


code:
import numpy as _num
_num.version.version
_num.version.version.split('.')[:2]
majver, minver = [float(i) for i in _num.version.version.split('.')[:2]]
i

rawDescription: What is `scipy.i`?

description: What is `scipy.i`


code: 'salad: 1 hamburger: 2 water: 2'

rawDescription: how to omit parenthesis in return from a python def

description: Omit parenthesis in return from a python def


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim([0,5])
plt.ylim([0,5])
plt.plot([0,1,2,3,4,5])
locs, labels = plt.xticks()
labels = [float(item)*5 for item in locs]
plt.xticks(locs, labels)
plt.show()

rawDescription: Changing axis without changing data (Python)


code:
ax1.get_xlim()
ax2.get_xlim()

rawDescription: matplotlib - Second X axis has an offset (wrt 1st X axis) I can't pin down

description: Matplotlib - Second X axis has an offset (wrt 1st X axis) I can't pin down


code:
z = zip(x,y)
np.cov(z)

rawDescription: numpy covariance matrix

description: Numpy covariance matrix


rawDescription: PyQt: Activate QListWidget Item

description: PyQt: Activate QListWidget Item


rawDescription: How to split one list in a list of x list with python?

description: Split one list in a list of x list with python


code:
def add_poi(self, lat, lon):
    self.append(PoiData(lat, lon))

rawDescription: Python | How to create complex dictionary


code: self.skills[:] = (s for s in self.skills if s.id != skill_to_remove.id)

rawDescription: Python. How to efficiently remove custom object from array


code:
bulletGroup = [i for i in bulletGroup if i.buly < screen.get_height()]
for shot in bulletGroup:
    shot.buly += 3

rawDescription: Python. How to remove an object from list


code: L2 = line.strip().split('|')

rawDescription: removing mysterious line break python

description: Removing mysterious line break python


code:
# Create empty dataframe to fill with parsed values
new_bed = pd.DataFrame(data=np.zeros((0,len(columns))),columns=columns,dtype=int)

def bed_collapse(intermediate_bed, new_bed,columns=columns):
    ''' Takes a pandas dataframe bed file with overlap information and returns
    genomic regions without overlaps '''
    output_row = []
    for row in bed.itertuples():
        output = {}
        if row[7] == False and row[10] == False:
            # If row doesn't overlap next row, insert into new dataframe unchanged.
            output_row = list(row[1:5])
        elif row[7] == True and row[10] == False:
            # Only next region overlaps; take the chromosome and start coordinate
            output_row = list(row[1:3])
        elif row[7] == True and row[10] == True:
            # Next and previous regions overlap. Skip row.
            pass
        elif row[7] == False and row[10]  == True:
            # Only previous region overlaps; append stop coordinate and geneID to output_row variable
            output_row.append(row[3])
            output_row.append(row[4])
        if row[7] == False:
            #Zip columns and output_row values together to form a dict for appending
            for k, v in zip(columns,output_row): output[k] = v
            #print output
            new_bed = new_bed.append(output,ignore_index=True)
    output_bed = new_bed
    return output_bed

rawDescription: Comparing row values in pandas dataframe


code:
if __name__ == '__main__':
    ge_client = gevent.spawn(clientWorker, sys.argv[1] + "_node2python")
    zpc = zerorpc.Server(messagesOut)
    zpc.bind(sys.argv[1] + "_python2node")
    ge_server = gevent.spawn(zpc.run)
    gevent.joinall([ge_client, ge_server]) # up and running here.

rawDescription: Bidirectional ZeroRPC in Python client invoke causes AssertionError


code:
obj_list = sorted(
    chain(latest_news, videos, audio),
    key=get_ordering, # intermediate lambda is not needed here
    reverse=True
)

rawDescription: Combining & ordering querysets

description: Combining & ordering querysets


code:
import numpy as np
def h2(df, p):
    inrad = df.applymap(radians)
    dlon = inrad.longitude-inrad.longitude[p]
    dlat = inrad.latitude-inrad.latitude[p]
    lat1 = pd.Series(index = df.index, data = [df.latitude[p] for i in range(len(df.index))])
    a = np.sin(dlat/2)*np.sin(dlat/2) + np.cos(df.latitude) * np.cos(lat1) * np.sin(dlon/2)**2
    c = 2 * 1/np.sin(np.sqrt(a))
    km = 6367 * c
    return km

df = df.set_index('Provider ID')
df = df.astype(float)
df2 = pd.DataFrame(index = df.index, columns = df.index)
for c in df2.columns:
    df2[c] = h2(df, c)

print (df2)

rawDescription: Vectorizing a function in pandas

description: Vectorizing a function in pandas


code:
def add_optimal_edge(graph, rank, n=1): # you don't need to pass in the rank function necessarily
    ...

rawDescription: lookahead algorithm in Python

description: Lookahead algorithm in Python


rawDescription: How to sharex when using subplot2grid

description: Sharex when using subplot2grid


code:
from numpy import array,int64
import numpy as np
import time

time1 = []
time2 = []

nelements = np.logspace(1,7)

for i in nelements:
    arr = np.random.randint(0,i, i)

    start = time.time()
    first_occurences_mask = np.concatenate([[1], np.diff(arr)], axis=0) > 0
    stop = time.time()
    time1.append(stop-start)

    start = time.time()
    np.unique(arr,return_index=True)
    stop = time.time()
    time2.append(stop-start)

rawDescription: Fast way to keep one occurancy per element with numpy array and tuple


code:
print (path)

while Gtk.events_pending ():
  Gtk.main_iteration ()

print ("done")

rawDescription: How to hide a Gtk+ FileChooserDialog in Python 3.4?

description: Hide a Gtk+ FileChooserDialog in Python 3.4


code:
for line in new_listes(poem_lines):
    i = 0
    for word in line.split():
        for sylables in word_to_phonemes[word]:
            i += sum(number_count(char) for char in sylables)
    yield i

rawDescription: Counting Syllables In String

description: Counting Syllables In String


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

L, H = np.pi*np.mgrid[-1:1:100j, -1:1:100j]
T = np.cos(L)*np.cos(2*H)
H = np.cos(L) + H

plt.contourf(L, H, T, cmap="hot")
plt.show()

rawDescription: Contouring non-uniform 2d data in python/matplotlib above terrain


code: sorted(d, key=lambda x: score(x[1]))

rawDescription: Python: Sorting list containing tuples

description: Python: Sorting list containing tuples


code:
from sys import exit
exit(15)

rawDescription: Call Python From Bat File And Get Return Code


code: myData = [doc['myoutput']['Result']['CrossData'] for doc in db.collection.find({'myoutput.Status.Success':'true'}, {_id:0, myoutput:1})]

rawDescription: project nested columns in mongodb

description: Project nested columns in mongodb


code:
s1 = s.decode('unicode-escape')
s1

rawDescription: python 3, unicode conversion, two \u0000 as one character

description: Python 3, unicode conversion, two \u0000 as one character


code: output = { i : [ r for r in ref if re.match(r, i) ] for i in input }

rawDescription: Match two Python lists with regular expressions, and create dictionary output


code: [ d for d in dict_list if d["START"] == "Virginia" and d["END"] == "Boston" ]

rawDescription: Python: How to access the dictionary that has specific key-values in a list


rawDescription: Storing a large dictionary with non-unique key-value pairs


rawDescription: A more optimized code in recursion exercise


code:
def get_value(message, min_value, max_value):
    while True:
        value = int(input(message))
        if min_value <= value <= max_value:
            return value
        else:
            print("Invalid, enter a value from {} to {}".format(min_value, max_value))

#later, in `main` after getting the seating section
prompt = "Enter the amount of tickets sold: "

if section == "A":
    getSectionA(get_value(prompt, 0, 300))
if section == "B":
    getSectionB(get_value(prompt, 0, 500))
if section == "C":
    getSectionC(get_value(prompt, 0, 200))

rawDescription: Values aren't stored in python program

description: Values aren't stored in python program


code:
func()  # prints {'baz': 2, 'foo': 0, 'bar': 1}
func(foo=2)  # prints {'baz': 2, 'foo': 2, 'bar': 1}

params = {'bar':1000, 'hello':'world'}
func(**params)  # prints {'baz': 2, 'foo': 0, 'bar': 1000, 'hello': 'world'}

rawDescription: Dynamically define functions with varying signature


code: df1.apply(lambda x: pd.Series(1, pd.date_range(x.loc['Start'], x.loc['End'] - pd.offsets.Day(1), freq='D')).resample('M', how='sum'), axis=1).fillna(0)

rawDescription: Sum of days in intervals

description: Sum of days in intervals


code: python -u myprogram.py

rawDescription: Python script cannot read Popen output until process is finished (on Windows)


rawDescription: Why evaluating boolean objects takes time in python


code:
def map2(f, seq):
    it = imap(f, seq)
    if isinstance(seq, (tuple, list)):
        return type(seq)(it)
    else:
        return it

rawDescription: `map`-like function preserving sequence-type


code:
cov(x,x)#defaulting to ddof=1
x.var(ddof=1)
cov(x,x,ddof=0)
x.var()#defaulting to ddof=0

rawDescription: Why do numpy cov diagonal elements and var functions have different values?


code:
import codecs

X = []
with codecs.open('myfile.asc', encoding='utf-8-sig') as f:
    for line in f:
        s = line.split()
        X.append([float(s[i]) for i in range(len(s))])

rawDescription: read an ascii file into a numpy array

description: Read an ascii file into a numpy array


code:
def f_helper(args):
    f(*args)

rawDescription: Can I run multiple Ipython qt console in the same time?

description: Run multiple Ipython qt console in the same time


code:
target_dir = None
def SECdownload(year, month):
    import os
    from urllib.request import urlopen
    root = None
    feedFile = None
    feedData = None
    good_read = False
    itemIndex = 0
    edgarFilingsFeed = 'http://www.sec.gov/Archives/edgar/monthly/xbrlrss-' + str(year) + '-' + str(month).zfill(2) + '.xml'
    print(edgarFilingsFeed)
    #print( edgarFilingsFeed ) #from the slides
    if not os.path.exists( "sec/" + str(year) ):
        os.makedirs( "sec/" + str(year) )
    if not os.path.exists( "sec/" + str(year) + '/' + str(month).zfill(2) ):
        os.makedirs( "sec/" + str(year) + '/' + str(month).zfill(2) )
    global target_dir
    target_dir = "sec/" + str(year) + '/' + str(month).zfill(2) + '/'
    try:
        feedFile = urlopen( edgarFilingsFeed ) # urlopen will not work (python 3) needs from urllib.request import urlopen
        try:
            feedData = feedFile.read()
            good_read = True
        finally:
            feedFile.close()
    except HTTPError as e:
        print( "HTTP Error:", e.code )

rawDescription: Python GUI cannot see global variable

description: Python GUI cannot see global variable


code:
answer = []
for x, y in zip(list1, list2):
    if x == y:
        answer.append(x)

rawDescription: Count occurrences of number in two lists and return one list


code:
def ttest_1samp(a, popmean, axis=0):
    """
    ... doc string ...
    """
    a, axis = _chk_asarray(a, axis)
    n = a.shape[axis]
    df = n - 1

    d = np.mean(a, axis) - popmean
    v = np.var(a, axis, ddof=1)
    denom = np.sqrt(v / float(n))

    t = np.divide(d, denom)
    t, prob = _ttest_finish(df, t)

    return t,prob

def _ttest_finish(df,t):
    """Common code between all 3 t-test functions."""
    prob = distributions.t.sf(np.abs(t), df) * 2  # use np.abs to get upper tail
    if t.ndim == 0:
        t = t[()]

    return t, prob

rawDescription: How the ttest is calculated in numpy

description: How the ttest is calculated in numpy


code:
df1 = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD'))

df2 = df1.ix[4:8]
df2.reset_index(drop=True,inplace=True)
df2.loc[-1] = [2, 3, 4, 5]
df2.loc[-2] = [14, 15, 16, 17]
df2.reset_index(drop=True,inplace=True)

df3=pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], right_index=True, how='inner')

rawDescription: delete a part of pd.DataFrame with Python

description: Delete a part of pd.DataFrame with Python


code:
def match_all(the_list, to_match):
    matches = set(to_match).issubset
    return [sublist for sublist in the_list if matches(sublist)]

rawDescription: Efficient Matching of Sublists In Python


code: sorted(some_list, key = lambda x:x[1])

rawDescription: python nested list on second item

description: Python nested list on second item


code: print (datetime.datetime.now() + datetime.timedelta(weeks=4)).strftime('%a, %d %b %Y %H:%M:%S GMT')

rawDescription: How to set cookies with GAE/Python for 1 month?

description: Set cookies with GAE/Python for 1 month


code: stra = ' '.join(Lista).rstrip(',')

rawDescription: Python 2 string operation on a list

description: Python 2 string operation on a list


code:
datafile = [line.strip() for line in open('testfile')]
datafile = [line.split('\t') for line in datafile if line]
datalist = list(zip(*datafile))
result = []
for index in datalist:
    for i in index:
        result.append([int(string) for string in i.split(',')])
# you can access the result list by indexing:
print(result[:2], result[2:])
# or assign to new lists:
firstlist, secondlist = result[:2], result[2:]
print(firstlist, secondlist)

rawDescription: return a list of lists from a text file

description: Return a list of lists from a text file


code:
team_removed_runs = {}
for team, scores in league.iteritems():
    team_removed_runs[team] = [total_runs_scored - scores[0],
                               total_runs_allowed - scores[1]]

rawDescription: Subtracting by Dictionary Values from Iterated Total in For Loop Python


code:
import random

m = 2
n = random.randint(0 + m, 10 + m)
b = [random.randint(0, 12) for _ in range(n)]
print(b)

def MaxPairwiseProductFast(a):
    max_index1 = -1
    for i in range(0,n):
        if (max_index1 == -1) or (a[i] > a[max_index1]):
            max_index1 = i

    max_index2 = -1
    for j in range(0,n):
        if (j != max_index1) and ((max_index2 == -1) or (a[j] > a[max_index2])):
            max_index2 = j

    resutl = a[max_index1]*a[max_index2]

    print(resutl)

MaxPairwiseProductFast(b)

rawDescription: Multiplication of two biggest elements of the array on Python


rawDescription: More pythonic way to change multilevel dictionary values


code:
myRenderView.ViewSize = [1984, 1962]
SaveScreenshot('image.png', magnification=1, quality=100, view=myRenderView)

rawDescription: In Python script for Paraview, can I specify the resolution when I do a SaveScreenshot()?


code: for a, b, c in zip(*[iter(seq)]*3): pass

rawDescription: Split list in tuples of three

description: Split list in tuples of three


code:
import testa
testa.var = "test"

rawDescription: How to set dynamic global variables in Python?

description: Set dynamic global variables in Python


code: print(dt.strftime("%d-%b-%Y %H:%m:%S"))

rawDescription: How can this datetime variable be converted to the string equivalent of this format in python?


code:
j = 3
drange = []
for i in xrange(j):
    drange.extend([i]*2)

drange

rawDescription: How can I repeat elements in place in an array in Python?

description: Repeat elements in place in an array in Python


code:
import functools
process_CS = functools.partial(process, ClientScript, BP_ClientScript)

rawDescription: Generic python module

description: Generic python module


code:
class One:
    @staticmethod
    def get():
        return 1

class Two:
    def __init__(self):
        val = One.get()

rawDescription: Python: How to call a class in the same file


code: sorted(yourcounter, key=lambda i: yourcounter[i])

rawDescription: Put counter into a frequency ordered list


code:
test_str = "...foo" + ''.join(accents) + "...bar"
test_str
pattern.findall(test_str)
len(_)

rawDescription: Insert a space between a non-alphanumeric and alphanumeric char except specific char (Python)


code:
@app.route('/search')
def search():
    query = request.args('search')

rawDescription: Flask: how to implement a general searchbar for every view, without rewriting it?


rawDescription: Using Selenium to select an anchor with specific content


rawDescription: Calculate euclidean distance with numpy

description: Calculate euclidean distance with numpy


rawDescription: Python and numpy - removing rows from a corresponding matrix


code: test_tube[liquid] = test_tube.get(liquid, 0) + milliliters

rawDescription: memorize a value of a dictionary

description: Memorize a value of a dictionary


code:
import struct
import binascii
struct.pack('i', 123)  # Replace 123 with `file_1_size_bytes`
binascii.hexlify(struct.pack('i', 123))

rawDescription: Hexlify an integer in Python

description: Hexlify an integer in Python


code:
def my_view(request):
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST)
        if formset.is_valid():
            for author in formset.save(commit=False):
                author.user = request.user
                author.save()
            formset.save_m2m() # if your model has many to many relationships you need to call this

rawDescription: Passing instance/default value to a ModelFormSet for the empty forms to use, in a view


code:
out = 0
for bit in bitlist:
    out = (out << 1) | bit

rawDescription: Bits list to integer in Python

description: Bits list to integer in Python


code:
import pandas as pd
class MyDict(dict):
    def __str__(self):
        return str(pd.Series(self))

dct = {'cheese':'stilton', 'swallow':'african', 'ride':'coconuts'}
mydct = MyDict(dct)
print(mydct)

rawDescription: How to print dict as a pandas.Series

description: Print dict as a pandas.Series


rawDescription: Modifying List elements in a loop

description: Modifying List elements in a loop


code: df.prices.apply(lambda x: isinstance(x, float))

rawDescription: How to create a new derived column in a pandas dataframe new column using only notnull vaues

description: Create a new derived column in a pandas dataframe new column using only notnull vaues


code:
class Album(models.Model):
    category = models.ForeignKey(Category, related_name='albums')

rawDescription: How to use a ForeignKey field as filter in Django?

description: Use a ForeignKey field as filter in Django


code:
def unq_searchsorted_v1(A,B):
    out1 = (np.searchsorted(B,A,'right') - np.searchsorted(B,A,'left'))==1
    out2 = (np.searchsorted(A,B,'right') - np.searchsorted(A,B,'left'))==1
    return out1,out2

rawDescription: Find indices of common values in two arrays


code:
import subprocess
with open('CONTENT','w') as f1:
    p = subprocess.Popen("sort CONTENT1 | uniq", shell=True,
                         stdout=f1)

rawDescription: Redirecting Output of PIPE to a FILE in python


rawDescription: How can I vectorize the averaging of 2x2 sub-arrays of numpy array?

description: Vectorize the averaging of 2x2 sub-arrays of numpy array


code:
from setuptools import setup, Distribution

class BinaryDistribution(Distribution):
    def is_pure(self):
        return False

setup(
    name='md5',
    version='1.0',
    description='MD5 Library',
    packages=['md5'],
    package_data={
        'md5': ['libeay32.dll'],
    },
    distclass=BinaryDistribution
)

rawDescription: How can I make a Python Wheel from an existing native library?

description: Make a Python Wheel from an existing native library


code:
year, week, dow = datetime.today().isocalendar()
result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]
result
year, week, dow = datetime.today().isocalendar()
week = week + 1
result = [datetime.strptime(str(year) + "-" + str(week-1) + "-" + str(x), "%Y-%W-%w").day for x in range(1,7)]
result

rawDescription: Days/dates in a given week

description: Days/dates in a given week


code:
re.sub( 'src=\"(.+)\"', 'src="{{ \'\\1\' | asset_url }}"', test, flags=re.MULTILINE )
print(re.sub( 'src=\"(.+)\"', 'src="{{ \'\\1\' | asset_url }}"', test, flags=re.MULTILINE ))

rawDescription: Replacing html script element sources with regular expression in Python


code: CONFIG += c++11

rawDescription: Qt and parsing JSON data in C++

description: Qt and parsing JSON data in C++


code:
english = ['Program', 'Menu']
spanish = ['Programa', 'Menú']

def change_language_2(lang):
    root.title(lang[0])
    menuButton.config(text=lang[1])

rawDescription: Python Tk app - Allow for multiple languages


code: return flask.jsonify(**d)

rawDescription: How to create a json tree structure from SQLalchemy model

description: Create a json tree structure from SQLalchemy model


code: df['tmp'] = df.apply(lambda x: x.Question if x.Code == 30 else np.nan, axis=1).fillna(method='ffill')

rawDescription: Split Dataframe into multiple dataframes after a specific value


code: content = models.ManyToManyField('Content', through='ContentTag')

rawDescription: Django: counting tags of contents that match a query


code:
def Bezier(x_n, p0, p3) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    p1 = p0
    p2 = p3

rawDescription: using two consecutive values from a list in each iteration

description: Using two consecutive values from a list in each iteration


code:
value = self.optionMenu["menu"].entrycget(0, "label")
self.menuVar.set(value)

rawDescription: Set Python OptionMenu by index

description: Set Python OptionMenu by index


code:
baseArithOperand = powerExpr | real | identifier | groupedArithExpr
arithOperand <<= Group('-' + baseArithOperand) | baseArithOperand

rawDescription: Parser failing - pyparsing

description: Parser failing - pyparsing


code: driver.find_element_by_xpath("//a[span/span = 'Download de Arquivos']")

rawDescription: Python Selenium : Xpath element not found


code:
objects = [] #the object list
with open("path/to/file") as reader: #opens the file
    for line in reader: #iterates the lines
        objects.append(Object(*line.strip().split(", "))) #appends the objects to the list

rawDescription: getting strings from files split

description: Getting strings from files split


code:
class BunchOConstants(object):
    def __init__(self, **kwds):
        self.__dict__.update(kwds)
    @property
    def x(self):
        return self.y
    @x.setter
    def x(self,val):
        self.y=val
const=BunchOConstants(y=10,z='foo')

rawDescription: python binding of variable to particular expression

description: Python binding of variable to particular expression


code:
import mymodule
example = raw_input(' this is an example ')
mymodule.foo(example)

rawDescription: Can a python module read variables from the main program


code:
from socket import *

s = socket(AF_INET, SOCK_STREAM)
addr, port = "services.cyberprotection.agency", 9999
s.connect((addr, port)) # create the connection
data = s.recv(1024) # this receives the 3 numbers
nums = list(map(int, data.split())) # convert from str/bytes to int
print(nums)
ans = nums[0] * nums[1] // nums[2] # double slash means integer division
s.sendall(b"%i" % ans) # send the answer. % formatting works for bytes in Python 3 where .format doesn't (for bytes)
print(ans) # print the answer you calculated
print(s.recv(1024).decode()) # print the one the server sends

rawDescription: connecting to server and sending data to it in python

description: Connecting to server and sending data to it in python


rawDescription: How can I draw a bezier curve using Python's PIL?

description: Draw a bezier curve using Python's PIL


code:
import inspect

def getCallerModule():
    # gets globals of module called from, and prints out __file__ global
    print(inspect.currentframe().f_back.f_globals['__file__'])

rawDescription: (python) prepend script dir to a path

description: (python) prepend script dir to a path


code: from mymodule import foo, bar, baz, arr, tee, eff, emm

rawDescription: Python - Assign global variable to function return requires function to be global?


rawDescription: How to split string by space and treat special characters as a separate word in Python?

description: Split string by space and treat special characters as a separate word in Python


rawDescription: making binned boxplot in matplotlib with numpy and scipy in Python

description: Making binned boxplot in matplotlib with numpy and scipy in Python


code:
with open('result.png', 'wb') as png_file:
    png_file.write(data)

rawDescription: Re-Construct a png image from a GDK Pixbuf


code: qsort(arr, 0, newPivotIndex)

rawDescription: QuickSort in Python - program hangs for larger input sizes?


code: data = dict(raw_input().split() for _ in range(int(raw_input())))

rawDescription: Python taking paired string and integer input


code:
import pandas as pd
import ast

cols=['ID','Visit','Market','Event Time','Event Name']
with open(filename, 'rb') as f:
    data = ast.literal_eval(f.read())
    df = pd.DataFrame(list(data), columns=cols)
    print(df)

rawDescription: Problems importing text file into Python/Pandas


code:
index = 'SPY'  # Change to your ticker for the index.
s = pd.Series({symbol: returns[index].cov(returns[symbol])
               for symbol in df
               if symbol != index})

rawDescription: I want to find the Covariance between 1 column with all the other columns in a dataframe in pandas


code:
f = lambda obj: tuple(np.unique(obj[['C', 'D']].values))
df.groupby(['B', 'A']).apply(f).unstack()

rawDescription: Pandas DataFrame column to cell in pivot table


rawDescription: modify sign of numbers in two different columns of an RDD in PySpark

description: Modify sign of numbers in two different columns of an RDD in PySpark


code:
def flatten_count(iterable, element):
    count = 0
    for item in iterable:
        if item == element:
            count += 1
        if isinstance(item, list):
            count += flatten_count(item, element)
    return count

rawDescription: Python - Finding each occurrence of a value in a mixed array (integers, lists)


rawDescription: Gensim topic printing errors/issues

description: Gensim topic printing errors/issues


code:
dirList = [name for name in sorted(os.listdir(path))
           if name.endswith('.mp3')]

rawDescription: Why are these strings escaping from my regular expression in python?


code: type(str(''))

rawDescription: (unicode error) 'unicodeescape' codec can't decode bytes - string with '\u'


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

rawDescription: Extract path like strings from string

description: Extract path like strings from string


rawDescription: Dealing with multiple python versions when python files have to use #!/bin/env python


code:
c.execute("SELECT ID FROM artists WHERE name = ?", (FoundArtist,))
row = c.fetchone()
if row is None:
    c.execute("INSERT INTO artists(name) VALUES(?)", (FoundArtist,))
    artistID = c.lastrowid
else:
    artistID = row[0]

c.execute("SELECT ID FROM titles WHERE name = ?", (FoundTitle,))
row = c.fetchone()
if row is None:
    c.execute("INSERT INTO titles(name) VALUES(?)", (FoundTitle,))
    titleID = c.lastrowid
else:
    titleID = row[0]

c.execute("INSERT INTO plays VALUES(?,?,?,?)",
          (FoundPlayDate, FoundPlayTime, artistID, titleID))

rawDescription: Python & Sqlite3 - How to insert IDs from two select statements


code:
from matplotlib.pyplot import plot, show, subplots
import matplotlib.animation as animation

fig,ax=subplots(figsize=(20,10))
ax.set_xlim([0,20])
ax.set_ylim([0,10])

def animate(i):
    animlist = plot(matt[i][0],matt[i][1],'r',matt[i][2],matt[i][3],'b',marker='o',markersize=8)
    return animlist

def init():
    return []

anim=animation.FuncAnimation(fig,animate,frames=numlin,interval=1000,init_func=init,blit=True,repeat=0)
show()

rawDescription: Plot points with different colors in a matplotlib animation


code:
def compare(x1,x2):
    if x1[2] > x2[2]:
       return 1
    elif x1[2] < x2[2]:
       return -1
    else:
       return 0

rawDescription: python 2.4 sorting a text file by specific column

description: Python 2.4 sorting a text file by specific column


code:
marks
update(marks,'a','10',2)

rawDescription: Replacing values in csv by using python

description: Replacing values in csv by using python


code:
if (not "string1" in item
    and not "string2" in item
    and not "string3" in item
    and not "string4" in item):
    doSomething(item)

rawDescription: How to break the line in a python if statement without a syntax error?

description: Break the line in a python if statement without a syntax error


code:
class MyModel(models.Model):
    # ...

    @property
    def timedelta(self):
        try:
            return timedelta(microseconds=self.sum)
        except AttributeError:
            # instance was not annotated (from a regular queryset)
            return None

rawDescription: Using django 1.8 duration field to annotate a set of django objects


code:
labels = FixedFormatter(['{:5.2e}'.format(x * 1E13) for x in range(1,10)])
my_xaxis.set_major_formatter(labels)

rawDescription: Set ticks that aren't at powers of some base on a loglog plot


rawDescription: Python split twice with strip in one line


code:
import lxml.etree as ET
data = ET.parse('sample.xml')
regexpNS = "http://exslt.org/regular-expressions"
for entry in data.iter('entry'):
    A = entry.xpath('.//*[re:test(text(), ".*\(.*\).*")]',
                    namespaces={'re':regexpNS})

rawDescription: How to select a node whose subelement includes some text in Python?

description: Select a node whose subelement includes some text in Python


rawDescription: Python - Aggregate by month and calculate average


code:
with open(filename, 'rb') as handle:
    f = csv.reader(handle)

rawDescription: Python csv read file, what if I don't close the file?


rawDescription: How do I just extract the second component of a Python array?

description: Just extract the second component of a Python array


code: subprocess.call("perl myCode.pl >results.txt", shell=True)

rawDescription: Run Perl code (with output to file) from Python


code:
class CachedImage(models.Model):
    url = models.CharField(max_length=255, unique=True)
    photo = models.ImageField(upload_to=photo_path, blank=True)

    def cache(self):
        """Store image locally if we have a URL"""

        if self.url and not self.photo:
            result = urllib.urlretrieve(self.url)
            self.photo.save(
                    os.path.basename(self.url),
                    File(open(result[0]))
                    )
            self.save()

rawDescription: Programmatically saving image to Django ImageField


code:
from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))

rawDescription: How can I programatically change the background in Mac OS X?

description: Programatically change the background in Mac OS X


code: sum([float(d[item]) for item in combos[0]])

rawDescription: Optimized output from the python dictionary


rawDescription: Stripping text from one point to another in python


code: df.apply(lambda x: x['sent'] + pd.Timedelta(seconds=x['tz_offset']), 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 Question(models.Model):
    question = models.CharField(max_length=100)
    detail = models.TextField(null=True, blank=True)

class PossibleAnswer(models.Model):
    question = models.ForeignKey(Question)
    value = models.CharField(max_length=200)

class Answer(models.Model):
    possible_answer = models.ForeignKey(PossibleAnswers)

rawDescription: Django: Counting objects based on filter value that changes?


rawDescription: What does list[x::y] do?

description: What does list[x::y] do


code: httpd = make_server('', 8000, application, handler_class=NoLoggingWSGIRequestHandler)

rawDescription: Control wsgiref simple_server log

description: Control wsgiref simple_server log


code:
s ="{0} {1}".format ('foo','bar')
if something :
    do_something ('{0} {1} {2}'.format (1 ,2 ,3 ))

rawDescription: String formatting without index in python2.6


code: maximum = (df.a/df.index).max()

rawDescription: Python Pandas is it possible to find the max value in a generated series without having to store the series into memory?


code:
all_tds = []
for td in soup.findAll("table", bgcolor="#ffffff"):
    all_tds.append(td)

rawDescription: "td" before "for" loop

description: "td" before "for" loop


code:
for token in tokenize(string):
    print(token)

rawDescription: Match open and close brackets in garbled string


rawDescription: python variable value to trigger parameter default

description: Python variable value to trigger parameter default


code:
for key in ['date', 'name', 'languages', ...]:
    setattr(new_conf, key, request.POST[key])

    # Or if new_conf is a dict-like obj
    new_conf[key] = request.POST[key]

rawDescription: Template for extracting POST values in Django


code: list( itertools.product( *[(c, d.get(c)) if d.get(c) else c for c in s] ) )

rawDescription: Get ALL results of a word mapping with a dictionary


code:
try:
  yield 42
except:  # bare except, catches *anything*
  do_something()
  raise  # re-raise same exception
do_something()

rawDescription: Workaround for python 2.4's yield not allowed in try block with finally clause


rawDescription: If I use a for loop with a string, will it check character by character?


code:
class LabelMapperProxy(object):
    def __init__(self, mapper): self.mapper = mapper

rawDescription: Proxy class for accessing other class' items as attributes (__getitem__ infinite recursion)


code: vis = np.concatenate((img1, img2), axis=1)

rawDescription: Combining Two Images with OpenCV

description: Combining Two Images with OpenCV


code:
c = pycurl.Curl()
c.setopt(pycurl.URL, "https://example.com?param1=val1&param2=val2")
c.setopt(pycurl.HTTPGET, 1)
c.setopt(pycurl.CAINFO, 'ca.pem')
c.setopt(pycurl.SSL_VERIFYPEER, 1)
c.setopt(pycurl.SSL_VERIFYHOST, 2)
c.setopt(pycurl.SSLVERSION,     3)
c.setopt(pycurl.NOBODY, 1)
c.setopt(pycurl.NOSIGNAL, 1)
c.perform()
c.close()

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 functools import total_ordering

@total_ordering
class LogEntry(object):
    def __init__(self, time, message):
        self.time = time
        self.message = message

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return NotImplemented
        return self.time == other.time and self.message == other.message

    def __lt__(self, other):
        if not isinstance(other, self.__class__):
            return NotImplemented
        if self.time == other.time:
            return self.message < other.message
        return self.time < other.time

rawDescription: simple way to search a list ordered by integer timestamps

description: Simple way to search a list ordered by integer timestamps


code:
import re
with open("A.txt", "r") as f:
    lines = f.readlines()

label_ptrn = re.compile("^Scanning sequence ID\\:\\s*(?P<label>[A-Z0-9]+\\_[A-Z0-9]+)$")
line_ptrn = re.compile("^\s+(?P<start_value>\\d+)\\s+\\S+\\s+\\S+\\s+\\S+\\s+(?P<sequence>\\S+).*$")
inner_ptrn = re.compile("[A-Z]+")

all_matches = []
for line in lines:
    m = label_ptrn.match(line)
    if m:
        label = m.groupdict().get("label")
        continue
    m = line_ptrn.match(line)
    if m:
        start = m.groupdict().get("start_value")
        sequence = m.groupdict().get("sequence")
        mi = inner_ptrn.search(sequence)
        if not mi:
            continue
        span = mi.span()
        all_matches.append((label, int(start)+span[0], int(start)+span[1]))

rawDescription: How to extract start and end sites based on capital letter in a sequence?

description: Extract start and end sites based on capital letter in a sequence


code:
counter = make_counter()
counter()
counter()
# and so on...

rawDescription: state retention for classes and closures

description: State retention for classes and closures


code:
your_bytes_value = b'\x93\x4c\x00'
value = int.from_bytes(your_bytes_value, byteorder='big')
(value & 0x1fffff) >> 8

rawDescription: How to shift bits in a 2-5 byte long bytes object in python?

description: Shift bits in a 2-5 byte long bytes object in python


code:
it = iter(names)
with open('output.txt', 'w') as f:
    for pair in izip(it, it):
        f.write('%s is paired with %s\n' % pair)

rawDescription: Pairing a name from one text file with a random name from the same text file


rawDescription: Changing matshow xticklabel position from top to bottom of the figure


code: df['date'] = pd.to_datetime(df['date'])

rawDescription: Count of work hours from time series using pandas


code:
for node, subnodes in sorted( children.items() ):
    print( '%r : %r' % ( node, subnodes ) )

rawDescription: Array Associations Python

description: Array Associations Python


code: M = M*M

rawDescription: Walk through each column in a numpy matrix efficiently in Python


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

N = 1000 #number of points for plotting/interpolation

x, y, z = np.genfromtxt(r'dataa.txt', unpack=True)

xi = np.linspace(x.min(), x.max(), N)
yi = np.linspace(y.min(), y.max(), N)
zi = scipy.interpolate.griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')

fig = plt.figure()
plt.contour(xi, yi, zi)
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

rawDescription: Contour plot in Python importing txt table file


code:
veggies = []
fruits = []

for x in query_dict:
    if re.search('veggies',x['url']):
         veggies.append(x)
    if re.search('fruits',x['url']):
         fruits.append(x)

rawDescription: Why can't I split this python list?

description: Why can't I split this python list


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

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


code:
def __eq__(self, other):
    return type(self) == type(other) and self.number == other.number

rawDescription: Python set intersection and __eq__

description: Python set intersection and __eq__


code:
{'category': '22', 'description': 'Test Description', 'title': 'Test Title', 'privacyStatus': 'private', 'file': 'myfile.avi', 'keywords': ''}
{'category': 42, 'description': 'Test Description', 'title': 'Test Title', 'privacyStatus': 'some status not in choices - already parsed', 'file': 'myfile.avi', 'keywords': ''}

rawDescription: python argparse - pass values WITHOUT command line

description: Python argparse - pass values WITHOUT command line


code:
prefetch_query = Prefetch('message_set__title', queryset=Message.objects.all().order_by('-id'), to_attr='message_titles')
folders = Folder.objects.all().prefetch_related(prefetch_query)

rawDescription: Django ORM, latest items/messages by groups/folders


code:
def expand_ranges(string):
    def expand(start, stop):
        return ','.join(map(str, range(int(start), int(stop) + 1)))
    return ','.join([expand(*d.split('-')) if '-' in d else d for d in string.split(',')])

rawDescription: How to interpret a list of numbers from a string?

description: Interpret a list of numbers from a string


code:
reg = re.compile('\d+')
lst.sort(key=lambda s: int(reg.findall(s)[0]))

rawDescription: Sort strings accompanied by integers in list


code:
cur.execute("SELECT timestamp FROM test1 WHERE date = '2014-07-16'")
cur.fetchone()

rawDescription: How to obtain and then compare two timestamp values from postgreSQL via python?

description: Obtain and then compare two timestamp values from postgreSQL via python


rawDescription: Multiply all columns of a multi-indexed DataFrame by appropriate values in a Series


rawDescription: How to correctly call variables from a txt file into my python code?

description: Correctly call variables from a txt file into my python code


code:
for i, c in zip(problem, solution):
    if i != c:
        # that's the first set of chars, but we're already returning??
        return False

    if i == c or "#" == c:
        # wildcard works here, but already would have failed earlier,
        # and still an early return if it IS true!
        return True

rawDescription: Comparing similarity of two strings in Python


code:
import tkinter as tk
import random

COLORS =["red", "orange", "yellow", "green", "blue", "violet"]

class Application(tk.Frame):

    def __init__(self,master):
        self.master = master
        tk.Frame.__init__(self)
        self.pack()

        self._after_id = None
        self.entry = tk.Entry(self)
        self.entry.pack()
        self.entry.bind('<Key>',self.handle_wait)

    def handle_wait(self,event):
        # cancel the old job
        if self._after_id is not None:
            self.after_cancel(self._after_id)

        # create a new job
        self._after_id = self.after(1000, self.change_color)

    def change_color(self):
        random_color = random.choice(COLORS)
        self.entry.config(background=random_color)

root = tk.Tk()
app = Application(root)
app.mainloop()

rawDescription: Wait until user stopped typing in Tkinter


rawDescription: Storing a list, then reading it as integer


code:
get_text_column_row('#main > table:nth-child(6)', 'Points', '3')
get_text_column_row('#main > table:nth-child(6)', 'Last Name', '3')
get_text_column_row('#main > table:nth-child(6)', 'Last Name', '4')

rawDescription: How do I return a web page's table cell value without ID, using column and row names (not index)

description: Return a web page's table cell value without ID, using column and row names (not index)


rawDescription: How to implement n times nested loops in python?

description: Implement n times nested loops in python


code:
from django.conf import settings
settings.configure(
    DATABASE_ENGINE = 'postgresql_psycopg2',
    DATABASE_NAME = 'db_name',
    DATABASE_USER = 'db_user',
    DATABASE_PASSWORD = 'db_pass',
    DATABASE_HOST = 'localhost',
    DATABASE_PORT = '5432',
    TIME_ZONE = 'America/New_York',
)

rawDescription: Using Django database layer outside of Django?


rawDescription: Python dictionary random key print

description: Python dictionary random key print


code:
[] and [False]

[False] and []
[False] and [True]

rawDescription: Boolean list operation in python

description: Boolean list operation in python


code:
def func_wrapped(d, key):
    d[key] = func(d[key])
map(partial(func_wrapped, d), dict1)

rawDescription: Mapping func over dictionary

description: Mapping func over dictionary


code:
a = b'Path\xc3\xa9'
a
print(a)
print(a.decode())
sys.getdefaultencoding()
hash("Pathé")
hash(b"Path\xc3\xa9")

rawDescription: Accentuation in python: structure and for loop


code:
#! /usr/bin/env python3

import argparse
import sys

parser = argparse.ArgumentParser(description='...')
parser.add_argument(
    '--track',
    default='10m',
    dest='track',
    help="..."
)
args = parser.parse_args()
print(args)
print(sys.argv)

rawDescription: python 3: subprocessing a python script that uses argparse

description: Python 3: subprocessing a python script that uses argparse


code:
# globals.py
klaatu = "Once in Persia reigned a king ..."

rawDescription: Truly Global Variable in python

description: Truly Global Variable in python


code:
d = { 1 : 2, 3: 4 }
' '.join(str(v) for v in d.values())

rawDescription: Suppose I have a dictionary. How do I strip out all the keys? Edit: This is a nested dictionary


rawDescription: Python pandas: Keep selected column as DataFrame instead of Series


code:
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

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


rawDescription: How can I insert all the variable in a function automatically in python?

description: Insert all the variable in a function automatically in python


code:
with open('my_file.html', 'w') as fo:
    tsod.to_html(fo)

rawDescription: save pandas' to_html' as a file

description: Save pandas' to_html' as a file


code: [[(a,b),(c,a)] for a, b, c in itertools.product((0,1), repeat=3)]

rawDescription: plugging in values for each variable in a string

description: Plugging in values for each variable in a string


code:
while excludedWord in lst:
    lst.remove(excludedWord)

rawDescription: Deleting a specific word from a file in python


code:
import json
s = '{"name": "Alex"}'
obj = json.loads(s)
obj
obj["name"]

rawDescription: Very simple JSON decoding

description: Very simple JSON decoding


rawDescription: Rounding a number in python but keeping ending zeros


code:
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
_unistr.translate(remove_punctuation_map)

rawDescription: Most efficient way to strip forbidden characters in file name from Unicode string


code:
# use `numbers = 100` as an example
numbers = 100

prime = []
not_prime = []

for i in range(2,numbers+1):

    if i not in not_prime:
        prime.append(i)

        for x in range(i**2,numbers+1,i):
            not_prime.append(x)

# `enumerate` gives us a tuple of (index, element) in an iterable
# `start=1` tells enumerate to use a 1-based indexing rather than
# 0-based.
for idx, p in enumerate(prime, start=1):

    # "{:3d}" is a format string that is similar to the C-style
    # of %X.YA where `X` denotes the character width, `.Y` denotes
    # how many places to display in a floating point number,
    # and `A` denotes the type of what's being printed. Also note,
    # in Python, you don't need to use the `d` in `:3d`, you can just
    # do `{:3}`, but I've included it for your knowledge.
    #
    # the comma says 'don't add a newline after you print this'
    print ("{:3d}".format(p), end="")

    # if it's a multiple of 10, print a newline
    if idx % 10 == 0:

        # just print a newline
        print ()

rawDescription: How to print a list of integers in 10 columns?

description: Print a list of integers in 10 columns


code:
class NamePathColumn (ColumnClause):
    pass

@compiles (NamePathColumn)
def compile_name_path_column (element, compiler, **kwargs):
    return 'node.name_path' ## something missing?

rawDescription: SQLAlchemy: Recursive hybrid property in a tree node


code: list(nested(flat, 0))

rawDescription: How to build a nested list from a flat one in Python?

description: Build a nested list from a flat one in Python


code: lines = [ s.strip('"') for s in l.strip('[]').split(',') for l in open( 'myfile.txt', 'r' ).readlines() ]

rawDescription: Python how to read multiple inputs in a same line


rawDescription: Create complicated conditional column (geometric mean) Python


code:
nodes_between_set = set()
for path in paths_beween_generator:
    for node in path:
        nodes_between_set.add(node)

rawDescription: Getting subgraph of nodes between two nodes?


code:
def triadicIteractionGranular(signsQty):
    signs = [None for _ in range(signsQty)]
    comb = int(3**signsQty-1)

    def calSigns(combCopy):
        for n in xrange(signsQty):
            signs[n] = 1-combCopy%3 # [0,1,2] -> [1,0,-1], correct range for signs
            combCopy = combCopy//3

    while (comb >= 0):
        calSigns(comb)
        printIfTargetHit(signs)
        comb = comb - 1

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


code: import cv2

rawDescription: Change a pixel value

description: Change a pixel value


code:
tabToAdd  = Tabs.nameOfYourTab(self.nao, self.parent)
name = "string name of your tab"

rawDescription: Get the value from a variable

description: Get the value from a variable


code:
# R vectors are one-based (so 1+1=2)
model.rx2("coefficients").rx2("fixed").rx(2)

rawDescription: extract coefficients from R lme model in rpy2

description: Extract coefficients from R lme model in rpy2


code:
ldap_data = {'foo': 1, 'bar': 'baz'} # just some dummy data
data['ldap_data'] = ldap_data
data

rawDescription: dict.update overwrites existing keys, how to avoid?

description: Dict.update overwrites existing keys, how to avoid


code:
with open('test.txt') as f:
    data = [float(line.split()[-1]) for line in f if line.strip().startswith('X-DSPAM-Confidence:')]
    print(sum(data)/len(data))

rawDescription: slicing and dicing of a text file in python

description: Slicing and dicing of a text file in python


rawDescription: Select specified month date from numpy array (datetime object)


code:
Counter({('the', 'quick', 'person'): 2, ('and', 'the', 'quick'): 1,
  ('realize', 'his', 'speed'): 1, ('his', 'speed', 'and'): 1,
  ('person', 'did', 'not'): 1, ('quick', 'person', 'did'): 1,
  ('quick', 'person', 'bumped'): 1, ('did', 'not', 'realize'): 1,
  ('speed', 'and', 'the'): 1, ('not', 'realize', 'his'): 1})

rawDescription: Counting bigrams (pair of two words) in a file using python


rawDescription: Combine all elements of n lists in python


code:
import datetime
my_date = datetime.date.today()
datetime.datetime.combine(my_date, datetime.time.min)

rawDescription: Python: most efficient way to convert date to datetime


code:
import collections
import string

c = collections.Counter()
with open('DataSO.txt', 'rt') as f:
    for line in f:
        c.update(line.translate(string.maketrans("",""), string.punctuation).split())

rawDescription: Read words from .txt, and count for each words


code:
from collections import OrderedDict

city_file = open('US.txt', 'r')
states = OrderedDict()
cities = OrderedDict()
for row in city_file:
    data = [e.strip() for e in row.split('  ')]
    states[data[3]] = {
        'name': data[3],
        'code': data[4]
        }
    cities[data[5]] = {
        'name': data[5],
        'state': data[3],
        'zip_code': data[1],
        'latitude': data[8],
        'longitude': data[9]
    }

rawDescription: Python read file and assign split list data to dictionary


code:
def get_ugall_record(request):
    if 'ugq_no' in request.GET:
        qry_obj = db.Query(user_guide).order('ugq_no')
        return qry_response(qry_obj)
    elif 'faq_no' in request.GET:
        qry_obj = db.Query(faqs).order('faq_no')
        return qry_response(qry_obj)

def qry_response(qry_obj):
    all_list = []
    for q in qry_obj:
        all_list.append(q)
    return HttpResponse(serializers.serialize('json', all_list), mimetype='application/json')

rawDescription: How to get request.environ values in python?

description: Get request.environ values in python


code:
class Subclass1(BaseClass):
    def __init__(self):
        super( Subclass1, self ).__init__()
        self.specific()
        super( Subclass1, self ).finalizeInitialization()

rawDescription: How to perform common post-initialization tasks in inherited Python classes?

description: Perform common post-initialization tasks in inherited Python classes


code:
# For performance, memcached should be used.
strings = I18NString.objects.language(request.COUNTRY_CODE).all()
trans = dict((s.key, s.text) for s in strings)

rawDescription: Django Application Layout: Internationalization


code:
name,num
"smith, bob",2
carol,3
ted,4
alice,5

rawDescription: Save list of ordered tuples as CSV

description: Save list of ordered tuples as CSV


rawDescription: How do I update Django on Openshift?

description: Update Django on Openshift


code:
from random import randint

def digit_string(length):
    return "{0:0{1}d}".format(randint(0, 10**length - 1), length)

rawDescription: Typo - For loop not working correctly with argument


code:
def myadd(x,y):
     z = []
     for i in range(len(x)):
         z.append(x[i]+y[i])
     return tuple(z)

rawDescription: How to add with tuples

description: Add with tuples


code:
def get_rank(y, value_to_check):

    max_rank = len(y) # Default value in case no range found (as per 2.26 value example)

    for ii in xrange(len(y)-1,0,-1):
        if (y[ii] <= value_to_check <= y[ii-1]) or (y[ii] >= value_to_check >= y[ii-1]):
            max_rank = ii
            break

    return max_rank

rawDescription: Finding where a value lands between two numbers in Python


code:
def split_string(source,separators):
    return re.split('|'.join(re.escape(x) for x in separators),source)

rawDescription: Splitting Strings in Python with Separator variable


code:
def setCustAttr(self, name, value):
    if name not in ['bar', 'baz']:
        raise ValueError("Custom attribute must be 'bar' or 'baz'")
    if name == 'bar' and value < 0:
        raise ValueError("'bar' attribute must be non-negative")
    if name == 'baz' and value % 2:
        raise ValueError("'baz' attribute must be even")

    setattr(self, name, value)

rawDescription: Set a custom object attribute

description: Set a custom object attribute


code:
soup = BeautifulSoup(text, "html5")
new_tag = soup.new_tag('img', src='/some/url/here')
some_element.append(new_tag)

rawDescription: BeautifulSoup create a <img /> tag

description: BeautifulSoup create a <img /> tag


code:
from collections import Counter
termList = ["A", "A", "B", "C", "C", "C", "E"]
otherList = [["A", "E"], ["A", "B", "C", "C"], ["B", "B"], ["A", "C"]]

term_count = Counter(termList)
c = Counter()
for lst in otherList:
    c += Counter(lst)
    if any(c[v] > term_count[v] for v in c):
        break
    print(c)
else:
    print('Exhausted')

rawDescription: Count and sum all previous like terms

description: Count and sum all previous like terms


rawDescription: Modify Default Ttk Clam Widget Colors

description: Modify Default Ttk Clam Widget Colors


code: result = df3.groupby(['City_x', 'City_y']).count(); result

rawDescription: Count by combination

description: Count by combination


code:
import unittest.mock as mock

mock_argparse = mock.Mock()
with mock.patch.dict('sys.modules', argparse=mock_argparse):
    import argparse
    print(argparse.ArgumentParser())
# <Mock name='mock.ArgumentParser()' id='140681471282448'>

rawDescription: python mock patch top level packages

description: Python mock patch top level packages


code:
import re
search_text = 'blah Total: result'
result = re.findall(r'Total: (.*)', search_text)
result

rawDescription: Searching for text in Beautifulsoup

description: Searching for text in Beautifulsoup


code:
import matplotlib.pyplot as plt

fig1, ax = plt.subplots()
ax.plot(range(10))

fig2 = plt.figure()
fig2.axes.append(ax)

plt.show()

rawDescription: matplotlib: can I create AxesSubplot objects, then add them to a Figure instance?

description: Matplotlib: can I create AxesSubplot objects, then add them to a Figure instance


code:
# Third order polynomial
p = [4.5, 9.8, -9.2, 1.2]

# One-million element array
x = np.linspace(-10, 10, 1e6)

rawDescription: A faster numpy.polynomial?

description: A faster numpy.polynomial


code:
[(x, y, not random_list.index(y))
 for x in some_list
 for random_list, y in iter_with_list(random.sample([1,2,3,4,5], random.choice([1, 2, 3])))]

rawDescription: Python: list comprehension which references an internally generated list


code:
monlist = []
open("filename.txt", 'w')
for line in fv:
    monlist.append(line)
fv.close()

rawDescription: Dictionary creator (Python 3.x)

description: Dictionary creator (Python 3.x)


code:
def join_line(line_iter):
    """
    Take a iterable containing strings and right justify each
    at 8 spaces before joining
    """
    return ''.join(elem.rjust(8) for elem in line_iter)

with open('output','w') as f:
    f.writelines((join_line(row)+'\n') for row in csv_file)

rawDescription: Python - Writing white space to imported CSV data


code:
lst = ['milk', 'eggs', 'beef', 'oranges', 'dog food', 'chips', 'soda', 'bread']
splitList(lst, 3)
splitList([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)

rawDescription: Split a list into n items in a sublist with remainder being added


code: Namespace(input=[MyObj(name='one', rotate=True), MyObj(name='two', rotate=False), MyObj(name='three', rotate=True)])

rawDescription: python argparse always set defaults related to an optional argument

description: Python argparse always set defaults related to an optional argument


code:
a = append(a, b, axis=1)
del b

rawDescription: Numpy hstack explodes memory

description: Numpy hstack explodes memory


rawDescription: Python 3 string formatting with filler more than one character long


rawDescription: Complex comparisons on yesno filter?

description: Complex comparisons on yesno filter


code: assert nodistinctcols(X.T) == nodistinctcols_orig(X.T)

rawDescription: Speed up counting number of distinct columns


code: choices = {chromosome: chromosome.fitness for chromosome in chromosomes}

rawDescription: Fitness proportionate selection (roulette wheel selection) in Python


code:
http = urllib3.PoolManager()
my_url = "https://in.finance.yahoo.com/q/h?s=AAPL"
a = http.request("GET", my_url)
html = a.data.decode("utf-8")

from bs4 import BeautifulSoup

print([a["href"] for a in BeautifulSoup(html).find_all("a",href=True)])

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


rawDescription: Separate items in tuples in list when writing to csv


rawDescription: Python regex to print all sentences that contain two identified classes of markup


rawDescription: Using matplotlib, how do I whiten the background of the axis label?


code: result = reduce(update_theta, stuff, some_initial_theta)

rawDescription: Python: Functionally Merging Two Iterators Where One is Recursive


code: zip(*sorted(zip('LEAST', 'HDKEN'), key=lambda s:'STEAL'.index(s[0])))

rawDescription: How to sort one item to match another but applying the sort elsewhere?

description: Sort one item to match another but applying the sort elsewhere


code:
def isAlphabetical(word):
    for i in xrange(len(word) - 1):
        if word[i] > word[i+1]:
            return False
    return True

rawDescription: How to figure out if a word in spelled in alphabetical order in Python

description: Figure out if a word in spelled in alphabetical order in Python


code:
idx = coords / scaling[(slice(None),) + (None,)*(coords.ndim-1)]
new_data = ndi.map_coordinates(data, idx)

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


code:
bytes([157]) # this is equivalent to ord(157) in Python 2.x
bytes([157]).decode('cp437') # decode this to a unicode str with the desired encoding
print(bytes([157]).decode('cp437')) # now it's suitable for printing

rawDescription: encrypting a string via binary manipulation

description: Encrypting a string via binary manipulation


rawDescription: How to use import statement for custom modules in Python

description: Use import statement for custom modules in Python


code:
V = np.linspace(.1, .3, 25)
plt.contour(X,Y,Z,V, cmap=cm.RdBu)

rawDescription: How can I plot implicit functions in python?

description: Plot implicit functions in python


code: user = threadlocals.get_current_user

rawDescription: Model limit_choices_to={'user': user}

description: Model limit_choices_to={'user': user}


code: wtotal = sum(x[1] for x in bets.values() if x[0] == TEAM_BLUE);

rawDescription: Algorithm for betting and particularly winning the bet?


code:
from Tkinter import *

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("Simple")
        self.pack(fill=BOTH, expand=1)
        self.init_ui()

    def init_ui(self):
        self.frame = Frame(self, relief="flat", borderwidth=1)
        self.frame.grid(row=1,column=1,pady=4,padx=5,sticky=W)
        self.label=Label(self.frame,text="Scope:")
        self.label.pack(side="left", fill=None, expand=False)

        self.var = StringVar()
        self.var.set("today")

        self.list = OptionMenu(self.frame, self.var, "today","yesterday",
                               "this week","last week","this month",
                               "last month")
        self.list.pack(side="left", fill=None, expand=False)

        self.fetchButton = Button(self.frame, text="Fetch",command=self.handle)
        self.fetchButton.pack(side="left", fill=None, expand=False)

        self.area = Text(self,height=15,width=60)
        self.area.grid(row=2,column=1,rowspan=1,pady=4,padx=5)

        self.scroll = Scrollbar(self)
        self.scroll.pack(side=RIGHT, fill=Y)

        self.area.config(yscrollcommand=self.scroll.set)
        self.scroll.config(command=self.area.yview)
        self.scroll.grid(row=2, column=2, sticky='nsew')

        self.quitButton = Button(self, text="Cancel",command=self.quit)
        self.quitButton.grid(pady=4,padx=5,sticky=W,row=3, column=1)

    def handle(self):
        self.area.delete(1.0, END)
        self.area.insert(CURRENT,self.var.get())

if __name__ == "__main__":
    root = Tk()
    app = Example(root)
    root.mainloop()

rawDescription: Adding python functionality to Tkinter front end


code:
list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(out_path, 'wb')

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')

writer.writeheader() # Assumes Python >= 2.7
for row in list_of_dicts:
    writer.writerow(row)
out_file.close()

rawDescription: Write Python dictionary to CSV where where keys= columns, values = rows


rawDescription: Numpy: Transform sparse matrix to ndarray


code:
HarbName1 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName1")[0]
HarbName2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName2")[0]
HarbName3 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName3")[0]

rawDescription: Changing a variable during a loop, Python


code:
def proc(lock, number_of_active_processes, valor):
    lock.acquire()
    number_of_active_processes.value += 1
    print("Active processes:", number_of_active_processes.value)
    lock.release()
    # DO SOMETHING ...
    for i in range(1, 100):
        print(valor)
        valor = valor **2
    # (...)
    lock.acquire()
    number_of_active_processes.value -= 1
    lock.release()

if __name__ == '__main__':
    proc_number = cpu_count()
    number_of_active_processes = Value('i', 0)

    lock = Lock()
    values = [11, 24, 13, 40, 15, 26, 27, 8, 19, 10, 11, 12, 13]
    values_processed = 0

    processes = [Process() for _ in range(proc_number)]
    while values_processed < len(values)-1:
            for p in processes:
                if not p.is_alive():
                    p = Process(target=proc,
                                args=(lock, number_of_active_processes, values[values_processed]))
                    values_processed += 1
                    p.start()

rawDescription: Multiprocessing in Python to process a list of parameters


code: stuff = Source.objects.values('dbtype', 'host')

rawDescription: how to join an django model object response

description: Join an django model object response


code:
import os

class OpenCreateDirs(open):
    def __enter__(self, filename, *args, **kwargs):
        file_dir = os.path.dirname(filename)
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)

        super(OpenCreateDirs, self).__enter__(filename, *args, **kwargs)

rawDescription: Recursively create directories prior to opening file for writing


code:
from Tkinter import *
import random

def RGBs(num):
 # random list of list RGBs
 return [[random.randint(0,255) for i in range(0,3)] for j in range(0,num)]

def rgb2Hex(rgb_tuple):
    return '#%02x%02x%02x' % tuple(rgb_tuple)

def drawGrid(w,colors):
 col = 0; row = 0
 colors = [rgb2Hex(color) for color in colors]
 for color in colors:
  w.create_rectangle(col, row, col+1, row+1, fill=color, outline=color)
  col+=1
  if col == 100:
   row += 1; col = 0

root = Tk()
w = Canvas(root)
w.grid()
colors = RGBs(5000)
drawGrid(w,colors)
root.mainloop()

rawDescription: How to draw a bitmap real quick in python using Tk only?

description: Draw a bitmap real quick in python using Tk only


rawDescription: Finding total duration in time series data without overlap


code:
with open('/path/to/file.txt') as f:
    sections = list(per_section(f))  # default delimiter

with open('/path/to/file.txt.txt') as f:
    sections = list(per_section(f, lambda line: line.startswith('#'))) # comment

rawDescription: Splitting textfile into section with special delimiter line - python


twitter_user: bob

rawDescription: Send command from PHP to running Python script


code:
lcode = [ord(c) for c in code]
lcode
"".join([chr(c) for c in lcode])

rawDescription: Python: remove ^A in a string

description: Python: remove ^A in a string


code:
import os
os.system('"C:\Program Files\iOpus\iMacros\iMacros.exe" -macro my_macro.iim')

rawDescription: Integrating iMacros scripts into python

description: Integrating iMacros scripts into python


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QWidget):

    def __init__(self, parent=None):

        self.fileheader_fields=(
            "filetype","fileversion","numframes",
            "framerate","resolution","numbeams",
            "samplerate","samplesperchannel","receivergain",
            "windowstart","winlengthsindex","reverse",
            "serialnumber","date","idstring","ID1","ID2",
            "ID3","ID4","framestart","frameend","timelapse",
            "recordInterval","radioseconds","frameinterval","userassigned"
        )
        # just for test
        self.fileheader = {field: 'value of ' + field
                           for field in self.fileheader_fields}
        super(MainWindow, self).__init__(parent)
        self.table_widget = QtGui.QTableWidget()
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.table_widget)
        self.setLayout(layout)
        self.populate()

    def populate(self):
        self.table_widget.setRowCount(len(self.fileheader_fields))
        self.table_widget.setColumnCount(2)
        self.table_widget.setHorizontalHeaderLabels(['name', 'value'])
        for i, field in enumerate(self.fileheader_fields):
            name = QtGui.QTableWidgetItem(field)
            value = QtGui.QTableWidgetItem(self.fileheader[field])
            self.table_widget.setItem(i, 0, name)
            self.table_widget.setItem(i, 1, value)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    wnd = MainWindow()
    wnd.resize(640, 480)
    wnd.show()
    sys.exit(app.exec_())

rawDescription: Populating a table in PyQt with file attributes


rawDescription: Filter special chars such as color codes from shell output


code:
returned_tuple = wifi.add(h1, return_mobilityhelper=True)
mobilityhelper = returned_tuple[1]

rawDescription: How to add a variable of a method of a class in aonther program in python?

description: Add a variable of a method of a class in aonther program in python


code:
def sum_nums(low, high):
    result = 0
    for i in xrange(low, high+1):
        result += 1
    return result

rawDescription: How to parallel sum a loop using multiprocessing in Python

description: Parallel sum a loop using multiprocessing in Python


rawDescription: How to parse an XML file using Python?

description: Parse an XML file using Python


rawDescription: loop in tuple until a certain index is reach

description: Loop in tuple until a certain index is reach


code:
import itertools
x = itertools.count()
next(x)
next(x)
next(x)
# And so on...

rawDescription: Native infinite range?

description: Native infinite range


rawDescription: Python - sort lists based on their sum

description: Python - sort lists based on their sum


code:
from collections import namedtuple

QuuxReturnValue = namedtuple('QuuxReturnValue', ('foo', 'bar'))

def quux(*args, **kw):
    while True:
        yield QuuxReturnValue(foo='foo', bar='bar')

rawDescription: Return iterable of unpackable values that won't break client code if I start returning more data


rawDescription: Python reading until null character from Telnet


code:
d = {item.split('=', 1)[0]:i for i, item in enumerate(firstlist.split())}
d

rawDescription: Python: reordering a string(list) based on a previous list order


rawDescription: Numpy matrices - how to handle arbitrary size


code:
def maximize(a, b, lim):
    a.sort(reverse=True)
    b.sort()
    found = False
    best = 0
    j = 0
    for i in xrange(len(a)):
        while j < len(b) and a[i] * b[j] < lim:
            found = True
            if a[i]*b[j] > best:
                best, n1, n2 = a[i] * b[j], a[i], b[j]
            j += 1
    return found and (best, n1, n2)

rawDescription: python - 2 lists, and finding maximum product from 2 lists

description: Python - 2 lists, and finding maximum product from 2 lists


code:
[Section1]
somekey=val
anotherkey=val
wedontknowthesekeys=val
...

rawDescription: Read all the name and value pair in a section


rawDescription: How can I get the index of next non-NaN number with series in pandas?

description: Get the index of next non-NaN number with series in pandas


rawDescription: Summing similar elements within a tuple-of-tuples


code:
class Product(Base):
    __tablename__ = "product"

    id = Column(Integer, primary_key=True)
    name = Column(Unicode(140), unique=True, nullable=False)
    department = Column(Unicode(20))
    added = Column(DateTime, default=datetime.datetime.now)
    last_time_parsed = Column(DateTime)

    def repr(self):
        return "<Product(name=%s, department=%s, added=%s, last_time_parsed=%s)>" % (
                            self.name, self.department, self.added, self.last_time_parsed)

rawDescription: SqlAlchemy filter by time difference

description: SqlAlchemy filter by time difference


code:
# Mask of negative numbers
mask = x<0

# Differentiation between Consecutive mask elements. We would look for
# 1s and -1s to detect rising and falling edges in the mask corresponding
# to the islands of negative numbers.
diffs = np.diff(mask.astype(int))

# Mask with 1s at start of negative islands
start_mask = np.append(True,diffs==1)

# Mask of negative numbers with islands of one isolated negative numbers removed
mask1 = mask & ~(start_mask & np.append(diffs==-1,True))

# ID array for IDing islands of negative numbers
id = (start_mask & mask1).cumsum()

# Finally use bincount to sum elements within their own IDs
out = np.bincount(id[mask1]-1,x[mask1])

rawDescription: Summation of only consecutive values in a python array


code:
# shuffle the existing IDs so the assignment of the new IDs is random
a = []
sql = "SELECT ID FROM Clients"

for row in cursor.execute(sql):
    a.append(row.ID)

rawDescription: is there a way to speed up this python program? (short)

description: Is there a way to speed up this python program? (short)


code:
np.eye(1E6)
# ValueError: array is too big.

sparse.eye(1E6)
# <1000000x1000000 sparse matrix of type '<type 'numpy.float64'>'
# with 1000000 stored elements (1 diagonals) in DIAgonal format>

rawDescription: Build diagonal matrix without using for loop


code:
version = '''PHP executable        :  /usr/bin/php
PHP configuration     :  /etc/php5/cli/php.ini
PHP OS                :  Linux
Drush version         :  6.2.0
Drush configuration   :
Drush alias files     : '''

rawDescription: How to return data from python script

description: Return data from python script


code:
for d in dict_list:
    # Search each term.
    for term_regex, tag in zip(term_matchers, term_tags):
        if re.match(term_regex, d['text'], re.IGNORECASE):
            d['tag'] = tag
            break

rawDescription: Regex Python firstname lastname tag the keywords in json dump


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:
paths = list = ['C:/dir\\file.txt', 'C:/dir\\example.zip', 'C:/dir\\example2.zip']
paths = [path.replace('\\', '/') for path in paths]
paths

rawDescription: How to replace all recurrences of something in a list with something else

description: Replace all recurrences of something in a list with something else


code:
res = []
for i in xyz_set: # 0(n)
    count = 0
    for j in xyz_list: # 0(n)
        if i == j: # constant operation 0(1)
            count += 1 # constant operation 0(1)
    res.append(count) # constant operation 0(1)

rawDescription: How do i check the time complexity of a comprehension

description: Check the time complexity of a comprehension


rawDescription: How can I group a list of objects by continuity?

description: Group a list of objects by continuity


code:
records
records.update((k, 0) for k,v in records.iteritems() if v is None)
records

rawDescription: how to traverse through dict?

description: Traverse through dict


rawDescription: Axis in numpy multidimensional array

description: Axis in numpy multidimensional array


code: lst = [[] for _ in range(a)]

rawDescription: How to create a number of empty nested lists in python

description: Create a number of empty nested lists in python


code:
title = models.CharField(max_length=1000)
text = models.CharField(max_length=5000)

rawDescription: Django inlineformsets and general noobishness


rawDescription: Prossing Very Ugly Multi-line Json Object with Python


code:
with open('path/to/file.txt') as f:
    result = [map(int, line.split()) for line in f]
    # [list(map(int, line.split())) for line in f] in Python3

rawDescription: how to write the contents of a file into lists in python?

description: Write the contents of a file into lists in python


code:
def focusInEvent(self, event):
    event.accept()

    # insert your code here

rawDescription: How to make QtGui window process events whenever it is brought forward on the screen?

description: Make QtGui window process events whenever it is brought forward on the screen


rawDescription: Is there a statistics module for Python 2.7?


code: (a, (a*2 if return_two else a))           #This would always return a tuple of 2 values.

rawDescription: Unexpected python function return behavior


code:
@my_dec(100)
def testing(n):
   return n

rawDescription: Decorators with arguments

description: Decorators with arguments


code:
d = {lang:
        {i["suggestion"]: i["comment"]
        for i in ld if i["language"] == lang}
    for lang in {i["language"] for i in ld}}

print(d)

rawDescription: Transform dictionaries to a list of dictionaries according to their values


code:
...
...

class MyButton(Button):
    def dostuff(self, *args):
        print(args)

...
...

rawDescription: Can someone tell me where I'm going wrong with this structure?


code:
from types import MethodType, FunctionType
methodtypes = set((MethodType, FunctionType, classmethod, staticmethod))

def methods_in_order(cls):
    "Given a class or instance, return its methods in the order they were defined."
    methodnames = (n for n in (cls.__dict__ if type(cls) is type else type(cls).__dict__)
                   if type(getattr(cls, n)) in methodtypes)
    return sorted((getattr(cls, n) for n in methodnames),
                  key=lambda f: getattr(f, "__func__", f).func_code.co_firstlineno)

rawDescription: Is there a way to programatically determine the order in which functions are declared in a python module?


code:
s = 'abc' + 'd' + 'efg'
s

rawDescription: Alternative to python string item assignment


code: [list(v) for k,v in itertools.groupby(mylist,key=lambda x:x[:5])]

rawDescription: Python split a list into subsets based on pattern


rawDescription: analyzing a txt file in python by jumping the n_th element of a list

description: Analyzing a txt file in python by jumping the n_th element of a list


code: data_str = json.dumps(data_obj)

rawDescription: Javascript/python design assistance

description: Javascript/python design assistance


code:
from mongoengine import fields

def update_document(document, data_dict):

    def field_value(field, value):

        if field.__class__ in (fields.ListField, fields.SortedListField):
            return [
                field_value(field.field, item)
                for item in value
            ]
        if field.__class__ in (
            fields.EmbeddedDocumentField,
            fields.GenericEmbeddedDocumentField,
            fields.ReferenceField,
            fields.GenericReferenceField
        ):
            return field.document_type(**value)
        else:
            return value

    [setattr(
        document, key,
        field_value(document._fields[key], value)
    ) for key, value in data_dict.items()]

    return document

rawDescription: Update a MongoEngine document using a python dict?


code:
from concurrent import futures

def GetDict():
    return {'foo':'bar'}

# imports ...
# from Worker import GetDict

def ThreadStart():
    executor = futures.ThreadPoolExecutor(max_workers=4)
    future = executor.submit(GetDict)
    print(future.result()) # blocks until GetDict finished

    # or doing more then one:
    jobs = [executor.submit(GetDict) for i in range(10)]
    for j in jobs:
        print(j.result())

if __name__ == '__main__':
    ThreadStart()

rawDescription: Python threading: how to use return values of external scripts?


code:
guid=0 #for the 1st sheet
act = requests.get('https://docs.google.com/spreadsheets/d/177_dFZ0i-duGxLiyg6tnwNDKruAYE-_Dd8vAQziipJQ/export?format=csv&gid=%s' % guid)
dataact = act.content.decode('utf-8') #To convert to string for Stringio
actdf = pd.read_csv(StringIO(dataact),index_col=0,parse_dates=[0], thousands=',').sort()

rawDescription: Loading a generic Google Spreadsheet in Pandas


code:
s = [[u'wasn\u2019t', u'right', u'part', u'say', u'things',
      u'she\u2019s', u'hurt', u'terribly', u'she\u2019s',
      u'speaking']]

rawDescription: Why is re not working on my file?

description: Why is re not working on my file


rawDescription: Python - how to write strings to file without quotes and spaces?


code:
frame4.grid(row=2, column=0, sticky='WE', padx=5, pady=5, columnspan=3)
frame4.grid_columnconfigure(0, weight=1)
Button(frame4, text=' Done ', command=done).grid(
    row=0, column=0, padx=7, pady=2, sticky='E')
Button(frame4, text='Clear', command=clear).grid(
    row=0, column=1, padx=7, pady=2, sticky='E')

rawDescription: How to expand widgets size in a frame with respect to other frames in Tkinter (Help on:Tkinter grid management)

description: Expand widgets size in a frame with respect to other frames in Tkinter (Help on:Tkinter grid management)


code:
persons = df.set_index(['ID', 'NAME']).groupby(level=['ID', 'NAME'])
new_df =pd.DataFrame()
for details, phones in persons:
    person_phones = pd.concat([row for i, row in phones.iterrows()]).to_frame()
    person_phones.index = ['TEL_{}'.format(i) for i in range(len(person_phones))]
    new_df = pd.concat([new_df, person_phones], axis=1)

new_df.transpose().reset_index().rename(columns={'level_0': 'ID', 'level_1': 'NAME'})

rawDescription: How do I merge duplicate rows into one on a DataFrame when they have different values

description: Merge duplicate rows into one on a DataFrame when they have different values


code:
import numpy as np
rf = [[1,0,1,0,1,0,0,0]] * 8
m = np.array(rf)
m.diagonal(0)
m.diagonal(1)

rawDescription: How can I get step jump in for loop when it has a while conditioned on the for loop's variable

description: Get step jump in for loop when it has a while conditioned on the for loop's variable


rawDescription: Number divided by 4 by python regex

description: Number divided by 4 by python regex


code:
mask = np.ones(data.shape[1], dtype=np.bool)
mask[special_axis] = False
data_new = data[:, mask]

pca_transformed = PCA(n_components=14).fit_transform(data_new)

rawDescription: Retain specific component in PCA

description: Retain specific component in PCA


code:
with open("names.txt", "r") as fin:
    users = fin.read()

if "Smith" in users:
    print("truth")
else:
    print("false")

rawDescription: Strange behavior in python if/in word in file check


code: app.jinja_env.filters['regex'] = regex

rawDescription: Using regex in jinja

description: Using regex in jinja


code:
for f1, d1 in enumerate(data):
    for f2, d2 in enumerate(d1):
        for f3, d3 in enumerate(d2):
            for f4, d4 in enumerate(d3):
                for f5, value in enumerate(d4):
                    process_point(f1, f2, f3, f4, f5, value)

rawDescription: Iterating through multi-dimentional lists while remembering indices


code:
import numpy as np
np.random.shuffle(a)
a

rawDescription: python and numpy: Get random distribution from existing distribution

description: Python and numpy: Get random distribution from existing distribution


rawDescription: Squeezing characters with python

description: Squeezing characters with python


rawDescription: In place editing of Python dictionary or parsing json to object


code: ewma_frame = reduce(pd.DataFrame.combine_first, ewmas)

rawDescription: Ewma in pandas but over rolling weekly data.


code: a -= b  # Now use `a` instead of `c`.

rawDescription: NUMPY Operations: Memory Efficiency: PYTHON


code:
from blist import blist
b = blist([None])
b *= 5000
for i in range(100):b[i] = i

b.__sizeof__()
d = dict()
for i in range(100):d[i] = i

d.__sizeof__()
b = blist([None])
b *= 750
for i in range(30):b[i] = i

b.__sizeof__()
d = dict()
for i in range(30):d[i] = i

d.__sizeof__()

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


rawDescription: How to get the 'cardinal' day of the year in Pandas?

description: Get the 'cardinal' day of the year in Pandas


code:
@app.context_processor
def additional_context():
    return {
        'content': get_page_content_context(request.endpoint, g.language),
        'hot_links': get_hot_links(),
    }

rawDescription: Flask partial view for a list of items

description: Flask partial view for a list of items


code:
import pandas as pd
data = pd.DataFrame({"A": ["hello", "world"], "B": [1, 2]})
data["C"] = data.A.str[0]
data

rawDescription: Creating a new column in pandas dataframe as a function of another column


code: freq = numpy.fft.fftfreq(len(data), 0.001*(data[1,2] - data[0,2]))

rawDescription: converting time to Hz in python

description: Converting time to Hz in python


rawDescription: What is the best way to pass multiple parameters to class init in python?


code:
import collections

def my_mean(*args):
    if not args:
        return None
    if len(args) == 1 and isinstance(args[0], collections.Container):
        args = args[0]
    total = sum(args)
    ave = 1.0 * total / len(args)
    return ave

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


code:
import subprocess
subprocess.call(["python", "C:/hello.py"])

rawDescription: How to execute a python program by a button click on html page generated by django

description: Execute a python program by a button click on html page generated by django


rawDescription: Equivalent to (.*) in negative look behind assertion Regex Python


code:
class MyOtherQuery(Query):

  def _get_models(self):
    """Returns the query's underlying model classes."""
    if hasattr(query, 'attr'):
      # we are dealing with a subquery
      return [query.attr.target_mapper]
    else:
      return [
        d['expr'].class_
        for d in query.column_descriptions
        if isinstance(d['expr'], Mapper)
      ]

  def all_active(self):
    model_class = self._get_models()[0]
    return self.filter(model_class.is_active == True)

rawDescription: SQLAlchemy - can you add custom methods to the query object?


rawDescription: How To Add List Elements and Convert Them To A String


rawDescription: Numpy to check if a solution exists such that each row is < 0?


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\

        71

        Breakeven

        The Script

''')
search =soup.find('td', class_='style10')
search['class']
search['class'] = 'style14'
search['class']
list(search)
search.text

rawDescription: Replacing class name BeautifulSoup

description: Replacing class name BeautifulSoup


code:
cog = [{"money": i, "last": "0.001"} for i in range(20201, 20705)]
...
p_c['params'] = json.dumps(params)

rawDescription: Convert curl command into python code

description: Convert curl command into python code


code: readableMACaddress = '%02X-%02X-%02X-%02X-%02X-%02X' % (touple1, touple2, touple3, touple4, touple5, touple6)

rawDescription: Python get normal HEX format for MAC-Adress


rawDescription: How to save edited content in html

description: Save edited content in html


code:
from collections import defaultdict
match_results = defaultdict(lambda: defaultdict(int))

rawDescription: Python - Create names for dictionaries using variables from list


code:
from tkinter import *
import time

class Interface:
    def __init__(self, master):
        self.master = master
        self.browse_button= Button (master, text="Browse", command=self.browser)
        self.browse_button.pack()

    def browser (self):
        self.master.config(cursor="wait")
        self.master.update()
        self.read_file("filename")
        self.master.config(cursor="")

    def read_file (self, filename):
        time.sleep(5)  # actually do the read file operation here

window = Tk()
starter = Interface(window)
window.mainloop()

rawDescription: Blocking Tkinter interface until thread finishes its task


rawDescription: Should I use super() every time I call parent function or only inside overridden functions?


code:
import docx
from docx.oxml.shared import qn
tmp_doc = docx.Document()

# Generate content in tmp_doc document
tmp_doc.add_heading('New heading', 1)
# more content generation using docx API.
# ...

# Reference the tmp_doc XML content
tmp_doc_body = tmp_doc._document_part._element.body
# You could pretty print it by using:
#print(docx.oxml.xmlchemy.serialize_for_reading(tmp_doc_body))

rawDescription: python-docx insertion point

description: Python-docx insertion point


code:
adjectives = [['awesome', 'amazing'], ['good', 'nice' ]]
counts = Counter(adjective
                 for group in adjectives
                 for adjective in group)
counts

rawDescription: Python :getting the count for the adjectives in a string


rawDescription: Efficient way of searching a list of lists according to their hash value?


code:
router = routers.DefaultRouter()
router.register(r'Enviroment', views.EnviromentViewSet)
router.register(r'server', views.ServerViewSet)
router.register(r'datacenter', views.DatacenterViewSet)

urlpatterns = patterns('',url(r'^', include(router.urls)))

rawDescription: Clean way to implement views or methods with Django Rest Framework


code:
if event.type == pygame.QUIT:
    done = True

rawDescription: Keyboard Event - Pygame

description: Keyboard Event - Pygame


code:
callRow = calls.map(lambda t:

Row(userid=t[0],age=int(t[1]),country=t[2],nbrCalls=t[3]))
callsDF = ssc.createDataFrame(callRow)
callsDF.printSchema()
callsDF.registerTempTable("calls")
res = ssc.sql("select userid,age,max(ca),max(uk),max(us),max(xx)\
                    from (select userid,age,\
                                  case when country='CA' then nbrCalls else 0 end ca,\
                                  case when country='UK' then nbrCalls else 0 end uk,\
                                  case when country='US' then nbrCalls else 0 end us,\
                                  case when country='XX' then nbrCalls else 0 end xx \
                             from calls) x \
                     group by userid,age")
res.show()

rawDescription: Reshaping/Pivoting data in Spark RDD and/or Spark DataFrames


code:
def strToInt(s, acc):
    return strToInt(s[1:], 10 * acc + ord(s[0]) - 48) if s else acc

rawDescription: Python - String of Digits to Integer using Recursion?


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

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


code:
cons   = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda lst: lst[1] if lst else lst
nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)
length  = lambda lst, count=0: length(cdr(lst), count+1) if lst else count
begin   = lambda *args: args[-1]
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")

rawDescription: Python Linked List

description: Python Linked List


code:
array_a1 = np.array([[1, 2], [3, 4]])
array_a2 = np.array([[5, 6], [7, 8]])
array_a = np.array([array_a1, array_a2])
array_b = np.array([[9, 10], [11, 12]])
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:
from ctypes import *

rrpLib = cdll.rrpLib # or windll if it use STDCALL

getPluginManualAsPDF = rrpLib.getPluginManualAsPDF
getPluginManualAsPDF.restype = POINTER(c_ubyte)
getPluginManualAsPDF.argtypes = [c_void_p]

getPluginManualNrOfBytes = rrpLib.getPluginManualNrOfBytes
getPluginManualNrOfBytes.restype = c_long
getPluginManualNrOfBytes.argtypes = [c_void_p]

rawDescription: How to write a unsigned char* array containing hex values to file in python

description: Write a unsigned char* array containing hex values to file in python


rawDescription: Write a column next to list in csv_python


code:
from pprint import pprint as pp
pp(d)

{'Bar ': ['100', '200', '300'],
'Color': ['red', 'blue', 'yellow'],
'Cost ': ['45'],
'Foo ': ['1', '2', '3'],
'Shape': ['Square', 'triangle', 'rectangle']}

rawDescription: Convert text file to dictionary with one key and multiple values


code:
from BeautifulSoup import BeautifulSoup

html = '
Chinese New Year Sale
February 8, 2013 - February 10, 2013
'
date = BeautifulSoup(test).findAll('h2', {'class' : 'pointer'})[0].findAll('span')[0]
date = date.findAll(text=True)[0]
# Get start and end date separately
date_start, date_end = date.split(' - ')

rawDescription: How to parse html using beautifulsoap/python?

description: Parse html using beautifulsoap/python


code:
module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()

rawDescription: Python dynamic instantiation from string name of a class in dynamically imported module


code: dict(Foo(2, 3))

rawDescription: Extend python's dict functionality to user created classes


code:
class Model(model.Model):
        name = models.CharField(primary_key=True, max_length=16)
        name_org = models.CharField(max_length=16)

        # This should touch before saving
        def save(self, *args, **kwargs):
            self.name = re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', self.name)
            self.name_org = self.name # original "t(es)t"
            super(Model, self).save(*args, **kwargs)

rawDescription: Django - How can i modify text before save them to database?


code:
def tuple_less_than(tuple1, tuple2):
    for item1, item2 in zip(tuple1, tuple2):
        if item1 != item2:
            return item1 < item2
    return len(tuple1) < len(tuple2)

rawDescription: Tuple comparison in Python

description: Tuple comparison in Python


code:
for line in input_file:
    places = [len(x.partition('.')[2]) for x in line.split(',')]
    data = [float(x) for x in line.split(',')]

rawDescription: On significant figures of numbers in python


code: [('list item 1',), ('list item 2', [('list item 3',), ('list item 4', [('list item 5',)])]), ('list item 6',)]

rawDescription: How do I process a nested list?

description: Process a nested list


code:
class UserFavorites(db.Model):
    user_id = db.Column(db.Integer, db.ForeignKey(User.id), primary_key=True)
    color = db.Column(db.String, nullable=False, default='')
    shape = db.Column(db.String, nullable=False, default='')
    flower = db.Column(db.String, nullable=False, default='')

    user = db.relationship(User, backref=db.backref('favorites', uselist=False))

rawDescription: Creating a basic Table with Flask-SQLAlchemy


code:
import pytz
import datetime as dt
kuala_lumpur=pytz.timezone('Asia/Kuala_Lumpur')
localtz=pytz.timezone('Europe/London')

rawDescription: Get system date/time in Python after changing time zone


code:
d = defaultdict(int)
L = [["toto", 3], ["titi", 10], ["toto", 2]]
for i, j in L:
    d[i] += j

d.items()

rawDescription: Sum a multidimensional list in python

description: Sum a multidimensional list in python


code:
a = "hello %s"
a
a % "dave"

rawDescription: Is there a good standard for adding data to a string if already saved as a str object


code:
# Add one more element to idx for correct indexing on the last column
idx = list(idx)
idx.append(len(df))

# Loop over the idx locations to fill the columns
for i in range(len(dfnew.columns)):
    dfnew.iloc[:, i] = df.iloc[idx[i]+2:idx[i+1], 1].values

rawDescription: Use Python and Pandas to split data in a text file


code:
dic=dict.fromkeys("spam",[])
[id(x) for x in dic.values()]    #all of them are same objects
dic['s'].append(1)   #changing one changes others as well
dic

rawDescription: Strange Output When Iterating Over a Dict of Lists


code:
c = Counter(dict(listB))
c

rawDescription: Comparing a list to a tuple

description: Comparing a list to a tuple


code:
import re
item = "Water\n100ml\n"
re.match(r"([0-9]+)([a-z]+)", item.split()[1], re.I).groups()

rawDescription: Python - How can I separate characters and integers from a string into sub-strings?


rawDescription: Update list to include new elements of another list (primefactor computation)


code:
class YourPloneFixture(PloneSandboxLayer):
    defaultBases = (PLONE_FIXTURE,)

    def setUpZope(self, app, configurationContext):

        # Required by Products.CMFPlone:plone-content
        z2.installProduct(app, 'Products.PythonScripts')

    def setUpPloneSite(self, portal):

        # Installs all the Plone stuff. Workflows etc.
        self.applyProfile(portal, 'Products.CMFPlone:plone')

        # Install portal content. Including the Members folder!
        self.applyProfile(portal, 'Products.CMFPlone:plone-content')

rawDescription: How to add Members folder in plone.app.testing?

description: Add Members folder in plone.app.testing