code: new = [i + ' ' + str(f.count(i)) for i in f]

rawDescription: How to count characters in a file and print them sorted alphanumerically

description: Count characters in a file and print them sorted alphanumerically


code:
seen = set()
seen_add = seen.add
[[x for x in lst if x not in seen and not seen_add(x)] for lst in L]

rawDescription: Need an order preserve nested list duplicate remover


rawDescription: Python: Ordering partial elements in List for Genetic Algorithm


code:
from timeit import default_timer as tc
import numpy as np
import sympy as sy
from numpy.polynomial.polynomial import polyval2d as P2

def using_poly(coefficient_matrix, S=sy.S):
    order = coefficient_matrix.shape[0]
    x = sy.Symbol('x')
    y = sy.Symbol('y')
    dct = {i:S(val) for i, val in np.ndenumerate(coefficient_matrix)}
    z = sy.Poly(dct, x, y)
    return z

def using_loop(coefficient_matrix):
    order = coefficient_matrix.shape[0]
    coefficient_matrix = coefficient_matrix.T.ravel()[::-1]
    order_x = order
    order_y = order
    deg_x = order - 1
    deg_y = order - 1
    x = sy.Symbol('x')
    y = sy.Symbol('y')
    z = 0
    for i2 in range(order_y):
        for i3 in range(order_x):
            z = z + coefficient_matrix[i3 + order_x*i2]*(x**(deg_x - i3))*(y**(deg_y - i2))
    return z

def using_P2(coefficient_matrix):
    x = sy.Symbol('x')
    y = sy.Symbol('y')
    z = P2(x, y, coefficient_matrix)
    # make the polynomial a logical sequence of monomials
    z = sy.expand(z)
    return z

order = 33
np.random.seed(2015)
coefficient_matrix = np.random.rand(order, order)
# coefficient_matrix = np.arange(1, order*order+1).reshape(order,order)

for func in (using_loop, using_P2, using_poly):
    t0 = tc()
    func(coefficient_matrix)
    t1 = tc()
    print('{:15s}: {:>5.2f}'.format(func.__name__, t1-t0))

rawDescription: Faster way to attach 2d polynomial coefficients to terms in Python?


code:
d = defaultdict(list)

for (name, rol), total_exp_inthisRole in employeeExp.items():
    d[name].append(rol, total_exp_inthisRole)

rawDescription: Using python groupby or defaultdict effectively?


code:
('FlyMatchedOutput', [1, 2, 3])
('FlyMatchedOutput', [2, 3, 4])
('FlyMatchedOutput', [1, 2, 3])
('FlyNotMatchedOutput', [2, 3, 4])

rawDescription: Python - If any element in list is in line


code:
class A(Base):
    __tablename__ = 'table_A'
    id = Column(Integer, primary_key=True)
    a = Column(String(32), index=True)
    b = Column(String(32), index=True)

rawDescription: Multiple columns index when using the declarative ORM extension of sqlalchemy


code:
from StringIO import StringIO
s = StringIO("""men peter123 the pants are too tight for my liking!
kids georgel i really like this toy, it keeps my kid entertained for days! It is affordable and comes on time, i strongly recommend it
health kksd1 the health pills is drowsy by nature, please take care and do not drive after you eat the pills
office ty7d1 the printer came on time, the only problem with it is with the duplex function which i suspect its not really working""")

for line in s:
    category, user, review = line.split(None, 2)
    print ("category: {} - user: {} - review: '{}'".format(category,
                                                           user,
                                                           review.strip()))

rawDescription: Parsing txt file in python where it is hard to split by delimiter


code:
import matplotlib.pyplot as plt
lines = plt.plot([1,2,3],[4,5,6],[7,8],[9,10])
lines[0].get_data()
lines[1].get_data()

rawDescription: Retrieve XY data from matplotlib figure

description: Retrieve XY data from matplotlib figure


code:
class X:
    def __init__(self, nowfunc=datetime.now):
        self._nowfunc = nowfunc

def next_date(self):
    now = self._nowfunc()
    ...

rawDescription: How to test methods that compute relative time in python using unitttest?

description: Test methods that compute relative time in python using unitttest


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

with named_pipe() as path:
    trim = Popen(["sox", path, '-t', 'wav', 'out.wav', 'trim', '0.0', '3.0'])
    check_call(["sox", "input.wav", path, "pad", "0.0", "3.0"]) # pad
rc = trim.wait()

rawDescription: Wait for external program to finish writing to file


code:
TOTAL_TIME: 2.252639
CONNECT_TIME: 0.331571
PRETRANSFER_TIME: 0.331634
STARTTRANSFER_TIME: 0.638206

rawDescription: Getting DNS resolution time and response time with Python


code:
from example import *
x = factory()
type(x)
consumer(x)

rawDescription: boost python explicit typecast needed

description: Boost python explicit typecast needed


code:
import wx
import sys
import threading

def post():
    a = 0
    for stop in range(100):
        a = (a + 1) % 10
        data = str(a) * 1000 + " <END>"
        print(data)
    for i, line in enumerate(frame.monitor.Value.split("\n")[:-1]):
        if not line.endswith(" <END>"):
            print("Invalid line %d" % (i+1))

class Redirect:
    def __init__(self, ctrl):
        self.out = ctrl

    def write(self, string):
        wx.CallAfter(self.out.AppendText, string)

class GUI(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.monitor = wx.TextCtrl(self, wx.ID_ANY, style = wx.TE_MULTILINE | wx.TE_READONLY)
        redir = Redirect(self.monitor)
        sys.stdout = redir

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.monitor, 1, wx.GROW | wx.ALL)
        self.SetSizer(self.sizer)
        self.Show(True)

if __name__ == "__main__":
    app = wx.App(False)
    frame = GUI(None)
    t = threading.Thread(target=post)
    t.start()
    app.MainLoop()

rawDescription: wxPython: CallAfter(AppendText,string) does not print entire string

description: WxPython: CallAfter(AppendText,string) does not print entire string


code: col.aggregate([{"$project": { "item1": 1, "is_subset": { "$setIsSubset": [ ['a', 'b', 'c'], "$item1" ] }}},{"$match": {"is_subset": True}}])

rawDescription: mongo - find items who at least match an array of values

description: Mongo - find items who at least match an array of values


code:
df = pd.DataFrame( { "grp" : np.repeat( np.arange(1000), 100 ),
                     "x"   : np.random.randn(100000)           } )

rawDescription: How to be a faster Panda with groupbys

description: Be a faster Panda with groupbys


code:
def countzero(fname):
    try:
        with open(fname) as f:
            return sum(line.strip() == '0' for line in f)
    except IOError:
        # not a file we can read
        return None

rawDescription: Search within a file in python

description: Search within a file in python


code:
from django.db import models
model = models.get_model('timeapp', 'Employee')
dep_field = model._meta.get_field_by_name('department')
dep_field[0].rel.field_name
dep_field[0].rel.to

rawDescription: How to introspect django model fields?

description: Introspect django model fields


code:
def get_schedules_with_retries(callable, max_retry_count = 3):
  retry_count = 0
  while retry_count < max_retry_count:
    schedules = get_more_raw_schedules()
    try:
      callable(schedules)
    except:  # Note: could filter types, bind name etc.
      traceback.print_exc()
    if schedules.count > 0:
      break
    else:
      retry_count+=1
  return schedules

get_schedules_with_retries(lambda schedules: single_expression)

def more_complex_function(schedules):
  pass # do another thing here
get_schedules_with_retries(more_complex_function)

rawDescription: How could I pass block to a function in Python which is like the way to pass block in Ruby


code:
data = {i: np.loadtxt(lines[i * n + 1: n * (i + 1)], dtype=float)
    for i in xrange(blocks)}

rawDescription: How to read different parts or blocks of a file with numpy

description: Read different parts or blocks of a file with numpy


code: call("pip install psycopg2",shell=True)

rawDescription: install dependency in Bitnami Odoo Stack

description: Install dependency in Bitnami Odoo Stack


code:
formula = mycell.input_value
formula
lst = formula.split('"')
lst[1], lst[3]

rawDescription: Retrieve value of links from Google Sheet?


code:
class MiscQuestionForm(BootstrapForm):

    def __init__(self, *args, **kwargs):
        misc = kwargs.pop('misc')
        super(MiscQuestionForm, self).__init__(*args, **kwargs)

        for question in misc:
            if question.answer_type == 1:  # bool
                self.fields['custom_%s' % question.pk] = forms.BooleanField(
                        label=question, required=True)
            else:  # textfield
                self.fields['custom_%s' % question.pk] = forms.CharField(
                        label=question, widget=forms.Textarea,
                        required=True)

rawDescription: Can I pass a variable into a form while declaring it in a view in Django

description: Pass a variable into a form while declaring it in a view in Django


rawDescription: Convert a list of elements in a string

description: Convert a list of elements in a string


code: i,j = np.where( a==value )

rawDescription: Index of element in Numpy array

description: Index of element in Numpy array


code:
# First figure out where the array is zero
zindex = numpy.where(temp_board == 0)
# Make a set of tuples out of it
zindex = set(zip(*zindex))
# Make a set of tuples from indices_to_watch too
indices_to_watch = set([(0,1), (1,2)])
# Find the intersection.  These are the indices that need to be set
indices_to_set = indices_to_watch & zindex
# Set the value
temp_board[zip(*indices_to_set)] = level

rawDescription: Numpy masked array modification

description: Numpy masked array modification


code:
while os.path.dirname(path) != '/':
    path = os.path.dirname(path)

path

rawDescription: Python: Get URL path sections

description: Python: Get URL path sections


code: re.sub(r'\\sum ([\d,]+) \\end', lambda m: str(add(m.group(1))), text)

rawDescription: Replace all occurrences of a regexp group after processing the strng in the group


code:
#web2py_controller.py

def run_echo():
    proc_srvr = xmlrpclib.ServerProxy("http://localhost:12345")
    proc_srvr.echo_fn()

rawDescription: Unable to open a Python subprocess in Web2py (SIGABRT)


code:
import subprocess
import re

lsblk = subprocess.Popen(['lsblk'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in lsblk.stdout:
    if 'disk' in line:
        parts = re.split(r'\s+', line.strip())
        name, majmin, rm, size, ro, devtype = parts[:6]
        if len(parts) > 6:
            mountpoint = parts[6]
        else:
            mountpoint = None
        print(majmin)
returncode = lsblk.wait()
if returncode:
    print("things got bad. real bad.")

rawDescription: Capture bash output in a python array

description: Capture bash output in a python array


rawDescription: Properly extract data from JSON string

description: Properly extract data from JSON string


code:
with open('csv1.csv') as csv1:
    print(read_csv(csv1))

rawDescription: Merge three csv files with same headers in Python


code:
import re

text = 'gfgfdAAA1234ZZZuijjk'

try:
    found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '' # apply your error handling

# found: 1234

rawDescription: how to extract a substring from inside a string in Python?

description: Extract a substring from inside a string in Python


code: np.sqrt((X * X).sum(axis=1))

rawDescription: Normalizing rows of a matrix python

description: Normalizing rows of a matrix python


code:
if some_thing: # don't do anything
    pass
else:
    some_thing = some_thing_else

rawDescription: Output Daffodils-Numbers with python

description: Output Daffodils-Numbers with python


code:
from django import forms
from myproject.formfields import ChoiceField

NAMES = (
    ('brad', 'Brad'),
    ('sam', 'Sam'),
)

class MyForm(forms.Form):
    names = ChoiceField(choices=NAMES, blank_choice='Please choose:')

rawDescription: Showing "Please choose:" in a Django's `Select` widget


code:
if grab_lines: #in python 'is True' is implicit for many types.
    line = [line.split()[0]]+[str(float(element)*.529) for element in line.split()[1:]]+['\n']
    molecule_data.append('\t'.join(line))

rawDescription: How to extract data from a text file with python script?

description: Extract data from a text file with python script


rawDescription: Disablling scrolling of a scroll bar while keeping it visible in wxPython


rawDescription: Check if all elements of one array is in another array


code:
words = collections.Counter([word for line in open(filepath) for word in line.strip()])
words = dict((k,v) for k,v in words.iteritems if len(k)>=2)
mostFrequent = [w[0] for w in words.most_common(10)]
leastFrequent = [w[0] for w in words.most_common()[-10:]]

rawDescription: Retrieving total number of words with 2 or more letters in a document using python


code:
t = '08:00-18:00'
times = t.split('-')
start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
if start_time <= datetime.datetime.now().time() < end_time:
        print("Shop open")

rawDescription: Check if current current hour is available in python list


rawDescription: pandas how to convert a dataframe into a dictionary of tuples tuple using 1 col as key and the rest as a tuple of form (col2:col3)

description: Pandas how to convert a dataframe into a dictionary of tuples tuple using 1 col as key and the rest as a tuple of form (col2:col3)


code:
def same_structure(a, b):
    if isinstance(a, list) and isinstance(b, list) and len(a) == len(b):
        return all(same_structure(A, B) for A, B in zip(a, b))
    return (not isinstance(a, list) and not isinstance(b, list))

rawDescription: How to properly use recursion in this (simple) python procedure?

description: Properly use recursion in this (simple) python procedure


rawDescription: Trying to determine the "height" of organisms Using Python Code


code: self.fig = Figure(figsize=(5,5), dpi=100)

rawDescription: Matplotlib animation inside your own PyQt4 GUI


code:
i = len(l) - 1
jIndex = (i - 1) % len(l)
kIndex = (i + 1) % len(l)

j = l[jIndex]
k = l[kIndex]

rawDescription: Pythonic Circular List

description: Pythonic Circular List


rawDescription: Using a loop to make a dictionary

description: Using a loop to make a dictionary


rawDescription: Filtering in Django by a set of String

description: Filtering in Django by a set of String


code:
import multiprocessing
import time
import os

def f(x):
    print("PID: %d" % os.getpid())
    time.sleep(x)
    complex_obj = 5 #more complex axtually
    return complex_obj

if __name__ == '__main__':
    multiprocessing.set_start_method('spawn')
    pool = multiprocessing.Pool(4, maxtasksperchild=1)
    pool.map(f, [5]*30, chunksize=1)
    pool.close()

rawDescription: multiprocessing.Pool with maxtasksperchild produces equal PIDs

description: Multiprocessing.Pool with maxtasksperchild produces equal PIDs


rawDescription: Pandas DataFrame.groupby including index


rawDescription: Data transformation for machine learning


code:
s1 = "William"
subs = {'i': 'eye'}
s2 = ''.join(subs.get(c, c) for c in s1)
print(s2)

rawDescription: Replacing a letter with a word

description: Replacing a letter with a word


rawDescription: Remove non-GtkListBoxRow parent from GtkListBox


code:
s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
    sys.stdout.write(line)

rawDescription: Python - Comparing two CSV documents from the same python script from an update to another one


code:
MyTestCase.setUpClass
One
MyTestCase2.setUpClass
Three
MyTestCase.setUpClass
Two

rawDescription: Is it unconventional to override unittest.TestCase's init in Python


code:
masked_a = np.ma.masked_invalid(a)

result2 = masked_a * b

rawDescription: Numpy: multiplying with NaN values without using nan_to_num


code:
[...]
t = loader.get_template('sometemplate.html')
c = Context({
    'my_data': my_data, # or whatever
})
return t.render(c) # this gets inserted into the invoking template

rawDescription: Abstract Django Application from "Project"


code:
@app.route('/_stuff', methods= ['GET'])
def stuff():
    cpu=round(getCpuLoad())
    ram=round(getVmem())
    disk=round(getDisk())
    return jsonify(cpu=cpu, ram=ram, disk=disk)

rawDescription: Flask : How to update and render a variable periodically?


code:
for i in range (1,18):
   if os.path.isfile("galmasksciPHOTOf105w"+str(i)+".fits") and os.path.exists("fittedsciPHOTOf105w"+str(i)+".fits"):
       img1= pf.getdata("galmasksciPHOTOf105w"+str(i)+".fits")
       img2= pf.getdata("fittedsciPHOTOf105w"+str(i)+".fits")
       img3=(img2)[2]
       newimg=img1/img3
       pf.writeto("dividedsciPHOTOf105w"+str(i)+".fits",newimg, clobber=True)

rawDescription: Ignoring a missing file in a for loop- Python


code: grid1D[dist] = 0

rawDescription: scipy -- how to insert an array of zeros into another array with different dimensions

description: Scipy -- how to insert an array of zeros into another array with different dimensions


code: map(None, *result)

rawDescription: Python list rearranging

description: Python list rearranging


rawDescription: Is this entity definition model too verbose?


code:
from nltk.probability import UniformProbDist as U
UD=U([1,2,3,4])

rawDescription: How to use Python nltk's ProbDistI class

description: Use Python nltk's ProbDistI class


code:
import itertools
import math

def iden(x):
    return x

def log(x):
    return math.log(x)

def exp(x):
    return 1/(1+math.exp(-x))

X = [1, 2, 3]
funcs = [iden, log, exp]

def apply(functions, values):
    return [func(val) for func,val in zip(functions, values)]

values = [apply(f, X) for f in itertools.product(funcs, repeat=len(funcs))]

rawDescription: Get all combinations of list multiple arrays


code:
for f in sorted(fruitList):
    print(f)

rawDescription: How to use for and while loop to sort in alphabetical order using python?

description: Use for and while loop to sort in alphabetical order using python


code:
dict1 = {'a':(1, 4, 7), 'b':(2, 5, 8), 'c':(3, 6, 9)}
{x:tuple(z for z in y for _ in xrange(2)) for x,y in dict1.iteritems()}

rawDescription: duplicating values in a certain way inside a list inside a dictionary

description: Duplicating values in a certain way inside a list inside a dictionary


code:
from scipy import stats
kld = stats.entropy(distributions.T[:,:,None], distributions.T[:,None,:])

rawDescription: Efficient way of computing Kullback–Leibler divergence in Python


code:
eth1 = [ethrema(w) for w in text]
#AND
eth2 = [ethremb(w) for w in text]

rawDescription: Transforming early modern English into 20th century spelling using the NLTK


code:
df.join(df["B"].apply(lambda fruit : pd.Series([url for url in
                     search(fruit, stop=stop, pause=2.0)][:stop])))

rawDescription: Pandas: Iterate on a column one row at a time to automate a google search?


code: output = subprocess.check_output(['/usr/bin/python2', 'scriptInV2.7.py', '-arg1', '-arg2'])

rawDescription: Using subprocess with script using another version


code:
import pandas as pd
import numpy as np
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()
r = robjects.r
r.library("randomForest")
r.library("caret")

def convert_factor(obj):
    """
    Taken from jseabold's PR: https://github.com/pydata/pandas/pull/9187
    """
    ordered = r["is.ordered"](obj)[0]
    categories = list(obj.levels)
    codes = np.asarray(obj) - 1  # zero-based indexing
    values = pd.Categorical.from_codes(codes, categories=categories,
                                       ordered=ordered)
    return values

df = pd.DataFrame(data=np.random.rand(100, 10),
                  columns=["a{}".format(i) for i in range(10)])
df["b"] = ['a' if x < 0.5 else 'b' for x in np.random.sample(size=100)]
train = df.ix[df.a0 < .75]
withheld = df.ix[df.a0 >= .75]

rf = r.randomForest(robjects.Formula('b ~ .'), data=train)
pr = convert_factor(r.predict(rf, withheld))

withheld['pr'] = pr
print(withheld)

rawDescription: Rpy2 and Pandas: join output from predict to pandas dataframe


code:
file_list = drive.ListFile({'q': "title='hello.doc' and trashed=false"}).GetList()
if len(file_list) == 1:
    file = file_list.next()
updated_content = file.GetContentString() + "New content"
file.SetContentString(updated_content)
file.Upload()

rawDescription: Google Drive SDK: I want to update a file, not create new one


code: df.rename(columns=lambda x: int(x[1:]))

rawDescription: Renaming columns in pandas dataframe using regular expressions


code:
from StringIO import StringIO
mytext='''%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7'''

myfile=StringIO(mytext)
mydict={}
for x in myfile.readlines():
    if x.startswith('%'):
        mydict.setdefault(x.strip('%').strip(),[])
        lastkey=x.strip('%').strip()
    else:
        mydict[lastkey].append([int(x1) for x1 in x.split(' ')])

rawDescription: smart way to read multiple variables from textfile in python

description: Smart way to read multiple variables from textfile in python


rawDescription: Pythonic way of calculating A x A' (without numpy)


code:
from shapely.geometry import LineString

line1 = LineString([(0,0), (1,0), (1,1)])
line2 = LineString([(0,1), (1,1)])

print(line1.intersection(line2))

rawDescription: How do I find the intersection of two line segments?

description: Find the intersection of two line segments


code:
l = [+3, +4, -7, -5]
[reduce(lambda x, y: x + y, l[:i+1]) for i in range(len(l), 10)]

rawDescription: Are there any analogues in the standard library?


rawDescription: python regex string split

description: Python regex string split


rawDescription: Dealing with floating points: With numpy python in particular


rawDescription: Python like Ruby inheritance

description: Python like Ruby inheritance


rawDescription: Change set of indices

description: Change set of indices


code:
import pandas as pd
import numpy as np
np.random.seed(2016)

df = pd.DataFrame({'Group': ['A', 'C', 'B', 'A', 'C', 'C'],
                   'ID': [1, 2, 3, 4, 5, 6],
                   'Value': np.random.randint(1, 100, 6)})

grouped = df.groupby('Group')
values = grouped['Value'].agg('sum')
id_df = grouped['ID'].apply(lambda x: pd.Series(x.values)).unstack()
id_df = id_df.rename(columns={i: 'ID{}'.format(i + 1) for i in range(len(id_df))})
result = pd.concat([id_df, values], axis=1)
print(result)

rawDescription: Pandas groupby result into multiple columns


code:
years = (2012, 2013)
months = range(1,13)
data = {'search': u'Hľadanie'}
for y in years:
        for m in months:
                days = cal.monthrange(y,m)[1]
                data['days'] = str(days - 1)
                data['data'] = dt.date(y,m,days).isoformat()

rawDescription: Scraping historic data with Python from a specific website - table created out of a form with many rows with isolated header. Automation needed


code:
plt.plot( absc, US )

plt.plot( absc, EastCst )
plt.plot( absc, NewEng, '#251BE0' )
plt.plot( absc, EastCst, '#1BE0BF' )
plt.plot( absc, CenAtl, '#E0771B' )
plt.plot( absc, LwrAtl, '#CC1BE0' )
plt.plot( absc, Midwst, '#E01B8B' )
plt.plot( absc, GulfCst, '#E01B3F' )
plt.plot( absc, RkyMt )
plt.plot( absc, WCst )
plt.plot( absc, CA )

plt.legend( ('US', 'EastCst', 'NewEng' , 'EastCst', 'CenAtl', 'LwrAtl', 'Midwst', 'GulfCst', 'RkyMt', 'WCst', 'CA')  )
plt.title('Diesel price')
locs,labels = plt.xticks(absc, dates)
plt.show()

rawDescription: Extract information from Gmail with Python


code: list([y[0] for y in x[1]] for x in itertools.groupby(lst, operator.itemgetter(1)))

rawDescription: Group same elements in list python

description: Group same elements in list python


code: str([value1, value2])

rawDescription: Hash values with different data types together?


code:
self.all_rolls = [] #if you dont want to get an empty list each button click, you might want to make this definition under __init__
self.roll = randint(1,6)
self.all_rolls.append(self.roll)
#to use your rolls, you can iterate over that list
for item in self.all_rolls:
   print (item)  #this is just for an example ofcourse

rawDescription: Python Tk: Can't Retrieve Dice Roll Integer for Calculations


code:
def iter_tree_widget(root):
    iterator = QtGui.QTreeWidgetItemIterator(root)
    while True:
        item = iterator.value()
        if item is not None:
            yield item
            iterator += 1
        else:
            break

rawDescription: Qt treewidget python; iterate columns

description: Qt treewidget python; iterate columns


code:
class RedirectText:
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

rawDescription: Printing Scapy output to wxPython Text Controller


code: non_match == ['winter-time|winter|winter season']

rawDescription: Check for Partial Match in 1 List With Partial Match Another List - Possible With List Comprehension?


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d

N = 12
arr = np.arange(N*2).reshape(N,2)
words = np.array(['foo', 'bar', 'baz', 'quux', 'corge'])
df = pd.DataFrame(words[arr % 5], columns=list('XY'))
df['Z'] = np.linspace(1, 1000, N)
Z = np.log10(df['Z'])
Xuniques, X = np.unique(df['X'], return_inverse=True)
Yuniques, Y = np.unique(df['Y'], return_inverse=True)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.scatter(X, Y, Z, s=20, c='b')
ax.set(xticks=range(len(Xuniques)), xticklabels=Xuniques,
       yticks=range(len(Yuniques)), yticklabels=Yuniques)
plt.show()

rawDescription: scatter plots with string arrays in matplotlib

description: Scatter plots with string arrays in matplotlib


rawDescription: Why isn't my dictionary printing correctly?


code:
def accumulate_by_category(word_values, cat_sums, cats):
    """ modify the category sums by adding the values of the given words """
    for word, value in word_values.items():
        for cat in cats[word]:
            cat_sums[cat] += value

rawDescription: Searching a dictionary for a key, adding the value of that key's value to another key value pair


code: words = (w for w in nltk.corpus.brown.words() if re.search(r"\w", w))

rawDescription: NLTK: Find contexts of size 2k for a word


code: alist = numbers.split()

rawDescription: Need help removing duplicates numbers in Python exercise


code:
urls.py
from django.conf.urls import patterns, include, url
from fights.views import FightView, random_fight

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', random_fight, name='home'),
    url(r'^fight/(?P<fight_id>\d+)/$', FightView.as_view(), name='fight_view'),
    url(r'^admin/', include(admin.site.urls)),
)

rawDescription: What Form should I create to display these models?


code:
import re

text = '''
Cat, 5 kg
Dog, 10 kg
Human, 50 kg
'''.strip()

def divide_numbers(s, n):
    def sub(m):
        return str(int(m.group(0))//n)
    return re.sub('[0-9]+', sub, s)

print(divide_numbers(text, 5))

rawDescription: How to scale all numbers in a string while keeping the format the same in Python?

description: Scale all numbers in a string while keeping the format the same in Python


rawDescription: Splitting binary file content in two parts using single byte separator in python


code:
class struct(dict):
    def __getattribute__(self, key):
        return self[key]

s = struct(a=5, b=7)
s.a

rawDescription: Is there an existing Python class that can hold any user attributes?


code:
for d in myjson:
    d['tagnames'] = [tagnames_map[t] for t in tagnames_map.viewkeys() & d['tags']]

rawDescription: Faster way to do a correspondence replace operation in python?


code: names = [prop for prop in dir(self.__class__) if prop[1] != "_"]

rawDescription: Python: How can I get a list of function names from within __getattr__ function?


code:
request.session[ 'type' ] = 'f' #when Freshman is clicked
request.session[ 'type' ] = 's' #when Freshman is clicked

rawDescription: How to handle two versions of the same site

description: Handle two versions of the same site


code:
class Configuration(db.Model):
  _INSTANCE = None

  @classmethod
  def get_instance(cls):
    if not cls._INSTANCE:
      cls._INSTANCE = cls.get_or_insert('config')
    return cls._INSTANCE

rawDescription: What is a good place to store configuration in Google AppEngine (python)


rawDescription: Modifying multidimensional numpy subarrays indexed by lists


code:
def date_range(date1,date2):
    while date1 < date2:
        yield date1
        date1 = date1 + timedelta(days=1)

rawDescription: Finding dates between two dates

description: Finding dates between two dates


code: df = pd.read_csv('data', parse_dates=[0], index_col=[0], dayfirst=True); df

rawDescription: Sorting data in a .csv by month and year and calculating the mean


code: print(format(obj, 'pretty'))

rawDescription: what is the Pythonic way to implement a __str__ method with different format options?

description: What is the Pythonic way to implement a __str__ method with different format options


code:
def Window(self):
    ...
    self.buttons()
    self.button1.grid(row = 0, column = 0, columnspan=2,rowspan=2,pady=5,padx=5)
    ...

rawDescription: Tkinter: How to call a Button from another class method?


code: notdone_df = df[df['Result'] == "Not-Done"]

rawDescription: How to do this pandas group by and count functionality?

description: Do this pandas group by and count functionality


rawDescription: Spark: Using iterator lambda function in RDD map()


code:
import pickle
import os
import multiprocessing

class MyClass:
    ids_list = range(300)
    folder = os.path.join(os.getcwd(), 'app_geo')
    STOP_TOKEN = 'stop queue'

    def main(self):

        # >>> Queue part shared between processes <<<
        manager = multiprocessing.Manager()
        remove_id_queue = manager.Queue()

        remove_id_process = multiprocessing.Process(target=self.remove_id_from_file,
                                                    args=(remove_id_queue,))
        remove_id_process.start()
        # >>> End of queue part <<<

        pool = multiprocessing.Pool(3)

        def kill_pool(err_msg):
            print(err_msg)
            pool.terminate()

        for osm_id in self.ids_list:
            pool.apply_async(self.handle_country_or_region,
                             kwds=dict(country_id=osm_id),
                             error_callback=kill_pool)

        pool.close()
        pool.join()

        # >>> Anti-zombie processes queue part <<<
        remove_id_queue.put(self.STOP_TOKEN)
        remove_id_process.join()
        manager.shutdown()
        # >>> End

    def handle_country_or_region(self, country_id=None, queue=None):
        # here I do some task
        queue.put(country_id)

    def remove_id_from_file(self, some_queue):
        while True:
            osm_id = some_queue.get()
            if osm_id == self.STOP_TOKEN:
                return
            self.ids_list.remove(osm_id)
            with open(self.folder + '/ids_list.pickle', 'wb') as f:
                pickle.dump(self.ids_list, f)

rawDescription: Cant stop\kill all processes at once produced by multiprocessing.Pool


code:
data2indx = data2.index.tolist()
data1tm = data1['timestamp'].tolist()
data2sub = pd.DataFrame(columns = data2.columns)

rawDescription: Return "Iterable" Numbers for Indices in Python Pandas


code:
class Upload(webapp.RequestHandler):
    def post(self):
        image = self.request.get("Filedata")
        photo = Photo()
        photo.imageblob = db.Blob(image)
        photo.put()

rawDescription: Python app engine: how to save a image?

description: Python app engine: how to save a image


code: rows = (buttons + 5) / 6

rawDescription: Mathemmatical formula for incremental breakdowns


code: soup = BeautifulSoup(res.content, 'html5lib')

rawDescription: BeautifulSoup fails to parse html with `html5lib`


code:
for r in all_data.columns.values:
    all_data[r] = all_data[r].map(str)
    all_data[r] = all_data[r].map(str.strip)
tuples = [tuple(x) for x in all_data.values]

rawDescription: how to transform pandas dataframe for insertion via executemany() statement?

description: Transform pandas dataframe for insertion via executemany() statement


rawDescription: How to find exact place for given value in python dictionary?

description: Find exact place for given value in python dictionary


rawDescription: How to append to a custom python Sequence?

description: Append to a custom python Sequence


code:
lsblk = subprocess.Popen(['lsblk'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
blockdevs = [line.strip() for line in lsblk.stdout if 'disk' in line]
returncode = lsblk.wait()
if returncode:
    print("things got bad. real bad.")
print(blockdevs)

rawDescription: Capture bash output in a python array

description: Capture bash output in a python array


code:
set = TimeSet()
set.add(os.path.abspath(os.path.join(src_path, pdf_name)), app.config['PDF_PERSISTENCE'])

rawDescription: Remove old temporary files when user is logged out


code:
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from lxml.html import fromstring

data = """

                    10

                    14

                100

                1

"""

tree = fromstring(data)
for item in tree.xpath("//div[@class='menu-item-prices']/table/tr"):
    prices = [float(price.strip()) for price in item.xpath(".//td[@class='menu-item-price-amount']/text()")]
    print(max(prices))

rawDescription: Use xpath to get maximum value within tables


code: Product.objects.filter(colors__in=[red, blue]) # Red and blue being Color instances

rawDescription: Django filter filter with lists

description: Django filter filter with lists


code:
class band_detail(DetailBand):
    height=0.7*cm
    elements=[
        ObjectValue(attribute_name='jd_job', left=0.1*cm),
        ObjectValue(attribute_name='c_name', left=1.5*cm),
        ObjectValue(attribute_name='clientname', left=5.8*cm),
        ObjectValue(attribute_name='jd_return', left=10.1*cm),
        ObjectValue(attribute_name='jd_delivery', left=12.6*cm),
        ObjectValue(attribute_name='get_j_status1_display', left=15.1*cm),
        ObjectValue(attribute_name='get_j_status2_display', left=17.6*cm),
        ObjectValue(attribute_name='jd_prodref', left=20.1*cm),
        ObjectValue(attribute_name='userformalname', left=23*cm),
        ObjectValue(attribute_name='jd_gross', left=26.7*cm, width=1.7*cm, style={'alignment':TA_RIGHT}, get_value=lambda instance: intcomma(instance.jd_gross)),
        ]
    borders = {'bottom': True}

class band_summary(ReportBand):
    height = 1.7*cm
    elements = [
        Label(text='Records printed:', top=1*cm, left=0.5*cm),
        ObjectValue(expression='count(jd_job)', top=1*cm, left=5.6*cm),
        Label(text="Total Value:", top=1*cm, left=22*cm),
        ]
    borders = {'top': True}

def __init__(self, *args, **kwargs):
    super(JobdetailsReport, self).__init__(*args, **kwargs)

    self.band_page_header.elements += [
        Label(text="Job No.", top=0.8*cm, left=0.1*cm),
        Label(text="Client", top=0.8*cm, left=1.5*cm),
        Label(text="Delivery", top=0.8*cm, left=5.8*cm),
        Label(text="Return", top=0.8*cm, left=10.1*cm),
        Label(text="Delivery", top=0.8*cm, left=12.6*cm),
        Label(text="Physical Status", top=0.8*cm, left=15.1*cm),
        Label(text="Accts Status", top=0.8*cm, left=17.6*cm),
        Label(text="Reference", top=0.8*cm, left=20.1*cm),
        Label(text="Our Contact", top=0.8*cm, left=23*cm),
        Label(text="Gross", top=0.8*cm, left=27*cm),
        ]

    myset = self.queryset
    grosstotal = 0
    for myline in myset:
        if myline.jd_gross:
            grosstotal += myline.jd_gross
    ugrosstotal = intcomma(grosstotal)
    self.band_summary.elements += [
        SystemField(expression=ugrosstotal, top=1*cm, left=26.5*cm, width=1.9*cm, style={'alignment':TA_RIGHT}),
        ]

rawDescription: Python GeraldoReports - Format a summed value with commas


rawDescription: grep a string after pattern match in python

description: Grep a string after pattern match in python


code: re.findall("\s?(" + "[A-Za-z]*[AEIOUaeiou]"*n + "[b-df-hj-np-tv-z]*)", f.read())

rawDescription: Regular expressions Python. Matching words in a text file with 1 or more vowels depending on input?


code:
valid_List=["10.1.2.3","10.2.3.4","10.2.4.5","10.2.3.7"]
filename="abc.txt"

if_found = [False for v in valid_List]

f = open(filename,"r")
lines = f.readlines()
f.close()

f = open(filename,"w")
for line in lines:
    flag = True
    deleted = ''
    for _,i in enumerate(valid_List):
        if line == i+" "+ "ok"+"\n":
            flag = False
            if_found[_] = True
            deleted = i
            break
    if flag:
        #print("Writing ip not to be deleted")
        f.write(line)
    else:
        print(deleted," Deleted")
f.close()

for _,i in enumerate(if_found):
    if not i:
        print(valid_List[_]," Not Found")

rawDescription: Python delete line/lines from file without modifying existing contents


code: [[tuple([ann for ann in word if ann is not None]) for word in sent] for sent in added_annotation_sents]

rawDescription: How to find elements of an array in Python and add more information to it

description: Find elements of an array in Python and add more information to it


code:
1 and 'bar'
bool(1 and 'bar')

rawDescription: Python - Interesting boolean and string behavior


code:
for i in range(1, len(tuple_grps)+1):
    for xs in itertools.combinations(tuple_grps, i):
        for ys in itertools.product(*xs):
            print(ys)

rawDescription: Python combinations no repeat by constraint


rawDescription: How to set the ticks on a logarithmic axis in matplotlib

description: Set the ticks on a logarithmic axis in matplotlib


code:
def draw_button2():
    pylab.figure()
    a = pylab.axes([0.1, 0.1, 0.8, 0.8])
    b = Button(a, 'Button 2')
    b.on_clicked(draw_button1)
    pylab.show()
    return b

b = draw_button2()

rawDescription: Button does not work in second (nested) figure


code:
myfile = open("readnwrite.txt", "r+")
myfile.write("This should be at the top of the file now.")
myfile.close()

rawDescription: Opening and reading txt files

description: Opening and reading txt files


code: request.session['content'] = content

rawDescription: django - how to implement a 2-step publish mechanism

description: Django - how to implement a 2-step publish mechanism


code:
#!/usr/bin/env python3

# standard includes
import sys

# dbus includes
import gi.repository.GLib
import dbus
import dbus.service
import dbus.mainloop.glib

# project includes
import common

class EchoServerObject(dbus.service.Object):

    # TODO it would be nice to make a better decorator using annotations:
    #   def foo(self, a: 's', b: 's') -> '': pass
    # but the existing dbus decorator does its own reflection which
    # fails if there are any annotations (or keyword-only arguments)
    @dbus.service.method(common.ECHO_INTERFACE,
            in_signature='s', out_signature='')
    def echo(self, message):
        message = str(message) # get rid of subclass for repr
        print('server: a client said %r' % message)

    @dbus.service.method(common.QUIT_INTERFACE,
            in_signature='', out_signature='')
    def quit(self):
        # this should be a separate object, but I'm
        # showing how one object can have multiple interfaces
        self.mainloop.quit()

def stop():
    bus = dbus.SessionBus()

    proxy = bus.get_object(common.ECHO_BUS_NAME, common.ECHO_OBJECT_PATH)
    iface = dbus.Interface(proxy, common.QUIT_INTERFACE)

    iface.quit()

def server():
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    bus = dbus.SessionBus()
    try:
        name = dbus.service.BusName(common.ECHO_BUS_NAME, bus, do_not_queue=True)
    except dbus.NameExistsException:
        sys.exit('Server is already running.')
    else:
        print('Server is not running yet. Putting on listening ears.')
    echo = EchoServerObject(bus, common.ECHO_OBJECT_PATH)

    mainloop = gi.repository.GLib.MainLoop()
    echo.mainloop = mainloop
    mainloop.run()

def main(exe, args):
    if args == ['stop']:
        stop()
    elif not args:
        server()
    else:
        sys.exit('Usage: %s [stop]' % exe)

if __name__ == '__main__':
    main(sys.argv[0], sys.argv[1:])

rawDescription: SImple (but specific) listener and sender Python 3 DBus example


code:
dict3 = dict2.copy()
dict3.update(dict1)

rawDescription: check two dictionaries that have similar keys but different values

description: Check two dictionaries that have similar keys but different values


rawDescription: list of lists to either autovivify or recursive data structure

description: List of lists to either autovivify or recursive data structure


code:
import pprint

data = [{"name":"item.key" , "value":"value"},
   {"name":"item.key2" , "value":"value2"},
   {"name":"item.list.0" , "value":"listValue1"},
   {"name":"item.list.1" , "value":"listValue2"},
   {"name":"item.list.2" , "value":"listValue3"},
   {"name":"item.list2.0.key1" , "value":"list2Key1Value"},
   {"name":"item.list2.0.key2" , "value":"list2Key2Value"},
   {"name":"item.list2.0.key3" , "value":"list2Key3Value"},
   {"name":"item.list3.0.key1" , "value":"list3Key1Value"},
   {"name":"item.list3.0.key2" , "value":"list3Key2Value"},
   {"name":"item.list3.0.key3" , "value":"list3Key3Value"},
   {"name":"other.key" , "value":"otherKeyValue"}]

obj = {}
def addObj(o, path, value):
    if len(path) > 1:
        o = o.setdefault(path.pop(0), {})
        addObj(o, path, value)
    else:
        o[path.pop(0)] = value

for item in data:
    parts = item['name'].split(".")
    addObj(obj, parts, item['value'])

# this function assumes all keys are strings
def convert(obj):
    if isinstance(obj, dict):
        if all(key.isdigit() for key in obj.keys()):
            return [convert(obj[key])
                    for key in sorted(obj.keys(), key=int)]
        return dict((key, convert(value)) for key, value in obj.items())
    return obj

pprint.pprint(convert(obj))

rawDescription: Convert list to nested lists and dicts

description: Convert list to nested lists and dicts


code:
class RegisteredCoursesForm(Form):
    courses = FieldList(FormField(CourseForm), min_entries=10, max_entries=10)
    # Any other fields can go here (e.g., user_id).

rawDescription: Form with multiple identical lines

description: Form with multiple identical lines


code:
def numpy_gcd(a, b):
    a, b = np.broadcast_arrays(a, b)
    a = a.copy()
    b = b.copy()
    pos = np.nonzero(b)[0]
    while len(pos) > 0:
        b2 = b[pos]
        a[pos], b[pos] = b2, a[pos] % b2
        pos = pos[b[pos]!=0]
    return a

rawDescription: Numpy gcd function

description: Numpy gcd function


code:
from scipy.spatial import cKDTree

k = cKDTree(data[:, 6:8]) # creating the KDtree using the Xpos and Ypos

xyCenters = np.array([[200.6, 310.9],
                      [300, 300],
                      [400, 400]])
print(k.query(xyCenters))
# (array([ 1.59740195,  1.56033234,  0.56352196]),
#  array([ 2662, 22789,  5932]))

rawDescription: Finding the correspondence of data from one data set in the other


code:
from collections import Counter
Counter(at_mentions.sum())

rawDescription: Split a Pandas 'findall' result list into multiple items, to group by uniques


code:
from datetime import datetime
import time

last_login_date = datetime.strptime(last_login, "%m/%d/%Y at %H:%M:%S %p")
print(time.mktime(last_login_date.timetuple()))

rawDescription: Using beautifulsoup to extract data that's hard to identify


code:
for old, new in zip(l,ll):
    os.rename(old,new)

rawDescription: Python basic - renaming files

description: Python basic - renaming files


rawDescription: Add Variables to Tuple

description: Add Variables to Tuple


code:
# admin.py
from django.contrib import admin
from .models import StartupType

class StartupTypeAdmin(admin.ModelAdmin):
    def get_ordering(self, request):
        language_code = request.LANGUAGE_CODE[:2]
        return ('name_%s' % language_code,)

admin.site.register(StartupType, StartupTypeAdmin)

rawDescription: Is it possible to order a Django Model using the active language?


code:
import datetime
your_timestamp = 1331856000000
date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

rawDescription: How to convert integer timestamp to Python datetime

description: Convert integer timestamp to Python datetime


code:
a = func(x)      # Assign a
while a:         # Loop while a is True
    # use a
    a = func(x)  # Re-evaluate a

rawDescription: Assignments in conditions

description: Assignments in conditions


code:
import math
sum(n >> i for i in range(int(math.log(n, 2)) + 1))

rawDescription: List comprehension to return the sum of n/2...?


code:
from rpy2.robjects import r
from rpy2.robjects import pandas2ri
def data(name): return pandas2ri.ri2py(r[name])

rawDescription: Are there any example data sets for Python?


code:
class Foo():
    @property
    def bar(self): return 'bar'

foo = Foo()
foo.bar
type(foo).bar

rawDescription: Accessing descriptor instance

description: Accessing descriptor instance


code: apply(blsimpv_, axis=1)

rawDescription: Spreadsheet like functions in pandas

description: Spreadsheet like functions in pandas


code:
class Category(models.Model):
    title = models.ForeignKey(Title, verbose_name="Title", to_field='title')

    class Meta:
        ordering = ['title']

    def __unicode__(self):
        return self.title.title

rawDescription: ForeignKey returns id when editing the form


code:
# initial string
input_string = "123245wkjsvd :/'"
# Convert string to list of characters
list_of_chars = list(input_string)
# Sort list
list_of_chars.sort()
# Convert to string
output_string = ''.join(list_of_chars)

rawDescription: how can i convert a string like 123245wkjsvd :/' to list and sort?

description: Convert a string like 123245wkjsvd :/' to list and sort


rawDescription: Pandas drops timestamp columns in resample


code:
parts = re.split(r'[(|)]', line)
data = parts[0]
values = parts[1:-1]
values

rawDescription: Python: splitting a complex string including parentheses and |


code:
def zip_with_scalar(l, o):
    return ((i, o) for i in l)

rawDescription: Python: zip list with a single element

description: Python: zip list with a single element


code:
d = defaultdict(lambda: [])

for x in DictList:
    s = frozenset((x["name1"], x["name2"]))
    d[s].append(x)

rawDescription: Extract a pair with same values in a list of dictionary in python


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

xpos = [1, 2]
ypos = [2003, 2008]
zpos = [0, 0]

dx = 1
dy = 1
dz = [2, 3]

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.bar3d(xpos, ypos, zpos, dx, dy, dz)
plt.show()

rawDescription: How to customize axes in 3D hist python/matplotlib

description: Customize axes in 3D hist python/matplotlib


rawDescription: Translating Array Manipulation in C++ to Python


code:
EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']

def filter_function(tarinfo):
    if tarinfo.name in EXCLUDE_FILES:
        return None
    else:
        return tarinfo

mytarfile.add(..., filter=filter_function)

rawDescription: Python tarfile and excludes

description: Python tarfile and excludes


code:
def negative_length(x):
    while x < 0:
        x = int(input('That was negative. Please input a non-negative length:'))
    return x

x = input('Enter a length:')
x = negative_length(x)

rawDescription: Run while loop one extra time after condition is met


code:
line = '1/2/3/some text and 5/4=3'
values = line.split('/', 3)
values

rawDescription: How to convert string input into tuple with integers and a string

description: Convert string input into tuple with integers and a string


code:
sys.stdout.flush()
os.system('/Developer/Tools/GetFileInfo ' + p)

rawDescription: Inconsistency in modified/created/accessed time on mac


code:
from scipy.interpolate import LinearNDInterpolator

ex = LinearNDInterpolator((x, y, z), v)
ex((800, 4.5, 2))
#array(1.0)

ex([[800, 4.5, 2], [800, 4.5, 3]])
#array([ 1.,  2.])

rawDescription: How to define values for RegularGridInterpolator

description: Define values for RegularGridInterpolator


code: {{ typeLabels[someType] }}

rawDescription: How to use a lookup table in Jinja?

description: Use a lookup table in Jinja


code:
import threading
import time

def workerA(lock):
    for i in range(5):
        lock.acquire_for('A')
        print('Start A - %s' % i)
        time.sleep(0.5)
        print('End A - %s' % i)
        lock.release_to('B')

def workerB(lock):
    for i in range(5):
        lock.acquire_for('B')
        print('Start B - %s' % i)
        time.sleep(2)
        print('End B - %s' % i)
        lock.release_to('A')

class LockWithOwner:

    lock = threading.RLock()
    owner = 'A'

    def acquire_for(self, owner):
        n = 0
        while True:
            self.lock.acquire()
            if self.owner == owner:
                break
            n += 1
            self.lock.release()
            time.sleep(0.001)
        print('Waited for {} to be the owner {} times'.format(owner, n))

    def release_to(self, new_owner):
        self.owner = new_owner
        self.lock.release()

lock = LockWithOwner()
lock.owner = 'A'

t1 = threading.Thread(target=workerA, args=(lock, ))
t2 = threading.Thread(target=workerB, args=(lock, ))

t1.start()
t2.start()

t1.join()
t2.join()

print('done')

rawDescription: How to synchronize two alternating threads

description: Synchronize two alternating threads


code:
class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.Integer, unique=True, index=True)
    posts = db.relationship('Post', backref='poster', lazy='dynamic')
    comments = db.relationship('Comment', backref='commenter', lazy='dynamic')

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(32), index=True)
    body = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    comments = db.relationship('Comment', backref='comment_on_post', lazy='dynamic')

class Comment(db.Model):
    __tablename__ = 'comments'
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))

rawDescription: How to specify more than 1 backref

description: Specify more than 1 backref


code:
@add_tests(args, build_name1)
class TestEquals(unittest.TestCase):
    ...

rawDescription: Dynamically adding tests to my Test Cases


code: e = Employee({"name": "abc", "age": 32})

rawDescription: Set attributes from dictionary in python


code:
df = pd.melt(df, id_vars=['weight'], value_vars=value_vars, value_name='P')
df.sort(inplace=True)
df.reset_index(drop=True, inplace=True)

rawDescription: Merge multiple DataFrame columns into one


rawDescription: python 2.7 string_name.find() function always returning -1 when using variable

description: Python 2.7 string_name.find() function always returning -1 when using variable


code:
import re

match = re.search(r'^http://[a-zA-Z0-9-]+.domain.com/motors/used-cars/(.+)', url)
if match:
    if match.group(1).startswith('?page='):
        return None
    return url

rawDescription: how to set "any string" as a regular expression in Python

description: Set "any string" as a regular expression in Python


code:
import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

x = np.array([0,1,2,3,4,5,6,7,8,9,10])

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, x**2*np.exp(-x))
def todate(x, pos, today=DT.date.today()):
    return today+DT.timedelta(days=x)
fmt = ticker.FuncFormatter(todate)
ax.xaxis.set_major_formatter(fmt)
fig.autofmt_xdate(rotation=45)
plt.show()

rawDescription: replace numbers on X axis with dates when using line plot in matplotlib

description: Replace numbers on X axis with dates when using line plot in matplotlib


code:
ns = 'http://webservices.amazon.com/AWSECommerceService/2011-08-01'
items = data[0].findall('{%s}Item' % ns)
items

rawDescription: Can't access child elements in XML

description: Can't access child elements in XML


code:
for indexes, value in np.ndenumerate(a):
    x,y,z = indexes
    print(x,y,z,value)

rawDescription: Writing a 3D numpy array to files including its indices


code:
assert(get_type(["hello", "world"]) == "character")
assert(get_type("hello") == "character")
assert(get_type(['1.0', '0.0']) == "numeric")
assert(get_type([0, 1, 2]) == "numeric")
assert(get_type(0.100) == "numeric")

rawDescription: Distinguish between 'character' and 'numeric' data types in Python


code:
def set_variable_to_use(value):
    global variable_to_use
    variable_to_use = value

rawDescription: Passing a string to module "once"

description: Passing a string to module "once"


rawDescription: Remove elements from a int array that have value 0 and save the deleted index


rawDescription: how can I get the total bytes sent and received using python 2.7?

description: Get the total bytes sent and received using python 2.7


code:
[{u'Page1_Level1.html': [{u'Page1_Level2.html': [{u'Page1_Level3.html': []},
                                                 {u'Page2_Level3.html': []},
                                                 {u'Page3_Level3.html': []}]}]},
 {u'Page2_Level1.html': [{u'Page2_Level2.html': []}]}]

rawDescription: Converting HTML list to nested Python list


rawDescription: Python 2.7.8: Printing a sub-dictionary value?


code:
import ctypes
lib = ctypes.cdll.LoadLibrary('x')
fun = lib.fun
fun.restype = ctypes.POINTER(ctypes.c_double)
v = fun()
v.contents.value = 2.0
v = fun()

rawDescription: Change value in shared library with ctypes


code:
fd = open(filename, 'rU')
chars = []
for line in fd:
    chars.extend(line)

rawDescription: Break string into list of characters in Python


code: bar = bar.next_bar = next_bar

rawDescription: Why is assigning to multiple targets (identifier/attribute) producing strange results?


rawDescription: remove this unidentified character "\" from string python

description: Remove this unidentified character "\" from string python


code:
class MyTask(Task):
    abstract = True   # means this base task won't be registered
    loglevel = logging.DEBUG
    logger = logging.getLogger('foo'),

rawDescription: How to get all tasks and periodic tasks in Celery

description: Get all tasks and periodic tasks in Celery


code:
@api.model
def get_age_comp(self):
    for student in self.search([('gender','=','m'), ('birth_date', '<=', date.today() - relativedelta(years=20))]):
        self.env.cr.execute('INSERT INTO stat VALUES(%s,%s)', (student.name, student.birthdate))

rawDescription: Automated Action Birthday =19

description: Automated Action Birthday =19


code:
class Person(object):
    def __init__(self):
       self.name = ""
       self.age  = ""
       self.addresses = []

rawDescription: Python OOP: How do I link multiple classes objects to one object


code:
values = []
for _ in range(_):
    if value2 > value1:
        values.append([name1, name2, value2 - value1])

rawDescription: Trying to create a (list or array, not sure) with data I have outputted from a nested for loop


code:
def put(self, id):
        if checkUser(id):
            args = self.reqparse.parse_args()
            deleteUser(id)      #Deletes user with this id
            addUser(User(args['name'], args['email'], args['password'], args['role']))
            # Missing return when succees
        abort(404) # Always executing

rawDescription: PUT curl request returns bad URI (flask-RESTful)


rawDescription: How to insert unescaped html fragment in Beautiful Soup 4

description: Insert unescaped html fragment in Beautiful Soup 4


rawDescription: change string during pyparsing

description: Change string during pyparsing


code:
for name in [company_name, company_address, company_logo, company_cat, company_lat, company_phone, company_fax]:
    name = str(name)

rawDescription: Change type of group of objects

description: Change type of group of objects


code:
import urllib2

url = 'baseuri:port/resource'
username = 'user'
password = 'pswd'

pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwmgr.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = urllib2.build_opener(authhandler)
response = opener.open(theurl)

rawDescription: REST GET request on Python sending named argument


rawDescription: numpy: most efficient frequency counts for unique values in an array

description: Numpy: most efficient frequency counts for unique values in an array


code: APIMethod(api, 'users' + '.' + 'get')

rawDescription: Why can I call all these methods that aren't explicitly defined in a class?


code: ', '.join(names).split(', ')

rawDescription: Tuple unpacking

description: Tuple unpacking


code:
class Point(namedtuple('Point', 'x y')):
    __cache = {}
    def __new__(cls, x, y):
        return Point.__cache.setdefault((x, y),
                                         super(cls, Point).__new__(cls, x, y))

rawDescription: How to make two objects have the same id in python?

description: Make two objects have the same id in python


code:
urlpatterns = patterns('',
    (r'^compare/(\d+)/(\d+)/$', 'my.compareview'),
)

rawDescription: Are asynchronous Django model queries possible?


code:
with open('newCIK.csv') as reader2_file:
    reader2 = csv.reader(reader2_file)

    with open('search.file') as f_in, open('SP500_10K.csv', 'w') as f_out:
        reader = csv.reader(f_in, delimiter='|')
        writer = csv.writer(f_out, delimiter='|')

        for line in reader:
            reader2_file.seek(0)  # rewind to the start
            for cik in reader2:
                if cik in line:
                    writer.writerow(line)

rawDescription: Python 3.4 : match from csv and return new csv with matched values


rawDescription: Django 1.9: Create complex custom filter method for QuerySet


rawDescription: How does "foo(*a)" work in Python?

description: How does "foo(*a)" work in Python


rawDescription: Given a list of numbers, find a fix range that can cover the most numbers


code:
import types

class what:
    def __init__(self):
        s = 'def yolo(self):\n\tself.extra = "Hello"\n\tprint self.extra'
        exec(s)
        self.yolo = types.MethodType(yolo, self)

what().yolo()

rawDescription: exec to add a function into a class

description: Exec to add a function into a class


code:
def _launch(self, process_obj):
    code = 1
    parent_r, child_w = os.pipe()
    self.pid = os.fork()
    if self.pid == 0:
        try:
            os.close(parent_r)
            if 'random' in sys.modules:
                import random
                random.seed()
            code = process_obj._bootstrap()
        finally:
            os._exit(code)
    else:
        os.close(child_w)
        util.Finalize(self, os.close, (parent_r,))
        self.sentinel = parent_r

rawDescription: What does the term bootstrap refer to in Python Multiprocessing.Process Module?


code:
def count(filename, what):
    strategy = {'lines': lambda x: bool(x.strip()),
                'words': lambda x: len(x.split()),
                'chars': len
    }

    strat = strategy[what]
    with open(filename) as f:
        return sum(strat(line) for line in f)

rawDescription: Preffered way of counting lines, characters and words from a file as a whole in Python


code:
class A(object):
    _COUNTER = 0

    def __init__(self):
        A._COUNTER += 1

rawDescription: How can I increase counter properties of class when a instance is called?

description: Increase counter properties of class when a instance is called


code: someMethod = someDecorator(someMethod)

rawDescription: Using python decorator with or without parentheses


code:
from django.contrib.flatpages import views

urlpatterns += [
    url(r'^about-us/$', views.flatpage, {'url': '/about-us/'}, name='about'),
    url(r'^license/$', views.flatpage, {'url': '/license/'}, name='license'),
]

rawDescription: What is the correct way to link Django Flatpages?


code:
from _version import __version__
parser.add_argument('--version', action='version',
                    version='%(prog)s {version}'.format(version=__version__))

rawDescription: Python's argparse to show program's version with prog and version string formatting


code:
import lxml.html as LH

content = '''
Hello Hello2
Hello3
go home, dude!
'''

doc = LH.fromstring(content)
texts = [elt.text_content() for elt in doc.xpath('//a')]
print(texts)

rawDescription: match string pattern in python

description: Match string pattern in python


rawDescription: How to apply formatted printing to a python list?

description: Apply formatted printing to a python list


code:
import wx

class PageOne(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.query_find_btn = wx.Button(self, 4, "BTN", (40,40))
        self.Bind(wx.EVT_BUTTON, self.AddList, id = 4)

    def AddList(self, evt):
        # PageOne -> Notebook -> Panel -> MyFrame ( 3x GetParent() )
        self.GetParent().GetParent().GetParent().SecondFrame.list1.InsertStringItem(0,'Hello')

class PageTwo(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.list1 = wx.ListCtrl(self,-1,wx.Point(0,0),wx.Size(400,400),style=wx.LC_REPORT |   wx.SUNKEN_BORDER)
        self.list1.InsertColumn(0,'values')

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self,parent,id,title,size=(400,400),pos=wx.Point(100,100),
        style=wx.SYSTEM_MENU |wx.CAPTION )

        p = wx.Panel(self)
        nb = wx.Notebook(p)

        # add self.
        self.MainFrame = PageOne(nb)
        self.SecondFrame = PageTwo(nb)

        # add self.
        nb.AddPage(self.MainFrame, "One")
        nb.AddPage(self.SecondFrame, "Two")

        sizer = wx.BoxSizer()
        sizer.Add(nb, 1, wx.EXPAND)
        p.SetSizer(sizer)

class MyApp(wx.App):
    def OnInit(self):
        self.frame=MyFrame(None,-1,'Unknown.py')
        self.frame.Centre()
        self.frame.Show()
        return True

if __name__ == '__main__':
    app = MyApp(False)
    app.MainLoop()

rawDescription: using listctrl in notebook wxPython

description: Using listctrl in notebook wxPython


code: d * a + e * b + f * c

rawDescription: How may I project vectors onto a plane defined by its orthogonal vector in Python?


code:
o = Course(course_nro='abcd')
session.add(o)
session.commit()

rawDescription: Converting SQL commands to Python's ORM

description: Converting SQL commands to Python's ORM


code: inds = [i for (i, xy_) in enumerate(xy) if xy_ in set(c)]

rawDescription: select rows in pandas DataFrame using comparisons against two columns

description: Select rows in pandas DataFrame using comparisons against two columns


code:
import cProfile
cProfile.run('foo()')

rawDescription: Measuring performance in Python

description: Measuring performance in Python


code: funcs["add_3"] = some_func

rawDescription: Function in Class __init__ Dict | Functions Evaluated on Call of Class


rawDescription: Setting a Value in a Nested Python List Automatically Iterates


code:
from sortedcontainers import SortedDict
d = SortedDict({100: 'a', 27: 'b', 1234: 'c'})
d.keys()
d.keys()[0]
d[d.keys()[0]]

rawDescription: Python support sorted dictionary -- similar to C++ map?


rawDescription: how print_parts() function work in composing program chapter2.3

description: How print_parts() function work in composing program chapter2.3


code: split_list = [the_list[i:i+n] for i in range(0, len(the_list), n)]

rawDescription: how to parse a list or string into chunks of fixed length

description: Parse a list or string into chunks of fixed length


code:
cur.execute("UPDATE Table1 SET Name = replace(Name, '\n', '') "
            "WHERE Name like '%\n%'")

rawDescription: Deal with new line character “\n” in Sqlite database using Python?


rawDescription: How do you make use of a counter with recursion in Python?

description: Make use of a counter with recursion in Python


code:
label_to_number = {label: i for i, label in enumerate(set(labels), 1)}
[(label_to_number[label], label) for label in labels]

rawDescription: Python: Enumerate a list of string 'keys' into ints


code:
a
b
print(a) # str
print(b) # str
print(np.column_stack((a,b)))

rawDescription: Why doesn't my array space correctly when I use np.savetxt


code:
1.0.is_integer()
1.1.is_integer()

rawDescription: Use xlrd to convert XLSX to XML

description: Use xlrd to convert XLSX to XML


code:
if 'host' in host_info:
    del host_info['host']

rawDescription: Create constants for offsets into a list


code:
firstDay = np.min(log[:, 0])
firstMonday = first_monday(firstDay)

def first_monday(firstDay):
    firstEntry = firstDay.astype('M8[D]')
    beforeMonday = np.busday_offset(firstEntry, -1, 'forward', [1,0,0,0,0,0,0])
    if firstEntry - beforeMonday == np.timedelta64(7, 'D'):
        return firstEntry
    else:
        return beforeMonday

rawDescription: numpy: get rid of loop

description: Numpy: get rid of loop


code: replace_in_config('gco:', '_stripped')

rawDescription: How to parse the xml to find the text value of the following node in python?

description: Parse the xml to find the text value of the following node in python


rawDescription: Python Read selected Excel columns into arrays


code:
width = 5
value = 2
'{1:0{0}}'.format(width, value)

rawDescription: How to pad leading zero (in a function) dynamically?

description: Pad leading zero (in a function) dynamically


code:
def imgArray():
    filepath = os.path.join(STATIC_PATH, "\\images")
    images =[f for f in os.listdir(filepath) if f.endswith('.jpg')]
    return images

rawDescription: Using list from views in Django 1.8.1 as an array in javascript template


code:
tree = etree.fromstring('''\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<item id="123">
    ABC
</item>
''')
tree.attrib['id']

rawDescription: Get attribute of first element using lxml


code:
z = np.linspace(-3, 3, 600)
rho = np.cosh(z)  # take constant b = 1

rawDescription: Python: How to revolve a surface around z axis and make a 3d plot?


code:
sx = sy = sL = 0
for i in range(len(points)):   # counts from 0 to len(points)-1
    x0, y0 = points[i - 1]     # in Python points[-1] is last element of points
    x1, y1 = points[i]
    L = ((x1 - x0)**2 + (y1 - y0)**2) ** 0.5
    sx += (x0 + x1)/2 * L
    sy += (y0 + y1)/2 * L
    sL += L
xc = sx / sL
yc = sy / sL

rawDescription: How to compute the center of a polygon in 2D and 3D space

description: Compute the center of a polygon in 2D and 3D space


code: my_ordered_dict = OrderedDict(( (key1, value1), (key2, value2), (key3, value3) ))

rawDescription: Python: Writing an empty dictionary with strings thats ordered


code:
fruits1 = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
fruits2 = ['apple#1', 'apple#2', 'apple#3', 'apple#4', 'orange#1', 'orange#2']

rawDescription: String loops in Python

description: String loops in Python


code:
def _get_userid(details, request):
    userre = re.compile("""^([a-zA-Z1-9\.]+):([a-zA-Z1-9\.:-]+)$""", re.I)
    userpass = base64.b64decode(details[1])
    res = userre.search(userpass)
    if res:
        return res.group()[0]

def authcheck(username, password, request):
    user = Users.by_username(username, enabled=True)
    host = request.registry.settings.get("authentication.host", "127.0.0.1")
    maxattempts = request.registry.settings.get("authentication.maxattempts",5)
    base = _get_userid(request.authorization, request)
    if request.redis.exists("pimssess:%s" % base64.b64encode(request.remote_addr+":"+base)):
        store = pickle.loads(request.redis.get("pimssess:%s" % base64.b64encode(request.remote_addr+":"+base)))
        if store.get("auth.attempts").get(request.remote_addr):
            if store["auth.attempts"][request.remote_addr] >= maxattempts:
                raise HTTPMethodNotAllowed(body="You have been locked out for 5 minutes")

    if user and user.agent and not user.is_http_auth:
        raise HTTPMethodNotAllowed(body="You are not permitted http access")
    if user and user.agent and user.host != host:
        raise HTTPMethodNotAllowed(body="Your host is not permitted http access")
    if user and user.agent and not user.validate_password(password):
        time.sleep(1.5)
        raise HTTPForbidden(body="Failed login, Incorrect password")
    return getGroups(username)

rawDescription: Multiple Authhentication Policies in Pyramid


code: buffer1[pos:pos+len(buffer2)] = buffer2

rawDescription: How to copy a python bytearray buffer?

description: Copy a python bytearray buffer


code:
import os
ppid = os.getppid()

rawDescription: Kill process by ppid in python?

description: Kill process by ppid in python


code: part1, delimiter, part2 = foo.rpartition('_')

rawDescription: Splitting string with multiple delimiters in python


code:
nums = [1,2,3,4,5,6,7,8,9,0]
exclude = set(range(4, 8))
[n for n in nums if n not in exclude]

rawDescription: Can I use the slice method to return a list that excludes ranges in the middle of the original list?

description: Use the slice method to return a list that excludes ranges in the middle of the original list


rawDescription: How to substitute character in string using regex

description: Substitute character in string using regex


code:
from xml.etree import ElementTree
import os

def dict_to_xml(dict_, parent_node=None, parent_name=''):
    def node_for_value(name, value, parent_node, parent_name):
        """
        creates the
<input>...</input>
 elements.
        returns the
 element.
        """
        value= os.path.join(parent_name, value)
        node= ElementTree.SubElement(parent_node, 'li')
        child= ElementTree.SubElement(node, 'input')
        child.set('type', 'checkbox')
        child.set('id', value)
        child= ElementTree.SubElement(child, 'label')
        child.set('for', value)
        child.text= name
        return node

    # create an
 element to hold all child elements
    if parent_node is None:
        node= ElementTree.Element('ul')
        node.set('id', 'master')
    else:
        node= ElementTree.SubElement(parent_node, 'ul')

    # add the sub-elements
    for key,value in dict_.iteritems():
        if isinstance(value, dict):
            child= node_for_value(key, key, node, parent_name)
            dict_to_xml(value, child, key)
        else:
            node_for_value(key, value, node, parent_name)
    return node

rawDescription: Recursion: Nested dictionaries to XML(HTML)


rawDescription: Delete Column in Pandas based on Condition


rawDescription: How to get the number of hours since, from a UTC timestamp?

description: Get the number of hours since, from a UTC timestamp


code:
from collections import defaultdict

accounts = defaultdict(list)
accounts['11163722404385'] = [('a', 'list'),('another', 'list')]
accounts['1116372240485'] = [('one', 'more')]

with open(r'C:\temp\out.txt', 'a') as writer:
    for k,v in accounts.iteritems():
        csv = ';'.join([','.join(t) for t in v])
        writer.write("%s,%s\n" % (k, csv))

rawDescription: How to write Default dictionary values to a file with new line?

description: Write Default dictionary values to a file with new line


rawDescription: Extract integer part from String in python


code:
for item in fulllist:
    try:
        item_print=item.find("span", class_="modelYearSort").string
    except AttributeError:
        continue #skip to the next loop.
    else:
        item_print=item_print + "|" + item.find("span", class_="mmtSort").string
        seller_phone=item.find("span", class_="seller-phone")
        print(seller_phone)
        # item_print=item_print + "|" + item.find("span", class_="seller-phone").string
        item_print=item_print + "|" + item.find("span", class_="priceSort").string
        item_print=item_print + "|" + item.find("span", class_="milesSort").string
        print(item_print)

rawDescription: BeautifulSoup - Handing of cases where variable.find( ).string returns empty


rawDescription: How do I do multiple joins and aggregation with django ORM?

description: Do multiple joins and aggregation with django ORM


code: df = pd.DataFrame(map(list, 'MTAQDD,MTAQDD,MTSQED,MTAQDD,MKAQHD'.split(',')))

rawDescription: protein sequence coding

description: Protein sequence coding


code:
_DBNAME_MAP = {
    'psycopg2': 'postgres',
    'MySQLdb': 'mysql',
    'sqlite3': 'sqlite',
    'sqlite': 'sqlite'
    }

def get_dbname(dbobj):
    mod = dbobj.__class__.__module__.split('.', 1)[0]
    return _DBNAME_MAP.get(mod)

rawDescription: Find databasetype ( SQlite, Mysql, PostgreSQL ) from dbapi in python


code:
def runs_of_ones_array(bits):
  # make sure all runs of ones are well-bounded
  bounded = numpy.hstack(([0], bits, [0]))
  # get 1 at run starts and -1 at run ends
  difs = numpy.diff(bounded)
  run_starts, = numpy.where(difs > 0)
  run_ends, = numpy.where(difs < 0)
  return run_ends - run_starts

rawDescription: find length of sequences of identical values in a numpy array

description: Find length of sequences of identical values in a numpy array


rawDescription: Randomly Interleave 2 Arrays In Python

description: Randomly Interleave 2 Arrays In Python


rawDescription: efficient way to hold and process a big dict in memory in python

description: Efficient way to hold and process a big dict in memory in python


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

a = np.random.normal(size=200)
b = np.random.normal(size=200)

fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
n, bins, patches = ax1.hist(a)
ax1.set_xlabel('Angle a (degrees)')
ax1.set_ylabel('Frequency')

fig2 = plt.figure()
ax2 = fig2.add_subplot(1, 1, 1)
n, bins, patches = ax2.hist(b)
ax2.set_xlabel('Angle b (degrees)')
ax2.set_ylabel('Frequency')

rawDescription: How to create multiple histograms on separate graphs with matplotlib?

description: Create multiple histograms on separate graphs with matplotlib


code:
import os
os.system('/Library/Frameworks/GDAL.framework/Programs/ogr2ogr -f "GeoJSON" output.json input.shp')

rawDescription: launching something within python

description: Launching something within python


rawDescription: Is there a way to create argument in python's argparse that returns true in case no values given


code:
python3 --version #shows the version of your python3 if exist

python2 --version #shows the version of your python2 if exist

python --version # shows which version in in use by default

rawDescription: How to find the different installations of Python and remove them?

description: Find the different installations of Python and remove them


code:
class Project(models.Model):
    name = models.CharField(max_length=100)
    users = models.ManyToManyField(User)

class Task(models.Model):
    project = models.ForeignKey(Project, related_name='project_tasks')
    name = models.CharField(max_length=300)
    assignee = models.ForeignKey(User, related_name='tasks')

rawDescription: have multiple users as one model field in many to one format django models

description: Have multiple users as one model field in many to one format django models


code:
from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import proj3d

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure(figsize=(5,5))
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

"""
Scaling is done from here...
"""
x_scale=1
y_scale=1
z_scale=2

scale=np.diag([x_scale, y_scale, z_scale, 1.0])
scale=scale*(1.0/scale.max())
scale[3,3]=1.0

def short_proj():
  return np.dot(Axes3D.get_proj(ax), scale)

ax.get_proj=short_proj
"""
to here
"""

ax.plot(z, y, x, label='parametric curve')
ax.legend()

plt.show()

rawDescription: matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?

description: Matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot


rawDescription: How to query an HDF store using Pandas/Python

description: Query an HDF store using Pandas/Python


code:
@my_patch(some_module, 'MyClass')
def test_something(self, fake_my_class):
    ...

rawDescription: Mock class used in isinstance checks which has dynamic attributes


rawDescription: Assemble strings for particular ID by order of index. Python


code:
class ClassroomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classroom
        depth = 1

rawDescription: How do I include related model fields using Django Rest Framework?

description: Include related model fields using Django Rest Framework


rawDescription: Grab all but one element in pandas series


rawDescription: how do you obtain the address of an instance after overriding the __str__ method in python

description: Obtain the address of an instance after overriding the __str__ method in python


code:
import demjson

result = demjson.decode(jsonp_payload)

rawDescription: Python: Bad JSON - Keys are not quoted

description: Python: Bad JSON - Keys are not quoted


code: 'Hello'

rawDescription: Why doesn't this __repr__ function return a string?


code:
def GroupColFunc(df, ind, col):
    if df[col].loc[ind] > 1:
        return 'Group1'
    else:
        return 'Group2'

rawDescription: Groupby with User Defined Functions Pandas


rawDescription: Python - Should I be using string prefix r when looking for a period (full stop or .) using regex?


code:
def find_class(self, module, name):
    # Subclasses may override this:
    __import__(module)  # straight-forward import, you can ovveride it.
    mod = sys.modules[module]
    klass = getattr(mod, name)
    return klass

rawDescription: How to control what gets imported when you unpickle python object?

description: Control what gets imported when you unpickle python object


code:
with open('file.dat', 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        print(binascii.hexlify(chunk))

rawDescription: pythonic way to hex dump files

description: Pythonic way to hex dump files


rawDescription: Python Regex Pattern Replacement

description: Python Regex Pattern Replacement


rawDescription: python random mouse movements

description: Python random mouse movements


code:
import whatever
import functools

def prefix_function(function, prefunction):
    @functools.wraps(function)
    def run(*args, **kwargs):
        prefunction(*args, **kwargs)
        return function(*args, **kwargs)
    return run

def this_is_a_function(parameter):
    pass # Your own code here that will be run before

whatever.this_is_a_function = prefix_function(
    whatever.this_is_a_function, this_is_a_function)

rawDescription: Hook python module function

description: Hook python module function


code:
DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = { 'db_b':'db_b'}

DATABASES = {
    'default': {
            'ENGINE': 'backend_of_your_choice',
            'NAME': 'default',
            'USER': 'xxx',
            'PASSWORD': 'xxx',
            'HOST': '127.0.0.1',
            'PORT': '',
    },

    'db_b': {
            'ENGINE': 'backend_of_your_choice',
            'NAME': 'db_b',
            'USER': 'xxx',
            'PASSWORD': 'xxx',
            'HOST': '127.0.0.1',
            'PORT': '',
},}

rawDescription: Want to implement multiple database in django project


code:
import re

print(re.findall('\((.*?)\)',s)[-1])

rawDescription: How to extract last set of parentheses in a string

description: Extract last set of parentheses in a string


code:
import glob
import os

out_filename = "combined.files.csv"
if os.path.exists(out_filename):
    os.remove(out_filename)

read_files = glob.glob("*.csv")
with open(out_filename, "w") as outfile:
    for filename in read_files:
        with open(filename) as infile:
            for line in infile:
                outfile.write('{},{}\n'.format(line.strip(), filename))

rawDescription: Merging all csvs in a folder and adding a new column with filename of original file in Python


code: {'Squid W': 12, 'Sponge B': 14, 'Mr K': 19, 'Patrick S': 9}

rawDescription: Python: reading txt file containing (alphabet and number) and updating the number


code:
_heap = Heap()
add = _heap.add
getmin = _heap.getmin
getmax = _heap.getmax

rawDescription: Call function from class without declaring name object


code:
df['Datetime'] = pd.to_datetime(df.Datetime)  # You can skip this step if you already have it as Datatime object
df1 = df.groupby(['User_ID', df.Datetime.dt.year]).apply(lambda x: x.Datetime.dt.month.nunique())
ids = df1[df1 >= 12].index.get_level_values('User_ID')
df[df.User_ID.isin(ids)]

rawDescription: pandas - apply datetime functions

description: Pandas - apply datetime functions


code: a = [[0 for y in range(8)] for x in range(8)]

rawDescription: More elegant way to create a 2D matrix in Python


rawDescription: Combining numpy with sympy

description: Combining numpy with sympy


rawDescription: Finding Incrementing value from list

description: Finding Incrementing value from list


code:
data = [tuple(int(n) for n in line.split()) for line in ins]
print(data) # [(1, 3, 4), (5, 5, 6)]

rawDescription: Python read file into 2d list

description: Python read file into 2d list


code:
p=argparse.ArgumentParser(add_help=False)
sp=p.add_subparsers()
p1=sp.add_parser('test',add_help=False)
p.print_help()     # no -h for main
p1.print_help()   # no -h for sub
p.parse_args(['-h'])
p.parse_args(['test','-h'])

rawDescription: Python argparse - disable help for subcommands?


rawDescription: Pull files into script from two directories back


code: headers = sorted_data[0].keys()

rawDescription: Sort in Python changing column order

description: Sort in Python changing column order


code: cons

rawDescription: Generating a 'sequence of dicts' for scipy.optimize.minimize


code:
o2 = O2()
o2.var
o2.method
o2.method()

rawDescription: Confused with getattribute and setattribute in python


code:
# illustration how I typically use it
weak_call = WeakCallback(self._something_changed)
long_lived_object.connect("on_change", weak_call)

rawDescription: How to store callback methods?

description: Store callback methods


code:
def forceDefaultStyle(self, event):
    hEventObject = event.GetEventObject()
    hEventObject.SetStyle(0, len(self.hRepositoryTextfield.GetValue()), wx.TextAttr(wx.RED))
    hEventObject.SetFont(self.hFontLabel)

rawDescription: wxPython - wx.TextCtrl - forcing styles

description: WxPython - wx.TextCtrl - forcing styles


code:
def new(inputfile,history_ends,
        historyjobs=historyjobs,targetjobs=targetjobs):

    # checking the file
    with open(inputfile,'r') as f:
        for line in f:
            job = map(int,line.split())
            (historyjobs if job[0]  < history_ends
             else targetjobs).append(job)

    while True:
        k = 0
        zhlistsub = [i for i, element in enumerate(historyjobs)
                     if element[3:6] == targetjobs[k][3:6] ]
        if zhlistsub:
            listcreate(*quickzh(zhlistsub))
        tj00 = targetjobs[0][0]
        while True:
            if targetjobs[0][0]!=tj00:
                break
            historyjobs.append(targetjobs.pop(0))
        if len(targetjobs)==0:
            break

rawDescription: To make the following code run faster?

description: To make the following code run faster


code:
def make_dist_mat(xy):
    d0 = np.subtract.outer(xy[:,0], xy[:,0])
    d1 = np.subtract.outer(xy[:,1], xy[:,1])
    return np.hypot(d0, d1)

make_dist_mat(df[['X', 'Y']].astype(float).values)

rawDescription: Pandas Dataframe: Operations on columns without iterrows()


rawDescription: Pythonic way of determining if the current element is the first or last element of a generator?


rawDescription: Fancy indexing in pandas

description: Fancy indexing in pandas


code:
class unique_element:
    def __init__(self,value,occurrences):
        self.value = value
        self.occurrences = occurrences

def perm_unique(elements):
    eset=set(elements)
    listunique = [unique_element(i,elements.count(i)) for i in eset]
    u=len(elements)
    return perm_unique_helper(listunique,[0]*u,u-1)

def perm_unique_helper(listunique,result_list,d):
    if d < 0:
        yield tuple(result_list)
    else:
        for i in listunique:
            if i.occurrences > 0:
                result_list[d]=i.value
                i.occurrences-=1
                for g in  perm_unique_helper(listunique,result_list,d-1):
                    yield g
                i.occurrences+=1

a = list(perm_unique([1,1,2]))
print(a)

rawDescription: permutations with unique values

description: Permutations with unique values


rawDescription: url_for for class-based views in Flask-Admin

description: Url_for for class-based views in Flask-Admin


code: np.where(arr_b > 0.0, arr_a, np.nan)

rawDescription: Subsetting 2D array based on condition in numpy python


code:
qparams = (
    ('cli', 10),
    ('url', 'www.google.com'),
)

rawDescription: Python 'requests' adding parameters in the wrong order


code:
urlpatterns = [
  url(r'^my-api/action$', custom_action_view),
]

rawDescription: Django-rest-framework @detail_route for specific url


code:
Blue:  ['img2' 'img3' 'img4']
White:  ['img3']
Green:  ['img2']
Yellow:  ['img3']
Red:  ['img1' 'img2' 'img3']

rawDescription: Python: Saving all instances from inside a loop to variable to call later


rawDescription: Wrapper for libeay32.dll: how to import macro?


code:
self.collection.update({"email": "email"},
        {
        "$set": {
            "pwd_list.0": {
                        "pwd": "NEW VALUE",
                        "pwd_date": "str(int(time.time()))"
                        }
               }
        })

rawDescription: Pymongo How to update specific value of row in array


code: df.drop('params', axis=1, inplace=True)

rawDescription: What is the best way to store and use information between two objects in python?


code:
m.fit(X / np.std(X, 0), y)
print(m.coef_)

rawDescription: How to find the importance of the features for a logistic regression model?

description: Find the importance of the features for a logistic regression model


code:
from django.db.models.fields import EmailField
def email_field_init(self, *args, **kwargs):
  kwargs['max_length'] = kwargs.get('max_length', 200)
  CharField.__init__(self, *args, **kwargs)
EmailField.__init__ = email_field_init

rawDescription: django auth User truncating email field

description: Django auth User truncating email field


rawDescription: merge identity matrices in specific way

description: Merge identity matrices in specific way


code:
import bisect
from collections import defaultdict
b=[(10,40),(40,60),(60,90),(90,100)]
b1 = sorted( set(z for x in b for z in x))
b1
dic = defaultdict(list)

dic.values()

rawDescription: Grouping of element in a list given a list of intervals


code:
import collections
import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

GENERIC_READ  = 0x80000000
GENERIC_WRITE = 0x40000000
OPEN_EXISTING = 3

INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
ERROR_FILE_NOT_FOUND = 0x0002

class COMMPROP(ctypes.Structure):
    _fields_= (('wPacketLength',       wintypes.WORD),
               ('wPacketVersion',      wintypes.WORD),
               ('dwServiceMask',       wintypes.DWORD),
               ('dwReserved1',         wintypes.DWORD),
               ('dwMaxTxQueue',        wintypes.DWORD),
               ('dwMaxRxQueue',        wintypes.DWORD),
               ('dwMaxBaud',           wintypes.DWORD),
               ('dwProvSubType',       wintypes.DWORD),
               ('dwProvCapabilities',  wintypes.DWORD),
               ('dwSettableParams',    wintypes.DWORD),
               ('dwSettableBaud',      wintypes.DWORD),
               ('wSettableData',       wintypes.WORD),
               ('wSettableStopParity', wintypes.WORD),
               ('dwCurrentTxQueue',    wintypes.DWORD),
               ('dwCurrentRxQueue',    wintypes.DWORD),
               ('dwProvSpec1',         wintypes.DWORD),
               ('dwProvSpec2',         wintypes.DWORD),
               ('wcProvChar',          wintypes.WCHAR * 1))

    class _CONST:
        COMMPROP_INITIALIZED = 0xE73CF52E
        SP_SERIALCOMM = 0x00000001
        BAUD_USER = 0x10000000 # programmable baud rate
        DATABITS_16X = 0x0020 # hardware wide data path

        PROV_SUBTYPE = collections.OrderedDict([
            ('UNSPECIFIED',    0x00000000),
            ('RS232',          0x00000001),
            ('PARALLELPORT',   0x00000002),
            ('RS422',          0x00000003),
            ('RS423',          0x00000004),
            ('RS449',          0x00000005),
            ('MODEM',          0x00000006),
            ('FAX',            0x00000021),
            ('SCANNER',        0x00000022),
            ('NETWORK_BRIDGE', 0x00000100),
            ('LAT',            0x00000101),
            ('TCPIP_TELNET',   0x00000102),
            ('X25',            0x00000103),
        ])

        PROV_CAPABILITIES = collections.OrderedDict([
            ('DTRDSR',        0x0001), # data-terminal-ready / data-set-ready
            ('RTSCTS',        0x0002), # request-to-send / clear-to-send
            ('RLSD',          0x0004), # receive-line-signal-detect
            ('PARITY_CHECK',  0x0008),
            ('XONXOFF',       0x0010), # XON/XOFF flow control
            ('SETXCHAR',      0x0020), # settable XON/XOFF
            ('TOTALTIMEOUTS', 0x0040), # total (elapsed) time-outs
            ('INTTIMEOUTS',   0x0080), # interval time-outs
            ('SPECIALCHARS',  0x0100),
            ('16BITMODE',     0x0200),
        ])

        SETTABLE_PARAMS = collections.OrderedDict([
            ('PARITY',       0x0001),
            ('BAUD',         0x0002),
            ('DATABITS',     0x0004),
            ('STOPBITS',     0x0008),
            ('HANDSHAKING',  0x0010), # flow control
            ('PARITY_CHECK', 0x0020),
            ('RLSD',         0x0040), # receive-line-signal-detect
        ])

        SETTABLE_BAUD = collections.OrderedDict([
            (75,     0x00000001),
            (110,    0x00000002),
            (134.5,  0x00000004),
            (150,    0x00000008),
            (300,    0x00000010),
            (600,    0x00000020),
            (1200,   0x00000040),
            (1800,   0x00000080),
            (2400,   0x00000100),
            (4800,   0x00000200),
            (7200,   0x00000400),
            (9600,   0x00000800),
            (14400,  0x00001000),
            (19200,  0x00002000),
            (38400,  0x00004000),
            (56000,  0x00008000),
            (57600,  0x00040000),
            (115200, 0x00020000),
            (128000, 0x00010000),
        ])

        SETTABLE_DATA = collections.OrderedDict([
            (5,  0x0001), # 5 data bits
            (6,  0x0002), # 6 data bits
            (7,  0x0004), # 7 data bits
            (8,  0x0008), # 8 data bits
            (16, 0x0010), # 16 data bits
        ])

        SETTABLE_STOP = collections.OrderedDict([
            (1,   0x0001), # 1 stop bit
            (1.5, 0x0002), # 1.5 stop bits
            (2,   0x0004), # 2 stop bits
        ])

        SETTABLE_PARITY = collections.OrderedDict([
            ('NONE',  0x0100), # no parity
            ('ODD',   0x0200), # odd parity
            ('EVEN',  0x0400), # even parity
            ('MARK',  0x0800), # mark parity
            ('SPACE', 0x1000), # space parity
        ])

    @property
    def max_baud(self):
        s = self.dwMaxBaud
        m = self._CONST.SETTABLE_BAUD
        if s == self._CONST.BAUD_USER:
            return 0
        else:
            return m[s]

    @property
    def prov_subtype(self):
        s = self.dwProvSubType
        m = self._CONST.PROV_SUBTYPE
        return [x for x, c in m.items() if c & s]

    @property
    def prov_capabilities(self):
        s = self.dwProvCapabilities
        m = self._CONST.PROV_CAPABILITIES
        return [x for x, c in m.items() if c & s]

    @property
    def settable_params(self):
        s = self.dwSettableParams
        m = self._CONST.SETTABLE_PARAMS
        return [x for x, c in m.items() if c & s]

    @property
    def settable_baud(self):
        s = self.dwSettableBaud
        m = self._CONST.SETTABLE_BAUD
        return [x for x, c in m.items() if c & s]

    @property
    def user_settable_baud(self):
        return bool(self.dwSettableBaud & self._CONST.BAUD_USER)

    @property
    def settable_data(self):
        s = self.wSettableData
        m = self._CONST.SETTABLE_DATA
        return [x for x, c in m.items() if c & s]

    @property
    def wide_settable_data(self):
        return bool(self.wSettableData & self._CONST.DATABITS_16X)

    @property
    def settable_stop(self):
        s = self.wSettableStopParity
        m = self._CONST.SETTABLE_STOP
        return [x for x, c in m.items() if c & s]

    @property
    def settable_parity(self):
        s = self.wSettableStopParity
        m = self._CONST.SETTABLE_PARITY
        return [x for x, c in m.items() if c & s]

LPCOMMPROP = ctypes.POINTER(COMMPROP)

class SECURITY_ATTRIBUTES(ctypes.Structure):
    _fields_ = (('nLength',              wintypes.DWORD),
                ('lpSecurityDescriptor', wintypes.LPVOID),
                ('bInheritHandle',       wintypes.BOOL))

LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)

kernel32.CreateFileW.restype = wintypes.HANDLE
kernel32.CreateFileW.argtypes = (
    wintypes.LPCWSTR,      # _In_     lpFileName
    wintypes.DWORD,        # _In_     dwDesiredAccess
    wintypes.DWORD,        # _In_     dwShareMode
    LPSECURITY_ATTRIBUTES, # _In_opt_ lpSecurityAttributes
    wintypes.DWORD,        # _In_     dwCreationDisposition
    wintypes.DWORD,        # _In_     dwFlagsAndAttributes
    wintypes.HANDLE)       # _In_opt_ hTemplateFile

kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)

kernel32.GetCommProperties.argtypes = (
    wintypes.HANDLE, # _In_  hFile
    LPCOMMPROP)      # _Out_ lpCommProp

def get_comm_properties(handle_or_port):
    if isinstance(handle_or_port, str):
        handle = kernel32.CreateFileW(
                        handle_or_port,
                        GENERIC_READ | GENERIC_WRITE,
                        0,    # exclusive access
                        None, # default security
                        OPEN_EXISTING,
                        0,
                        None)
        if handle == INVALID_HANDLE_VALUE:
            raise ctypes.WinError(ctypes.get_last_error())
        close_handle = True
    else:
        handle = handle_or_port
        close_handle = False
    try:
        prop = COMMPROP()
        if not kernel32.GetCommProperties(handle, ctypes.byref(prop)):
            raise ctypes.WinError(ctypes.get_last_error())
    finally:
        if close_handle:
            kernel32.CloseHandle(handle)
    return prop

rawDescription: Python serial module failing to configure port


code: ax.plot(x_new, piecewise_linear(x_new, *p), '-', ms[::20], degrees[::20], 'o')

rawDescription: Plotting a piece-wise fit to non-linear data


code: {u'bd792fcb87': [{u'delivery_time': u'6-10', u'quantity_min': 1, u'hash': u'bd792fcb87', u'qty_order_interval': 1, u'price': u'5,90\xa0\u20ac', u'tax': 0.21, u'delivery_desc': u'Aanvraag / Demande / Anfrage', u'price_unlocalized': 5.9, u'localitemid': u'2000010600', u'currency': u'\u20ac', u'quantity_available': 0, u'delivery_time_max': 10, u'quantity_interval': 1, u'price_quantity': 1, u'price_vat': u'7,14\xa0\u20ac'}]}

rawDescription: Python scrape with BeautifulSoup

description: Python scrape with BeautifulSoup


rawDescription: Python algorithm for converting an integer to binary: questions about efficiency


code:
def padded_bin_with_complement(x):
    if x < 0:
        return bin((2**16) - abs(x))[2:].zfill(16)
    else:
        return bin(x)[2:].zfill(16)

rawDescription: Alternative of showbits() in Python to show 16 bit binary representation


code:
result = [data[0]]
for change, t in data[1:]:
    result.append((result[-1][0]+change, t))

rawDescription: Python Convert ordered list of relative changes to absolute changes


code:
sum(teamAwinprops.values()) + sum(teamBwinprops.values())
teamAwincount
teamBwincount

rawDescription: monte carlo simulation python

description: Monte carlo simulation python


rawDescription: Use a loop to plot n charts Python

description: Use a loop to plot n charts Python


rawDescription: Python setting Decimal Place range without rounding?


code:
user_input = 'file write hi.txt { range(10) | random }'
template = env.from_string(user_input)
result = template.render()
print(result)

rawDescription: Python 3 - Replacing part of a string with imformation from the string


code:
from itertools import dropwhile, groupby

def section(fle, start, end):
    with open(fle) as f:
        grps = groupby(dropwhile(lambda x: x.strip() != start, f),
                       key=lambda x: x.startswith(end))
        for k, v in grps:
            if not k:
                yield list(map(str.strip,v))

rawDescription: How to start checking from specific part of a list in python

description: Start checking from specific part of a list in python


rawDescription: Flask, setting JSON in a cookie, and decoding it on the client (in javascript)


rawDescription: Joining String after certain steps

description: Joining String after certain steps


code: df.groupby(level=0).filter(lambda x: len(x['bar']) >= 2)

rawDescription: Pandas: Filtering pivot table rows where count is fewer than specified value


code:
def count(M, N):
    i = 0
    count = 0
    while True:
        try:
            i = N.index(M, i)+1
            count += 1
        except ValueError:
            break
    return count

rawDescription: Counting substrings in string

description: Counting substrings in string


rawDescription: Fast vectorized indexing in numpy

description: Fast vectorized indexing in numpy


code:
def __init__(self,name):
    self.__name__=name
    number_hops=10
    self.number_hops=number_hops
def __repr__(self):
    return self.__name__

rawDescription: Python3 Classes- Can you change it into a string?