code:
class DictProxy(object):
    def __init__(self, col, keyattr, valattr = None):
        self.obj = None
        self.col = col
        self.keyattr = keyattr
        self.valattr = valattr

    def __get__(self, obj, class_):
        self.obj = obj
        return self

    def __repr__(self):
        outdict = {}
        for k, v in getattr(self.obj, self.col).iteritems():
            if not k is None:
                if self.valattr == None:
                    outdict[getattr(k, self.keyattr)] = v
                elif v is not None:
                    outdict[getattr(k, self.keyattr)] = getattr(v, self.valattr)
                else:
                    outdict[getattr(k, self.keyattr)] = None
        return repr(outdict)

    def __getitem__(self, key):
        keyobj = [obj for obj in getattr(self.obj, self.col) if getattr(obj, self.keyattr) == key]
        if not len(keyobj):
            return None
        if self.valattr == None:
            return getattr(self.obj, self.col)[keyobj[0]]
        else:
            return getattr(getattr(self.obj, self.col)[keyobj[0]], self.valattr)

    def __contains__(self, key):
        return len([obj for obj in getattr(self.obj, self.col) if getattr(obj, self.keyattr) == key]) != 0

def dict_proxy(*arg):
    return DictProxy(*arg)

rawDescription: Change collection class key of reference in association_proxy


rawDescription: Allowing the use of the token `class` as a named parameter in a method signature


code:
class NewStyleCar(object):
    ...

rawDescription: What' the meaning of the brackets in the class?


code: dates = [v[1] for k,v in E.iteritems()]

rawDescription: Dictionary conversion to list in Python

description: Dictionary conversion to list in Python


code:
def GetOutput(file_name):
  file_size = file_len(file_name)
  file_line = randrange(file_size) + 1
  return linecache.getline(file_name, file_line)

file_1 = GetOutput(file_1)
file_2 = GetOutput(file_2)
...

rawDescription: Read files and count lengths for dictionary variable in python


code: podium = podium.append(frequence)

rawDescription: type of variable through indentation of loops Python

description: Type of variable through indentation of loops Python


code:
def foo(x):
    return x+1, x+2

rawDescription: Python: Efficiently calling subset variables of multiple returns function


code:
datetime.strptime("2004 60", "%Y %j")
datetime.strptime("2005 60", "%Y %j")

rawDescription: Python parsing for MySQL import

description: Python parsing for MySQL import


code:
import numpy as np
arr = np.random.random((2,3,4,5,6,6))

rawDescription: Numpy einsum broadcasting

description: Numpy einsum broadcasting


rawDescription: Delete and index and associated data from a pandas dataframe


code:
import copy

def fltr(node, vals):
    if isinstance(node, dict):
        retVal = {}
        for key in node:
            if key in vals:
                retVal[key] = copy.deepcopy(node[key])
            elif isinstance(node[key], list) or isinstance(node[key], dict):
                child = fltr(node[key], vals)
                if child:
                    retVal[key] = child
        if retVal:
             return retVal
        else:
             return None
    elif isinstance(node, list):
        retVal = []
        for entry in node:
            child = fltr(entry, vals)
            if child:
                retVal.append(child)
        if retVal:
            return retVal
        else:
            return None

rawDescription: Python filter nested dict given list of key names


code: lines = [float(line.strip().replace(',','.')) for line in open(filename)]

rawDescription: what is a quick way to import a text file in python?

description: What is a quick way to import a text file in python


code:
class Foo(object):
    pass

f2 = Foo()

rawDescription: Access all instances of a class while debugging


rawDescription: How to hide <matplotlib.lines.Line2D> in IPython notebook

description: Hide <matplotlib.lines.Line2D> in IPython notebook


rawDescription: PyAudio Responsive Recording

description: PyAudio Responsive Recording


code: dictionary = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

rawDescription: Pythonic way to update nested dictionaries in Python


code:
a = np.sum(D1*L1)
b = np.sum(D2*L2)

rawDescription: Is there any fastest way to execute For loops in python?


code:
for k, v in dc.items():
    an = eval(v[0])(v[1], v[2])
    print(an, an.name, an.age)
    zoo[an.name] = an

rawDescription: Dynamically create class instances from given strings and save deep copy in dictionary


code:
import numpy as np
N = 2000000
M = 5000
totalIDs = np.random.randint(0, 10000000, N)
totalIDs = np.unique(totalIDs)
np.random.shuffle(totalIDs)
v1 = np.random.rand(len(totalIDs))
v2 = np.random.rand(len(totalIDs))

subsampleIDs = np.random.choice(totalIDs, M)
subsampleIDs = np.unique(subsampleIDs)
np.random.shuffle(subsampleIDs)

rawDescription: doing better than numpy's in1d mask function: ordered arrays?

description: Doing better than numpy's in1d mask function: ordered arrays


code:
class Meta(type):
    def __new__(cls, clsname, clsbase, clsdict):
        newcls = super().__new__(cls, clsname, clsbase, clsdict)
        def custom_repr(self):
            return '{}, Custom __repr__'.format(clsname)
        newcls.__repr__ = custom_repr
        return newcls

class Foo(metaclass=Meta):
    pass

rawDescription: Can one modify the default repr behavior through a metaclass?


code:
if j == L or seq[i] < seq[M[j]]:
    M[j] = i

rawDescription: Longest increasing subsequence

description: Longest increasing subsequence


code:
tasks = []

for i in xrange(10):
    tasks.append(power.delay(i, 2))

amass.delay([], tasks)

rawDescription: Running a task after all tasks have been completed


code:
for i, row in enumerate(reader):
    if i == N:
        print("This is the line.")
        print(row)
        break

rawDescription: Best way to access the Nth line of csv file

description: Access the Nth line of csv file


code:
class GenericA(ComplexModel):
    i = Integer
    s = Unicode
    d = DateTime

rawDescription: How do you @rpc _returns polymorphic types in spyne?


code:
try:
    yield int(item)
    continue
except (ValueError, TypeError) as WrongTypeError:
    pass

rawDescription: Yield Only Once Per Iteration

description: Yield Only Once Per Iteration


code: result = test.split('of')[1].split(" ")[1]

rawDescription: Split string in the Python script

description: Split string in the Python script


code:
generator = gen()
directories = []
generator_wrapper = (directories.append(foo['name']) or foo
                         for foo in generator)

rawDescription: Capture-and-yield in a list comprehension


rawDescription: Finding groups of increasing numbers in a list


code:
class EditEventForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EditEventForm, self).__init__(*args, **kwargs)
        self.fields['bands'].queryset= \
                      Bands.objects.filter(Q(name='band1')|Q(name='band2'))
    class Meta:
        model = Event

rawDescription: Fill Django Form Field Data with Db Data


code: shared_data = multiprocessing.sharedctypes.RawArray("c", data)

rawDescription: Lock free read only List in Python?

description: Lock free read only List in Python


code: football[football['team'] == 'Lions']

rawDescription: Efficiently grouping the rows of a Pandas DataFrame by the value of a column?


code:
table2 = pd.to_datetime(table2)
idx = table2.searchsorted(df['Date'].values)

rawDescription: Complicated datetime merge pandas

description: Complicated datetime merge pandas


code:
my_lst = [0 for _ in range(15)]

for i in random.sample(range(15), 5):
    my_lst[i] = 1

rawDescription: Random.randint on lists in Python

description: Random.randint on lists in Python


code:
import boto.iam
conn = boto.iam.connect_to_region('us-east-1')
summary = conn.get_account_summary()

rawDescription: How to check whether MFA is enabled for root account in AWS using boto?

description: Check whether MFA is enabled for root account in AWS using boto


code:
import gconf
client = gconf.Client()
# Get a value and introspect its type:
value = client.get('/apps/gnome-terminal/profiles/Default/background_color')
value.type
value.get_string()

rawDescription: GNOME configuration database type-inference


code: np.save('my_array.npy', my_array)

rawDescription: By dumping a python list, creating a python ".py" file which returns the same python list


code:
file1 = {}
for line in open('file1', 'r'):
    k, v = line.strip().split(':')
    file1[k] = v

rawDescription: Text processing with two files

description: Text processing with two files


code:
class Option(models.Model):
    question = models.ForeignKey(Question)
    value = models.CharField(max_length=200)
    def get_percentage(self):
        total_count = Answer.objects.filter(option__question=self.question).count()
        cnt = Answer.objects.filter(option=self).count()
        perc = cnt * 100 / total_count
        return perc

rawDescription: django: calculate percentage based on object count

description: Django: calculate percentage based on object count


code:
firsts = df1.index.get_level_values('first')
df1['value2'] = df2.ix[firsts].values

rawDescription: Merge multi-indexed with single-indexed data frames in pandas


code: df['country'] = df['country'].str.strip(' ')

rawDescription: How to edit source csv file data using pandas

description: Edit source csv file data using pandas


code:
if score != '? - ?':
    data.append({
        'team1': team1.text.strip(),
        'team2': team2.text.strip(),
        'score': score
    })

rawDescription: BeautifulSoup data scrapping and database


code:
('COMMAND ', '   PID', '      USER', '  FD', '     TYPE', 'DEVICE', ' SIZE/OFF', '  NODE', 'NAME')
('init    ', '     1', '      root', ' cwd', '  unknown', '      ', '         ', '      ', '/proc/1/cwd (readlink: Permission denied)')
('init    ', '     1', '      root', ' rtd', '  unknown', '      ', '         ', '      ', '/proc/1/root (readlink: Permission denied)')
('python  ', ' 30077', '     user1', ' txt', '      REG', '   8,1', '  2617520', '461619', '/usr/bin/python2.6')

rawDescription: Splitlines in Python a table with empty spaces


code:
my_data = "
Hello, world!
"
z.writestr("hello.html", my_data)

rawDescription: Zipping dynamic files in App Engine (Python)


code:
mylist = [['a','b','c'],['d','e','f']]
'd' in [j for i in mylist for j in i]

rawDescription: What is the most efficient way to search nested lists in python?


code:
def f(O1,O2):
    if O1%4==3 or O2%4==3: return 2
    return cmp(O1,O2)

def GetMinOs(Os):
    Mn=set([])
    NotMn=set([])
    for O1 in Os:
       for O2 in Os:
           rel=f(O1,O2)
           if rel==1:       NotMn|=set([O1])
           elif rel==-1:    NotMn|=set([O2])
    Mn=Os-NotMn
    return Mn

def GetMinOs2(Os):
    Ol=list(Os)
    l=len(Ol)
    i=0
    j=1
    while i<l:
        while j<l:
            rel=f(Ol[i],Ol[j])
            if rel==1:
                l-=1
                Ol[i]=Ol[l]
                j=i+1
                break
            elif rel==-1:
                l-=1
                Ol[j]=Ol[l]
            else:
                j+=1
        else:
            i+=1
            j=i+1
    return set(Ol[:l])

Os=set(range(1000))

if __name__=='__main__':
    answer=GetMinOs(Os)
    result=GetMinOs2(Os)
    assert answer==result

rawDescription: Find in a dynamic pythonic way the minimum elements in a partially ordered set


code:
from itertools import chain
categories = list(chain.from_iterable(categories.values))

rawDescription: Python Pandas: "Reduce" function for Series


code:
buttons = dict()
for k in range(len(info)):
    buttons[k] = Button(top, text=info[k], command=lambda a=k: my_function(buttons[a]))

rawDescription: Tkinter: creating an arbitrary number of buttons/widgets


code:
# file group_by_trailing_py2.py
import os
import csv
from itertools import groupby

DELIM=';'
IN_FILENAME = 'My Product.csv'
OUT_FILENAME = 'My Product.grouped.csv'

############  skip this if you run  it against productive data ###############
DATA = '''111 ; Info1 ; Description 1 ; Remarks1
123 ; Info1 ; Description 1 ; Remarks1
156 ; Info2 ; Description 2 ; Remarks2
124 ; Info3 ; Description 3 ; Remarks3'''

if (os.environ.get('WITH_DATA_GENERATION')):
    open(IN_FILENAME,'w').write(DATA)
##############################################################################

keyfunc = lambda row: row[1:]

with open(IN_FILENAME) as csv_file:
    rows = sorted(csv.reader(csv_file, delimiter=DELIM), key=keyfunc)

it = map(lambda t: [", ".join(v[0].strip() for v in t[1]) + " "] + t[0],
            groupby(rows, key=keyfunc))

with open(OUT_FILENAME, 'w') as csv_file:
    writer = csv.writer(csv_file, delimiter=DELIM)
    for row in it:
        writer.writerow(row)

rawDescription: How to sort .csv file values by combining like strings using python3

description: Sort .csv file values by combining like strings using python3


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)

year = [1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014]
value = np.random.rand(23)

ser =  pd.Series(index = year,data=value)
df =ser.to_frame()

df.reset_index(inplace=True)
df.columns = ['year','value']
df.plot(kind='scatter',x='year',y='value')
plt.show()

rawDescription: How to Scatter Plot Series using Pandas

description: Scatter Plot Series using Pandas


code:
def insert_gen(orig_string, insertions):
    prev_key = 0
    for key, value in insertions:
        yield orig_string[prev_key:key] # yield text from the previous insert to this one
        yield value                     # yield the "inserted" text
        prev_key = key
    yield orig_string[prev_key:]        # yield trailing text (after last insert)

rawDescription: Efficient way to do string insertion in python?


code:
a
result = unformat(a, "{id:2d}{type:2s}{a:3d}{b:4s}{c:5d}{d:2s}")
result

rawDescription: Python parse issue

description: Python parse issue


code:
print(a,b,c,d,e)
print(b,c,d,a,e)

rawDescription: list items to its own variable

description: List items to its own variable


code:
def List_Value_Removal(old, reference, ID):
    return zip(*((v, ref) for v, ref in zip(old, reference) if ref != ID))

rawDescription: Python: Deleting Specific value from the list


code:
from django.shortcuts import render_to_response
import django.template
import django.http

def view_template(request, template_name):
    try:
        return render_to_response(template_name)
    except django.template.TemplateDoesNotExist:
        raise django.http.Http404('No such file: %s' % template_name)

rawDescription: Django: dynamic template rendering

description: Django: dynamic template rendering


code:
#!/usr/bin/env python
import shlex
from subprocess import Popen, PIPE

cmd = shlex.split(r'isql -v -b -d, DSN_NAME "DOMAIN\username" password')
process = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, errors = process.communicate(
    b"SELECT column_name, data_type "
    b"FROM database_name.information_schema.columns "
    b"WHERE table_name = 'some_table';")

rawDescription: Using subprocess to get output

description: Using subprocess to get output


rawDescription: Is there a in built method from python csv module to enumerate all possible value for a specific column?


code:
import csv
import os

graphs = set(os.listdir("C:/graph folder"))
with open("C:/*my dir*/UCSC to Ensembl.csv", "rb") as f:
    reader = csv.reader(f, delimiter = ',')
    for row in reader:
        if row[0] + "_nt_counts.txt" in graphs:
            print (row[1])

rawDescription: Python reading files in a directory

description: Python reading files in a directory


code:
import matplotlib.pyplot as plt

MP_TICKSIZE = [10.0, 15.0, 20.0]

plt.subplot(111)

x = [1.0, 2.0, 3.0]
y = [1.0, 2.0, 3.0]

plt.plot(x,y)

plt.gca().set_xticks([t for t in x])

count = 0
for tick in plt.gca().xaxis.get_major_ticks():
    tick.label1.set_fontsize(MP_TICKSIZE[count])
    count += 1

plt.show()

rawDescription: change fontsize of each tick of one axis with python matplotlib

description: Change fontsize of each tick of one axis with python matplotlib


code:
for item in g_d4:
    links_2=soup.find_all('a', href=re.compile('^http://www.barneys.com/barneys-new-york/men/'))
    pattern_2=re.compile("clothing/(\w+)")
    matches = set()
    for link in links_2:
        match_1=pattern_2.search(link["href"])
        if match_1:
            matches.add(match_1.group(1))
    print(matches)

rawDescription: Print just first output line

description: Print just first output line


code:
def test_inside_patch(self):
    def othermethod(self):
        self.x = 5
        self.y = 16
    patcher = patch('__main__.MyClass.some_method', new=othermethod)
    patcher.start()
    a = MyClass()
    a.some_method()
    self.assertEqual(a.x, 5)
    self.assertEqual(a.y, 16)
    patcher.stop()

rawDescription: Mocking a class method and changing some object attributes in Python


code:
# prepare args using list comprehension
rect_args_list = [ tuple(item[1:]) + ( 16, 16) for item in tails ]
for rect_args in rect_args_list:
    pygame.draw.rect(windowSurface, RED, rect_args)

rawDescription: Getting a specific value from a tuple within a list


code:
G.node['abc']['dob'] # 1185
G.node['abc']['pob'] # usa
G.node['abc']['dayob'] # monday

rawDescription: Storing and Accessing node attributes python networkx


code:
def parser(lines):
    block = []
    while lines :

        if lines[0].startswith('if'):
            bl = ' '.join(lines.pop(0).split()[1:]).replace('(', '').replace(')', '')
            block.append({'name':bl, 'children':parser(lines)})

        elif lines[0].startswith('else'):
            be = ' '.join(lines.pop(0).split()[1:]).replace('(', '').replace(')', '')
            block.append({'name':be, 'children':parser(lines)})

        elif not lines[0].startswith(('if','else')):
            block2 = lines.pop(0)
            block.append({'name':block2})
        else:
            break
    return block

rawDescription: Converting an "If Else" statement to a JSON file


code:
from collections import Counter

site_counts = Counter(value[0] for value in inputdict.values())

rawDescription: Counting first element in python and printing?


code:
import numpy as np
import pandas as pd
nan = np.nan

df = pd.DataFrame({'A':[1,1,nan],'B':[6,nan,2],'C':[nan,5,4]})
ser = pd.Series([11,12,13], index=list('ABC'))
print(df.fillna(ser))

rawDescription: Pythom, pandas dataframes. pd.fillna() for specific colunms with specific values


code:
from lxml import html

url = "http://site.com"
doc = html.parse(url).getroot() # download & parse webpage
doc.make_links_absolute(url)
for element, attribute, link, _ in doc.iterlinks():
    if (attribute == 'href' and element.tag == 'a' and
        'somepage' in link): # or e.g., re.search('somepage', link)
        print(link)

rawDescription: How to find and extract link from webpage?

description: Find and extract link from webpage


code:
if __name__ == '__main__':
    import os
    calc(os.getcwd())

rawDescription: input file in directory which is not in same directory as script being run

description: Input file in directory which is not in same directory as script being run


rawDescription: python and sqlite - escape input

description: Python and sqlite - escape input


rawDescription: Calculate value relative to another value


rawDescription: How to hide a Widget when the program starts in PyQt?

description: Hide a Widget when the program starts in PyQt


code:
positions = {10: (1, 30), 20: (20, 30), 30: (40, 40)}

# In practice, you want to create and add to this list
# the same time you add keys and values to the positions dictionary.
times = sorted(positions.keys())

t = 23
# Get the nearest time values (higher and lower)
# Test them both to see which is closer (ie. whether we
# should round up or down)
index = bisect.bisect(times, t)
l_i = max(index - 1, 0)
r_i = min(index, len(times) - 1)
if abs(times[l_i] - t) < abs(times[r_i] - t):
    t_nearest = times[l_i]
else:
    t_nearest = times[r_i]

position = positions[t_nearest]

rawDescription: Efficiently associating a single value with an interval


code:
# Assuming Linux. Word list may also be at /usr/dict/words.
# If not on Linux, grab yourself an enlish word list and insert here:
words = set(x.strip().lower() for x in open("/usr/share/dict/words").readlines())

# The above english dictionary for some reason lists all single letters as words.
# Remove all except "i" and "u" (remember a string is an iterable, which means
# that set("abc") == set(["a", "b", "c"])).
words -= set("bcdefghjklmnopqrstvwxyz")

# If there are more words we don't like, we remove them like this:
words -= set(("ex", "rs", "ra", "frobnicate"))

# We may also add words that we do want to recognize. Now the domain name
# slartibartfast4ever.co.uk will be properly counted, for instance.
words |= set(("4", "2", "slartibartfast"))

rawDescription: Breaking a string into individual words(Python)


code: SUCCESS

rawDescription: Python lambda self composing function: How to return a function that is repeated n amount of times?


code:
from scipy.signal.ltisys import TransferFunction as TransFun
from numpy import polymul,polyadd

class ltimul(TransFun):
    def __neg__(self):
        return ltimul(-self.num,self.den)

    def __mul__(self,other):
        if type(other) in [int, float]:
            return ltimul(self.num*other,self.den)
        elif type(other) in [TransFun, ltimul]:
            numer = polymul(self.num,other.num)
            denom = polymul(self.den,other.den)
            return ltimul(numer,denom)

    def __div__(self,other):
        if type(other) in [int, float]:
            return ltimul(self.num,self.den*other)
        if type(other) in [TransFun, ltimul]:
            numer = polymul(self.num,other.den)
            denom = polymul(self.den,other.num)
            return ltimul(numer,denom)

    def __rdiv__(self,other):
        if type(other) in [int, float]:
            return ltimul(other*self.den,self.num)
        if type(other) in [TransFun, ltimul]:
            numer = polymul(self.den,other.num)
            denom = polymul(self.num,other.den)
            return ltimul(numer,denom)

    def __add__(self,other):
        if type(other) in [int, float]:
            return ltimul(polyadd(self.num,self.den*other),self.den)
        if type(other) in [TransFun, type(self)]:
            numer = polyadd(polymul(self.num,other.den),polymul(other.den,self.num))
            denom = polymul(self.den,other.den)
            return ltimul(numer,denom)

    def __sub__(self,other):
        if type(other) in [int, float]:
            return ltimul(polyadd(self.num,-self.den*other),self.den)
        if type(other) in [TransFun, type(self)]:
            numer = polyadd(polymul(self.num,other.den),-polymul(other.den,self.num))
            denom = polymul(self.den,other.den)
            return ltimul(numer,denom)

    def __rsub__(self,other):
        if type(other) in [int, float]:
            return ltimul(polyadd(-self.num,self.den*other),self.den)
        if type(other) in [TransFun, type(self)]:
            numer = polyadd(polymul(other.num,self.den),-polymul(self.den,other.num))
            denom = polymul(self.den,other.den)
            return ltimul(numer,denom)

    # sheer laziness: symmetric behaviour for commutative operators
    __rmul__ = __mul__
    __radd__ = __add__

rawDescription: Multiply scipy.lti transfer functions

description: Multiply scipy.lti transfer functions


code:
for i, listbox_entry in enumerate(my_listbox.get(0, END)):
    if listbox_entry == old_breakfast_string:
        my_listbox.delete(i)
        my_listbox.insert(i, new_breakfast_string)

rawDescription: Loop over tkinter Listbox

description: Loop over tkinter Listbox


code:
import jinja2
print(jinja2.Template('''
{{ (1.55555|round(2)|string).rstrip('.0') }}
{{ (1.5|round(2)|string).rstrip('.0') }}
{{ (1.0|round(2)|string).rstrip('.0') }}
{{ (1|round(2)|string).rstrip('.0') }}
''').render())

rawDescription: How to round to zero decimals if there is no decimal value with Jinja2?

description: Round to zero decimals if there is no decimal value with Jinja2


code:
t = open('test.txt')
maxmin_ratios = find_maxmin_ratios(t)
maxmin_ratios
average_max = sum([maxmin[0] for maxmin in maxmin_ratios.values()])/float(len(maxmin_ratios))
average_min = sum([maxmin[1] for maxmin in maxmin_ratios.values()])/float(len(maxmin_ratios))
average_max, average_min

rawDescription: Calculate the greatest distance between any two strings in a group, using Python


code:
counts = collections.defaultdict(int)
for row in my_reader:
    counts[row[3]] += 1

rawDescription: Count numbers from row in CSV file

description: Count numbers from row in CSV file


code:
import json
import pandas as pd
import networkx as nx
from networkx.readwrite import json_graph

df_objs = pd.DataFrame({'uuid':list('ABCD'), 'name':['foo','bar','baz','quux']})
df_calls = pd.DataFrame({'calling':['A','A'], 'called':['B','C']})
objs = df_objs.set_index('uuid').to_dict(orient='index')
g = nx.DiGraph()
g.add_nodes_from(objs.items())
g.add_edges_from(df_calls[['calling','called']].drop_duplicates().values)

g_tree = nx.DiGraph(nx.bfs_edges(g, 'A'))

for obj_id in g_tree.nodes():
    g_tree.node[obj_id] = g.node[obj_id]

print(g_tree.nodes(data=True))
# [('A', {'name': 'foo'}), ('C', {'name': 'baz'}), ('B', {'name': 'bar'})]

data = json_graph.tree_data(g_tree, root='A')
print(json.dumps(data))
# {"children": [{"name": "baz", "id": "C"}, {"name": "bar", "id": "B"}],
#  "name": "foo", "id": "A"}

rawDescription: Unable to generate network data in tree format while retaining node attributes


code:
import Tkinter as tk

root  = tk.Tk()
d = {}

window = tk.Frame(root, borderwidth=2, relief="groove")
window.pack(fill="both", expand=True)

for row in range(9):
    for column in range(9):
        entry = tk.Entry(window, width=1, relief="flat", font=("Calibri",16))
        entry.grid(row=row, column=column, sticky="nsew")
        d[(row,column)] = entry

root.mainloop()

rawDescription: Python tkinter create buttons with loop and edit their parameters


code:
from collections import defaultdict

values_to_keys = defaultdict(set)

for key, value in input_dict:
    values_to_keys[value].add(key)

rawDescription: return key by value in dictionary

description: Return key by value in dictionary


code:
#!/usr/bin/env python
from __future__ import print_function
import io
import os
import sys
from subprocess import Popen

ON_POSIX = 'posix' in sys.builtin_module_names

# create a pipe to get data
input_fd, output_fd = os.pipe()

# start several subprocesses
processes = [Popen([sys.executable, 'child.py', str(i)], stdout=output_fd,
                   close_fds=ON_POSIX) # close input_fd in children
             for i in range(5)]
os.close(output_fd) # close unused end of the pipe

# read output line by line as soon as it is available
with io.open(input_fd, 'r', buffering=1) as file:
    for line in file:
        print(line, end='')
#
for p in processes:
    p.wait()

rawDescription: Python subprocess in parallel

description: Python subprocess in parallel


code:
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating

def parse(s):
    x, y, z  = s.split(",")
    return Rating(int(x), int(y), float(z))

ratings = (sc.textFile("data/mllib/als/test.data")
  .map(parse)
  .union(sc.parallelize([Rating(1, 5, 4.0)])))

model = ALS.train(ratings, 10, 10)

rawDescription: Spark ALS predictAll returns empty

description: Spark ALS predictAll returns empty


rawDescription: Why is attribute being inherited across classes in Python?


code: Model1.objects.extra(where = ['field in (SELECT field from myapp_model2 WHERE ...)'])

rawDescription: Most efficient way to use the django ORM when comparing elements from two lists


code:
counter = Counter.objects.get_or_create(name = name)
counter.count = F('count') +1
counter.save()

rawDescription: Atomic increment of a counter in django

description: Atomic increment of a counter in django


code:
sine_tone(
    # see http://www.phy.mtu.edu/~suits/notefreqs.html
    frequency=440.00, # Hz, waves per second A4
    duration=3.21, # seconds to play sound
    volume=.01, # 0..1 how loud it is
    # see http://en.wikipedia.org/wiki/Bit_rate#Audio
    sample_rate=22050 # number of samples per second
)

rawDescription: Python library for playing fixed-frequency sound


code:
def alertParent(self, key, item):
    strChange = "[{0}] = {1}".format(key, item)
    self.parent.notifyChange(self.id, strChange)

rawDescription: How to detect what element of a nested list has changed? (python)

description: Detect what element of a nested list has changed? (python)


rawDescription: Insert missing elements in a nested list based on a condition - Python


code:
try:
    while True:
        l3.remove(edge)
except ValueError:
    pass

rawDescription: Constant time random selection and deletion


rawDescription: Feedparser newbie questions

description: Feedparser newbie questions


rawDescription: How to add to dictionaries, but not dictionaries - Python

description: Add to dictionaries, but not dictionaries - Python


code: [elem.strip('()').split('+') for elem in "(A+B)*(C+D)".split("*")]

rawDescription: Python List Indexing and Returning the Item


code:
from itertools import product

def test(max_buildings=6, max_floors=6):
    for nbuildings, nfloors in product(range(max_buildings), range(max_floors)):
        for heights in product(range(nfloors), repeat=nbuildings):
            assert max_water_heldover(heights) == max_water_heldover_bruteforce(heights), heights

rawDescription: Algorithm to solve for water accumulation given building heights


code: list_of_tuples[0][0] = 7

rawDescription: Can I put a tuple into an array in python?

description: Put a tuple into an array in python


code:
from pygame import *
from pygame.locals import *
from math import *

#----------------------------------------------------------------------

init()

screen = display.set_mode((800,600))

clock = time.Clock()

hours = 5
minutes = 59
seconds = 50

hours2 = 5
minutes2 = 59
seconds2 = 50

time_to_move_clock_1 = time.get_ticks()
time_to_move_clock_2 = time.get_ticks()

running=True
while running:

    # events

    for e in event.get():
        if e.type == QUIT:
            running = False

    # (variable) modifications

    if time_to_move_clock_1 <= time.get_ticks():
        time_to_move_clock_1 += 1000 # 1000ms = 1s

        seconds_ang = 270 + 6 * seconds

        seconds_dx = int(cos(radians(-seconds_ang))*200)
        seconds_dy = int(sin(radians(-seconds_ang))*200)

        minutes_ang = 270 + 6 * (minutes + seconds/60.)

        minutes_dx = int(cos(radians(-minutes_ang))*200)
        minutes_dy = int(sin(radians(-minutes_ang))*200)

        hours_ang = 270 + 30 * (hours + minutes/60.)

        hours_dx = int(cos(radians(-hours_ang))*150)
        hours_dy = int(sin(radians(-hours_ang))*150)

        seconds += 1

        if seconds == 60:
            seconds = 0
            minutes += 1

            if minutes == 60:
                minutes = 0
                hours += 1

                if hours == 12:
                    hours = 0

    if time_to_move_clock_2 <= time.get_ticks():
        time_to_move_clock_2 += 100 # 100ms = 0.1s (10 times faster)

        seconds_ang2 = 270 + 6 * seconds2

        seconds_dx2 = int(cos(radians(-seconds_ang2))*100)
        seconds_dy2 = int(sin(radians(-seconds_ang2))*100)

        minutes_ang2 = 270 + 6 * (minutes2 + seconds2/60.)

        minutes_dx2 = int(cos(radians(-minutes_ang2))*100)
        minutes_dy2 = int(sin(radians(-minutes_ang2))*100)

        hours_ang2 = 270 + 30 * (hours2 + minutes2/60.)

        hours_dx2 = int(cos(radians(-hours_ang2))*75)
        hours_dy2 = int(sin(radians(-hours_ang2))*75)

        seconds2 += 1

        if seconds2 == 60:
            seconds2 = 0
            minutes2 += 1

            if minutes2 == 60:
                minutes2 = 0
                hours2 += 1

                if hours2 == 12:
                    hours2 = 0

    # draw

    screen.fill((0,0,0))
    draw.circle(screen, (255,255,255), (400,300), 200, 3)
    draw.line(screen,(0,255,255), (400,300), (400 + hours_dx, 300 - hours_dy), 5)
    draw.line(screen,(255,255,0), (400,300), (400 + minutes_dx, 300 - minutes_dy), 2)
    draw.line(screen,(255,0,255), (400,300), (400 + seconds_dx, 300 - seconds_dy), 1)

    draw.circle(screen, (255,255,255), (100,100), 100, 3)
    draw.line(screen,(0,255,255), (100,100), (100 + hours_dx2, 100 - hours_dy2), 5)
    draw.line(screen,(255,255,0), (100,100), (100 + minutes_dx2, 100 - minutes_dy2), 2)
    draw.line(screen,(255,0,255), (100,100), (100 + seconds_dx2, 100 - seconds_dy2), 1)

    # flip

    display.flip()

    # FPS (Frames Per Seconds)

    clock.tick(25)

quit()

rawDescription: Clock in Python

description: Clock in Python


rawDescription: python generator of generators?

description: Python generator of generators


rawDescription: Spark - Nested RDD Operation

description: Spark - Nested RDD Operation


rawDescription: ranking tuples with ties

description: Ranking tuples with ties


code:
import numpy as np
from mayavi import mlab

np.random.seed(1977)
x, y, z = np.random.random((3, 10))

mlab.points3d(x, y, z)
mlab.show()

rawDescription: Setting parallel prospective in mlab/mayavi/python


code:
@some_decorator
@staticmethod
def bar(**kwargs):
    pass

rawDescription: How to use the same python decorator for all types of methods/functions?

description: Use the same python decorator for all types of methods/functions


rawDescription: Django passing a string in url

description: Django passing a string in url


code:
groups = list(df.groupby(dcs, as_index=False))
print(groups[0][0])
print(groups[0][1])

rawDescription: How to speed up complex/difficult data filtering in pandas

description: Speed up complex/difficult data filtering in pandas


rawDescription: How to compute jaccard similarity from a pandas dataframe

description: Compute jaccard similarity from a pandas dataframe


code:
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField(blank=True, null=True)
    hobbies = models.CharField(max_length=200, blank=True, null=True)

rawDescription: UserCreationForm Django

description: UserCreationForm Django


rawDescription: Convert Pandas Column to DateTime II

description: Convert Pandas Column to DateTime II


code: np.allclose(r1, r2)

rawDescription: Levinson algorithm in python

description: Levinson algorithm in python


code: y

rawDescription: Creating a X input matrix and y output vector via Python


s: test

rawDescription: Why pycharm reports "can not find reference 'isoformat'" in line 6


code:
exist = {u'title': 2, u'actual bitrate': 4, u'id': 1, u'game slot': 0, u'Suggested Bitrate': 3}
l = [1.0, u'GOLD_Spider Solitaire', u'Spider\\nSolitaire', 120000.0, 120000.0]
dict((k, l[v]) for k, v in exist.iteritems())

rawDescription: What's an elegant way to create a dictionary from another dictionary's keys and an array of values?


code:
if cmds.window("GE_ui_window", exists=True):
    cmds.deleteUI("GE_ui_window")
cmds.window("GE_ui_window", title="My custom Graph Editor")

cmds.frameLayout("GE_ui_frameLayout", p="GE_ui_window", lv=False, bv=False )

if cmds.scriptedPanel("GE_ui_scriptedPanel", exists=True):
    cmds.deleteUI("GE_ui_scriptedPanel")
cmds.scriptedPanel("GE_ui_scriptedPanel", unParent=True, type="graphEditor", label='Sample')
cmds.scriptedPanel( "GE_ui_scriptedPanel", e=True, parent="GE_ui_window|GE_ui_frameLayout")

cmds.showWindow("GE_ui_window")

rawDescription: How do I parent new, user-created buttons inside the Graph Editor window?

description: Parent new, user-created buttons inside the Graph Editor window


rawDescription: fnmatch and recursive path match with `**`

description: Fnmatch and recursive path match with `**`


code:
s = df.groupby(['gameId', 'player']).size().reset_index(0, drop=True)
s[:] = np.arange(len(s)) % 2 + 1
df['player_alias'] = s.reindex(df.player).values

rawDescription: Pandas: Dataframe self-join with complex conditions


code:
from django.contrib.auth.decorators import login_required
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
    (r'^foo/$', login_required(direct_to_template), {'template': 'foo_index.html'}),
    )

rawDescription: Limited access to different roles in Django


code:
import json
json_string = '''\
{
    "vacation":
    [
        {
            "dates": [
                {
                    "duration": 360,
                    "dateTo": "4.2.2014",
                    "dateFrom": "2.1.2014"
                }
            ],
            "worker": "8"
        },
        {
            "dates": [
                {
                    "duration": 420,
                    "dateTo": "",
                    "dateFrom": "29.01.2015",
                    "errCode": "1",
                    "errMsg": "Missing dateTo"
                }
            ],
            "worker": "2"
        }
    ],
    "general": {
        "scriptComment": "",
        "scriptTo": "",
        "errCode": "2",
        "errMsg": "Missing comment.",
        "scriptFrom": "01.01.2014"
    }
}
'''
def remove_error_info(d):
    if not isinstance(d, (dict, list)):
        return d
    if isinstance(d, list):
        return [remove_error_info(v) for v in d]
    return {k: remove_error_info(v) for k, v in d.items()
            if k not in {'errMsg', 'errCode'}}

data = json.loads(json_string)
data = remove_error_info(data)
print(json.dumps(data, sort_keys=True, indent=4))

rawDescription: python delete all specific keys in json

description: Python delete all specific keys in json


code:
import struct

matrix = array(...)

st_i = struct.Struct('I')
st_f = struct.Struct('f')
float_values = [
    st_f.unpack(st_i.pack(int(''.join(map(str, a)), 2)))
    for a in matrix
]

rawDescription: Convert a binary string into IEEE-754 single precision - Python


code:
class Actor(object):
    def __init__(self):
        self.pos = Vector()
        self.vel = Vector()

rawDescription: 3D Collision detection not functioning properly


code:
import threading
def my_inline_function(some_args):
    #do some stuff
    download_thread = threading.Thread(target=function_that_downloads, args=my_args)
    download_thread.start()
    #continue doing stuff

rawDescription: background function in Python

description: Background function in Python


code:
Record(parent_list=[1,2]).save()
record = Record.objects.last()
record.parent_list # returns [1L, 2L]

rawDescription: I have a list of long integers that I assign to a django model charfield. The list of longs get converted to list of unicodes


rawDescription: Implementing Google's DiffMatchPatch API for Python 2/3


code:
foo = list(itertools.islice([1,2,3], 1)); it = iter([1,2,3]); x = itertools.chain(foo, it);
x.next()
x.next()
x.next()
x.next()
x.next()

rawDescription: Retrieving minimum value from a Python heapq


code: app.conf.CELERY_SEND_EVENTS = TRUE

rawDescription: Implementing Twisted style local multiple deferred callbacks in Celery


code:
worker_hours = {
    'John': [8, 8, 4, 3, 8],
    'Leo': [5, 6, 7, 8, 9],
    'Sammy': [4, 5, 6, 8, 8],
    'Ken': [8, 8, 8, 8, 8]}
def calc_check(workers):
    return sum(sum(hours) * 13 for hours in workers.values())

calc_check(worker_hours)
from itertools import chain
def calc_check(workers):
    return sum(chain.from_iterable(workers.values())) * 13

calc_check(worker_hours)

rawDescription: Looping and returning all values in a dictionary


code:
class Base(object):
    __metaclass__ = ABCMeta

    ns = "http://www.foo.com/bar"
    em = ElementMaker(namespace=ns, nsmap={'bar': ns})
    em.__isabstractmethod__ = False  # <-----

    @abstractmethod
    def addfeature(self):
        pass

rawDescription: class attribute considered abstract method in python 2.7 - abc module

description: Class attribute considered abstract method in python 2.7 - abc module


code:
for o in self.oranges:
    o.update()

rawDescription: how to make a list of images and draw them in random position in pygame?

description: Make a list of images and draw them in random position in pygame


code:
TEST = [1, 2, 3, 4, 5, 6]
for k in range(8):
    print("k={} -> {}".format(k, list(gen_k_slices(TEST, k))))

rawDescription: Select adjacent couples (or triads, etc ) from a list


rawDescription: How to check for common elements between two lists in python

description: Check for common elements between two lists in python


code: mapped = meanings[flags]

rawDescription: Create string ndarray from ndarray of int 'flags' using list of string meanings


rawDescription: Syntax confusion about code in pip installer, "get-pip.py"


code:
model = CountVectorizer()
transformed_train = model.fit_transform(train_corpus)
transformed_test = model.transform(test_corpus)

rawDescription: CountVectorizer deleting features that only appear once


code:
c = Counter('aaab')
c.update(Counter('babac'))
c

rawDescription: Why doesn't collections.Counter override __iadd__ method?


code:
inf = np.iinfo('i8').max
np.where(cond, arr, -inf).argmax(axis=1)

rawDescription: How do I vectorize this loop in numpy?

description: Vectorize this loop in numpy


code:
def test():

    number = input('Input a number then press enter:')
    print(number)
    prompt = input('Continue (y/n)? ')

    if prompt == 'y':
        number = input('Input a number then press enter:')
        print(number)
        prompt = input('Continue (y/n)? ')
    elif prompt == 'n':
        pass

    else:
        while prompt != 'y' or prompt != 'n':
            prompt = input('Continue (y/n)? ')

rawDescription: User input and stuck in while loop

description: User input and stuck in while loop


code: __import__('os').system('rm -rf /')

rawDescription: Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me?


code: raw = data.file.read()

rawDescription: Python bottle - How to upload media files without DOSing the server


code:
from django.shortcuts import render

def general(request):
    return render(request, 'blog/generalq.html', {})

rawDescription: How to link html files together using Django 1.9?

description: Link html files together using Django 1.9


code:
import re
str = '''東野 圭 吾「夢幻花」「白夜行」他
'''
match = re.findall(r'「([^」]*?)」', str)
print(match)

rawDescription: How can I match multiple elements enclosed in corner brackets with python regex?

description: Match multiple elements enclosed in corner brackets with python regex


code:
sll
fll = [[float(i) for i in l] for l in sll]
fll

rawDescription: Remove string quotes from array in Python


code:
hdulists = [pyfits.open(
                ('/home/ssridhar/mock_test_files/Roncarelli_test'
                '/roncarelli_dist_halo{0}.fits').format(n)
            ) for n in range(1, 23)]

rawDescription: Shortening a Python program

description: Shortening a Python program


code:
import xbmcaddon
addon = xbmcaddon.Addon()
myidnmame_enabled = addon.getSetting('myidname.enabled') == 'true'

rawDescription: how to check the value to overwritten them in xbmc?

description: Check the value to overwritten them in xbmc


code:
import random
x= random.normalvariate(2,17)

rawDescription: How do you generate a random number in a range with a specific average in python?

description: Generate a random number in a range with a specific average in python


code:
class Item(object):

    all = weakref.WeakValueDictionary()

    def __init__(self, uniq_key, title=None):
        self._key = uniq_key
        self.title = title
        # here, if needed, you could check that the key
        # is not ALREADY present in self.all
        self.all[self._key] = self

    def adjust_key(self, newkey):
        # "key non-uniqueness" could be checked here too
        del self.all[self._key]
        self.all[newkey] = self
        self._key = newkey

    def get_key(self):
        return self._key

    key = property(get_key, adjust_key)

rawDescription: Python data structure for a collection of objects with random access based on an attribute


code:
points = itertools.product(range(0, 8 * a, a), repeat=3)
points = (p for p in points if p != (4 * a, 4 * a, 4 * a))
with open("filename", "w") as f:
    for id_p in enumerate(points, 1):
        f.write("%4.d  1  4  %4.3f  %4.3f  %4.3f\n" % id_p)

rawDescription: Python: If in a For Loop

description: Python: If in a For Loop


code:
def get_data():
    data = memcache.get("key")
    if data is not None:
        return data
    else:
        data = self.query_for_data()
        memcache.add("key", data, 60)
        return data

rawDescription: How do I store a fetched entity in memcache for App Engine?

description: Store a fetched entity in memcache for App Engine


code:
s
a

rawDescription: How to make simplejson serializable class

description: Make simplejson serializable class


code:
from itertools import groupby
from operator import attrgetter

[list(g) for k, g in groupby(list_of_dts, key=attrgetter('hour'))]

rawDescription: Split list of datetime by hours using python


code:
# first connection
c1 = sqlite3.connect("file::memory:?cache=shared")

# second connection, to the *same database*
c2 = sqlite3.connect("file::memory:?cache=shared")

# third connection, to a different database altogether
c3 = sqlite3.connect('/tmp/sqlite3.db')
# can attach to the shared in-memory database
c3.execute("ATTACH DATABASE 'file::memory:?cache=shared' AS inmem")

rawDescription: How can I attach an in-memory SQLite database in Python?

description: Attach an in-memory SQLite database in Python


rawDescription: Most efficient way to strip a % from u'96.9%' and return a float


code:
def callback():
    # unhighlight everything from the beginning to the end
    text.tag_add('unhighlight', 1.0, END)

    # insert new text and apply the highlight tag to it
    text.insert(END, 'hello world ', 'highlight')

rawDescription: How to color the last word added in text with tkinter

description: Color the last word added in text with tkinter


code:
def normalize(probs):
    prob_factor = 1 / sum(probs)
    return [prob_factor * p for p in probs]

rawDescription: Normalize Small Probabilities in Python

description: Normalize Small Probabilities in Python


code:
d1 = {'goods.H.p': 0.5, 'goods.H.theta': 100, 'goods.H.sigma': 20}
d2 = {'goods.H.theta': 100, 'goods.H.sigma': 20, 'goods.H.p': 0.5}

collectn.find(d1).count()
collectn.find(d2).count()

rawDescription: Pymongo or Mongodb is treating two equal python dictionaries as different objects. Can I force them to be treated the same?


code:
for reg in RegionIDArray:
    page = 0

rawDescription: Crawl Multiple pages of a website with using Selenium (Python3)


code:
[x[1] for x in myList]
# [None, None, None, None]

rawDescription: How to access tuple elements in a nested list

description: Access tuple elements in a nested list


code:
def _argparse():
    import argparse

    def positive_int(s):
        v = int(s)
        if v < 1:
            raise argparse.ArgumentTypeError('{:r} must be a positive integer'.format(s))
        return v

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="""Filter text files and write min value.

    Performs these operations on the text files in supplied `filedir`:

    1. In each file, identify lines starting with the matching `maxprefix`
       which do *not* contain the maximum value for that prefix in that file.
    2. DESTRUCTIVELY REWRITE each file with lines found in step 1 removed!
    3. Write the minimum value (for all lines in all files) to `outputfile`.
    """)
    parser.add_argument('filedir',
        help="Directory containg the text files to process. WILL REWRITE FILES!")
    parser.add_argument('maxprefix', nargs="?", default="ENSG",
        help="Line prefix which should have values less than max value removed in each file")
    parser.add_argument('outputfile', nargs="?", default="output.txt",
        help="File in which to write min value found. WILL REWRITE FILES!")
    parser.add_argument('-p', '--parallel', metavar="N", nargs="?", type=positive_int, const=10,
        help="Process files in parallel, with N workers. Default is to process a file at a time.")
    return parser.parse_args()

if __name__ == '__main__':
    args = _argparse()
    fileglob = os.path.join(args.filedir, '*.txt')
    prefix = args.maxprefix
    outputfile = args.outputfile
    if args.parallel:
        multi_main(fileglob, prefix, outputfile, args.parallel)
    else:
        main(fileglob, prefix, outputfile)

rawDescription: Finding minimum value of word from a lot of files in python?


code: classe_final['class'] = np.where(joined['price'] > joined['percentil_75'], 4, np.where( joined['price'] > joined['percentil_50'], 3, np.where( joined['price'] > joined['percentil_25'], 2, 1 ) ) )

rawDescription: python, operation on big pandas Dataframe

description: Python, operation on big pandas Dataframe


code:
def string_in_list(s, entities):
    """Return elements of entities that contain given string."""
    for e in entities:
        if s in e:
            yield e

huge_list = ['you', 'say', 'hello', 'I', 'say', 'goodbye']  # ...
matches = string_in_list('y', huge_list)  # look for strings with letter 'y'
next(matches)  # first match
next(matches)  # second match

rawDescription: Find + Find next in Python

description: Find + Find next in Python


rawDescription: Slicing URL with Python

description: Slicing URL with Python


code: first_date = date["items"][0]["date"]

rawDescription: How to read a particular data format

description: Read a particular data format


code: qs.query.set_limits(start, stop)

rawDescription: Limiting the number of results from a Django QuerySet, without using slice


code:
sizes = rescale(graph.degree(), out_range=(0, 10))
plot(graph, vertex_size=sizes)

rawDescription: How to use igraph python's metamagic class?

description: Use igraph python's metamagic class


code: colors = get_n_colors(len(domain))

rawDescription: Convert categorical variable to color with Matplotlib


code:
from itertools import combinations

shots = range(1,11)
N = 3

coms = [c for n in range(1, N+1) for c in combinations(shots, n)]

rawDescription: Trying to find all possible combinations and groupings


rawDescription: How to test if a link target is a pdf file if the link does not contain .pdf

description: Test if a link target is a pdf file if the link does not contain .pdf


rawDescription: Python - List of unique dictionaries

description: Python - List of unique dictionaries


code:
datestr = "12-Oct-2010 06:40"
datetime.datetime.strptime(datestr, '%m-%b-%Y %H:%M')

rawDescription: how to parse time stamps in Python from PyPI packages (eg. 12-Oct-2010 06:40)

description: Parse time stamps in Python from PyPI packages (eg. 12-Oct-2010 06:40)


code:
def do_scale(self, tag):
    factor = int(self.spinbox[tag].get())
    (width, height) = self.default[tag]
    (x0,y0,x1,y1) = self.canvas.coords(tag)
    width = factor * width
    height = factor * height
    x1 = x0 + width
    y1 = y0 + height
    self.canvas.coords(tag, x0,y0,x1,y1)

rawDescription: Tkinter Resizable Objects Python Canvas

description: Tkinter Resizable Objects Python Canvas


code: string = "The brown fox jumped over the red barn, and fled."

rawDescription: Python regex endline

description: Python regex endline


code:
class MyTime:
    def __init__(self, hrs=0, mins=0, secs=0):
       self.totalsecs = hrs*3600 + mins*60 + secs

    @property
    def hours(self):
       return self.totalsecs // 3600

    @property
    def minutes(self):
        return self._get_leftoversecs() // 60

    @property
    def seconds(self):
        return self._get_leftoversecs() % 60

    def _get_leftoversecs(self):
        return self.totalsecs % 3600

    def increment(self, t):
        self.totalsecs += t

rawDescription: Python3/Classes/OOP/ How do you change a objects self values with a method?


code:
from bs4 import BeautifulSoup
text="""

Paragraph.

"""
soup = BeautifulSoup(text)
str(soup)

rawDescription: Prettify the code using Beautiful Soup

description: Prettify the code using Beautiful Soup


code: from ROOTFOL import *

rawDescription: Pydev tags import as "unresolved import" but code using this import works fine.


code:
@admin.route('/manage')
@admin.route('/manage/<current>')
@login_required
def manage(current = None):
    if current == 'menu_settings':
        template = 'admin/manage/site_configuration.html'
        title = 'Site configuration'
    elif current == 'internet_market':
        template = 'admin/manage/internet_market.html'
        title = 'Internet market'
    elif current is None:
        template = 'admin/manage/default.html'
        title = 'Default page for manage'
    else:
        flask.abort(404)

    return render_template(template, title=title, current=current)

rawDescription: dynamic render_template() in flask

description: Dynamic render_template() in flask


code:
from time import strftime
current_month = strftime('%B')

rawDescription: How to check what month it is? Python

description: Check what month it is? Python


rawDescription: Numpy vectorize, using lists as arguments


code: dict(zip(hdr, elt))["c"]

rawDescription: Finding the corresponding item in two tuples with Python


code:
return [Attribute(attr['internalname'], attr['value'])
        for attr in attributes if attr['internalname'] in attributenames]

rawDescription: Pythonic way using list comprehension

description: Pythonic way using list comprehension


rawDescription: List Comprehensions - How to have strings and integers in one list?


rawDescription: get packet size in scapy / python

description: Get packet size in scapy / python


rawDescription: Countdown timer giving me negative numbers


rawDescription: how to do linear interpolation on a 2D numpy array having sparse data?

description: Do linear interpolation on a 2D numpy array having sparse data


code:
row = ["to", "be", "or", "not", "to", "be"]
seen = dict()
seen_setdefault = seen.setdefault
new_row = ["" if cell in seen else seen_setdefault(cell, cell) for cell in row]
new_row

rawDescription: How do you remove duplicates from a list in Python whilst preserving order and length?

description: Remove duplicates from a list in Python whilst preserving order and length


code: lst = [x[0] for x in nodes if x[0] not in ssa_flat]

rawDescription: compare two lists and return not matching items

description: Compare two lists and return not matching items


rawDescription: Disable autosave on update in SQLAlchemy


rawDescription: What module is PYSIGNAL defined in PyQt4


code:
class ModelMeta(type):
    """Metaclass used to set database Property definitions on Models."""

    def __init__(cls, name, base, namespace):
        """Store Property instance definitions on the class as a dictionary."""

        # Get inherited Properties
        cls._properties = cls._get_initial_properties()

        # Add new Properties
        cls._register_properties(namespace)

    ### ...other class methods snipped for brevity... ###

    def _initialize_property(cls, key, property_instance):
        """
        Set the Model class attribute based on the Property definition.

        :param key: Class attribute key
        :type key: str

        :param property_instance: Property instance
        :type property_instance bulbs.property.Property

        """
        if property_instance.fget:
            fget = getattr(cls, property_instance.fget)
            # TODO: implement fset and fdel (maybe)
            fset = None
            fdel = None
            property_value = property(fget, fset, fdel)
        else:
            property_value = None
        setattr(cls, key, property_value)

rawDescription: Python Bulbs framework example of fget argument in a bulbs object init method


code: names = ['abe', 'matt', 'roscoe']

rawDescription: mapping dictonary a key with multiple values to json in python

description: Mapping dictonary a key with multiple values to json in python


code: True or WHATEVER # always True

rawDescription: Why is 'True or False' faster than 'False or True'?


code: [getattr(o, '__name__', None) for n, o in inspect.getmembers('')]

rawDescription: How to get name from method-wrapper, builtin_function_or_method types for inspect.getmembers predicate

description: Get name from method-wrapper, builtin_function_or_method types for inspect.getmembers predicate


code:
def gen():
    yield None

gen().__name__
gen().__name__ = 'foo'

rawDescription: Changing the __name__ of a generator

description: Changing the __name__ of a generator


code:
while True:
    q = "MATCH (n:Node) RETURN n"
    result = graph.cypher.execute(q)
    my_node = result[0][0]
    my_node.pull()
    print(my_node)

rawDescription: Is py2neo caching burning me?

description: Is py2neo caching burning me


rawDescription: Speed up a delta filter in python/numpy

description: Speed up a delta filter in python/numpy


rawDescription: Game scraping python regular expression

description: Game scraping python regular expression


code:
#! /usr/bin/python

from xml.dom.minidom import parse
import xml.dom.minidom
import csv

def writeToCSV(myLibrary):
    with open('output.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(['title', 'author', 'author'])
        books = myLibrary.getElementsByTagName("book")
        for book in books:
            titleValue = book.getElementsByTagName("title")[0].childNodes[0].data
            authors = [] # get all the authors in a vector
            for author in book.getElementsByTagName("author"):
                authors.append(author.childNodes[0].data)
            writer.writerow([titleValue] + authors) # write to csv

doc = parse('library.xml')
myLibrary = doc.getElementsByTagName("library")[0]
# Print each book's title
writeToCSV(myLibrary)

rawDescription: Parsing XML and writing to CSV file

description: Parsing XML and writing to CSV file


code:
import timeit
timeit.timeit(stmt='[n ** 0.5 for n in range(100)]', setup='import math', number=10000)
timeit.timeit(stmt='[math.sqrt(n) for n in range(100)]', setup='import math', number=10000)

rawDescription: Using exponentiation **0.5 less efficient than math.sqrt?


code:
from first import first
first([False, False, False, 10, False, False])

rawDescription: Find a unique element in a list

description: Find a unique element in a list


rawDescription: Python: List Comparison to find unique element count of lists


code:
def column_matches(line, substring, which_column):
    return line.split('\t')[which_column] == substring

rawDescription: Python Search function in a tab delimited column file


code:
var1 = subprocess.Popen(['echo', '"Hey', 'StackOverflow!"'], stdout=subprocess.PIPE).communicate()[0]
# String contained in var1: "Hey StackOverflow!"\n
var2 = subprocess.Popen(['echo', 'Hey StackOverflow!'], stdout=subprocess.PIPE).communicate()[0]
# String contained in var2: Hey StackOverflow!\n
var1 != var2
# True

rawDescription: Redirecting command output to a string - Python 3.4.3 - Not working on the new version


code:
def timedelta_to_microtime(td):
  return td.microseconds + (td.seconds + td.days * 86400) * 1000000

rawDescription: timedelta convert to time or int and store it in GAE (python) datastore

description: Timedelta convert to time or int and store it in GAE (python) datastore


rawDescription: Reverse a list without reversed command

description: Reverse a list without reversed command


code: response = json.dumps(response.text, sort_keys = True, indent = 4, separators = (',', ': '))

rawDescription: Pretty Display JSON data from with Flask


code:
from sqlalchemy import text, bindparam

users_myisam.select(
  text("MATCH (name,description) AGAINST (:value)",
       bindparams=[bindparam('value', q)])
)

rawDescription: Proper use of MySQL full text search with SQLAlchemy


code:
r = requests.get(url)
data = BeautifulSoup(r.text)
my_prices = [price.text for price in data.find_all("example", {"class":"example"})]

rawDescription: How to change text to digits and save into array in Python

description: Change text to digits and save into array in Python


code:
# -*- coding: utf-8 -*-
import scrapy
from scrapy import signals
from scrapy.exporters import CsvItemExporter

class NgaCsvPipeline(object):
    def __init__(self):
        self.files = {}

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def spider_opened(self, spider):
        ofile = open('%s_items.csv' % spider.name, 'w+b')
        self.files[spider] = ofile
        self.exporter = CsvItemExporter(ofile,
            fields_to_export = ['accession', 'title', 'date', 'inscription'])
        self.exporter.start_exporting()

    def spider_closed(self, spider):
        self.exporter.finish_exporting()
        ofile = self.files.pop(spider)
        ofile.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

rawDescription: Change Naming Convention for Images Pipeline


code:
for dir in list2:
    for path in list1:
        if path.find(dir) != -1:
            print(path)

rawDescription: Matching substring in another string

description: Matching substring in another string


code:
big = np.full(arr[:,0].max()+1, np.nan)
big[arr[:,0]] = arr[:,1]
big[vals]

rawDescription: How to extract those rows in a 2d array whose first element is in a different list?

description: Extract those rows in a 2d array whose first element is in a different list


code:
from reportlab.lib.units import inch
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph
from reportlab.platypus import Table
from reportlab.lib import colors

# Creates a table with 2 columns, variable width
colwidths = [2.5*inch, .8*inch]

# Two rows with variable height
rowheights = [.4*inch, .2*inch]

table_style = [
    ('GRID', (0, 1), (-1, -1), 1, colors.black),
    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    ('ALIGN', (1, 1), (1, -1), 'RIGHT')
]

style = getSampleStyleSheet()

title_paragraph = Paragraph(
    "My Title Here",
    style["Normal"]
)
# Just filling in the first row
data = [[title_paragraph, 'Random text string']]

# Now we can create the table with our data, and column/row measurements
table = Table(data, colwidths, rowheights)

# Another way of setting table style, using the setStyle method.
table.setStyle(tbl_style)

report.append(table)

rawDescription: What determines the vertical space in Reportlab tables?


code: [list(map(tuple, line)) for line in image]

rawDescription: changing sub-sublist into tuples in python

description: Changing sub-sublist into tuples in python


rawDescription: Prototyping-orientated features in Python?


code: df2['AVG_HR'] = df2.groupby(df2.index.map(lambda t: t.hour))['avg_hr'].transofrm('mean')

rawDescription: pandas, combining multiple dataframes

description: Pandas, combining multiple dataframes


code:
from fractions import Fraction, gcd

def recover_integer_vector(u, denom=50):
    '''
    For a given vector u, return the smallest vector with all integer entries.
    '''

    # make smallest non-zero entry 1
    u /= min(abs(x) for x in u if x)

    # get the denominators of the fractions
    denoms = (Fraction(x).limit_denominator(denom).denominator for x in u)

    # multiply the scaled u by LCM(denominators)
    lcm = lambda a, b: a * b / gcd(a, b)
    return u * reduce(lcm, denoms)

rawDescription: Denormalize unit vector

description: Denormalize unit vector


code:
from decimal import Decimal

values = [
    ('tens',   Decimal(10)),
    ('fives',  Decimal(5)),
    ('ones',   Decimal(1)),
    ('tenths', Decimal('0.1'))
]

def get_digits(num):
    output_dict = {}
    for place, value in values:
        output_dict[place] = int(num // value)  # Cast from Decimal to int
        num = num % value
    return output_dict

num = Decimal('277.9')
print(get_digits(num))
# {'tens': 27, 'ones': 2, 'tenths': 9, 'fives': 1}

num = Decimal('277.6')
print(get_digits(num))
#{'tens': 27, 'ones': 2, 'tenths': 6, 'fives': 1}

rawDescription: Precision of decimals in Python

description: Precision of decimals in Python


code: b = a + np.uint8(10)

rawDescription: numpy type conversions for arrays vs. scalars

description: Numpy type conversions for arrays vs. scalars


rawDescription: Pythonic formatting from 1 to 01

description: Pythonic formatting from 1 to 01


code:
xpath = "//td[@class='right column-datavalue lastColOfRow']"
dues = driver.find_element_by_xpath(xpath)

rawDescription: Unique content identifier with Selenium: InvalidSelectorError


code: ['Name', 'Home Airport','Destination' 'Stopovers','Cheapest Route']

rawDescription: Writing to csv file more than one user input?


rawDescription: How do I get the maximum within a subset of my dataframe in Pandas?

description: Get the maximum within a subset of my dataframe in Pandas


code:
ircSend('NICK ' + nick + '\r\n')
ircSend('USER john_bot john_bot bla :john_bot\r\n')

data = ircRecv() # explained later
if data.find('PING') != -1:
    ircSend('PONG ' + data.split()[1] + '\r\n')

ircSend('JOIN :' + chan + '\r\n')
ircSend('PRIVMSG ' + chan + ' :Hello.\r\n')

rawDescription: Python IRC Bot won't join channels on some servers, and I don't know how to make it respond to user input


code:
df['date'] = (tmp['year'] + tmp['day'] + tmp['month']).apply(lambda d: strptime(d, '%y%d%m'))
df['value'] = tmp['value']
del df['first_column']

rawDescription: How to split a dataframe column into multiple columns with a Pandas converter

description: Split a dataframe column into multiple columns with a Pandas converter


rawDescription: efficient numpy array creation

description: Efficient numpy array creation


rawDescription: insert text in the sections of circle in matplotlib

description: Insert text in the sections of circle in matplotlib


rawDescription: Can I convert a tuple to a parameter list 'inline'?

description: Convert a tuple to a parameter list 'inline'


code:
from pyspark.statcounter import StatCounter

def compute_stats(rdd):
    return rdd.aggregateByKey(
        StatCounter(), StatCounter.merge, StatCounter.mergeStats
    ).collectAsMap()

rawDescription: Is it possible to scale data by group in Spark?


rawDescription: How to programmatically create new objects from rows of data in Python / Pandas

description: Programmatically create new objects from rows of data in Python / Pandas


code:
import matplotlib as mpl
mpl.rcParams['font.family'] = 'GroovyGhosties'

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.title('Everything is crazy!!!', size=32)
plt.show()

rawDescription: How to use a (random) *.otf or *.ttf font in matplotlib?

description: Use a (random) *.otf or *.ttf font in matplotlib


code:
# Tests and comparison to string.split()

import os.path

def cut_path(filename):
    l = []
    while True:
        head, tail = os.path.split(filename)
        l.insert(0, tail)
        if head == "/":
            l.insert(0, "")
            break
        filename = head
    return "/".join(l[:7])

def cut_string(filename):
    return "/".join( filename.split("/")[:7] )

def test(filename):
    print("input:", filename)
    print("string.split:", cut_string(filename))
    print("os.path.split:", cut_path(filename))
    print()

test("/a/b/c/d/e/f/g/h")
test("/a/b/c/d/e/f/g/h/")
test("/a//b///c/d/e/f/g/h")

# input: /a/b/c/d/e/f/g/h
# string.split: /a/b/c/d/e/f
# os.path.split: /a/b/c/d/e/f
#
# input: /a/b/c/d/e/f/g/h/
# string.split: /a/b/c/d/e/f
# os.path.split: /a/b/c/d/e/f
#
# input: /a//b///c/d/e/f/g/h
# string.split: /a//b///c
# os.path.split: /a/b/c/d/e/f

rawDescription: Python: cut equivalent in Python?

description: Python: cut equivalent in Python


rawDescription: How can I use ijson

description: Use ijson


code:
df.t.dt.normalize()
# equivalent to
pd.DatetimeIndex(df.t).normalize()

rawDescription: Dropping time from datetime <[M8] in Pandas


code:
program_starts = time.time()
while(True):
    now = time.time()
    print("It has been {0} seconds since the loop started".format(now - program_starts))

rawDescription: Time a while loop python

description: Time a while loop python


code:
import numpy as np
a = np.array(L)
a**2
np.sum(a**2)
np.prod(a)

rawDescription: Arithmetic operations in a list

description: Arithmetic operations in a list


code:
import pandas as pd
pd.pivot_table(df, values=['open', 'close'], rows=df.index, cols='token')

rawDescription: Groupby by name and get a dataframe with hierarical columns in pandas


code:
for a, b, c in zip(a_list, b_list, c_list):
   pass

rawDescription: python multiple 'for' statement in one row

description: Python multiple 'for' statement in one row


rawDescription: Naming coordinates in python

description: Naming coordinates in python


rawDescription: Converting a List within a List from String to Integers


rawDescription: Detect gray things with OpenCV

description: Detect gray things with OpenCV


code:
a_dict = {}

for attr in dir(settings):
    value = getattr(settings, attr)
    a_dict[attr] = value

for key, value in a_dict.items():
            print('%s = %r' % (key, value))

rawDescription: List quickly all settings of your Django project


code:
content =  'I opened my mouth, "Good morning!" I said cheerfully. "How is everyone?"'
content = re.sub(r'".*?"', '""', content)
print(content)

rawDescription: Python regex replace text in quotes except quotes themselves


code: [(x, tuple(y for j, y in enumerate(nums) if j != i)) for i, x in enumerate(nums)]

rawDescription: Python list combination

description: Python list combination


code: codes_cnt = Item.objects.values('category_codes', 'unique_codes').distinct().count()

rawDescription: Merging rows when counting - Django/SQL

description: Merging rows when counting - Django/SQL


code:
def get_text(element):
    return element.text + \
        ''.join(c.tail for c in element.findall('*') if c.tail is not None)

rawDescription: Recursive traversal of xml tags is not printing the value of the (sub tags) Ref.tail


code: df2.loc[:, to_shift]

rawDescription: For any rows with a NaN in a Pandas DataFrame, shift by 1


code:
CONFIG = "some string"
ANOTHER = [ "some", "list" ]
MORE = "another value"

rawDescription: Using Python as the config language for a Python program


rawDescription: pandas dataframe aggregate - why does it return column names?

description: Pandas dataframe aggregate - why does it return column names


code:
from datetime import datetime
today = datetime.now()
today
today.strftime("%I %p")

rawDescription: What's the fastest way to get time in am/pm?


code:
len(row_counts)
"""
5
"""

rawDescription: How to count rows in a data frame in Pandas conditionally against values in another column of the same data frame?

description: Count rows in a data frame in Pandas conditionally against values in another column of the same data frame


rawDescription: advanced numpy/pandas indexing

description: Advanced numpy/pandas indexing


code: collections.deque(chan, maxlen=0)

rawDescription: Drain or discard a generator without looping?


code:
def assemble_fast1(x, n):
    res = list(x)
    while len(res) <= n:
        res.extend(['01'[c=='0'] for c in res])
    return ''.join(res)

rawDescription: How do i speed up this piece of code?

description: Speed up this piece of code


code: ['DoesNotExist', 'Meta', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_base_manager', '_carousel_cache', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_ordering', '_check_swappable', '_check_unique_together', '_db_connection', '_default_manager', '_deferred', '_do_insert', '_do_update', '_get_FIELD_display', '_get_basepath', '_get_children_path_interval', '_get_database_connection', '_get_database_cursor', '_get_lastpos_in_path', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_parent_path_from_path', '_get_path', '_get_pk_val', '_get_serializable_model', '_get_unique_checks', '_inc_path', '_inst', '_int2str', '_meta', '_perform_date_checks', '_perform_unique_checks', '_placeholder_cache', '_prepare_pos_var', '_prepare_pos_var_for_add_sibling', '_prepare_pos_var_for_move', '_process_foreign_keys', '_render_meta', '_save_parents', '_save_table', '_set_pk_val', '_state', '_str2int', '_valid_pos_for_add_sibling', '_valid_pos_for_move', '_valid_pos_for_sorted_add_sibling', '_valid_pos_for_sorted_move', 'add_child', 'add_root', 'add_sibling', 'add_url', 'alias_reference', 'aliaspluginmodel', 'alphabet', 'carousel', 'carousel_id', 'carouselplugin', 'changed_date', 'check', 'child_plugin_instances', 'clean', 'clean_fields', 'cmsplugin_ptr', 'cmsplugin_ptr_id', 'cmsplugin_set', 'column', 'copy_plugin', 'copy_relations', 'copy_url', 'creation_date', 'date_error_message', 'delete', 'delete_url', 'depth', 'dump_bulk', 'edit_url', 'file', 'find_problems', 'fix_tree', 'flash', 'full_clean', 'gap', 'get_ancestors', 'get_annotated_list', 'get_breadcrumb', 'get_breadcrumb_json', 'get_children', 'get_children_count', 'get_database_vendor', 'get_depth', 'get_descendant_count', 'get_descendants', 'get_descendants_group_count', 'get_first_child', 'get_first_root_node', 'get_first_sibling', 'get_foreign_keys', 'get_instance_icon_alt', 'get_instance_icon_src', 'get_last_child', 'get_last_root_node', 'get_last_sibling', 'get_media_path', 'get_next_by_changed_date', 'get_next_by_creation_date', 'get_next_sibling', 'get_parent', 'get_plugin_class', 'get_plugin_class_instance', 'get_plugin_instance', 'get_plugin_name', 'get_position_in_placeholder', 'get_prev_sibling', 'get_previous_by_changed_date', 'get_previous_by_creation_date', 'get_root', 'get_root_nodes', 'get_short_description', 'get_siblings', 'get_sorted_pos_queryset', 'get_translatable_content', 'get_tree', 'googlemap', 'has_change_permission', 'id', 'inheritpageplaceholder', 'is_child_of', 'is_descendant_of', 'is_leaf', 'is_root', 'is_sibling_of', 'language', 'link', 'load_bulk', 'move', 'move_url', 'multicolumns', 'node_order_by', 'notify_on_autoadd', 'notify_on_autoadd_children', 'num_children', 'numchild', 'numconv_obj', 'numconv_obj_', 'objects', 'page', 'parent', 'parent_id', 'path', 'picture', 'pk', 'placeholder', 'placeholder_id', 'placeholderreference', 'plugin_type', 'position', 'post_copy', 'prepare_database_save', 'reload', 'render_plugin', 'save', 'save_base', 'serializable_value', 'set_base_attr', 'set_translatable_content', 'shinyapppluginmodel', 'steplen', 'teaser', 'text', 'translatable_content_excluded_fields', 'unique_error_message', 'validate_unique', 'video']

rawDescription: Django-CMS Custom plugin and placeholders


code:
from collections import defaultdict

lines = defaultdict(int)
for val in names.values():
    lines[val] += 1

for k, v in lines.items():
    print("Files with {} lines: {}".format(k, v))

rawDescription: Python script counting lines in multiple text files in one directory and producing simple report


code:
if event.type == pygame.QUIT:
    sys.exit()

rawDescription: How do I add key commands to sprite?

description: Add key commands to sprite


code:
import types
r= types.SimpleNamespace()
r.attribute1= "hello"
r.attribute2= "there"
r.attribute3= 3.14

rawDescription: Why Python does not support record type i.e. mutable namedtuple


code: ''.join(['first', 'second', 'other'])

rawDescription: Python - How to concatenate to a string in a for loop?


rawDescription: how to set the index page in django like http://127.0.0.1:8000/

description: Set the index page in django like http://127.0.0.1:8000/


code:
def check_proxy():
     import urllib
     http_proxy = urllib.getproxies().get('http')
     # some “complex” code that uses http_proxy

rawDescription: unit test for proxy checking

description: Unit test for proxy checking


code:
match1.group()
match1.group() == match2.group()

rawDescription: set() not removing duplicates

description: Set() not removing duplicates


code:
messages.add_message(request, messages.INFO, 'An info.')
messages.add_message(request, messages.SUCCESS, 'An success.')

rawDescription: Modifying the warning message when deleting an object in django admin?


code:
with open('/var/log/debug.log', 'w') as fh:
    fh.write( str( [data] ) )

rawDescription: How can I identify invisible characters in python strings?

description: Identify invisible characters in python strings


rawDescription: To find same row in tic tac toe using a formula


rawDescription: Most idiomatic way of applying modulo to list in python


code:
def sign_switch(oneDarray):
    inds=[]
    for ind in range(len(oneDarray)-1):
        if (oneDarray[ind]<0 and oneDarray[ind+1]>0) or (oneDarray[ind]>0 and oneDarray[ind+1]<0):
            inds.append(ind)
    return np.array(inds)

switched_frames = sign_switch(filtered_signs)

rawDescription: How can I extract this obvious event from this image?

description: Extract this obvious event from this image


code: name, view, id, *tokens = k

rawDescription: How do I unpack a list with fewer variables?

description: Unpack a list with fewer variables


code: s.connect(lambda: self.done())

rawDescription: Does PyQT4 signal.connect keep objects live?


code:
df2 = pandas.DataFrame({'quartile boundaries': pctile_object.levels,
                        'midway point': bin_halfway})

rawDescription: Pandas assign each row the mean of its bin


code:
from collections import MutableSequence, Iterable

class MyList(MutableSequence):
    def __init__(self, type, iterable=()):
        self._data = []
        self._type = type
        self.extend(iterable)

    def insert(self, index, item):
        if not isinstance(item, self._type):
            raise TypeError
        self._data.insert(index, item)

    def __len__(self):
        return len(self._data)

    def __getitem__(self, *args):
        return self._data.__getitem__(*args)

    def __delitem__(self, *args):
        self._data.__delitem__(*args)

    def __setitem__(self, key, value):
         if isinstance(value, collections.Iterable) and isinstance(key, slice):
             values = []
             for val in value:
                 if not isinstance(value, self._type):
                     raise TypeError
         else:
             if not isinstance(value, self._type):
                 raise TypeError
         self._data[k] = value

rawDescription: How to make an iterable class in Python in which only a specific type is allowed to be the element?

description: Make an iterable class in Python in which only a specific type is allowed to be the element


rawDescription: Python Ctypes Null Terminated String Block


code:
# client_id - first parameter in braces from the url
# order_id - 2nd parameter in braces from the url
def order_view(request, client_id, order_id):
    order = models.Order.objects.get(pk=int(order_id))
    if request.POST.get('delete'):
        order.delete()

rawDescription: Delete order number in django

description: Delete order number in django


rawDescription: Most efficient way of keeping only the unique items in a list in Python


code:
def encode(s):
    last  = s[0]
    count = 0
    for c in s:
        if last != c:
            yield '%s%i' % (last, count)
            last = c
            count = 0
        count += 1
    yield '%s%i' % (last, count)

rawDescription: python encoder and decoder

description: Python encoder and decoder


rawDescription: Parsing string sections

description: Parsing string sections


type: SELL

type: BUY

rawDescription: Hacking JavaScript Array Into JSON With Python


rawDescription: Format string - spaces between every three digit


code:
samples = [sample() for _ in range(100000)]
samples.count(0)
samples.count(1)
samples.count(2)

rawDescription: Generating weighted random numbers

description: Generating weighted random numbers


code:
def dd():
    return defaultdict(int)

dict1 = defaultdict(dd) # dd is a module-level function

rawDescription: Can't pickle defaultdict

description: Can't pickle defaultdict


code:
import Tkinter as tk

def cinterp(x1,x2,x,c1,c2):
    """
    interpolate two colors.  c1 and c2 are 3-tuples of rgb values --
    e.g. (0,0,255)

    x1,x2 and x are used to determine the interpolation constants.
    """
    s1=float(x-x1)/(x2-x1)
    s2=1.-s1
    return [int(s1*i+s2*j) for i,j in zip(c1,c2)]

root=tk.Tk()
cvs=tk.Canvas(root,width=100,height=50)
cvs.grid(row=0,column=0)
width=int(cvs['width'])
height=int(cvs['height'])
for i in range(width):
   fill=cinterp(0,width,i,(255,0,0),(255,255,255))
   fs="#%02x%02x%02x"%(fill[0],fill[1],fill[2])
   cvs.create_rectangle(i,1,i+1,height,fill=fs,width=0)

root.mainloop()

rawDescription: Crossfading between label colors over time in tkinter?


code:
from flask import Flask
from flask.ext.socketio import SocketIO, emit, send

app = Flask(__name__)
socketio = SocketIO(app)

import socket_views

if __name__ == '__main__':
    socketio.run(app)

rawDescription: How to handle dynamic decorators in python easily?

description: Handle dynamic decorators in python easily


code:
class Something(object):
    def test_x(self):
        # here the various assertEqual etc. do not resolve, but you can use them
        # as if they were present, since in real test-cases they will be inherited
        # from unittest.TestCase.
        ...
    ...

class TestCase1(unittest.TestCase, Something):
    def setUp(self):
        ...

rawDescription: Python nose test inheritance: load unit test fixtures from subclasses


code:
xml = ('''
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/schemas/govtalk/govtalkheader"
xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"
xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.govtalk.gov.uk/schemas/govtalk/govtalkheader">
<EnvelopeVersion>1.0</EnvelopeVersion>
<Header>
<MessageDetails>
<Class>CompanyDetails</Class>
<Qualifier>request</Qualifier>
<TransactionID>14456553</TransactionID>
</MessageDetails>
<SenderDetails>
<IDAuthentication>
<SenderID>My_SenderID</SenderID>
<Authentication>
<Method>CHMD5</Method>
<Value>e999e113407884fa410fa2f53bc23952</Value>
</Authentication>
</IDAuthentication>
<EmailAddress>sometest@some.email.address</EmailAddress>
</SenderDetails>
</Header>
<GovTalkDetails>
<Keys/>
</GovTalkDetails>
<Body>
<CompanyDetailsRequest xmlns="http://xmlgw.companieshouse.gov.uk/v1-0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://xmlgw.companieshouse.gov.uk/v1-0/schema/CoDets.xsd">
<CompanyNumber>01002361</CompanyNumber>
<GiveMortTotals>1</GiveMortTotals>
</CompanyDetailsRequest>
</Body>
</GovTalkMessage>
''')

rawDescription: Python: Making a request with suds

description: Python: Making a request with suds


rawDescription: Calculate permutations

description: Calculate permutations


code:
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
from govcrawl.spiders.simple_spider import DomainSimpleSpider
import urlparse, re
from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor

start_url = ...
url_parts = urlparse.urlparse(start_url)
allowed_domain = url_parts.netloc
allowed_path = '/'.join(url_parts.path.split('/')[:-1])

spider = DomainSimpleSpider(
   start_urls = [start_url],
   allowed_domains = [allowed_domain],
   allow = re.compile(r".*%s.*" % re.escape(allowed_path), re.IGNORECASE),
   tags = ('a', 'area', 'frame'),
   attrs = ('href', 'src'),
   response_type_whitelist = [r"text/html", r"application/xhtml+xml", r"application/xml"]
)
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal = signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start()
reactor.run()

rawDescription: CrawlSpider fails to follow rule for some websites


code: t.replace(day=1) < f.replace(day=1)

rawDescription: Determine larger month, ignoring the day


code: return getResponse()

rawDescription: Python array behaving weirdly

description: Python array behaving weirdly


code: wb2s1.append({'A' : 'This is A1', 'C' : 'This is C1'})

rawDescription: Openpyxl to write in a single cell

description: Openpyxl to write in a single cell


code:
idx = myDictBefore['a'].index(2)
myDictBefore['a'].pop(idx)
myDictBefore['b'].pop(idx)

rawDescription: Python 2.7.9 dictionary find and delete

description: Python 2.7.9 dictionary find and delete


code:
seen[:] = [item for item in seen
           if sum(1 for k in maxx if item==k.f) >= 3]

rawDescription: PYTHON - 'for' index changing because of list.pop() call


code:
import csv
from collections import OrderedDict

file = open('example.csv', mode='r')

csvReader = csv.reader(file)

# get rid of header row
header = next(csvReader)
# print(header)

odict = OrderedDict()
for row in csvReader:
    odict[row[0]] = row[1:]
    # print(row)

print(odict)

rawDescription: Creating an OrderedDict from a csv file

description: Creating an OrderedDict from a csv file


code:
a = np.array((0, 1))
b = np.array((2, 1))
c = np.array((-1, -1))
numpy.column_stack((a,b,c))

rawDescription: Concatenating column vectors using numpy arrays


code:
d = dict(re.findall(r'([A-Za-z]+) = (\S+)', s))
d['LogonType']

rawDescription: Python - Searching file lines for multiple patterns efficiently


code: '{:<{width}}'.format('Hello World!', width = 20)

rawDescription: How to make specific parts of a text line indented properly?

description: Make specific parts of a text line indented properly


rawDescription: How to zoom out of page using python selenium

description: Zoom out of page using python selenium


code:
class Sprite(object):
    """simple base class for visible game objects
    pygame.sprite.Sprite(*groups): return Sprite

    The base class for visible game objects. Derived classes will want to
    override the Sprite.update() and assign a Sprite.image and
    Sprite.rect attributes.  The initializer can accept any number of
    Group instances to be added to.

    When subclassing the Sprite, be sure to call the base initializer before
    adding the Sprite to Groups.
    """

    def __init__(self, *groups):
        self.__g = {} # The groups the sprite is in
        if groups: self.add(groups)

    def add(self, *groups):
        """add the sprite to groups
        Sprite.add(*groups): return None

        Any number of Group instances can be passed as arguments. The
        Sprite will be added to the Groups it is not already a member of.
        """
        has = self.__g.__contains__
        for group in groups:
            if hasattr(group, '_spritegroup'):
                if not has(group):
                    group.add_internal(self)
                    self.add_internal(group)
            else: self.add(*group)

    def remove(self, *groups):
        """remove the sprite from groups
        Sprite.remove(*groups): return None

        Any number of Group instances can be passed as arguments. The Sprite will
        be removed from the Groups it is currently a member of.
        """
        has = self.__g.__contains__
        for group in groups:
            if hasattr(group, '_spritegroup'):
                if has(group):
                    group.remove_internal(self)
                    self.remove_internal(group)
            else: self.remove(*group)

    def add_internal(self, group):
        self.__g[group] = 0

    def remove_internal(self, group):
        del self.__g[group]

    def update(self, *args):
        """method to control sprite behavior
        Sprite.update(*args):

        The default implementation of this method does nothing; it's just a
        convenient "hook" that you can override. This method is called by
        Group.update() with whatever arguments you give it.

        There is no need to use this method if not using the convenience
        method by the same name in the Group class.
        """
        pass

    def kill(self):
        """remove the Sprite from all Groups
        Sprite.kill(): return None

        The Sprite is removed from all the Groups that contain it. This won't
        change anything about the state of the Sprite. It is possible to continue
        to use the Sprite after this method has been called, including adding it
        to Groups.
        """
        for c in self.__g.keys():
            c.remove_internal(self)
        self.__g.clear()

    def groups(self):
        """list of Groups that contain this Sprite
        Sprite.groups(): return group_list

        Return a list of all the Groups that contain this Sprite.
        """
        return self.__g.keys()

    def alive(self):
        """does the sprite belong to any groups
        Sprite.alive(): return bool

        Returns True when the Sprite belongs to one or more Groups.
        """
        return (len(self.__g) != 0)

    def __repr__(self):
        return "<%s sprite(in %d groups)>" % (self.__class__.__name__, len(self.__g))

rawDescription: Understand object orientated python - initialization of objects in pygame


code:
def deep_list(self):
    """fully copies trees of tuples to a tree of lists.
       deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]"""
    if type(self.x)!=type( () ):
        return self.x
    return map(deep_list, self.x)

rawDescription: Python calling map() with 'self'

description: Python calling map() with 'self'


code:
"""An application that maps from XML to the domain object
using a configurable "builder".
"""
import model
import source
import builder_1
import builder_2
import builder_today

# Configure this:  pick a builder is appropriate for the data:
b= builder_today.MyTargetBuilder()

s= source.SSXML_Source( sys.argv[1] )
for r in s.rows():
    data= b.makeFromXML( r )
    # ... persist data with a DB save or file write

rawDescription: Which language is easiest and fastest to work with XML content?


code:
with open('file.srt') as subs, open('outfile.srt', 'w') as out:
    for line in subs:
        if not line.startswith(u'\u266a'):
            out.write(line)

rawDescription: Detecting "♪" in String

description: Detecting "♪" in String


code:
# base.txt
somelib1
somelib2

rawDescription: Conditionally installing importlib on python2.6


code:
def alphagen(n=27):
    if n<0 or n > 27: n = 27
    for i in range(n):
        yield chr(ord('A') + i)

rawDescription: Is there a way to subclass a generator in Python 3?


code:
formatter = "{:06d}".format
[formatter(item) for item in data]

rawDescription: add leading zeros to a list of numbers in Python

description: Add leading zeros to a list of numbers in Python


code:
import foo
foo.module_method()
foo.ModClass.static_method()
foo.ModClass.class_method()
instance = ModClass()
instance.instance_method()

rawDescription: In Python how do I use a class method without passing an instance to it?


code: dict(zip(func.func_code.co_freevars, (c.cell_contents for c in func.func_closure)))

rawDescription: How to map func_closure entries to variable names?

description: Map func_closure entries to variable names


code:
# Wait 0 milliseconds
cv2.waitKey(0)

rawDescription: How do can I use OpenCV imshow to display the most recent image in a loop without keyboard feedback


code:
expr = r"\$(word\d)\$(?:, \$(word\d)\$)*"
c = re.compile(expr, re.DEBUG)

rawDescription: python match only captures first and last group - am I misunderstanding something?

description: Python match only captures first and last group - am I misunderstanding something


rawDescription: How to insert and select greek words in mysqldb

description: Insert and select greek words in mysqldb


code:
class SubThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True # Makes the thread a daemon thread
        ...

rawDescription: How to force main thread to close if a sub thread is alive in python?

description: Force main thread to close if a sub thread is alive in python


code:
with open('badwords.txt','r') as f:
   pat='(?i)'+'|'.join(fnmatch.translate(badword)[:-1] for badword in
                       f.read().splitlines())

rawDescription: batch search and replace strings in filenames with python

description: Batch search and replace strings in filenames with python


code:
@lru_cache_class(maxsize=32)
class C2(object):
    def __init__(self, num):
        self.num = num

rawDescription: Unique representations of Python objects


code: rev = {v:k for k,vs in dict1.iteritems() for v in vs}

rawDescription: Comparing multiple dictionaries and generating another dictionary using python


code: crypto.dump_certificate(type, cert)

rawDescription: PyOpenSSL convert certificate object to .pem file


code:
id, provider_id, title = row[0], row[2], row[4]
cursor.execute("INSERT INTO vendor_id VALUES (%s, %s, %s)", id, provider_id, title)

rawDescription: Add SQL variables in through MySQLdb

description: Add SQL variables in through MySQLdb


code: c = dict((k, a[k]/v) for k,v in b.iteritems())

rawDescription: pythonic way to match dictionaries

description: Pythonic way to match dictionaries


code:
def make_names(*args):
    return map(" ".join, zip(*args))

rawDescription: combining and looping through lists python

description: Combining and looping through lists python


rawDescription: Checking if a tuple is in range

description: Checking if a tuple is in range


code:
M = len(A)
C = np.empty(M)
for i in xrange(M):
    C[i] = (A <= A[i]).dot(B)

rawDescription: Efficient 1D array comparison, scaling and summation


code:
color = wx.NamedColour("orange")

some_window.SetForegroundColour("orange")

rawDescription: How to use named colors in wxpython?

description: Use named colors in wxpython


rawDescription: python: converting list into string, adding ',' only when '|' is not around

description: Python: converting list into string, adding ',' only when '|' is not around


code: r, g, b = np.rollaxis(n_test, axis=-1)

rawDescription: finding colors in Image and redraw on second image(using numpy)

description: Finding colors in Image and redraw on second image(using numpy)


code:
import request
from requests.auth import HTTPBasicAuth
proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
}
auth = HTTPBasicAuth("appuser", "apppass")
a = 4
b = 5
data = {"a": a, "b": b}
url = "http://example.com/formaction/url"
req = requests.post(url, data=data, proxies=proxies, auth=auth)

rawDescription: Login, Navigate and Retrieve data behind a proxy with Python


code: figure(figsize=(xsize,ysize))

rawDescription: Boxplots in matplotlib - Making room for the text


rawDescription: Python sort list of lists / ascending and then decending


rawDescription: python 2.7 grab IPs from Source code

description: Python 2.7 grab IPs from Source code


code:
for lab in Labels:
    lab.bind("<Enter>", lambda event, label=lab: changeBGEnter(label))
    lab.bind("<Leave>", lambda event, label=lab: changeBGLeave(label))

rawDescription: Python Tkinter loop to change button color on Enter and on Leave (python 3.4, Windows 10)


code:
# Python and Gevent
from gevent.pywsgi import WSGIServer
from gevent import monkey
monkey.patch_all() # makes many blocking calls asynchronous

def application(environ, start_response):
    if environ["REQUEST_METHOD"]!="POST": # your JS uses post, so if it isn't post, it isn't you
        start_response("403 Forbidden", [("Content-Type", "text/html; charset=utf-8")])
        return "403 Forbidden"
    start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
    r = environ["wsgi.input"].read() # get the post data
    return r

address = "youraddresshere", 8080
server = WSGIServer(address, application)
server.backlog = 256
server.serve_forever()

rawDescription: How to set up Python server side with javascript client side

description: Set up Python server side with javascript client side


code:
left = pd.DataFrame({'Date': ['date1', 'date2', 'date3'], 'v': [1, 2, 3]})
right = pd.DataFrame({'Date': ['date2']})
joined = pd.merge(left, right, on='Date')

rawDescription: indexing a data frame using multiple date time in Python

description: Indexing a data frame using multiple date time in Python


rawDescription: Get docstring from script by Sphinx

description: Get docstring from script by Sphinx


code:
def eventcateg_detail(request):
        ca = EventTypeCategory.objects.all()
        categories ={}
        for cat in ca:
            if cat.sub_categ_id:

               #Since the ca queryset already contains all items you can use that to get the child category
               category = ca.objects.get(id=cat.sub_categ_id)

               #Add to dictionary. NOTE: If you ever get more than one sub-category
               #you need to build a list of sub-categories before adding it to the dict.
               categories[cat.id] = category.name
        return render(request,"events/categ.html",{ 'obj': ca, 'categ' :categories})

rawDescription: How to access a list and dictionary in same for loop at template level in Django

description: Access a list and dictionary in same for loop at template level in Django


rawDescription: How to make custom overlay Text window (similar to Tool Tip )

description: Make custom overlay Text window (similar to Tool Tip )


code: masked.blit(mask, (0, 0), None, pygame.BLEND_RGBA_MULT)

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


code:
fig.subplots_adjust(bottom=0.25)
ax1 = fig.add_axes([0.05, 0.10, 0.9, 0.1])
norm = mpl.colors.Normalize(vmin=dz.min(), vmax=dz.max())
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=mpl.cm.cool,
                               norm=norm,
                               orientation='horizontal')

rawDescription: generating custom colorbar: match data with color scheme

description: Generating custom colorbar: match data with color scheme


code: df.query('col not in [@pd.NaT]')

rawDescription: pandas query None values

description: Pandas query None values


code: scipy.linalg.block_diag( matrix_list[ii] for ii in  range(len(matrix_list)) )

rawDescription: Using linalg.block_diag for variable number of blocks