code:
sec = {} #construct a dictionary
for index, directionpair in enumerate(sections):
    long_name = directionpair[1] #take the second element of the pair
    short_name = ''
    for C in long_name: #for each character in long_name
        if C in ' /': #every time you find a forward slash in long_name, write '-' in short-name instead
            short_name += '-'
        elif C not in "'." : #in short-string, add all lower-case versions of the character if it's not a '.'
            short_name += C.lower()
    sec[short_name] = index

rawDescription: Python - Can someone explain to me what this does and how it works?


code:
for index, item in enumerate(arr):
    if item > 100:
        return index, item

rawDescription: Python: finding an element in an array

description: Python: finding an element in an array


rawDescription: Python: An elegant/efficient way to evaluate function over bi-dimensional indexes?


code:
import re
mystring = '"hello":"noun":"a greeting";"hello":"verb":"the;action;of;greeting"'
result = re.findall(r'"(.+?)":"(.+?)":"(.+?)"', mystring)
for item in result:
    print(*item)

rawDescription: Python Complicated Splitting of a String


code:
myfiles = [ 'relative/path/foo.jpg',
            'http://static.mysite.com/absolute/path/bar.jpg' ]

rawDescription: Python images display Django

description: Python images display Django


code:
filename="summary_Cells_a_01_2_1_45000_it_1.txt"
match = re.search(r'summary_Cells_(\w+)_01_2_1_(\w+)_it_(\w+).txt', filename)
match.group()
match.group(0)
match.group(1)
match.group(2)
match.group(3)

rawDescription: Searching for multiple substrings of unknown size in string in python


code:
chart_types = {
    'bar': add_bar_chrt,
    'column': add_column_chrt,
    'pie': add_pie_chart,
    'line': add_line_chart,
}
def chart_selector(slide, df_table, chart_type, *args, **kwargs):
    return chart_types[chart_type](slide, df_table, *args, **kwargs)

rawDescription: Python: setting a parameter for a function within a function


code:
def syf(A, E=True):
    if E == True:
        return np.concatenate((A[1:], A[-1].reshape(Yshape)), axis=0) - A
    else:
        return np.concatenate((A[1:], Yzeros), axis=0) - A

rawDescription: Fastest way to shift a Numpy array

description: Fastest way to shift a Numpy array


code: from socket import socket

rawDescription: Query about Creating a Socket in Python

description: Query about Creating a Socket in Python


code:
import locale, datetime

locale.setlocale(locale.LC_TIME, 'en_US')
datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')

rawDescription: RFC 1123 Date Representation in Python?

description: RFC 1123 Date Representation in Python


code:
from django.shortcuts import render_to_response
from django.core.cache import cache

def home(request):
    data = {
        'gcal': cache.get('google_calendar')
    }
    return render_to_response('home.html', data)

rawDescription: Caching calendar data from Google Calendar


code:
import numpy as np
import itertools as it

# first 7 rows add 1 to a and 1 to c
add1 = np.array([1, 0, 1, 0])

# next 5 rows add 1 to b and 1 to d
add2 = np.array([0, 1, 0, 1])

# stack them accordingly
upper = np.vstack(list(it.chain(it.repeat(add1, 7),
                                it.repeat(add2, 5))))

# lower is the negated version of upper
lower = -upper

# stack them
both = np.vstack((upper,
                  lower))

# with cumsum we'll get for each row the relative distance to the first row
# (istead of distance to previous)
sums = np.cumsum(both, axis=0)

# prepend 0 vector to retain the the first row
sums = np.vstack((np.zeros_like(add1), sums))

# create the frist row
l = np.array([0, 0, 2137, 1419])

# now just add up row and sums
result = l+sums

print(result)

rawDescription: Python array: formulas to populate array with data


code:
def transform(inp):
    destination = {}

    for key, value in inp.items():
        keys = key.split(".")
        d = destination
        for key in keys[:-1]:
            if key not in d:
                d[key] = {}
            d = d[key]

        d[keys[-1]] = value

    return destination

rawDescription: Convert one level dictionary to structure of nested dictionaries


code: assert d1[1] is d2['a'] and d1[1] is d3['one']

rawDescription: How to store a one-to-one relationship table for fast lookups in Python?

description: Store a one-to-one relationship table for fast lookups in Python


code:
# Python
class Foo: pass
class Bar: pass
p = Foo()
p.__class__ == Foo # => True
p.__class__ = Bar
p.__class__ == Foo # => False

rawDescription: Concrete types and abstract types in Java when compared to other languages


code:
from Tkinter import *

master = Tk()

listbox = Listbox(master)
listbox.pack()

listbox.insert(END, "a list entry")

for item in ["one", "two", "three", "four"]:
    listbox.insert(END, item)

mainloop()

rawDescription: creating an interactive Python GUI that generates a new list

description: Creating an interactive Python GUI that generates a new list


code: pattern = re.compile(r'(.)\1?' , re.IGNORECASE | re.DOTALL)

rawDescription: Getting a list with new line characters

description: Getting a list with new line characters


rawDescription: pandas concat/merge and sum one column

description: Pandas concat/merge and sum one column


code: df['dayOfWeek2'] = df.time.apply(lambda x:x.strftime('%w'))

rawDescription: Deriving new data from Pandas datetime column


code:
from matplotlib.ticker import NullFormatter
ax2.axes.get_xaxis().set_major_formatter(NullFormatter())

rawDescription: remove tick labels in Python but keep gridlines

description: Remove tick labels in Python but keep gridlines


code:
import wx

class MyFrame ( wx.Frame ):

    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Test", pos = wx.DefaultPosition, size = wx.Size( 200,200 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

        sizer_inside = wx.BoxSizer( wx.VERTICAL )

        # Adding a button and a textCtrl widget
        self.button = wx.Button( self, wx.ID_ANY, u"Click Me", wx.DefaultPosition, wx.DefaultSize, 0 )
        sizer_inside.Add( self.button, 0, wx.ALIGN_CENTER|wx.ALL, 5 )
        self.textCtrl = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_NO_VSCROLL )
        sizer_inside.Add( self.textCtrl, 0, wx.ALIGN_CENTER|wx.ALL, 5 )

        self.SetSizer( sizer_inside )
        self.Layout()
        self.Centre( wx.BOTH )
        self.Show()

        self.counter = 0

        # Binding Events
        self.Bind( wx.EVT_BUTTON, self.on_click )
        self.Bind( wx.EVT_CHOICE, self.test_dummy)

    #Event handlers
    def on_click( self, event ):
        self.counter += 1
        wx.PostEvent(self.GetEventHandler(), wx.PyCommandEvent(wx.EVT_CHOICE.typeId, self.GetId()))

    def test_dummy(self, event):
        self.counter += 1
        self.textCtrl.SetValue(str(self.counter))

if __name__ == "__main__":
    app = wx.App(False)
    MyFrame(None)
    app.MainLoop()

rawDescription: How to programmatically generate an event in wxPython

description: Programmatically generate an event in wxPython


code:
import itertools
def sync(n):
  if n == 3: return -1 # error
  return 0
lines = [1, 2, 3, 4, 5, 6]
[ x for x in itertools.takewhile(lambda x: sync(x) == 0, lines) ]

rawDescription: One-liner for calling a function for each line in a file


code:
class Thing:
   def __init__(self, **kwargs):
       self.__dict__.update(kwargs)

rawDescription: Python 3 object construction: which is the most Pythonic / the accepted way?


code:
def find_sessions_to_delete(cutoff):
    to_delete = []

    # process each jobdir separately
    for jobdir in glob('/root/job*'):
        # produce a list of (timestamp, path) tuples for each session directory
        session_dirs = [(os.path.getctime(p), p)
                        for p in glob(os.path.join(jobdir, 'session*'))]
        session_dirs.sort(reverse=True)  # sort from newest to oldest
        # remove first two elements, they are kept regardless
        session_dirs = session_dirs[2:]
        # Add list of paths whose ctime lies before the cutoff time
        to_delete.extend(p for t, p in session_dirs if t <= cutoff)

    return to_delete

rawDescription: Retrieving specific directories using os.walk()


rawDescription: python, deleting characters from a line, but leaving numbers and special symbols

description: Python, deleting characters from a line, but leaving numbers and special symbols


code:
with open(fileName) as fi:
    data = fi.read()

l = [i.strip() for i in re.split('[IVXLCDM]+\n\n', text) if i.strip()]
for i in l:
    print(i.split('\n\n')[-1])
    print('\n')

rawDescription: find last paragraph of each section from a book

description: Find last paragraph of each section from a book


code:
def createColorList(r,g,b, numTint):
    tintList = []
    for x in range(0, numTint):
        tintList.append((r,g,b))
    return tintList

rawDescription: How to create and fill 2d list in python. Basically trying to create a list of rgb values

description: Create and fill 2d list in python. Basically trying to create a list of rgb values


rawDescription: How can I solve system of linear equations in SymPy?

description: Solve system of linear equations in SymPy


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.transforms import BlendedGenericTransform

delays = np.array([0.5, 2.3, 'L', 0.9, 'L', 2], dtype=object)
x = np.arange(delays.size)

fig, ax = plt.subplots()
ax.plot(x[delays != 'L'], delays[delays != 'L'], 'bo')

flags = x[delays == 'L']
ax.plot(flags, np.zeros_like(flags), 'rx', clip_on=False, mew=2,
        transform=BlendedGenericTransform(ax.transData, ax.transAxes))

# Expand axis limits by 0.5 in all directions for easier viewing
limits = np.array(ax.axis())
ax.axis(limits + [-0.5, 0.5, -0.5, 0.5])

plt.show()

rawDescription: matplotlib: draw special symbol when a value appears

description: Matplotlib: draw special symbol when a value appears


rawDescription: making multi-index in pandas dataframes in Python?

description: Making multi-index in pandas dataframes in Python


code:
new_array = array[array != 0]        # using only one comparison

new_array = array[np.nonzero(array)] # using np.nonzero

new_array = array[np.where(array)]   # using np.where

rawDescription: Remove a value from 1D array

description: Remove a value from 1D array


code:
def keyPressEvent(self, qKeyEvent):
    print(qKeyEvent.key())
    if qKeyEvent.key() == QtCore.Qt.Key_Return:
        print('Enter pressed')
    else:
        super().keyPressEvent(qKeyEvent)

rawDescription: Why keyPress Event in PyQt does not work for key Enter?


code: new_list = list(l)

rawDescription: python variable assignment using time slices

description: Python variable assignment using time slices


code:
class AgeField(serializers.WriteableField):
    def to_native(self, age):
        return age * 100

    def from_native(self, age):
        return int(age) / 100

class MySerializer(serializers.ModelSerializer):
    age = AgeField(source='age')

    def restore_object(self, attrs, instance=None):
        """
        Deserialize a dictionary of attributes into an object instance.
        You should override this method to control how deserialized objects
        are instantiated.
        """
        if instance is not None:
            instance.update(attrs)
            instance.update({'age', attrs['age'] / 100})
            return instance
        return attrs

class Meta:
    model = MyModel
    fields = ('field1', 'field2', 'age')

rawDescription: What method can I use just before deserialization in Django REST?


code:
from django.utils import six
from rest_framework import serializers

class MyPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):

    def to_representation(self, value):
        return six.text_type(value) # returns the string(Python3)/ unicode(Python2) representation now instead of pk

rawDescription: How to get string representation of PrimaryKeyRelatedField in JSON

description: Get string representation of PrimaryKeyRelatedField in JSON


code:
def foo(self): return self._foo
foo = property(foo)

rawDescription: How does the @property decorator work?

description: How does the @property decorator work


code: c = a * b

rawDescription: What is this operator *= -1

description: What is this operator *= -1


code:
from collections import defaultdict

IndexDict = defaultdict(dict)
for key, value in  dct.iteritems():
    for i, v in enumerate(value):
       IndexDict[i][key] = v

rawDescription: How to map string id, index and value in a nested python dictionary

description: Map string id, index and value in a nested python dictionary


code:
if all(item == 0 for item in list1):
   print("something")

rawDescription: how do I print in python if a list contains only 0s?

description: Print in python if a list contains only 0s


code:
search_string = 'search'
with open('infile.txt', 'r') as infile, open('outfile.txt', 'w') as outfile:
    for line in infile:
        if search_string in line:
            outfile.writelines([line, next(infile), next(infile)])

rawDescription: using python, Search for a text and print next few lines in python

description: Using python, Search for a text and print next few lines in python


rawDescription: Numpy: Indexing of arrays

description: Numpy: Indexing of arrays


code:
df = pd.DataFrame.from_records(dat).set_index(0)
counts = df.groupby(lambda x: floor(x / 0.5) * 0.5).count()
counts

rawDescription: python making list of tuples into definite sized intervals

description: Python making list of tuples into definite sized intervals


code:
if filename.endswith(".css"):
    with open(os.path.join(dirname, filename), "r") as assetfile:
        assetdata = assetfile.read().replace("\n", "")
    cssMinified = io.StringIO()
    cssMinified.write(rcssmin.cssmin(assetdata, keep_bang_comments=True))
    themePak.writestr(os.path.join(dirname, filename), cssMinified.getvalue())

if filename.endswith(".js"):
    with open(os.path.join(dirname, filename), "r") as assetfile:
        assetdata = assetfile.read().replace("\n", "")
    jsMinified = io.StringIO()
    jsMinified.write(rjsmin.jsmin(assetdata, keep_bang_comments=True))
    themePak.writestr(os.path.join(dirname, filename), jsMinified.getvalue())

rawDescription: Minify all CSS and Javascript in a directory


code:
len(set(x)) == 1
len(set(y)) == 1

rawDescription: Is there any easy way to compare list items in python?


code: [y for x, y in sorted(zip(myorderList, myList))]

rawDescription: Python ordering the list according to another list


code:
top = []

with open('numbers.txt') as f:

    # the first ten numbers are going directly in
    for line in f:
        top.add(int(line.strip()))
        if len(top) == 10:
            break

    for line in f:
        num = int(line.strip())
        min_top = min(top)
        if num > min_top:    # check if the new number is a top one
            top.remove(min_top)
            top.append(num)

print(sorted(top))

rawDescription: Code: Code isn't working to sort through a list of 1 million integers, printing top 10


code: re.findall(r'TEST_CMD\.([^(]+)', ss)

rawDescription: Best way to parse/find text with Python

description: Parse/find text with Python


code:
res.mean(axis=1)
# masked_array(data = [5.0 3.125],
#             mask = [False False],
#       fill_value = 1e+20)

res.mean(axis=1).compressed()
# array([ 5.   ,  3.125])

rawDescription: Fastest way to filter values in np array based on changing threshold


code:
type_name = "Person"
Person = type(type_name, (object,), { '__init__': make_init(mapy) })

rawDescription: How to convert Python dict to a specifically-typed object?

description: Convert Python dict to a specifically-typed object


rawDescription: Multi-Axis Graph with Line on top. Matplotlib


code: arr = [u + 1 for u in range(10)]

rawDescription: Edit a list while iterating over it (the pythonic way!)


code:
from scipy.interpolate import BarycentricInterpolator

# create some data points
points1 = [[0, 2], [1, 4], [2, -2], [3, 6], [4, 2]]
points2 = [[1, 1], [2, 5], [3, -1]]

# put data into x, y tuples
x1, y1 =zip(*points1)
x2, y2 = zip(*points2)

# create the interpolator
bci1 = BarycentricInterpolator(x1, y1)
bci2 = BarycentricInterpolator(x2, y2)

# define dense x-axis for interpolating over
x1_new = np.linspace(min(x1), max(x1), 1000)
x2_new = np.linspace(min(x2), max(x2), 1000)

# plot it all
plt.plot(x1, y1, 'o')
plt.plot(x2, y2, 'o')
plt.plot(x1_new, bci1(x1_new))
plt.plot(x2_new, bci2(x2_new))
plt.xlim(-1, 5)

rawDescription: Emulating Excel's "scatter with smooth curve" spline function in Matplotlib for 3 points


code: ', '.join(['"{}"'.format(value) for value in lst])

rawDescription: Join a list of strings such that each string is within quotes and comma separated


code:
class _mystring(object):

    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def _strGet(self):
        pass

    def _strSet(self,value):
        self._str = value

    str = property(_strGet, _strSet)

class uppercase(_mystring):

    def _strGet(self):
        return self._str.upper()
    str = _mystring.str.getter(_strGet)

rawDescription: Inheriting setter, overwriting getter in python abstract class


code:
pix=widget.grab()
pix.save("save.png")

rawDescription: How to make a snapshot of a specific huge PyQt window?

description: Make a snapshot of a specific huge PyQt window


code: valNZ=myArray[nzEntries]

rawDescription: How to randomly change positions of non-zero entries of an array where certain rows are excluded

description: Randomly change positions of non-zero entries of an array where certain rows are excluded


rawDescription: Combining rows in pandas

description: Combining rows in pandas


code:
def next_int(self):
    self.recv_buf_i += 4
    return struct.unpack_from("i", self.recv_buf, self.recv_buf_i-4)[0]

rawDescription: Faster sockets in Python

description: Faster sockets in Python


code:
class ChildSerializer(Serializer):
    def to_representation(self, instance):
        foo = instance.foo  # comes from parent serializer
        ...

class RootSerializer(Serializer):
    child = ChildSerializer()
    def to_representation(self, instance):
        instance.foo = 'foo'  # parent is setting state
        ...

rawDescription: Accessing serializer instances in nested serializer's field


rawDescription: Fixing faulty unicode strings

description: Fixing faulty unicode strings


code: xmin, xmax = g.ax_marg_y.get_xlim()

rawDescription: Rescale axis on Seaborn JointGrid KDE marginal plots


code:
m = 1000
n = 1000
x = np.random.rand(m, n)
y = np.random.rand(m, n)

rawDescription: Python Multiple Simple Linear Regression


code:
('// The variable counter, which is about to be defined, is going', '')
('// to start with a value of 0, which is zero.', '')
('// Now, we are going to loop, hold on to your hat.', '')
('', '/* counter is less than one hundred */')
('', '/* Every time we loop, we INCREMENT the value of counter,\n   Seriously, we just add one to it. */')
('// And then, we are done.', '')

rawDescription: Regex to capture the c langage comment use python


code: freqs = dict([(b,a) for (a,b) in exampleData])

rawDescription: Python, SUM of multiply

description: Python, SUM of multiply


code:
import xml.etree.ElementTree as etree

def find_translation(tree, id_):
    # Search fot the GH element with the given identification, and return
    # its translation if found. Otherwise None is returned implicitly.
    for gh in tree.iter('GH'):
       id_elem = gh.find('./id')
       if id_ == id_elem.text:
           # The related GH element found.
           # Find metadata entry, extract the translation.
           # Warning! This is simplification for the fixed position
           # of the Translation entry.
           me = gh.find('./metadata/entry')
           assert len(me) == 2     # metadata/entry has two elements
           cl1 = me[0]
           assert cl1.text == 'Translation'
           cl2 = me[1]

           return cl2.text

# Body of the program. --------------------------------------------------

english_tree = etree.parse('en.xml')
french_tree = etree.parse('fr.xml')

for gh in french_tree.iter('GH'): # iterate through the GH elements only
   # Get the identification of the GH section
   id_elem = gh.find('./id')
   id_ = id_elem.text

   # Find and check the metadata entry, extract the French translation.
   # Warning! This is simplification for the fixed position of the Translation
   # entry.
   me = gh.find('./metadata/entry')
   assert len(me) == 2     # metadata/entry has two elements
   cl1 = me[0]
   assert cl1.text == 'Translation'
   cl2 = me[1]
   fr_translation = cl2.text

   # If the French translation is empty, put there the English translation
   # from the related element.
   if cl2.text is None:
       cl2.text = find_translation(english_tree, id_)

with open('fr2.xml', 'w') as fout:
   fout.write(etree.tostring(french_tree.getroot()).decode('utf-8'))

rawDescription: Python replace XML content with Etree

description: Python replace XML content with Etree


code:
class Pizza(models.Model):
   toppings = models.ManyToMany('Topping')

class Topping(models.Model):
   name = models.CharField(max_length=100)

rawDescription: How does a model relate to another model via Foreignkey?


code:
class EditableListCtrl(wx.ListCtrl, listmix.TextEditMixin):
    # TextEditMixin allows any column to be edited other than those specifically vetoed
    def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        """Constructor"""
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        listmix.TextEditMixin.__init__(self)

rawDescription: WxPython ListCtrl index 0 item non editable


code:
import sys
sys.argv = ['test.py', '\xe2\x80\x94-test', '\xe2\x80\x9cTest\xe2\x80\x9d']
map = {0x2014: u'-', 0x201c: u"'", 0x201d: u"'"}
sys.argv[1:] = [s.decode('utf8').translate(map).encode('utf8') for s in sys.argv[1:]]
sys.argv

rawDescription: Python arguments are read as code

description: Python arguments are read as code


code:
sim_list = []
sim_list.append(simulation('foo'))
sim_list.append(simulation('bar'))

for sim in sim_list:
    sim.start()

rawDescription: Python Multiprocessing - apply class method to a list of objects


code: '{grandparent}/parent/{parent}/child'

rawDescription: Endpoints Proto Datastore - Path {requirement} variable used for keys randomly breaks


code:
dis = {}
for elem in lw:
    dis[elem] = []
    # ...

rawDescription: PYTHON - creating multiple lists in a loop


rawDescription: Reshape sparse matrix efficiently, Python, SciPy 0.12


code:
for rank, rank in rank_choices:
    Rank.objects.create(rank=rank)

Rank.objects.order_by('rank')  # alphabetical
rank_lookup = {rank: n for n,(rank,rank) in enumerate(rank_choices)}
cases = [When(rank=rank, then=Value(rank_lookup[rank])) for rank in rank_lookup]
cases
Rank.objects.annotate(my_order=Case(*cases, output_field=IntegerField())).order_by('my_order')
Rank.objects.annotate(my_order=Case(*cases, output_field=IntegerField())).order_by('-my_order')

rawDescription: How can I order a Django query against a custom list of values?

description: Order a Django query against a custom list of values


code:
reader = csv.reader(open("file.csv"))
for row in reader:
  for value in row:
    ...

rawDescription: Create KML file for Google Maps from CSV


code:
max_index = -1
max_value = 0
for i, z in enumerate(x):
    value = abs(z[0])
    if value > max_value:
        max_index = i
        max_value = value

print(x[max_index])

rawDescription: How to find the index of the maximum absolute of the first time in a list of tuples?

description: Find the index of the maximum absolute of the first time in a list of tuples


code: return (True, t, result)

rawDescription: Returning success or failure as well as result from function


code:
EOF = chr(4)
import zmq

def file_sink(filename, url):
    """forward messages on zmq to a file"""
    socket = zmq.Context.instance().socket(zmq.PULL)
    socket.bind(url)
    written = 0
    with open(filename, 'wb') as f:
        while True:
            chunk = socket.recv()
            if chunk == EOF:
                break
            f.write(chunk)
            written += len(chunk)

    socket.close()
    return written

rawDescription: Python: write to single file from multiple processes (ZMQ)


code:
main_array = ['bacon', 'cheese', 'milk', 'cake', 'tomato']
second_array = ['cheese', 'tomato']
set(main_array) & set(second_array)

rawDescription: Python, remove all occurrences of string in list


code: b = map(list, zip(*a))

rawDescription: Re assign a list efficiently

description: Re assign a list efficiently


code:
pos = data.index(replaceText)
data[pos:pos+1] = replaceData

rawDescription: python: how to replace a string in a list of string with a list of strings?

description: Python: how to replace a string in a list of string with a list of strings


code:
# Get number of rows in either A or B
N = B.shape[0]

# Store columnw-wise in A and B, as they would be used at few places
sA = A.sum(0)
sB = B.sum(0)

# Basically there are four parts in the formula. We would compute them one-by-one
p1 = N*np.einsum('ij,ik->kj',A,B)
p2 = sA*sB[:,None]
p3 = N*((B**2).sum(0)) - (sB**2)
p4 = N*((A**2).sum(0)) - (sA**2)

# Finally compute Pearson Correlation Coefficient as 2D array
pcorr = ((p1 - p2)/np.sqrt(p4*p3[:,None]))

# Get the element corresponding to absolute argmax along the columns
out = pcorr[np.nanargmax(np.abs(pcorr),axis=0),np.arange(pcorr.shape[1])]

rawDescription: Efficient pairwise correlation for two matrices of features


code: pd.pivot_table(df, values='citation', rows='paper', columns='year', fill_value=0)

rawDescription: Pandas: Add new columns based on others columns


code:
content = """
print _(
    'Test #A'
    )

print _(
    '''Test #B'''
    '''Test #C'''
)
"""
import re
m = re.findall(r'(?s)_\((.*?)\)', content)
for i, match in enumerate(m, 1):
    print("Match {0}: {1}".format(i, match))

rawDescription: Python regexp everything between parenthesis on multiple lines


code:
def flatten(aList):
    t = []
    for i in aList:
        if not isinstance(i, list):
             t.append(i)
        else:
             t.extend(flatten(i))
    return t
flatten([1, 1])
flatten([1, 1])
flatten([[[1]], [[[5]]]])
flatten([1, 1, [42, 81]])

rawDescription: Flatten an irregular list of lists in Python recursively


code: sheet_ranges = wb['range names']

rawDescription: "Worksheet range names does not exist" KeyError in openpyxl


code:
from _sorteddict import sortedset as sortedset
from _sortedlist import sortedlist as sortedlist

rawDescription: Python can't import blist classes

description: Python can't import blist classes


code:
# here's generic pandas
df_new = pd.merge(df1,df2)

# example with itertoolz and bcolz
from toolz.itertoolz import join as joinz
import bcolz

#convert them to ctables
zdf1 = bcolz.ctable.fromdataframe(df1)
zdf2 = bcolz.ctable.fromdataframe(df2)

#column 2 of df1 and column 1 of df2 were the columns to join on
merged = list(joinz(1,zdf1.iter(),0,zdf2.iter()))

# where new_dtypes are the dtypes of the fields you are using
# mine new_dtypes= '|S8,|S8,|S8,|S8,|S8'
zdf3 = bcolz.fromiter(((a[0]+a[1]) for a in merged), dtype = new_dtypes, count = len(merged))

rawDescription: Python bcolz how to merge two ctables

description: Python bcolz how to merge two ctables


code: [data[index] for index in range(len(data)) if mask[index]]

rawDescription: Python reduce list by mask

description: Python reduce list by mask


rawDescription: Reshaping Arrays in Numpy with variables


code:
listoflists = [['A', 'B', 'C', 'D'], ['B', 'A', 'C', 'D'], ['B', 'C', 'D', 'A']]

def borda(listoflists):
    outdict = {}
    for singlelist in listoflists:
        # Below, we're just turning singlelist around in order to
        # make use of index numbers from enumerate to add to the scores
        for index, item in enumerate(singlelist[2::-1]):
            if item not in outdict:
                outdict[item] = index + 1
            else:
                outdict[item] += index + 1

    highestitem = max(outdict.iteritems(), key=lambda i: i[1])[0]
    outlist = [outdict[item[0]] for item in sorted(outdict.keys())]

    return (highestitem, outlist)

rawDescription: Reiterating over lists and dictionaries

description: Reiterating over lists and dictionaries


code:
from django.conf.urls import patterns, include, url
from django.contrib import admin

from . import views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'dj1.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),

    url(r'^myapp/', include('myapp.urls')),

)

rawDescription: Where to implement python classes in Django?


code:
'single quotes'
"double quotes"
""" triple-double quotes """  #This can contain line breaks!

rawDescription: String literal with triple quotes in function definitions


code: df.to_csv('powdata.txt', sep='\t')

rawDescription: Writing lists of data to a text file column by column


code:
indices = [125,144,192]
from itertools import product,izip,repeat
list(product(*izip(repeat(0,len(indices)),indices)))

rawDescription: Iterate over all possible combinations of list elements and use as indices in Python


code:
class dataMatrix:
    def __init__(self, filepath):
        self.path = filepath

        # Load the .csv file to count the columns.
        self.csvdataframe = pd.read_csv(filepath)
        self.numcolumns = len(self.csvdataframe.columns)
        self.csvdataframe.columns = range(self.numcolumns)

rawDescription: Using Pandas read_csv() on an open file twice


code: [d['value'] for d in l if 'value' in d]

rawDescription: python getting a list of value from list of dict

description: Python getting a list of value from list of dict


code:
import json
encoded = json.dumps(obj)
obj = json.loads(encoded)

rawDescription: Is something like ConfigParser appropriate for saving state (key, value) between runs?


code:
set2 = set(arr2)
[item for item in arr1 if item in set2]

rawDescription: Sort a list according to another list in Python


code:
classifier = PositiveNaiveBayesClassifier.train(positive_featuresets,
    unlabeled_featuresets)

rawDescription: Creating a feature dictionary for Python machine learning (naive bayes) algorithm


code: forms[3]['sex'] = ['male']

rawDescription: How do you select choices in a form using Python?

description: Select choices in a form using Python


code:
slice_indices(l=11, n=3)
slice_indices(l=30, n=4)

rawDescription: Splitting a list into a list of block indices


rawDescription: string: extract first six characters after the last /

description: String: extract first six characters after the last /


code: pairs = zip(p1, pK)

rawDescription: Shannon entropy to mutual information

description: Shannon entropy to mutual information


code:
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

rawDescription: Flask display user register, or already login in every template of each module


code:
class JonProperty(object):
    def __init__(self, name):
        self.name = name

    def __get__(self, obj, objtype):
        return getattr(obj, self.name)

    def __set__(self, obj, val):
        setattr(obj, self.name, float(val))

rawDescription: Can I add parameters to a python property to reduce code duplication?

description: Add parameters to a python property to reduce code duplication


code:
class Worker(QThread):
    intReady = pyqtSignal(int)

    def run(self):
        for i in range(1, 10):
            time.sleep(1)
            self.intReady.emit(i)

rawDescription: How do I keep GUI from freezing, while calling a function? (PyQT4, Python3)

description: Keep GUI from freezing, while calling a function? (PyQT4, Python3)


code:
class f(sy.Function):
    def inverse(self, argindex=1):
        return g

    def _eval_simplify(self, ratio, measure):
        if isinstance(self.args[0], self.inverse()):
            return self.args[0].args[0]
        return self

rawDescription: SymPy: simplifying of inverse function

description: SymPy: simplifying of inverse function


code:
class use_defaults:
    def __init__(self, deflt_func):
        self.deflt_func = deflt_func

    def __call__(self, func):
        defltargs = dict(zip(getargspec(self.deflt_func).args,
                            getargspec(self.deflt_func).defaults))

        defaults = (list(func.__defaults__)
                    if func.__defaults__ is not None
                    else [])

        func_args = reversed(getargspec(func).args[:-len(defaults)])

        for func_arg in func_args:
            if func_arg not in defltargs:
                # Default arguments doesn't allow gaps, ignore rest
                break
            defaults.insert(0, defltargs[func_arg])

        # Update list of default arguments
        func.__defaults__ = tuple(defaults)

        return func

def f(accuracy=1e-3, nstep=10, b = 'bbb'):
    print ('f', accuracy, nstep, b)

@use_defaults(f)
def g(first, accuracy, nstep, a = 'aaa'):
    f(accuracy, nstep)
    print ('g', first, accuracy, nstep, a)

g(True)
g(False, 2e-5)
g(True, nstep=32)

rawDescription: Avoiding code repetition in default arguments in Python


code: import socket, itertools; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(('', 5555)); s.listen(1); accepter = s.accept(); reduce(lambda x, y: accepter[0].recv(1024), itertools.count())

rawDescription: Python one liner silent socket listener

description: Python one liner silent socket listener


code:
def correct_over_six(exam_solutions, student_answers):
    correct = 0
    for x, y in zip(exam_solutions, student_answers):
        correct += (x == y)
        if correct >= 6:
            return True
    return False

rawDescription: compare the contents of two lists

description: Compare the contents of two lists


rawDescription: Subtract and add two lists without changing their order in Python


code:
for x, y in indices:
    mat[x][y] = 0

rawDescription: Access matrix by list of matrix indices in Numpy


code:
import sys
def importanyasname(actualname, fakename):
    __import__(actualname)
    sys.modules[fakename] = sys.modules[actualname]

rawDescription: How could you swap out a particular database implementation in python?


code: Y = pdist(X, f)

rawDescription: Clustering in python(scipy) with space and time variables


code:
UNASSIGNED = {'displayName': 'Unassigned'}
for issue in myVals:
    assignee = (issue['fields']['assignee'] or UNASSIGNED)['displayName']

rawDescription: Checking null object from JSON response in Python


code:
class Foo:
    pass

foo = Foo()
foo
type(foo)
foo.__class__
Foo.mro()
issubclass(Foo, object)
isinstance(foo, object)
type(foo).mro()
issubclass(type(foo), object)

rawDescription: Does NoneType class inherit object class?


rawDescription: How to do a paged query with empty collections in SQLAlchemy?

description: Do a paged query with empty collections in SQLAlchemy


code:
from operator import iadd

reduce(add, myList[0], [])

rawDescription: How to print list of list into one single list in python without using any for or while loop?

description: Print list of list into one single list in python without using any for or while loop


code: list_ip = host_list - ip_value

rawDescription: How to execute two loop simultaneously in python?

description: Execute two loop simultaneously in python


code: test_data['has_deposit'] is True

rawDescription: Python advice with some code

description: Python advice with some code


code: plt.hlines(centroids, xmin=0, xmax=len(data), lw=1.)

rawDescription: plot the centroid values over the existing plot using matplotlib

description: Plot the centroid values over the existing plot using matplotlib


code: hasattr(fn, '__call__')

rawDescription: python 3: how to check if an object is a function?

description: Python 3: how to check if an object is a function


rawDescription: Python/pandas idiom for if/then/else

description: Python/pandas idiom for if/then/else


code: data = json.loads(r.text[19:-1])

rawDescription: Parse JSON from response with python requests


code:
import import_me
from common import myapp_common1
from common import myapp_common2

rawDescription: Importing from another directory

description: Importing from another directory


code:
(data2
  .repartition("Year", "CountryCode")
  .groupBy("Year", "CountryCode")
  .pivot("IndicatorCode2", columns)
  .max("Value"))

rawDescription: Spark 1.6 DataFrame pivot funtion

description: Spark 1.6 DataFrame pivot funtion


code:
x, y = 0, 0
for i, (dx, dy) in enumerate(xy):
    x += dx
    y += dy
    xy[i] = (x, y)

rawDescription: Python: how to revise tuples in an list?

description: Python: how to revise tuples in an list


code:
import os
import mimetypes

from django import shortcuts
from django import http
from django.conf import settings
from django.views.static import was_modified_since
from django.utils.http import http_date

from .models import *

def serve_upload(request, upload_id):
    upload = shortcuts.get_object_or_404(UploadModel, pk=upload_id)
    fullpath = upload.file.path

    if request.user != upload.user:
        return http.HttpResponseForbidden()

    statobj = os.stat(fullpath)
    mimetype, encoding = mimetypes.guess_type(fullpath)
    mimetype = mimetype or 'application/octet-stream'
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return http.HttpResponseNotModified(mimetype=mimetype)
    response = http.HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    response["Content-Length"] = statobj.st_size
    if encoding:
        response["Content-Encoding"] = encoding
    return response

rawDescription: protecting user uploaded files django

description: Protecting user uploaded files django


code:
np.sum(np.atleast_2d(a), axis=1)
np.sum(np.atleast_2d(6.0), axis=1)

rawDescription: Sum up over np.array or np.float

description: Sum up over np.array or np.float


code:
url = self.request.get('url')

request = urllib2.Request(url)
request.get_method = lambda: 'HEAD'
response = urllib2.urlopen(request)
info = response.info()
content_length = int(info.get('Content-length'))
logging.debug('Downloading {}B video'.format(content_length))

del(info)
del(response)
del(request)

request = urllib2.Request(url)
start = 0
filename = '/MY-BUCKET/video/test_large.mp4'
f = gcs.open(filename, 'w', content_type='video/mp4')
while True:
    end = start + RANGE
    request.headers['Range'] = 'bytes={}-{}'.format(start, end)

    f.write(urllib2.urlopen(request, timeout=60).read())

    if end >= content_length:
        break

    start = end + 1

f.close()

rawDescription: Can AppEngine *pull* in data over 32MB?

description: Can AppEngine *pull* in data over 32MB


rawDescription: Access dictionary from a list

description: Access dictionary from a list


code:
my_list = []
for n in range(56000):
        my_list[n] = True

rawDescription: Reducing memory used by a large dict

description: Reducing memory used by a large dict


rawDescription: What is the purpose of the `//` operator in python?


code:
import random
inventory = ["Armour","Sword","Healing Potion"]
health=100

def randDmg():
    dealtDamage = random.randint(1,10)
    print("You have taken "+str(dealtDamage)+" damage.")
    return dealtDamage

def dmgCheck():
    global health
    damage = randDmg()
    if "Armour" in inventory:
        damage = damage/2
    else:
        damage = damage
    health-=damage
    return health

print("Your new health is" + str(dmgCheck()))
print("Your new health is" + str(dmgCheck()))

rawDescription: Python - Get a function to overwrite a variable


code:
class MyAction(argparse._StoreTrueAction):
    def __call__(self, parser, namespace, values, option_string=None):
        # adapt from _StoreConst
        # leave the self.dest set; could deactivate
        setattr(namespace, self.dest, self.const)
        setattr(namespace, 'flaga', True)
        setattr(namespace, 'flagb', True)

parser.add_argument("--flagc", action=MyAction)

print(parser.parse_args('--flaga'.split()))
print(parser.parse_args('--flagc'.split()))
print(parser.parse_args('--flagc --no-flaga'.split()))

rawDescription: CLI option that is an aggregation of two other options and precedence, in python


code:
@BuildResets
class Session(object):
    self.a_set = Persist(False)
    self.b_set = Reset(False)
    def reset(self):
        for name in self.resetable:
            setattr(self, name, False)

rawDescription: Python object state tracking idiom

description: Python object state tracking idiom


code:
if x in set([1,2,3]):
    pass # do something

rawDescription: Using lists and tuples in Python if statements


code:
if (sign) == 2 and (answer) == number1+number2:
    score += 1

rawDescription: Python v3.3.5 maths questions program

description: Python v3.3.5 maths questions program


code: _file = re.sub(r'BEGIN COPYRIGHT[\w\s]*?END COPYRIGHT',_copyright, _file)

rawDescription: Replacing a string between two strings on more then one occation with regex, python


code: m = pd.melt(df, id_vars=['Year'], var_name='Name')

rawDescription: Pandas Melt Function

description: Pandas Melt Function


code:
def __init__(self, **flags):
    self.__dict__.update(flags)

rawDescription: Is there a shorthand to create member variables from function arguments in python?


code:
squared_X = X.copy()
# now square the data in squared_X
squared_X.data **= 2

# and sum each row:
squared_sum = squared_X.sum(1)
# and delete the squared_X:
del squared_X

rawDescription: element-wise operations on a sparse matrix

description: Element-wise operations on a sparse matrix


rawDescription: How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay?

description: Find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay


code:
@bottle.hook('before_request')
def setup_request():
    try:
        beaker_session = request.environ['beaker.session']
    except:
        #redirect('/login')
        abort(401, "Failed beaker_session in slash")

    try:
        name = beaker_session['name']
    except:
        redirect('/login')

rawDescription: bottle hooks with beaker session middleware and checking logins

description: Bottle hooks with beaker session middleware and checking logins


code:
df1
df2

rawDescription: pandas merging based on a timestamp which do not match exactly

description: Pandas merging based on a timestamp which do not match exactly


code: setattr(myobject, "a", value)

rawDescription: Passing an Python Class Attribute Given a String


code:
from django.core.exceptions import ObjectDoesNotExist
try:
    p2.restaurant
except ObjectDoesNotExist:
    print("There is no restaurant here.")

rawDescription: Check if a OneToOne relation exists in Django


code: self.tail = self.tail.next = Element(element, None)

rawDescription: Issue with Python implementation of assignment chaining


code:
#! /usr/bin/python3.2

import tkinter
import Pmw

root = tkinter.Tk()
Pmw.initialise(root)

sf = Pmw.ScrolledFrame(root)
sf._clipper.config(width=100, height = 200)
sf.interior().configure(height=80, width=80, bg='yellow')

sf.pack()

root.mainloop()

rawDescription: Tkinter ScrolledFrame initial dimensions


code:
b1 = Block() # Makes a block object.
b1.block_color # Will access b1's unique color.

rawDescription: Implementing an ever changing color system in pygame


rawDescription: Python - regex to match url with mongo object id


code: next((i,x) for i,x in enumerate(a) if x > 1.3)

rawDescription: Getting the index of a list for the first value that satisfies a criterion


code: names = type("Names", [object], myvars)

rawDescription: Parse key value pairs in a text file

description: Parse key value pairs in a text file


code: p.apply(np.sum, axis='major')  # use linalg function here instead of np.sum

rawDescription: How to combine the data from many data frames into a single data frame with an array as the data values

description: Combine the data from many data frames into a single data frame with an array as the data values


rawDescription: Cumulative addition/multiplication in NumPy


code:
""" Module that monkey-patches json module when it's imported so
JSONEncoder.default() automatically checks for a special "to_json()"
method and uses it to encode the object if found.
"""
from json import JSONEncoder

def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj)

_default.default = JSONEncoder().default  # Save unmodified default.
JSONEncoder.default = _default # replacement

rawDescription: Making object JSON serializable with regular encoder


code:
for elem in soup:
    if getattr(elem, 'name', None) == u'html':
        soup = elem
        break

soup.find_all('meta')

rawDescription: Beautifulsoup functionality not working properly in specific senario


code:
def produce_steps():
    while condition:
        ...
        yield step_value

for count, step_value in enumerate(produce_steps()):
    ...

rawDescription: Using enumerate function in while loops

description: Using enumerate function in while loops


code:
class FooForm(forms.ModelForm):
    class Meta:
        model = Foo
    my_option = ChoiceField(
        label = 'Options',
        choices = (
            (0, 'Don\'t change anything.'),
            (1, 'Do some crazy stuff.'),
            (2, 'Do other stuff.'),
        ),
        initial = 0,
        widget = RadioSelect,
    )

rawDescription: Django Admin Radio Buttons

description: Django Admin Radio Buttons


code:
p1 = subprocess.Popen(['ps', 'ax'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'bash'], stdin=p1.stdout,    stdout=subprocess.PIPE)
p3 = subprocess.Popen(['wc', '-l'], stdin=p2.stdout, stdout=subprocess.PIPE); p3.stdout.read()
p1 = subprocess.Popen(['ps', 'ax'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'bash'], stdin=p1.stdout,    stdout=subprocess.PIPE)
p3 = subprocess.Popen(['wc', '-l'], stdin=p2.stdout, stdout=subprocess.PIPE); p3.stdout.read()
p1 = subprocess.Popen(['ps', 'ax'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'bash'], stdin=p1.stdout,    stdout=subprocess.PIPE)
p3 = subprocess.Popen(['wc', '-l'], stdin=p2.stdout, stdout=subprocess.PIPE); p3.stdout.read()
p1 = subprocess.Popen(['ps', 'ax'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'bash'], stdin=p1.stdout,    stdout=subprocess.PIPE)
p3 = subprocess.Popen(['wc', '-l'], stdin=p2.stdout, stdout=subprocess.PIPE); p3.stdout.read()
p1 = subprocess.Popen(['ps', 'ax'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'bash'], stdin=p1.stdout,    stdout=subprocess.PIPE)
p3 = subprocess.Popen(['wc', '-l'], stdin=p2.stdout, stdout=subprocess.PIPE); p3.stdout.read()
p = subprocess.Popen('ps -ef | grep bash | wc -l ', stdout=subprocess.PIPE, shell=True) ; print(''.join(p.stdout.readlines()))
p = subprocess.Popen('ps -ef | grep bash | wc -l ', stdout=subprocess.PIPE, shell=True) ; print(''.join(p.stdout.readlines()))
p = subprocess.Popen('ps -ef | grep bash | wc -l ', stdout=subprocess.PIPE, shell=True) ; print(''.join(p.stdout.readlines()))
p = subprocess.Popen('ps -ef | grep [b]ash | wc -l ', stdout=subprocess.PIPE, shell=True) ; print(''.join(p.stdout.readlines()))
p = subprocess.Popen('ps -ef | grep [b]ash | wc -l ', stdout=subprocess.PIPE, shell=True) ; print(''.join(p.stdout.readlines()))
p = subprocess.Popen('ps -ef | grep [b]ash | wc -l ', stdout=subprocess.PIPE, shell=True) ; print(''.join(p.stdout.readlines()))

rawDescription: How can I combine three subprocess.popen into one line?

description: Combine three subprocess.popen into one line


code:
class CreateContactSerializer(serializers.Serializer):
    email_address = serializers.EmailField()
    status = serializers.SerializerMethodField('get_alternative_status')
    merge_fields = serializers.SerializerMethodField('get_merge_fields')

    def get_alternative_status(self, obj):
        return "subscribed"

    def get_merge_fields(self, obj):
        return {
            "FNAME": obj.first_name,
            "LNAME": obj.surname
        }

rawDescription: Make serializer for nested values in Django rest serializer


code:
fig = figure()
ax = Axes3D(fig)
ax.contour(xi, yi, zi) # ax.contourf for filled contours
show()

rawDescription: Plotting 3-tuple data points in a surface / contour plot using matplotlib


code:
import numpy as np
a = np.array([[1, 2],[3, 1]])
np.std(a, axis=0)
np.std(a, axis=0, ddof=1)

rawDescription: Difference between R.scale() and sklearn.preprocessing.scale()


code:
img
b = img < 100
b
pixels = img[b]
pixels
list(pixels)

rawDescription: Making Pixel Histogram.ValueError: The truth value of an array with more than one element is ambiguous


code:
from multiprocessing.pool import ThreadPool

def is_ssh_up(hostname, port=22):
    # try to connect here
    # ...
    # return results
    return hostname, is_up

hosts = ["host1", "host2", "google.com", "host3"]
pool = ThreadPool(20) # limit number of concurrent connections to 20
for hostname, is_up in pool.imap_unordered(is_ssh_up, hosts):
    status = "Up" if is_up else "Down" if is_up is not None else "Unknown"
    print("%s status is %s" % (hostname, status))

rawDescription: python : threads do not work properly in daemon

description: Python : threads do not work properly in daemon


rawDescription: How to efficiently select entries by date in python?

description: Efficiently select entries by date in python


code:
data = {
    "data1" : number1,
    "data2" : number2,
    "data3" : number3,
}

rawDescription: Finding a string in a list and returning a secondary value with python


code:
import regex
regex.findall(r'\p{Sc}', '$99.99 / €77')  # Python 3.x

rawDescription: What is regex for currency symbol?

description: What is regex for currency symbol


code: [[x,l.count(x)] for x in set(l)]

rawDescription: counting the number of samples in a numpy array

description: Counting the number of samples in a numpy array


code:
# package directory __init__.py
__version__ = 1.0

rawDescription: How do I assign a version number for a Python package using SVN and distutils?

description: Assign a version number for a Python package using SVN and distutils


rawDescription: Detect missing multiplication in math expression


code: print("".join([str(x) for x in l]))

rawDescription: list with numbers and strings to single string python

description: List with numbers and strings to single string python


code:
import numpy as np
from scipy.ndimage.interpolation import shift

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

shift(xs, 3, cval=np.NaN)

rawDescription: Shift elements in a numpy array

description: Shift elements in a numpy array


code:
import logging
logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s %(process)d/%(threadName)s: %(message)s")
logging.getLogger('this.is.the.module').warning('Testing for SO')

rawDescription: logger chain in python

description: Logger chain in python


code:
import pickle

list_of_ee = [["a","m",15],["w","p",34]]

with open("test.pickle", "wb") as f:
    f.write(pickle.dumps(list_of_ee))

with open("test.pickle", "rb") as f:
    bytes_data = f.read()
    lst = pickle.loads(bytes_data)

print(lst)
assert list_of_ee == lst

rawDescription: Import csv as list of list in python 3.3


code:
class RoomOutsideError(Exception):
    pass

# ...

def create_room(room):
    global map
    #set all tiles inside the room to passable

    # check for limits and raise exception
    #    (this will need handling outside this function)
    max_x, max_y = len(map) - 1, len(max[0]) - 1
    if room.x1+1 > max_x or room.x2 > max_x or \
       room.y1+1 > max_y or room.y2 > max_y:
           raise RoomOutsideError("Room outside map.")

    for x in range(room.x1 + 1, room.x2):
        for y in range(room.y1 + 1, room.y2):
            map[x][y].blocked = False
            map[x][y].block_sight = False

rawDescription: IndexError: list index out of range

description: IndexError: list index out of range


code:
import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

rawDescription: How to save and load cookies using python selenium webdriver

description: Save and load cookies using python selenium webdriver


code:
# Load modules and create a random graph
import networkx as nx, matplotlib.pyplot as plt
G = nx.gnp_random_graph(10, 0.15)

# Identify the largest component and the "isolated" nodes
components = list(nx.connected_components(G)) # list because it returns a generator
components.sort(key=len, reverse=True)
largest = components.pop(0)
isolated = set( g for cc in components for g in cc )

# Draw the graph
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos=pos, nodelist=largest, node_color='r')
nx.draw_networkx_nodes(G, pos=pos, nodelist=isolated, node_color='b')
nx.draw_networkx_edges(G, pos=pos)
plt.show()

rawDescription: Find and count the number of isolated and semi-isolated nodes in a network


code:
template = select_template(self.get_template_names())
latex_content = template.render(context)
latex_content = re.sub(r'\{ ', '{', latex_content)
latex_content = re.sub(r' \}', '}', latex_content)

rawDescription: How to properly set variables in a latex template for Django

description: Properly set variables in a latex template for Django


rawDescription: Python datetime formatted string to datetime object


code:
#this will get your folks in alpha
lines = f.readlines()
lines.sort()

#now, on each line, you want to split (that attrgetter is too complicated and
#blows up if <> 3 grades.

# use the special feature of split() with no parameter to remove all spaces and \t characters
fields = line.split()
name, grades = fields[0], fields[1:]

#cast your grades to integers
grades = [int(grade) for grade in grades]

#sort and pick the last one
grades.sort()
highest = grades[-1]

#or... use max as suggested
highest = max(grades)

#write to output file....

rawDescription: How to sort specific info in a file

description: Sort specific info in a file


code:
def log_event(context, event, params):
    context.log_event("Something happened %s, %s", event, params)

rawDescription: How does the functools partial work in Python?


rawDescription: How to convert utf-8 string to big5 with python?

description: Convert utf-8 string to big5 with python


code:
df.index.names = ['foo', 'bar']
df

rawDescription: convert sublevel into a single column

description: Convert sublevel into a single column


code:
outfile = open("numbers.csv", "a")

outfile.write(str(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) + "," + str(round(number_1, 2)) + "," + str(round(number_2, 2)) + "," + str(round(number_3, 2))+ "," + str(round(number_4, 2)) + "," + str(round(number_5, 2)) + "," + str(round(number_6, 2)) + "," + str(round(number_7, 2)) + "," + str(round(number_8, 2)) + "," + str(round(number_9, 2)) +"\n")

rawDescription: writing strings to 2 decimal places in a cvs file

description: Writing strings to 2 decimal places in a cvs file


code:
df = DataFrame(dict(A = [1.5,2.5], B = [2.5,3.0]))
df
df.applymap(lambda x: str(x).replace('.',','))

rawDescription: Python PANDAS write to csv: how to set decimal point (".", or ",")?


code:
import cPickle as pickle
import subprocess

class SomeClass(object):
    def FTPDownload(self):
        try:
            # The -u argument puts stdin, stdout and stderr into binary mode
            # (as well an makes them unbuffered). This is needed to avoid
            # an issue with writing pickle data to streams in text mode
            # on Windows.
            ftpReq = subprocess.Popen(['python', '-u', 'dwnldMedia.py'],
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            stdout, stderr = ftpReq.communicate()
            if stdout:
                # convert object returned into a Python obj
                results = pickle.loads(stdout)
                print('  successful: {successful}'.format(**results))
                print('unsuccessful: {unsuccessful}'.format(**results))
            if stderr:
                print("stderr:\n{}".format(stderr))
        except subprocess.CalledProcessError as exception:
            print('exception: {}'.format(str(exception)))

if __name__ == '__main__':
    instance = SomeClass()
    instance.FTPDownload()

rawDescription: How to get subprocess.Popen to work correctly?

description: Get subprocess.Popen to work correctly


code:
[{'name': 'inAnalysis', 'order': 1},
 {'name': 'inQuest', 'order': 3},
 {'name': 'inDevelopment', 'order': 2}]

rawDescription: Adding a key value pair to a list of dicts based on another list Python


code:
from pprint import pformat as pf

class Matrix(object):
    def __init__(self, arrayOfRows=None, rows=None, cols=None):
        if arrayOfRows:
            self.data = arrayOfRows
        else:
            self.data = [[0 for c in range(cols)] for r in range(rows)]
        self.rows = len(self.data)
        self.cols = len(self.data[0])

    @property
    def shape(self):          # myMatrix.shape -> (4,3)
        return (self.rows, self.cols)
    def __getitem__(self, i): # lets you do myMatrix[row][col
        return self.data[i]
    def __str__(self):        # pretty string formatting
        return pf(self.data)

    @classmethod
    def map(cls, func, *matrices):
        assert len(set(m.shape for m in matrices))==1, 'Not all matrices same shape'

        rows,cols = matrices[0].shape
        new = Matrix(rows=rows, cols=cols)
        for r in range(rows):
            for c in range(cols):
                new[r][c] = func(*[m[r][c] for m in matrices], r=r, c=c)
        return new

rawDescription: Add two matrices in python

description: Add two matrices in python


code:
num1=int(input('Enter your number range: '))
items = list()
for x in range(1,num1+1):
    if x % 3 == 0:
        items.append("Fizz")
    if x % 5 == 0:
        items.append('Buzz')
    if x % 3 != 0 and x % 5 != 0:
        items.append(str(x))

print(*items, sep=',')

rawDescription: how do i properly make a for loop sit on one line, with commas and no spaces

description: Properly make a for loop sit on one line, with commas and no spaces


code:
def alter_list_data_to_serialize(self, request, data):
    """
    A hook to alter list data just before it gets serialized & sent to the user.

    Useful for restructuring/renaming aspects of the what's going to be
    sent.

    Should accommodate for a list of objects, generally also including
    meta data.
    """
    return data

rawDescription: django tastypie get related column total amount

description: Django tastypie get related column total amount


code:
@route('/my/internal/route')
@private_only
def internal_view():
    return some_data()

rawDescription: How to filter IP addresses by route in bottle?

description: Filter IP addresses by route in bottle


code:
l2d_labels = {}
l2d_labels[line2D_obj] = labels #labels having previously been defined

rawDescription: What is a simple, yet proper, way to add a container to a pre-exisiting object in python?


code:
import subprocess

reply = int(raw_input("Enter 1, 2 or 3: "))
commands = [[r'c:\delprof2\DelProf2.exe', '/l', '/c:' + item]
            for item in [itroom, second, csupport][reply - 1]]
# start child processes in parallel
children = map(subprocess.Popen, commands)
# wait for processes to complete, raise an exception if any of subprocesses fail
for process, cmd in zip(children, commands):
    if process.wait() != 0: # failed
       raise subprocess.CalledProcessError(process.returncode, cmd)

rawDescription: How do you add mutiple arguments to a subprocess line?

description: Add mutiple arguments to a subprocess line


code:
with MyZipFile('new.zip', 'w') as tempzip: # Use content manager of MyZipFile
  tempzip.write('sbdtools.py') # Write file to our archive

rawDescription: where is the __enter__ and __exit__ defined for zipfile?

description: Where is the __enter__ and __exit__ defined for zipfile


code:
def addtrans(services=services):
    ...
    # check that both users exist
    if not services.user_exists(to_id) or not services.user_exists(from_id):
        return "no such users"
    ...

rawDescription: How to mock the service layer in a python (flask) webapp for unit testing?

description: Mock the service layer in a python (flask) webapp for unit testing


code:
arr1 = np.array([1.7]) # shape (1,)
np.atleast_2d(arr1)
_.shape

rawDescription: Python: How can I force 1-element NumPy arrays to be two-dimensional?


code:
MY_ACCOUNTS = [
    {'login': 'my_login_1', 'pwd': 'my_pwd_1'},
    {'login': 'my_login_2', 'pwd': 'my_pwd_2'},
]

rawDescription: Scrap multiple accounts aka multiple logins


code:
import weakref

class Node:
# If this is Python 2, you need to explicitly inherit from object to
# be a new-style class with descriptor support (which allows properties), so
# the class line would be:
# class Node(object):
# On Py3, it's implicit and can be omitted

    # Ensure attribute readable so getter/setter don't need to use has/getattr
    # Will be allocated per-instance when self.parent is assigned in __init__
    # So on Py3.3+, it will still get the compact key-sharing dicts for attributes
    _parent = None

    # Adding defaults for all values matching Camera for simplicity
    def __init__(self, name='', attributes=None, children=None, parent=None):
        self.name = name
        self.attributes = attributes if attributes is not None else {}
        self.children = children if children is not None else []
        self.parent = parent
        for child in children:
            child.parent = self

    @property
    def parent(self):
        return self._parent() if self._parent is not None else None

    @parent.setter
    def parent(self, newparent):
        oldparent = self.parent
        # If setting to existing parent, then no-op
        # Remove this check and early-out if you want to be able to move
        # a node to the end of its parent's children by reassigning the same parent
        if newparent is oldparent:
            return
        if oldparent is not None:
            oldparent.children.remove(self)
        if self not in newparent.children:
            newparent.children.append(self)
        self._parent = weakref.ref(newparent) if newparent is not None else None

rawDescription: python parent child relationship class

description: Python parent child relationship class


code:
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.reverse import reverse

class ParameterisedHyperlinkedIdentityField(HyperlinkedIdentityField):
    """
    Represents the instance, or a property on the instance, using hyperlinking.

    lookup_fields is a tuple of tuples of the form:
        ('model_field', 'url_parameter')
    """
    lookup_fields = (('pk', 'pk'),)

    def __init__(self, *args, **kwargs):
        self.lookup_fields = kwargs.pop('lookup_fields', self.lookup_fields)
        super(ParameterisedHyperlinkedIdentityField, self).__init__(*args, **kwargs)

    def get_url(self, obj, view_name, request, format):
        """
        Given an object, return the URL that hyperlinks to the object.

        May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
        attributes are not configured to correctly match the URL conf.
        """
        kwargs = {}
        for model_field, url_param in self.lookup_fields:
            attr = obj
            for field in model_field.split('.'):
                attr = getattr(attr,field)
            kwargs[url_param] = attr

        return reverse(view_name, kwargs=kwargs, request=request, format=format)

rawDescription: django-rest-framework HyperlinkedIdentityField with multiple lookup args

description: Django-rest-framework HyperlinkedIdentityField with multiple lookup args


rawDescription: Django related key of the same model

description: Django related key of the same model


rawDescription: Use of SQL - IN in python

description: Use of SQL - IN in python


code:
for x in range(n):
    game=quietCraps()

rawDescription: Python calling a function with another function


code:
daysSick = [0, 0, 0, 0, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 6, 11, 15, 24]

# using a function
idxL = lambda val, lst:  [i for i,d in enumerate(lst) if d==val]

allVals = idxL(0,daysSick)
(0, 3)

rawDescription: How to do a binary search for a range of the same value?

description: Do a binary search for a range of the same value


rawDescription: How to remove \n from a list element?

description: Remove \n from a list element


code:
infile = open('hey.txt','r+')
content = infile.read()
text = ['foo','bar']
for item in text:
     content +=item  #adds 'foo' on first iteration, 'bar' on second
infile.write(content)
infile.close()

rawDescription: I need to open and rewrite a line in a file in Python


code:
success_flag = '/tmp/success.flag'
cmd = [ 'script', '-q', '-c', "sleep 2 && touch " + success_flag, '/dev/null']

rawDescription: Making sure a Python script with subprocesses dies on SIGINT


code:
flat_coord = np.ravel_multi_index(coord.T, (3,3))
sums = np.bincount(flat_coord, weights)
a = np.zeros((3,3))
a.flat[:len(sums)] = sums
a

rawDescription: Map arrays with duplicate indexes?

description: Map arrays with duplicate indexes


code:
import numpy as np
dat = bytearray(b'\x01\x00\x02\x00\x03\x00\x04\x00')
data = np.frombuffer(buffer(dat), dtype=np.uint16)

rawDescription: Reading binary data (image data type) from SQL database and inflate it, Matlab vs. Python


code:
opts, args = getopt.getopt(argv, "u:s")
urls = opts[0][1].split()

rawDescription: Python getopt get unlimited args

description: Python getopt get unlimited args


code:
for padsel in (pad[1:16] + [pad[0]]):
    print(str(hexlify(padsel)) +  "- selected pad")
    for i in range(256):    #increment guess
        g = unhexlify("000000000000000000000000000000" + "{:02x}".format(i))
        print(str(hexlify(g)) + "- guess")
        if attack(g,padsel,ct_prev, ct_target):
            m2 += "{:02x}".format(i)
            print(m2)
            break
        else:
            continue
m2 = m2[::-1]
print(m2 + "- m2")

rawDescription: Python - loop through list in specific order


code: 'Python stellatum'

rawDescription: Python 2.7.8 string slicing by letter?

description: Python 2.7.8 string slicing by letter


code: totalsum = np.sum([i * matrix for i in arr], 0)

rawDescription: Make numpy.sum() return a sum of matrices instead of a single number


code: a = ['Hello{}'.format(b) for b in a]

rawDescription: python add string to the start of each element in array

description: Python add string to the start of each element in array


rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


rawDescription: Python "none" printing

description: Python "none" printing


code:
myDicts = []
for i in myDictionary:
    data = {'event': '...', 'timestamp': '...'}
    myDicts.append(data)

rawDescription: Django For loop template for dict data

description: Django For loop template for dict data


rawDescription: NumPy: counting sizes of row-wise intersections between two arrays


rawDescription: How can I get pyplot images to show on a console app?

description: Get pyplot images to show on a console app


code:
from tkinter import *
from evilOverlappingModule import *

rawDescription: Tkinter importing without *?

description: Tkinter importing without *


code:
date_name = date_soup.find_all('a')[:203]
print([item.get_text(strip=True) for item in date_name])

rawDescription: Removing items from list if is not in '<a href'?


rawDescription: Python search folder and make a Dictionary


code:
request_queue = Queue()
for i in range(4):
    Worker( request_queue ).start()
for data in the_real_source:
    request_queue.put( data )
# Sentinel objects to allow clean shutdown: 1 per worker.
for i in range(4):
    request_queue.put( None )

rawDescription: python Pool with worker Processes

description: Python Pool with worker Processes


code:
def smallest_value_greater_than_0(numbers):
    value, key = min((v, k) for k, v in numbers.iteritems() if v > 0)
    return key, value

numbs = dict(A=2, B=3, C=0)
key, value = smallest_value_greater_than_0(numbs)     # key="A", value=2

rawDescription: How can I write a function that returns the smallest value greater than 0 from a list?

description: Write a function that returns the smallest value greater than 0 from a list


code:
class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        self.impl = _GetchUnix()
    def __call__(self):
        return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys
    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

getch = _Getch()

rawDescription: Python key binding/capture

description: Python key binding/capture


code:
for item in tree.iter('item'):
    product_id =  item.find('product_id').text
    product_name = item.find('product_name').text
    product_url = item.find('product_url').text
    advertiser = item.find('advertiser').text
    designer = item.find('designer').text
    image_url = item.find('image_url').text
    price = item.find('price').text
    commission = item.find('commission').text
    product_to_save = Product.objects.create(product_id=product_id, product_name=product_name, product_url=product_url, advertiser=advertiser, designer=designer, image_url=image_url, price=price, commission=commission)
    product_to_save.save()

rawDescription: Iterating ElementTree In Python Django

description: Iterating ElementTree In Python Django


code: instance = form.save(commit=False)

rawDescription: How can I save the same form more than once in Django 1.8?

description: Save the same form more than once in Django 1.8


code:
from itertools import product
num_loops = 5 # len(data) in your case
for item in product(range(n), repeat=num_loops):
    ... # item is a 5-tuple

rawDescription: How to handle a variable number of nested for loops?

description: Handle a variable number of nested for loops


code: [(exponent, sum(v for _,v in values)) for exponent, values in l_grouped]

rawDescription: How to add items in a list of tuples if the item is the same

description: Add items in a list of tuples if the item is the same


code:
{
    'owner__name': 'Richard',
    'adopted_date': 'date',
    'owner__count': 2
}

rawDescription: Annotate a column field from relation on django


code:
import csv

with open('Pfa.csv') as f: #'r' is default
    for row in csv.reader(f):
        key = row[0]
        try:
            values = Ndates[key]
            i = values.index(row[1])
        except (KeyError, ValueError):
            pass
        else:
            values.insert(i, row[4]) #this will insert *before* the match; use i + 1 insert *after*

rawDescription: Python: inserting into a list within a dictionary based on matching


code: from .other_file import some_func

rawDescription: Import with files names conflict

description: Import with files names conflict


code:
for key, group in groupby(data, key=itemgetter('Organization')):
    result[key] = {'Phone': [],
                   'Email': [],
                   'Website': []}
    for item in group:
        result[key]['Phone'].append(item['Phone'])
        result[key]['Email'].append(item['Email'])
        result[key]['Website'].append(item['Website'])

rawDescription: Sort a list of dictionaries while consolidating duplicates in Python?


code:
class MyEnum(object):
    One = 1
    Two = 2
    Three = 3

rawDescription: Q_ENUMS in PyQt4

description: Q_ENUMS in PyQt4


code:
negatives = np.where(cross_test < 0)
positives = np.where(cross_test >= 0)
plot(x, y1)
plot(x, y2)
plot(x, z)
plt.vlines(x_intersect[negatives], -20, 20)

rawDescription: Find the area between two curves ploted in matplotlib (fill_between area)


code: sorted = [text[i:i+2] for i in range(0, len(text), 2)]

rawDescription: Transpose multiple txt data files and import into excel or database


rawDescription: Find span where condition is True using NumPy


rawDescription: Matrix addition using triples representation in Python


code: print({k:d[k] for k in l if k in d})

rawDescription: Slicing a dictionary

description: Slicing a dictionary


code:
def get_freq_squared(shape, packed_complex=True):
    """Return the frequency squared for an n-d array.
    The returned image will match shape, if packed_complex is true the last
    dimension will be treated as 0,f,...,nf rather than 0,f,..., nf,...,-f
    """
    vecs = [np.fft.fftfreq(s, 1.0 / s) ** 2 for s in shape]

    if packed_complex:
        s = shape[-1]
        olds = (s-1)*2
        vecs[-1] = rfftfreq(olds, 1.0/olds)**2
    return reduce(np.add.outer, vecs)

rawDescription: Is there any python (numpy) synonym to i-variables (e.g., irow, iradius, itheta, etc.) in DM scripting?


rawDescription: Python: Why this tuple is printing the result and "None"? Also: Is there a better way to achieve the result?


code:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.properties import NumericProperty, ReferenceListProperty,\
    ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from random import randint

class PongPaddle(Widget):
    score = NumericProperty(0)
    orientation = ObjectProperty([0, 0])
    can_move = ObjectProperty(0)

    def bounce_ball(self, ball):
        if self.collide_widget(ball):
            vx, vy = ball.velocity
            if self.orientation[0] == 25:
                offset = (ball.center_y - self.center_y) / (self.height / 2)
                bounced = Vector(-1 * vx, vy)
                vel = bounced * 1.1
                ball.velocity = vel.x, vel.y + offset
            else:
                offset = (ball.center_x - self.center_x) / (self.width / 2)
                bounced = Vector(vx, -1 * vy)
                vel = bounced * 1.1
                ball.velocity = vel.x + offset, vel.y

class PongBall(Widget):
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)
    player3 = ObjectProperty(None)
    player4 = ObjectProperty(None)

    def initialize(self):
        SCORE = 1
        self.player1.orientation = [25, 200]
        self.player2.orientation = [25, 200]
        self.player3.orientation = [200, 25]
        self.player4.orientation = [200, 25]
        self.player1.score = SCORE
        self.player2.score = SCORE
        self.player3.score = SCORE
        self.player4.score = SCORE
        self.player1.can_move = 1
        self.player2.can_move = 1
        self.player3.can_move = 1
        self.player4.can_move = 1
        self.serve_ball()

    def serve_ball(self, vel=(4, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel

    def update(self, dt):
        self.ball.move()

        #bounce of paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)
        self.player3.bounce_ball(self.ball)
        self.player4.bounce_ball(self.ball)

        #bounce ball off bottom or top
        if ((self.ball.y < self.y) and not self.player3.can_move) \
           or ((self.ball.top > self.top) and not self.player4.can_move):
            self.ball.velocity_y *= -1
        if ((self.ball.x < self.x) and not self.player1.can_move) \
           or ((self.ball.right > self.width) and not self.player2.can_move):
            self.ball.velocity_x *= -1

        #went off to a side to score point?
        if self.ball.x < self.x and self.player1.can_move == 1:
            self.player1.score -= 1
            self.serve_ball(vel=(4, randint(1, 4)))
            if self.player1.score <= 0:
                self.player1.can_move = 0
        elif self.ball.x > self.width and self.player2.can_move == 1:
            self.player2.score -= 1
            self.serve_ball(vel=(-4, randint(1, 4)))
            if self.player2.score <= 0:
                self.player2.can_move = 0
        elif self.ball.y > self.height and self.player4.can_move == 1:
            self.player4.score -= 1
            self.serve_ball(vel = (randint(1, 4), -4))
            if self.player4.score <= 0:
                self.player4.can_move = 0
        elif self.ball.y < self.y and self.player3.can_move == 1:
            self.player3.score -= 1
            self.serve_ball(vel = (randint(1, 4), 4))
            if self.player3.score <= 0:
                self.player3.can_move = 0

        if self.player1.can_move + self.player2.can_move + \
           self.player3.can_move + self.player4.can_move == 1:
            self.ball.velocity = (0, 0)
            Clock.unschedule(self.update)

            self.win_label = Label(size_hint=(None, None),
                              text='[ref=winner]Winner![/ref]',
                              markup=True, font_size=70, color=[1,0,0,1])
            #win_label.texture_update()
            #self.win_label.pos = (self.width / 2, self.height / 2 - 70)
            self.win_label.center = self.center
##            win_label.size =  win_label.texture_size[0] + 20, \
##                             win_label.texture_size[1] + 20
            self.win_label.bind(on_ref_press=self.click_win_label)
            self.win_label.texture_update()
            self.add_widget(self.win_label)

    def click_win_label(self, instance, value):
        self.remove_widget(self.win_label)
        #self.remove_widget(instance) # this should also work:
        self.initialize()
        Clock.schedule_interval(self.update, 1.0 / 60.0)

    def on_touch_move(self, touch):
        if touch.x < self.width / 3 and touch.y > self.height / 6 \
            and touch.y < 5 * self.height / 6 and self.player1.can_move:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3 and touch.y > self.height / 6 \
            and touch.y < 5 * self.height / 6 and self.player2.can_move:
            self.player2.center_y = touch.y
        if touch.y < self.height / 3 and touch.x > self.width / 6 \
            and touch.x < 5 * self.width / 6 and self.player3.can_move:
            self.player3.center_x = touch.x
        if touch.y > 2* self.height / 3 and touch.x > self.width / 6 \
            and touch.x < 5 * self.width / 6 and self.player4.can_move:
            self.player4.center_x = touch.x

class PongApp(App):
    def build(self):
        game = PongGame()
        game.initialize()
        #game.serve_ball()
        Clock.schedule_interval(game.update, 1.0 / 60.0)
        return game

if __name__ == '__main__':
    PongApp().run()

rawDescription: Kivy - adding and removing labels

description: Kivy - adding and removing labels


code:
class Foo():
    pass

rawDescription: Python new-style classes and __subclasses__ function


code: print("6 Month Cost: %.2fUSD" % (cost * .6))

rawDescription: Round an answer to 2 decimal places in Python


rawDescription: Python Pandas cumulative column between datetime ranges


code:
odd_list = x[::2]
even_list = x[1::2]

rawDescription: Binary search a function, depending on even and odd input


rawDescription: Convert string to image in python

description: Convert string to image in python


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

a = zip(*indices)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(a[0], a[1], a[2])
plt.xlabel('x')
plt.ylabel('y')
plt.show()

rawDescription: Triangular indices for multidimensional arrays in numpy


rawDescription: Pandas count the number of different items within a column of data


code: translated = "".join(amino_acids.get(i, '!') for i in chunks("".join(rna), 3))

rawDescription: RNA to PROTEIN program questions

description: RNA to PROTEIN program questions


code:
columns = []
with open(file,'rU') as f:
    reader = csv.reader(f)
    for row in reader:
        if columns:
            for i, value in enumerate(row):
                columns[i].append(value)
        else:
            # first row
            columns = [[value] for value in row]
# you now have a column-major 2D array of your file.
as_dict = {c[0] : c[1:] for c in columns}
print(as_dict)

rawDescription: python csv to dictionary columnwise

description: Python csv to dictionary columnwise


rawDescription: Making nonzero elements in grayscale array equal to 1 in 'G' column in an RGB array in Python


code:
protein = '''DIMGYF*GLTGSR*VLSSGWIRAQSCTECG*SSEAGVEVRGVRQTDRHSQPARSAV*
SELQILFSFHLLSNCPELAPVAPGLVFRECPESLVSSRPREESPAAQALLTAAESSGTHAPAGGSRRAAAAA
KNFPGWEDRRQVAESRSQLLQAFPAS*ASPRR*RPEGGGEPRKRRRTCAQLRSHRLLNLGEREPRLPGAPSP
*QRRRGQVVGVRAAKTRRRPATAGSALIRSAGRAAALGSEFACGLRGTAAHEERSVSDRDFSKPGSARESTS
KSAGGILINPALPGASW*GGRSGDDSQRVRALLEKLSLSKAPGGAGVPRLPQPCCGPETCARSPN*PHVK*
RTVL*LQRWKRPSMTMPSTPRSSRPRADLMATVTPRS*'''

#Get rid of newlines
protein = protein.replace('\n', '')

print("5'3' Frame 1:\n{0}\n".format(protein))

maxloop = len(protein)
n = 0
while n < maxloop:
    met = protein.find("M", n)
    if met == -1:
        break

    stop = protein.find("*", met)
    if stop == -1:
        print('Error: no * found for frame starting at residue', met + 1)
        break

    orf = protein[met:stop]
    print("Open reading frame starting at residue", met + 1, ":", orf)

    n = stop + 1

rawDescription: Printing all occurrences in a string starting with x and ending with y


code:
class MyClass(object): pass

myobjects = {}
myobjects['key-name'] = MyClass()
myvar = myobjects['key-name']  # some time later...
myvar # what is myvar?
myobjects['key-name'] # myobjects['key-name'] is the same object

rawDescription: How can I get back the dynamically created objects of a class?

description: Get back the dynamically created objects of a class


code:
from .models import Post

def detail(request, post_id):
    try:
        post = Post.objects.get(pk=question_id)
    except Post.DoesNotExist:
        raise Http404("Error 404")
    return render(request, 'detail.html', {'post': post})

def remove(request, post_id):
    try:
        post = Post.objects.get(pk=question_id)
        post.remove()
    except Post.DoesNotExist:
        raise Http404("Error 404")
    return render(request, 'confirm.html', {'message': 'Post was removed'})

rawDescription: Call an object's method from Django's Template on click


code:
def getValueForSpecificKey(self, capturedLog, key, results=None):
    '''
    Get value from log for any specific key.
    capturedLog will be searched if it is a list or dictionary.
    Returns an empty list if the key is not found, or capturedLog is another type.
    '''
    if results is None:
        results = []               # start a new list if this is a non-recursive call

    if isinstance(capturedLog, dict):
        if key in capturedLog:
            results.append(capturedLog[key])     # found a result, add it to the list
            return results

        values = capturedLog.values()

    elif isinstance(capturedLog, list):
        values = capturedLog

    else:
        return results

    for value in values:  # recursive calls will add to the results list as necessary
        self.getValueForSpecificKey(value, key, results)

    return results

rawDescription: How to reset a global variable in python "recursive" function?

description: Reset a global variable in python "recursive" function


code:
dates = df['sample_date'].apply(lambda x: x.date())
total = df.groupby([dates, 'metric_name']).sum()
print(total)
#                               sample
# sample_date metric_name
# 2012-10-03  linkedin_profile     257
#             twitter_profile      972
#             youtube_video      19136

rawDescription: Transformations with DataFrame exporting series


code:
def switching_function(*args):
    some_screen_manager.current = 'whatever'

some_button.bind(on_press=switching_function)

rawDescription: Kivy: Changing screens in screen manager with an on_press event


code:
ROUTES = (webapp2.Route('/tasks/extraction', ExtractionWorker),
          webapp2.Route('/tasks/indexer', IndexingWorker))

rawDescription: App engine tasks are not executed in defined target


code:
exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
keyValList = ['type2','type3']
expectedResult = [d for d in exampleSet if d['type'] in keyValList]
expectedResult

rawDescription: python filter list of dictionaries based on key value

description: Python filter list of dictionaries based on key value


code:
import numpy as np
arr = np.recarray(10,dtype=[('x',int),('y',float,4)])
arr[:] = 0
arr
arr['x']
arr['y']

rawDescription: how to (simply) build a integer and float mixed numpy array


code:
['one|a|left',
 'one|a|right',
 'one|b|left',
 'one|b|right',
 'two|a|left',
 'two|a|right',
 'two|b|left',
 'two|b|right',
 'three|a|left',
 'three|a|right',
 'three|b|left',
 'three|b|right']

rawDescription: Python 3.3: All possible combinations of list


code:
if all(key in list for key in [keyword0, keyword1]):
    # do your work
    pass

rawDescription: Checking for a string/keyword in a list

description: Checking for a string/keyword in a list


code:
# get absolute path to proj/__init__.py
script_path = os.path.realpath(__file__)

# strip off the file name to get the absolute path to proj
proj_path = os.path.dirname(script_path)

# join on os.sep to get absolute path to proj/submodFolder
submod_path = os.path.join(proj_path, 'submodFolder')

# add the complete path to proj/submodFolder to sys.path
sys.path.append(submod_path)

rawDescription: python import from sub-directory in a git safe way

description: Python import from sub-directory in a git safe way


code: c = [b[i] for i in index]

rawDescription: Python: an efficient way to slice a list with a index list


rawDescription: Django -- Conditional Login Redirect

description: Django -- Conditional Login Redirect


code:
# Get indices  for sorted data
sort_idx = np.argsort(data,axis=1)

# Get sorted linear indices
row_offset = data.shape[1]*np.arange(data.shape[0])[:,None]
sort_lin_idx = sort_idx[:,1::] + row_offset

# Get duplicate linear indices and set those in data as 0s
dup_lin_idx = sort_lin_idx[np.diff(np.sort(data,axis=1),axis=1)==0]
data.ravel()[dup_lin_idx] = 0

rawDescription: Set duplicate elements as zeros

description: Set duplicate elements as zeros


code: "this" "is" "a test"

rawDescription: Python file delimited with double tabs

description: Python file delimited with double tabs


rawDescription: How to find all the indexes of all the occurrences of a word in a string

description: Find all the indexes of all the occurrences of a word in a string


code:
reports_by_status = {}
for report in reports:
    reports_by_status.set_default(report.status, []).append(report)

rawDescription: Is there a better way to split of objects by one of its attributes?


code:
type(ny)
type(wikipedia.page)

rawDescription: listing all attributes of an object

description: Listing all attributes of an object


code:
if any(word in stopWords for word in msg.split()):
    ...

rawDescription: If I have a list of words, how can I check if string does not contain any of the words in the list, and efficiently?


code:
import re
s="four digits 1234 five digits 56789 six digits 012345"
re.findall(r"\D(\d{5})\D", s)

rawDescription: Python Regular Expression Match All 5 Digit Numbers but None Larger


code:
def hasNoDuplicates(values):
    foundCounterExampleYet = False
    value = None
    while values:
       value = values.pop()
       if value in values:
           foundCounterExampleYet = True
           break
    return not(foundCounterExampleYet)

rawDescription: Test for list without duplicated elements


code:
def word_from_lst(lst, word):
    lst_ = lst[:]
    for c in word:
        if c in lst_:
          lst_.remove(c)
        else:
          return False
    return True

rawDescription: How to remove strings from a list in Python in a loop so it won't be used as a duplicate?

description: Remove strings from a list in Python in a loop so it won't be used as a duplicate


code:
def do_SAY(self, *msg):
    broadcast('SAID {} {}'.format(self.number, ' '.join(msg)))

rawDescription: Multiplayer Gaming via python

description: Multiplayer Gaming via python


code:
namespaces = {'ex': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'} # add more as needed

for cube in root.findall('.//ex:Cube[@currency]', namespaces=namespaces):
    print(cube.attrib['currency'], cube.attrib['rate'])

rawDescription: How to parse XML file from European Central Bank with Python

description: Parse XML file from European Central Bank with Python


code:
schema1 = SomeClass.SomeSchema
schema2 = schema1

rawDescription: Python Changes Both Variables When Set Equal?


code:
def firstMatch (date, lst):
    for i, sublist in enumerate(lst):
        if sublist[0] == date:
            return i

rawDescription: Index a list of lists

description: Index a list of lists


rawDescription: Difficulty creating new list grouping by a key using itertools in python


code:
for x in L[:]:
    if x == 1:
        L.remove(x)

L

rawDescription: Python - How to remove similar elements from a list?


code:
# Enthought library imports.
from envisage.ui.action.api import Action, Group, Menu, ToolBar
from envisage.ui.workbench.api import WorkbenchActionSet

class TestActionSet(WorkbenchActionSet):
    """ An action test useful for testing. """

    #### 'ActionSet' interface ################################################

    tool_bars = [
        ToolBar(name='Fred', groups=['AToolBarGroup']),
        ToolBar(name='Wilma'),
        ToolBar(name='Barney')
    ]

    actions = [
        Action(
            path='ToolBar',
            class_name='acme.workbench.action.new_view_action:NewViewAction'
        ),]

rawDescription: Python envisage framework

description: Python envisage framework


code:
import argparse

parser = argparse.ArgumentParser(description='SO test.')
parser.add_argument('--doh', action='store_true')
parser.add_argument('files', nargs='*')  # This is it!!
args = parser.parse_args()
print(args.doh)
print(args.files)

rawDescription: Using argparse in conjunction with sys.argv in Python


code:
import dbus

def advertise_service(sdp_record_xml):
    bus = dbus.SystemBus()
    manager = dbus.Interface(bus.get_object("org.bluez", "/"),
                             "org.bluez.Manager")
    adapter_path = manager.FindAdapter(self.device_id)
    service = dbus.Interface(bus.get_object("org.bluez", adapter_path),
                             "org.bluez.Service")
    service.AddRecord(sdp_record_xml)

rawDescription: Writing HID service with PyBluez

description: Writing HID service with PyBluez


code:
def post(self):
  deferred.defer(collectSomeStatistics,args)
  self.response.out.write("some output")

rawDescription: Processing data after returning content - GAE Python


code:
import pandas as pd
import numpy as np
data = np.random.random((8,3))*10000
df = pd.DataFrame (data)
pd.options.display.float_format = '{:20,.2f}'.format
print(df)

rawDescription: Py Pandas .format(dataframe)

description: Py Pandas .format(dataframe)


code: print('hello',5,end='**\n') # Python3 syntax, breaks on Python2

rawDescription: How to specify Python 3 source in Cython's setup.py?

description: Specify Python 3 source in Cython's setup.py


rawDescription: accessing lambda value passed to function python

description: Accessing lambda value passed to function python


rawDescription: NumPy - Set values in structured array based on other values in structured array


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

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

# modified string: I added a few terms
z = x*(k*a**9) + (k**1)*x**2 - k*a**8 + y*x*(k**2) + y*(x**2)*k**3 + x*(k*a**1) - k*a**3 + y*a**5

zmod = Add(*[argi for argi in z.args if argi.has(a)])

rawDescription: Collecting like term of an expression in Sympy


code:
import statsmodels.formula.api as sm
import numpy as np

data = {"a":[2, 3, 5], "b":[2, 3, 5], "c":[2, 3, 5]}
model = sm.ols(formula = 'a ~ np.power(b, 2) + b + c', data = data).fit()

rawDescription: python stats models - quadratic term in regression

description: Python stats models - quadratic term in regression


rawDescription: creating dictionary from space separated key=value string in python

description: Creating dictionary from space separated key=value string in python


code: ani = animation.FuncAnimation(fig, update, frames=data_gen(a), init_func=init, interval=10, blit=True)

rawDescription: matplotlib animation FuncAnimation frames argument

description: Matplotlib animation FuncAnimation frames argument


code: sorted(c, key=c.get)[-2]

rawDescription: How to find the 2nd max of a Counter - Python

description: Find the 2nd max of a Counter - Python


code: all(e.strip() in list2 for e in list1)

rawDescription: How to ignore '\n' while comparing two lists

description: Ignore '\n' while comparing two lists


code:
Model.clean()
""" This method should be used to provide custom model validation, and to
modify attributes on your model if desired. For instance, you could use it to
automatically provide a value for a field, or to do validation that requires
access to more than a single field: """

def clean(self):
    from django.core.exceptions import ValidationError

    if self.status == 'draft' and self.pub_date is not None:
        raise ValidationError('Draft entries may not have a publication date.')

rawDescription: Django sql check

description: Django sql check


code:
class Base:
    __count = 0

    @classmethod
    def _count(cls):
        Base.__count += 1
        return Base.__count

    def __init__(self):
        self.__id = self._count()

    @property
    def id(self):
        return self.__id

rawDescription: How to count the number of instance of a custom class?

description: Count the number of instance of a custom class


rawDescription: Generating iterables of iterables with python itertools. (using the repeat function)


code:
#!/usr/bin/env python
import time

def posix_time(utc_time_tuple):
    """seconds since Epoch as defined by POSIX."""
    # from https://gist.github.com/zed/ff4e35df3887c1f82002
    tm_year = utc_time_tuple.tm_year - 1900
    tm_yday = utc_time_tuple.tm_yday - 1
    tm_hour = utc_time_tuple.tm_hour
    tm_min = utc_time_tuple.tm_min
    tm_sec = utc_time_tuple.tm_sec
    # http://pubs.opengroup.org/stage7tc1/basedefs/V1_chap04.html#tag_04_15
    return (tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
            (tm_year-70)*31536000 + ((tm_year-69)//4)*86400 -
            ((tm_year-1)//100)*86400 + ((tm_year+299)//400)*86400)

now = time.localtime()
yesterday = time.gmtime(posix_time(now) - 86400)
print(yesterday)
# -> time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=22, tm_min=6, tm_sec=16, tm_wday=2, tm_yday=112, tm_isdst=0)

rawDescription: Time - get yesterdays date

description: Time - get yesterdays date


code:
import timeit
timeit.timeit('map(str.strip, "QVOD, Baidu Player".split(","))', number=100000)
timeit.timeit('map(stripper, "QVOD, Baidu Player".split(","))','stripper=str.strip', number=100000)
timeit.timeit("[item.strip() for item in 'QVOD, Baidu Player'.split(',')]", number=100000)

rawDescription: Splitting string and removing whitespace Python


code:
from subprocess import call, DEVNULL

if __name__ == "__main__":
    call('echo hello', shell=True, stdout=DEVNULL, stderr=DEVNULL)

rawDescription: Supressing output with os.system()

description: Supressing output with os.system()


code:
import numpy as np

def blit(dest, src, loc):
    pos = [i if i >= 0 else None for i in loc]
    neg = [-i if i < 0 else None for i in loc]
    target = dest[[slice(i,None) for i in pos]]
    src = src[[slice(i, j) for i,j in zip(neg, target.shape)]]
    target[[slice(None, i) for i in src.shape]] = src
    return dest

print(blit(np.zeros((7,7)), np.ones((3,3)), (5, 5)))

rawDescription: numpy blit (copy part of an array to another one with a different size)

description: Numpy blit (copy part of an array to another one with a different size)


code:
s = "foo    bar  baz                        bam"
countSpaces(s)

rawDescription: removing excess spaces from a string (and counting them)

description: Removing excess spaces from a string (and counting them)


code:
a  =Object()
b = Object()
a.speed = 5
b.speed = 10
a.speed, b.speed
a.set_all_speed(20)
a.speed, b.speed

rawDescription: Changing variables in multiple Python instances


code:
from sklearn import svm
X = [[1, 1, 0], [0, 0, 2]] # training data features
y = [0, 1] # class labels
clf = svm.SVC()
clf.fit(X, y)

rawDescription: What statistical learning algorithm library should I use?


rawDescription: pandas: calculate over multiindex

description: Pandas: calculate over multiindex


code: df_city['weighted_jobs'] = df_city['weight'] * df_city['jobs']

rawDescription: pandas: groupby and variable weights

description: Pandas: groupby and variable weights


code: testing = __name__ != "__main__"

rawDescription: Can I determine if an application is being run normally vs via a unittest in Python?

description: Determine if an application is being run normally vs via a unittest in Python


code:
import time
import multiprocessing as mp

def foo(x = 1):
    cnt = 1
    while True:
        time.sleep(1)
        print(x, cnt)
        cnt += 1

def timeout(func, args = (), kwds = {}, timeout = 1, default = None):
    pool = mp.Pool(processes = 1)
    result = pool.apply_async(func, args = args, kwds = kwds)
    try:
        val = result.get(timeout = timeout)
    except mp.TimeoutError:
        pool.terminate()
        return default
    else:
        pool.close()
        pool.join()
        return val

if __name__ == '__main__':
    print(timeout(foo, kwds = {'x': 'Hi'}, timeout = 3, default = 'Bye'))
    print(timeout(foo, args = (2,), timeout = 2, default = 'Sayonara'))

rawDescription: Timeout function using threading in python does not work