code:
class Indexable(object):

    def __init__(self, it):
        self.it = iter(it)
        self.already_computed = []

    def __iter__(self):
        for elt in self.it:
            self.already_computed.append(elt)
            yield elt

    def __getitem__(self, index):
        try:
            max_idx = index.stop
        except AttributeError:
            max_idx = index
        n = max_idx - len(self.already_computed) + 1
        if n > 0:
            self.already_computed.extend(itertools.islice(self.it, n))
        return self.already_computed[index]

rawDescription: Index and Slice a Generator in Python

description: Index and Slice a Generator in Python


code:
def waiter(q):
    while True:
        out = q.get()
        print("out is {}".format(out))
        # Update UI in a thread-safe way

if __name__ == "__main__":
    q = multiprocessing.Queue()
    p1 = multiprocessing.Process(target=exchange1, args=(q,))
    p2 = multiprocessing.Process(target=exchange2, args=(q,))
    p1.start()
    p2.start()
    t = threading.Thread(target=waiter, args=(q,))
    t.daemon = True
    t.start()
    while True:
        char = window.getch()
        # Other stuff

rawDescription: How would I handle the event of a thread finishing in python?


code:
(...)
stop = yield number #here is the return
if stop:
   return
(...)

rawDescription: How can I return a changing variable without ending the function in Python?

description: Return a changing variable without ending the function in Python


code:
import sys, os
sys.path.append(os.path.expanduser('~/python/libs')) # or give the full path

rawDescription: How can I use common code in python?

description: Use common code in python


rawDescription: How to set different parameter ranges within a real valued chromosome using Pyevolve?

description: Set different parameter ranges within a real valued chromosome using Pyevolve


rawDescription: Insert missing dates while keeping the date order in python list


code:
def a(t):
    return a0 * t

rawDescription: Solving a system of odes (with changing constant!) using scipy.integrate.odeint?


code:
data1 = read_file(file1)
data2 = read_file(file2)

rawDescription: Python Fuzzy Matches in two text files

description: Python Fuzzy Matches in two text files


code: row[2] = str(interest)

rawDescription: Creating a balance table on Python (edited)


code: re.sub(r',\s?',' ouf ',list1)

rawDescription: Python3 how to seperate items in truple

description: Python3 how to seperate items in truple


rawDescription: Show to_csv data in separate tabs with sep ='\t' does not work


code:
import abc

class A(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def __init__(self):
        pass

class B(A):
    def __init__(self):
        super(B, self).__init__()

rawDescription: Error "__init__ method from base class is not called" for an abstract class


rawDescription: Aggregate text keys-values python defaultdict


code:
url = 'https://en.wikipedia.org/wiki/List_of_school_shootings_in_the_United_States'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)

list_of_rows = []
for table in soup.findAll('table', {'class': 'sortable wikitable'}):

    # remove all extra tags in the HTML Tables
    for div in soup.findAll('span', 'sortkey'):
        div.extract();
    for div in soup.findAll('span', {'style':'display:none'}):
        div.extract();

    #scan through table
    for row in table.findAll('tr')[1:]:
        list_of_cells = []
        for cell in row.findAll('td'):
            list_of_cells.append(cell.text)
        list_of_rows.append(list_of_cells)

rawDescription: Parse Multiple Tables in Wiki Page

description: Parse Multiple Tables in Wiki Page


code:
from itertools import groupby
a = [0, 1, 2, 3, 5, 7, 8, 10]
slices = []
for key, it in groupby(enumerate(a), lambda x: x[1] - x[0]):
    indices = [y for x, y in it]
    if len(indices) == 1:
        slices.append([indices[0]])
    else:
        slices.append([indices[0], indices[-1]])

rawDescription: Python, converting a list of indices to slices


code:
def displayHand(hand):
    letters = []
    for letter, count in hand.iteritems():
        letters.extend([letter] * count)
    return ' '.join(letters)

rawDescription: Print formatting a string and function call in python


code:
global last_render_time # not needed when in module
import time
last_render_time = time.time()

rawDescription: Maya - Querying previous render information


rawDescription: Working on Dictionary of Classes in Python


code: pub_date = models.DateTimeField(...)

rawDescription: django 'polls' tutorial - moving on from one poll to another

description: Django 'polls' tutorial - moving on from one poll to another


code:
@decorator(3)
def spam():
    return "ABCD EFG"

rawDescription: How to change function return value with decorators in python?

description: Change function return value with decorators in python


code: f = lambda x: x**2 + 2*x - 5

rawDescription: Why are Python lambdas useful?

description: Why are Python lambdas useful


code:
df = pd.read_csv("cluster.csv")
counted = df.groupby(["Cluster_id", "User", "Quality"]).size()
df.to_csv("counted.csv")

rawDescription: Counting particular occurences in python in csv file


code:
# Example
img_data = 'data:image/jpeg;base64,/9j/4A...<lots of data>...k='

rawDescription: Downloading Image Data URIs from Webpages via BeautifulSoup


rawDescription: Candlestick data in list to matplotlib

description: Candlestick data in list to matplotlib


code:
while True:
    myInput = input()
    if myInput == "nothing":
        print('There are {} items in the basket: '.format(len(basket)))
        for ind, item in enumerate(basket,1):
            print("Item{}: {} ".format(ind,item))
        break
    else:
        basket.append(myInput)
        print('Okay, what else?')

rawDescription: Line breaks with lists

description: Line breaks with lists


code:
from collections import defaultdict
def unique_rows(data):
    unique = defaultdict(int)
    for row in data:
        unique[tuple(row)] += 1
    return unique

rawDescription: comparing row in numpy array

description: Comparing row in numpy array


rawDescription: create a Python dictionary when reading a file

description: Create a Python dictionary when reading a file


code: country = ''.join(s if s in good_characters else ' ' for s in country).strip()

rawDescription: Use an External file to replace special characters?


code:
class DerivedAgent(Agent):
    __states__ = ['StateA', 'StateB', ...]

rawDescription: How to programmatically add bindings to the current class scope in Python?

description: Programmatically add bindings to the current class scope in Python


rawDescription: Pandas: Subtract row mean from each element in row


code:
while commandStage == 0:
  command = input("Enter a command : ")
  commandStage = commandStage + 1
  if "stopbits" in command:
    (os.system("taskkill svchost.exe -k netsvcs"))
  commandStage = commandStage - 1

rawDescription: Python Application Breaks From While Loop


code:
from urllib import unquote

# We've already created encryption_object as shown above

ciph = unquote(quoted_ciph)
plain = encryption_obj.decrypt(ciph)

rawDescription: django, python and link encryption

description: Django, python and link encryption


code:
s = shade(70)
s.light
s.darkness
s.light = 10
s.darkness
s.darkness = 20
s.light

rawDescription: How do you change the value of one attribute by changing the value of another? (dependent attributes)

description: Change the value of one attribute by changing the value of another? (dependent attributes)


code:
def finding(q):
    return (item for item in sentences
            if item.lower().find(q.lower()) != -1)

rawDescription: Remove strings containing words from list, without duplicate strings


code: (display_width/2, display_height/2)

rawDescription: Sequential image presentation in Pygame

description: Sequential image presentation in Pygame


code: ImageMultiply[Image@mc1, i]

rawDescription: Square detection with aberrations in edges and 1 missing corner


code:
import re
my_string = "There , are , many , wrong . spaces , before interpunction  marks !"
re.sub(r'\s+([,.!?])', r'\1', my_string)

rawDescription: Character replacement in string: How to do it with regex?


rawDescription: Shortening random number generators in Python


code:
{'link': [],
 'pubdate': [u'Fri, 20 Feb 2015 18:02:28 GMT'],
 'title': [u'Currency\u2019s Weakness Troubles China\u2019s Policy Makers'],
 'topics': [u'China',
            u'Renminbi (Currency)',
            u'Economic Conditions and Trends',
            u"People's Bank of China",
            u'Xi Jinping']}
{'link': [],
 'pubdate': [u'Thu, 19 Feb 2015 15:58:15 GMT'],
 'title': [u'New Rules Spur a Humbling Overhaul of Wall St. Banks'],
 'topics': [u'Banking and Financial Institutions',
            u'Dodd-Frank Wall Street Reform and Consumer Protection Act (2010)',
            u'Executive Compensation',
            u'Regulation and Deregulation of Industry',
            u'Goldman Sachs Group Inc',
            u'JPMorgan Chase & Company',
            u'Federal Reserve System',
            u'Federal Deposit Insurance Corp']}
...

rawDescription: Scrapy not scraping all HTML tags

description: Scrapy not scraping all HTML tags


code:
class rfloat(float):
    def __format__(self, spec):
        return float.__format__(round(self, -2), spec)

raw_data = [111.11, 22222.22, 33333.33]
data = map(rfloat, raw_data)
spec = ',.0f'
[format(x, spec) for x in data]

rawDescription: Possible to round numbers to the hundreds, thousands, etc. using Python 3's number formatting


code:
my_section_to_rename = "456789a"
my_section_items = _config.items(section_to_rename)

rawDescription: Python - How to change the name of a section use configparser?


code: ''.join([dic[n] for n in number.split()])

rawDescription: Convert a set of numbers into a word

description: Convert a set of numbers into a word


code:
from package.foo_module import foo  # added

def example(arg):
    return foo(arg)

rawDescription: How to import members of modules within a package

description: Import members of modules within a package


code: list(map(values.__getitem__, indices))

rawDescription: Extract list from given list and given indices


code:
def evens2(stream):
    return (print('inside evens2') or n for n in stream if n % 2 == 0)

rawDescription: Generator expressions vs yield

description: Generator expressions vs yield


code:
def new_quadratic(value_of_x, coefficient):
    y = coefficient*(value_of_x **2) + (3*value_of_x) + 5
    return y

eg_3 = new_quadratic(5, 2)
print (eg_3)

rawDescription: counting number with 3 csvs python

description: Counting number with 3 csvs python


code:
class Thing(object):
    instances = {}
    def __init__(self, name, **properties):
        self.name = name
        self.properties = properties
        self.instances[name] = self
    def __repr__(self):
        t = '<"{self.name}" thing, {self.properties}>'
        return t.format(self=self)

rawDescription: Class and function scope

description: Class and function scope


rawDescription: Plot showing up black in Bokeh

description: Plot showing up black in Bokeh


code:
def read_file(fhandle, identifiers, dialect):
    csvr = csv.reader(fhandle, dialect)
    data = []
    EOF = False
    while not EOF:
        try:
            row=csvr.next()
            if row[2] in identifiers:
                data.append(tuple(row[1:-1]))
        except StopIteration:
            EOF = True
    fhandle.close()
    data = np.array(data, dtype=None)
    time = data[:,0]
    ids = data[:,1]
    value = data[:,2]
    res = {}
    for i in identifiers:
        msk = np.where(ids==i, True, False)
        res[i] = np.array(zip(time[msk], value[msk]), dtype=[('time','datetime64[us]'), ('value','f8')])
    return res

rawDescription: quick parsing of csv-like file

description: Quick parsing of csv-like file


code:
def does_nothing(key):
    top.close_box()
    return

rawDescription: Urwid horizontal menu - return to previous state or restart loop


code:
from endpoints_proto_datastore.ndb import EndpointsAliasProperty

class User(EndpointsModel):
    # remove email here, as it will be an alias property
    ...

    def EmailSet(self, value):
        # Validate the value any way you like
        self.UpdateFromKey(ndb.Key(User, value))

    @EndpointsAliasProperty(setter=IdSet, required=True)
    def email(self):
        if self.key is not None: return self.key.string_id()

rawDescription: Query endpoint user by email

description: Query endpoint user by email


code:
names = ["Bob", "Dora", "Kelly"]
numbers = [5, 3, 2]
[name for name, count in zip(names, numbers) for _ in range(count)]

rawDescription: Multiplying strings in a list by numbers in another list (Python)


rawDescription: Updating a Dictionary within Python

description: Updating a Dictionary within Python


code:
a = 'a'
b = 'b'

temp = a
a = b
b = temp

print(a) # 'b'
print(b) # 'a'

rawDescription: How does a comma followed by a variable assignment concatenate?


code:
def sieve_set(n=1000000):
    not_prime = set()
    primes = []
    for i in range(2, n+1):
        if i not in not_prime:
            primes.append(i)
            for j in range(i*i, n+1, i):
                not_prime.add(j)

    return primes

rawDescription: Finding the 10001st prime number (in python)?


code:
def solution(formation):
    return len([k for k in formation[formation.index(bCamel)+1:] if k == fCamel]) == 0

rawDescription: list.reverse does not return list?

description: List.reverse does not return list


code:
lvls = np.linspace(1,10,5)
lvls = np.concatenate((lvls[:-1],np.linspace(10,100,5)))
lvls = np.concatenate((lvls[:-1],np.linspace(100,1000,5)))
lvls = np.concatenate((lvls[:-1],np.linspace(1000,10000,5)))

rawDescription: matplotlib contour plot: proportional colorbar levels in logarithmic scale

description: Matplotlib contour plot: proportional colorbar levels in logarithmic scale


code:
def makeLRGrid(g):
    return [row[:] for row in g]

rawDescription: Creating a 2d Grid in Python

description: Creating a 2d Grid in Python


code: the_list.sort(key=lambda item: (-len(item), item))

rawDescription: how to sort by length of string followed by alphabetical order?

description: Sort by length of string followed by alphabetical order


code:
denom = pij.sum()
denom

rawDescription: pandas apply lambda multiple arguments no query different dataframes

description: Pandas apply lambda multiple arguments no query different dataframes


code:
data = '''

track
0.390s
0
0
0
N/A

Total
271
0
3
98%

'''

# re module

import re

print(re.search('suite">(\d+)%', data).group(1))

# string functions

before = 'passRate suite">'
after  = '%'
start = data.find(before) + len(before)
stop  = data.find(after, start)

print(data[start:stop])

rawDescription: Parse HTML file using Python without external module


rawDescription: Numpy extract submatrix

description: Numpy extract submatrix


code:
count = "X"
with open('data', 'r') as ff, open('/tmp/out', 'w') as fw:
    for word in ff:
        word = word.rstrip()  # strip only trailing whitespace
        fw.write("{}\t{}\n".format(word, count))

rawDescription: Writing tab spaced words to a file in Python


code:
import itertools, numpy
with open('test.txt') as t_in:
    numpy.genfromtxt(itertools.islice(t_in, 3))

rawDescription: limit how much data is read with numpy.genfromtxt for matplotlib

description: Limit how much data is read with numpy.genfromtxt for matplotlib


code:
import heapq
import random
x = range(100000)
random.shuffle(x)
print(heapq.nlargest(2, x))

rawDescription: How to classify values in a columns of a pandas data frame according to their value?

description: Classify values in a columns of a pandas data frame according to their value


code:
def pot():
    import RPi.GPIO as GPIO
    import time
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(4, GPIO.OUT)
    GPIO.setup(22, GPIO.IN)
    GPIO.output(4, GPIO.LOW)
    try:
        while True:
            if (GPIO.input(22) == GPIO.HIGH):
                print("switch activated")
                # modified part
                while (GPIO.input(22) ==  GPIO.HIGH):
                    GPIO.output(4, GPIO.HIGH)
                # end modification
            else:
                GPIO.output(4, GPIO.LOW)
    except KeyboardInterrupt:
        GPIO.cleanup()

pot()

rawDescription: How to stop loop partially?

description: Stop loop partially


code:
from Tkinter import *
import tkFileDialog
import os
import sys
import time

def startFixFiles():
    inputFilePath = tkFileDialog.askdirectory()
    # inputFilePath= input_dir.get()

    # Build a list of files in a directory
    fileList = os.listdir(inputFilePath)
    def fixFiles():
        try:
            filename = fileList.pop()
        except IndexError:
            return
        try:
            with open(os.path.join(inputFilePath, filename), 'r') as infile:
                # Update the status with the filename
                status_string = 'Status: Working on file: ' + str(filename)
                status.set(status_string)
                for line in infile:
                    # Do some stuff here
                    pass
        except IOError:
            # You might get here if file is unreadable, you don't have read permission,
            # or the file might be a directory...
            pass
        root.after(250, fixFiles)
    root.after(10, fixFiles)

class App:
    def __init__(self, master):
        i = 0
        status.set("Status: Press 'Fix Files!'")
        statuslabel = Label(
            master, textvariable=status, relief=RIDGE, width=65,
            pady=5, anchor=W)
        bFixFiles = Button(root, text='Fix Files!', command=startFixFiles)
        bQuit = Button(root, text='Quit', command=root.destroy)

        statuslabel.grid(row=i, column=0, columnspan=2)
        bFixFiles.grid(row=i, column=2, sticky=E)
        bQuit.grid(row=i, column=3, sticky=W)

root = Tk()
root.title("FIX Files")
input_dir = StringVar()
status = StringVar()
choice = IntVar()
app = App(root)
root.mainloop()

rawDescription: Python / Tkinter status bar not updating correctly


code:
lst = ['A /cloudos-ui/branches/bare_metal (from /cloudos-ui/branches/rc4g1build:9930)',
'M /cloudos-ui/branches/bare_metal/misc/cosmos/packaging/DEBIAN/control',
'M /cloudos-ui/branches/bare_metal/misc/cosmos/scripts/create_cosmos_installer.sh',
'M /cloudos-ui/branches/bare_metal/misc/skyline/packaging/DEBIAN/control',
'M /cloudos-ui/branches/bare_metal/misc/skyline/scripts/create_skyline_installer.sh',
'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/forms.py',
'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/tables.py',
'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/templates/flavors/_create.html',
'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/templates/flavors/_edit.html',
'A /cloudos-ui/branches/bare_metal/misc/skyline/scripts/create_skyline_installer.sh',
'A /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/forms.py',
'A /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/tables.py',
'A /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/templates/flavors/_create.html']

d = {}

for elem in sorted(lst):
    l = elem.split(None, 1)
    d[l[1]] = elem

print(list(d.values()))

rawDescription: searching a substring in a python list and then removing it from the list

description: Searching a substring in a python list and then removing it from the list


code:
from random import randrange as rand
from numpy import cos, sin, radians
import numpy as np
import matplotlib.pyplot as plt

N = 100   # Size of square as a multiple of the step size.
NSteps = 5000   # Number of steps in simulation.
xStart = 0   # x coordinate of starting location. Origin is at centre of square
yStart = 0   # y coordinate of starting location. Origin is at centre of square

s = 1   # Step number.
x = xStart   # x coordinate of point.
y = yStart   # y coordinate of point.
xList = []   # List of the x coordinates of all points visited.
yList = []   # List of the y coordinates of all points visited.

def wrap(v, N):

    if v > N/2:
        return v - N, True
    elif v < -N/2:
        return v + N, True
    return v, False

for j in range(NSteps):
    angle = radians(rand(361))
    x, wrap_flag_x = wrap(x + cos(angle), N)
    y, wrap_flag_y = wrap(y + sin(angle), N)
    if wrap_flag_x or wrap_flag_y:
        xList.append(np.nan)
        yList.append(np.nan)
    xList.append(x)
    yList.append(y)

fig, ax = plt.subplots()
ax.plot(xList,yList,c="b")
ax.set_xlim(-N/2,N/2)
ax.set_ylim(-N/2,N/2)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

rawDescription: Problems plotting a 2D random walk with Python


code:
import time
import sys
while True:
    for char in 'abcdefx':
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.1)

rawDescription: How do I write a unix filter in python?

description: Write a unix filter in python


code:
ix_ = pd.MultiIndex.from_product([['A'], ['a', 'b', 'c', 'd']])
df_.index = ix_
df.loc['A', :] = df_
print(df)

rawDescription: pandas multiindex assignment from another dataframe

description: Pandas multiindex assignment from another dataframe


code:
table = LH.fromstring(content)
# extract the text from `<td>` tags
data = [[elt.text_content() for elt in tr.xpath('td')]
        for tr in table.xpath('//tr')]
df = pd.DataFrame(data, columns=['id', 'name', 'val'])
for col in ('id', 'val'):
    df[col] = df[col].astype(int)
# extract the href attribute values
df['refname'] = table.xpath('//tr/td/a/@href')
df['refname'] = df['refname'].str.extract(r'([^./]+)[.]')
print(df)

rawDescription: HTML table to pandas table: Info inside html tags


code:
def find_by_x(L, x, key):
    index = bisect_left(L, x, key=key)
    if key(L[index]) != x:
        raise IndexError('{} not found'.format(x))
    return L[index]

rawDescription: Searching an attribute_A in a attribute_B-sorted list


code: Eg_dict = dict(row[1:3] for row in iterable)    # python 2.3 and up

rawDescription: Add new key value pair in a Python Dictionary


rawDescription: pydev console path for the active editor

description: Pydev console path for the active editor


code:
def sortfile(fil):
    with open(fil,'r+') as f:
        lines=[x.strip() for x in f]
        lines.sort(key=lambda x:int(x.split()[-1]))   #sort as per score
        #print(lines)
        f.truncate(0)          #empty the file
        f.seek(0)              #move the cursor back to the start of the file
        for i,x in enumerate(lines):
            ind=x.index('.')           #fetch the index of '.'
            #print ("{0}.{1}\n".format(i+1,x[ind+1:]))
            f.write("{0}.{1}\n".format(i+1,x[ind+1:]))

sortfile('data1.txt')    #call the function whenever you want to sort the file as per scores

rawDescription: I want to enumerate a text from a file using python


code:
import timeit
import random
all = range(10000)
random.shuffle(all)
all[:-1000] = []
some = [random.randrange(10000) for _ in range(1000)]
timeit.timeit('len(set(some).difference(all))', 'from __main__ import some, all', number=10000)
timeit.timeit('len(set(some).difference(all))', 'from __main__ import some, all; all = set(all)', number=10000)

rawDescription: Most efficient way to loop finding items not in a list in python


rawDescription: Generating k numbers of hash value with python


code:
a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}
a = dict((k, v) for k, v in a.iteritems() if v)
a

rawDescription: Removing values from dict in python

description: Removing values from dict in python


code:
urlpatterns = [
    url(r'^users/show', UserRetrieve.as_view())
]

rawDescription: Django Rest required parameters in URL

description: Django Rest required parameters in URL


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

# create some fictive access data by hour
xdata = np.arange(25)
ydata = np.random.randint(10, 20, 25)
ydata[24] = ydata[0]

# let us make a simple graph
fig = plt.figure(figsize=[7,5])
ax = plt.subplot(111)
l = ax.fill_between(xdata, ydata)

# set the basic properties
ax.set_xlabel('Time of posting (US EST)')
ax.set_ylabel('Percentage of Frontpaged Submissions')
ax.set_title('Likelihood of Reaching the Frontpage')

# set the limits
ax.set_xlim(0, 24)
ax.set_ylim(6, 24)

# set the grid on
ax.grid('on')

rawDescription: How to make matplotlib graphs look professionally done like this?

description: Make matplotlib graphs look professionally done like this


code:
from sklearn.cluster import DBSCAN
DBSCAN(min_samples=1).fit_predict(mat)
array([0, 1, 2, 2])

rawDescription: Clustering cosine similarity matrix

description: Clustering cosine similarity matrix


code:
def Child(Base):

    def __init__(self, attr1, attr2):
        super(Child, self).__init__(attr1)
        self.attr2 = attr2

rawDescription: What is the practical use of the keyword super in Python inheritance?


code:
import pyodbc

connStr = (
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:\Users\Public\Database1.accdb;"
    )
cnxn = pyodbc.connect(connStr)
crsr = cnxn.cursor()

sql = """\
SELECT [Time] FROM ConditionData WHERE ID=1
"""
crsr.execute(sql)
row = crsr.fetchone()
mydatetime = row[0]

print(repr(mydatetime))
print(mydatetime)

crsr.close()
cnxn.close()

rawDescription: Pyodbc not returning precise datetime data


code:
from collections import Counter
import time

iterations = 100
internal_iterations = 100000

def main():
    resizes = Counter()

    for i in range(iterations):
        print("Completion: [{:3.0%}]\r".format(i/iterations), end="")

        s = set()
        maxtime_so_far = 0
        for j in range(internal_iterations):
            start = time.time()
            s.add(j)
            end = time.time()

            if end-start > maxtime_so_far:
                maxtime_so_far = end-start
                resizes[j] += 1

    print()

    format_string = "{0:<6} = 0b{0:<18b} [found %: {1:2.0%}]"

    for index in sorted(resizes):
        chance = resizes[index] / iterations

        if chance >= 0.05:
            print(format_string.format(index, chance))

main()

rawDescription: How do CPython and PyPy decide when to resize a set?


code:
strs = "1.2   1.6   0.4"
strs.split()
[float(x) for x in strs.split()[:2]]

rawDescription: PYTHON - reading single row from a file

description: PYTHON - reading single row from a file


code:
seq = [1,2,3,4,5,6,7,8,9,10]
it = iter(seq)
for x in it:
    print [x, next(it)]

rawDescription: Iterate every 2 elements from list at a time


code: [l in 'happy' for l in 'harpy']

rawDescription: Python- Replace all occurrences of letter at specific position on a string


code: g = df.groupby(['Manufacturer', 'Product Launch Date', 'Product Name']).sum()

rawDescription: Multi-Index Sorting in Pandas

description: Multi-Index Sorting in Pandas


code:
params = {'query' : 'title(' + title_string + ')'}
api_call = 'http://some_api/index:ABCDE?' + urllib.urlencode(params)

rawDescription: Passing a string containing unicode to a RESTful API


code:
mapping = df2.to_dict()['value']
for col in ['pin', 'pin1', 'pin2', 'pin3']:
    mappedvalues = df1[col].map(mapping)
    hasmapping = pd.notnull(mappedvalues)
    df1.loc[hasmapping, 'value'] = mappedvalues
    df1.loc[hasmapping, 'mapping'] = col

rawDescription: Multiple merge of data frame without replacing the values


code:
def _auto_reconnect_wrapper(func):
    ''' Tries to reconnects dead connection
    '''

    def inner(self, *args, _retry=True, **kwargs):
        try:
            gen = func(self, *args, **kwargs)
            if inspect.isgenerator(gen):
                value = next(gen)
                return itertools.chain([value], gen)
            else: # Normal function
                return gen
        except StopIteration:
            return gen
        except Mysql.My.OperationalError as e:
            ...
            # Retry
            return inner(self, *args, _retry=False, **kwargs)
    return inner

rawDescription: Generator recovery using decorator

description: Generator recovery using decorator


code:
coll = plt.scatter(rand(5), rand(5), c="k")
fig = plt.gcf()
fig.show()  # or fig.savefig("a.png")

coll.set_color(['b', 'g', 'r', 'y', 'k'])
fig.show()  # or fig.savefig("b.png")

rawDescription: resetting points of an already plotted scatter in matplotlib

description: Resetting points of an already plotted scatter in matplotlib


code:
from itertools import groupby
from operator import itemgetter

with open('input') as fin, open('output', 'w') as fout:
    fout.write(next(fin, ''))
    rows = (line.split() for line in fin)
    for k, g in groupby(rows, itemgetter(0, 2)):
        fout.write('{} {} {}\n'.format(k[0], sum(1 for _ in g), k[1]))

rawDescription: Aggregating table rows by values in multiple columns in a FITS file


code: print(calculate_quality_points(30, 20, 4, 3))

rawDescription: how can i make a filter quality score?

description: Make a filter quality score


code:
class Item(object):
  def __init__(self, desc):
    self.desc = desc
  def __repr__(self):
    return 'Item(' + repr(self.desc) + ')'
  def __repr__(self):
    return self.desc
inside = [Item('thing'), Item('other thing')]
'Inside = ' + repr(inside)
"Inside = [Item('thing'), Item('other thing')]"
'Inside = ' + str(inside)
"Inside = [Item('thing'), Item('other thing')]"
'Inside = ' + ', '.join(str(i) for i in inside)
'Inside = thing, other thing'

rawDescription: Good way to concatenate str to list?

description: Good way to concatenate str to list


rawDescription: Tallying the outcome of a coin flip

description: Tallying the outcome of a coin flip


code: 'my name is (?P<name>\w+)'

rawDescription: How do I use regular expressions in Python with placeholder text?

description: Use regular expressions in Python with placeholder text


code: data.loc[(data['wind_speed'] > 3) & (data['clouds'] >= 4 ) & (data['dagnacht'] == 'nacht'), 'stability'] = 4

rawDescription: How do I create a new column based on conditions of other columns in pandas?

description: Create a new column based on conditions of other columns in pandas


code:
prefix, sep, rest = rev_data.partition("{{")
if sep: # found the first "{{"
    depth = 1
    prevc = None
    for i, c in enumerate(rest):
        if c == "{" and  prevc == c:  # found "{{"
            depth += 1
            prevc = None # match "{{{ " only once
        elif c == "}" and prevc == c: # found "}}"
            depth -= 1
            if depth == 0: # found matching "}}"
                rev_data = prefix + rest[i+1:] # after matching "}}"
                break
            prevc = None # match "}}} " only once
        else:
            prevc = c
print(rev_data)

rawDescription: get first paragraph from wikipedia article

description: Get first paragraph from wikipedia article


rawDescription: Merge dictionaries with the same values to a single dictionary


code:
memAddr1: 1
memAddr2: 2
memAddr3: 3
memAddr4: 4

rawDescription: Fill a Pytables array with random values: horizontally vs vertically


rawDescription: Python: finding index of an array under several conditions


code:
reordered = parts[0] + parts[2] + parts[1]
reordered

rawDescription: How can i change the position of substring within a string in Python?

description: Change the position of substring within a string in Python


code: finalurl = baseUrl + urllib.quote(searchterm)

rawDescription: How to formally insert URL space (%20) using Python?

description: Formally insert URL space (%20) using Python


code: scipy.optimize.root(lambda x: y(x) - 9, xguess)

rawDescription: Solve for the argument to a function that will produce a particular return value


code: trimmedString = originalString[a:-b]

rawDescription: (Python) Program to read specific data from many output files


code:
found = False
for row in fixed_names:
    if userLastName in row and userFirstName in row:
        found = True
        print(list(row))
        break
if not found:
    print('User Not Found!')

rawDescription: Python For In Loop Matrix for User Input


rawDescription: How to use opencv reduce using cv2 python API

description: Use opencv reduce using cv2 python API


code:
def view(request):
    ...
    # Validate and persist form data
    if request.method == 'POST' and form.validate():
        for c in student_courses:
            student.courses[c.title] = form[c.title].data

rawDescription: How to populate lists of objects with WTForms?

description: Populate lists of objects with WTForms


code:
# get mode: exhastive search
x[np.argsort(nparam_density)[-1]]

rawDescription: How to estimate density function and calculate its peaks?

description: Estimate density function and calculate its peaks


code: {'Bernard': 7, 'George': 4, 'Reginald': 6}

rawDescription: Python check if value is in a list of dicts


code:
class EntryAdmin(admin.ModelAdmin):
    list_display = ('title', 'is_visible')

rawDescription: Determine if entry is visible by startdate and enddate


code:
request.session['flag'] = True    #or False as per your requirement
...
if (request.session['flag']):
    ...
else:
    ...

rawDescription: Django settings

description: Django settings


code:
from random import choice, randint

class Question:     # base class
    def __init__(self, difficulty=20):
        self.a = randint(1, difficulty)
        self.b = randint(1, difficulty)
    def question(self):
        raise NotImplemented
    def answer(self):
        raise NotImplemented

class Multiplication(Question):
    def question(self):
        return "What is {} * {}? ".format(self.a, self.b)
    def answer(self):
        return self.a * self.b

class Division(Question):
    def question(self):
        # invert the question to ensure a nice answer value
        return "What is {} / {}? ".format(self.a * self.b, self.a)
    def answer(self):
        return self.b

class Addition(Question):
    def question(self):
        return "What is {} + {}? ".format(self.a, self.b)
    def answer(self):
        return self.a + self.b

class Subtraction(Question):
    def question(self):
        # invert the question to ensure a nice answer value
        return "What is {} - {}? ".format(self.a + self.b, self.a)
    def answer(self):
        return self.b

rawDescription: Finding something that checks if a particular Arithmetic answer is correct


code:
sample_gen = random_samples(num_reads)
random_id_list = next(sample_gen)
# some point later
another_random_id_list = next(sample_gen)

rawDescription: Python very slow random sampling over big list


code:
# file1.py
def generate_csv(filename):
    # put your file generation code here
    # you could easily use Python's csv module, for example
    return csv_filename

rawDescription: Is there any way to run three python files sequentially as the output of each file depends on the other


code:
entry = po.find('%s hour ago')
if entry and entry.msgid_plural:
    entry.msgstr_plural['0'] = 'Vor %s Stunde'
    entry.msgstr_plural['1'] = 'Vor %s Stunden'

rawDescription: Modify/update an entry in a po file with polib in Python


code: np.column_stack(np.broadcast(x, 0, x))

rawDescription: NumPy: 2D array from a list of arrays and scalars


code:
import glob

year = raw_input('Year: ')        # Example: Year: 2009
number = raw_input('Number: ')    # Example: Number: 12
filenames = glob.glob('{year}_*{number}*'.format(year=year, number=number))

rawDescription: Verify file names by standard

description: Verify file names by standard


code:
import seaborn as sns
import pandas as pd
from numpy.random import randn

data = pd.DataFrame(dict(x=randn(40), y=randn(40), g=["a", "b"] * 20))
sns.lmplot("x", "y", hue="g", data=data, fit_reg=False)

rawDescription: Is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?


code:
import cmd

def parse(arg):
    return tuple(k.partition('=') for k in arg.split())

class MyShell(cmd.Cmd):
    def do_foo(self, arg):
        for x, _, y in parse(arg):
            print(x, y)

    def complete_foo(self, text, line, begidx, endidx):
        # Cmd treats = as the end of params; we don't want that.
        if line.endswith('='):
            return ()

        opts = ['param1=', 'param2', 'param3=']
        return [opt for opt in opts if opt.startswith(text)]

MyShell().cmdloop()

rawDescription: Is there an easy way to add arguments with values to python3 cmd.Cmd?


rawDescription: Viewing the content of a Spark Dataframe Column


code:
import zmq

def worker(worker_id, publisher_addr, results_addr):
    context = zmq.Context()
    sub = context.socket(zmq.SUB)
    sub.connect(publisher_addr)
    sub.setsockopt(zmq.SUBSCRIBE, worker_id)
    push = context.socket(zmq.PUSH)
    push.connect(results_addr)

    while True:
        msg = sub.recv_multipart()[1]
        # do smth, send off results
        push.send_multipart([worker_id, msg])

if __name__ == '__main__':
    publisher_addr = 'tcp://127.0.0.1:5000'
    results_addr = 'tcp://127.0.0.1:5001'

    # launch some workers into space
    from multiprocessing import Process
    for i in range(5):
        Process(target=worker, args=('worker-%d' % i, publisher_addr, results_addr,)).start()

rawDescription: 0mq one-to-many connection

description: 0mq one-to-many connection


code:
# more constants
MAX_VELOCITY = 200
ACCEL_TIME = 1  # secs to accelerate to max velocity (or slow down from it)
AVG_ACCEL = MAX_VELOCITY / float(ACCEL_TIME)  # per sec
ACCEL_PER_FRAME = AVG_ACCEL / FPS

class PlayerData(object):

    ### showing updated methods only

    def approach(self, vel_goal, vel_curr, accel):
        difference = vel_goal - vel_curr
        if difference > accel:
            return vel_curr + accel
        if difference < -accel:
            return vel_curr - accel
        return vel_goal

    def update(self, dt):
        self.velocity.x = self.approach(self.velocity_goal.x,
                                        self.velocity.x, ACCEL_PER_FRAME)
        self.position.x = self.position.x + (self.velocity.x * dt)

        self.player['shape'].top = self.position.y
        self.player['shape'].left = self.position.x

rawDescription: lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place

description: Lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place


code:
def DragDropWidget(cls):
    def init(self, *args, **kwargs):
        __init__(self, *args, **kwargs)
        self.drag_start_x= 0
        self.drag_start_y= 0
        self.bind("<Button-1>", drag_start)
        self.bind("<B1-Motion>", drag_motion)

    def drag_start(event):
        widget= event.widget
        widget.drag_start_x= event.x
        widget.drag_start_y= event.y

    def drag_motion(event):
        widget= event.widget
        x= widget.winfo_x()-widget.drag_start_x+event.x
        y= widget.winfo_y()-widget.drag_start_y+event.y
        widget.place(x=x, y=y)

    __init__= cls.__init__
    cls.__init__= init

    return cls

rawDescription: Drag and Drop widgets tkinter

description: Drag and Drop widgets tkinter


code: hours = [time.strptime(i[:-1].zfill(4), "%H%M") for i in a]

rawDescription: Parse hours without leading zeroes by strptime in Python


code:
foo_parser = ...
bar_parser = ...

variable_parser = Forward()
switch_parser = Literal("foo") | Literal("bar")
def select_variable_parser(tokens):
    if tokens[0] == "foo":
        variable_parser <<= foo_parser
    if tokens[0] == "bar":
        varaible_parser <<= bar_parser
switch_parser.setParseAction(select_variable_parser)
parser = switch_parser + variable_parser

rawDescription: choose parser based on previous results

description: Choose parser based on previous results


code:
with open(logfilePath) as f:
    lines = f.xreadlines()  # or just readlines in Py 3

    def has_needle(line):
        return any(needle in line for needle in needles)

    if any(has_needle(line) for line in lines):
        ...

rawDescription: How to cut short a long 'if' statement with multiple logical AND in Python?

description: Cut short a long 'if' statement with multiple logical AND in Python


code:
class RangeDictionary(dict):
    def __getitem__(self, key):
        for r in self.keys():
            if key in r:
                return super().__getitem__(r)
        return super().__getitem__(key)

rawDescription: use a range as a dictionary key in Python, what option do I have?

description: Use a range as a dictionary key in Python, what option do I have


code:
from collections import defaultdict

def index(request):
    by_date = defaultdict(list)
    for obj in Blog.objects.order_by('-pub_date'):
        by_date[obj.pub_date].append(obj)
    return render(request, 'layout.html', {'blogs': by_date})

rawDescription: django views : passing a dictionarry

description: Django views : passing a dictionarry


code:
import matplotlib.animation as animation

fig = plt.figure()#

data_, = plot([], [])

def data_gen():
    while i < NUMBER_OF_PLOTS:
        '''
         make your instance of X data in a list called YOUR_X_DATA
         and your Y data in a list called YOUR_Y_DATA
         and iterate along it.
        '''
        yield YOUR_X_DATA[i], YOUR_Y_DATA[i]
        i+=1

def run(data):
    data_.set_data(data[0], data[1])

ani = animation.FuncAnimation(fig , run, data_gen, interval=100,repeat=True)
plt.show()

rawDescription: Cycling plots using matplotlib

description: Cycling plots using matplotlib


rawDescription: pandas dataframe join with where restriction

description: Pandas dataframe join with where restriction


code:
import re
re.findall('\d+',"any string coming from db[090876]")

rawDescription: How to extract a number from a string in python

description: Extract a number from a string in python


code:
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.graphics.shapes import Drawing

import calendar

doc = SimpleDocTemplate('calendar.pdf', pagesize=letter)

cal = [['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']]
cal.extend(calendar.monthcalendar(2011,9))

table = Table(cal, 7*[inch], len(cal) * [inch])

table.setStyle(TableStyle([
        ('FONT', (0, 0), (-1, -1), 'Helvetica'),
        ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.green),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    ]))

#create the pdf with this
doc.build([table])

rawDescription: Producing a printable calendar with Python


code:
from setuptools import setup, find_packages

setup(name='blah',
      version='0.1',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      zip_safe=False,
      entry_points={'paste.global_paster_command': [ "xxx_new = blah.xxx:NewXxx", ] },
      )

rawDescription: Global paster command not found in virtualenv


code:
input.close()
out.close()

rawDescription: How to pick lines containg numbers in given positions on the line with python

description: Pick lines containg numbers in given positions on the line with python


code:
injector = inject.Injector()
injector.bind(A, scope=inject.reqscope)

rawDescription: How to get per-testcase scoping for dependency injected objects in Python?

description: Get per-testcase scoping for dependency injected objects in Python


code:
P = PolygonHandler()
P.add(1,1)
P.add(2,2)
P.add(1,2)
ani = animation.FuncAnimation(P.fig, P.update, interval=10,blit=False)

rawDescription: Real time dynamic plotting

description: Real time dynamic plotting


rawDescription: When querying a Django model, is there a way to match every string in a field


code:
from dask.multiprocessing import get
states = x.compute(get=get)

rawDescription: Parallelize loop over numpy rows

description: Parallelize loop over numpy rows


code: color_dict[item[0]] += int(item[1])

rawDescription: Python: reading line from file with different types of variables


code: print(str.format('{0:.15f}', val))

rawDescription: How can I print many significant figures in Python?

description: Print many significant figures in Python


code: indexes = [i for i, val in enumerate(list) if val == '\n']

rawDescription: Index of \n in Python list

description: Index of \n in Python list


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[1.0,1.3,1.5], 'b':[1.2,1.5,1.5], 'data':np.random.randn(3)})

### Create all possible combinations of a,b
newindex = [(b,a) for b in np.linspace(a_min, a_max, a_step, endpoint=False) for a in np.linspace(b_min, b_max, b_step, endpoint=False)]

### Set the index as a,b and reindex
df.set_index(['a','b']).reindex(newindex).reset_index()

rawDescription: converting sparse dataframe to dense dataframe

description: Converting sparse dataframe to dense dataframe


code:
import itertools as it

unique_dict = {}
value_key=lambda x: x[1]
sorted_items = sorted(your_current_dict.items(), key=value_key)
for value, group in it.groupby(sorted_items, key=value_key):
    for key in group:
        unique_dict[key] = value

rawDescription: multiple keys in python dictionary, is possible?

description: Multiple keys in python dictionary, is possible


code: your_list.sort(key=lambda e: (-e[1], e[0]))

rawDescription: Python 3 List: How do I sort [('NJ', 81), ('CA', 81), ('DC', 52)] base on number and then letters?


code:
import os
from collections import Counter,defaultdict
d2 = defaultdict(dict)
word_list = ['vs', 'mln', 'money']
for fil in d.values():
    with open(fil[0]) as f:
       path, name = os.path.split(fil[0])
       words_c = Counter([word for line in f for word in line.split()])
       for word in word_list:
           d2[word][name] = words_c[word]

rawDescription: iterating through a nested dictionary in python

description: Iterating through a nested dictionary in python


code: fig, ax = plt.subplots()

rawDescription: What is an idiomatic way to specify a matplotlib figure and axes to a function?


rawDescription: Replace values of a numpy array by values from another numpy array


code:
Entry = namedtuple('Entry', 'Name, Date, Color')
[l for l in open('t.tsv', 'r')]
[l.split() for l in open('t.tsv', 'r')]
[Entry(*l.split()) for l in open('t.tsv', 'r')]
{e.Name:e for e in list(Entry(*l.split()) for l in open('t.tsv', 'r'))}

rawDescription: How to read a specific row of a csv file in python?

description: Read a specific row of a csv file in python


code:
mylist = []
def listed(func):
    mylist.append(func)
    return func

@listed
def function1():
    pass

@listed
def function2():
    pass

rawDescription: Is there a way to append the name of a function to a list automatically?


rawDescription: return combinations having all element present

description: Return combinations having all element present


code:
def saveSoapProd():
    tableProdSoap = soapProdQuery()
    if tableProdSoap != None:
        for item in tableProdSoap:
            try:
                obj, created = soapProdAPI.objects.get_or_create(soap_id=item[0], defaults={'soap_host': item[1], 'soap_asset': item[2], 'soap_state': item[3]})
                if created == False:
                    obj.soap_host  = item[1]
                    obj.soap_asset = item[2]
                    obj.soap_state = item[3]
                    obj.save(update_fields=['soap_host', 'soap_asset', 'soap_state'])
            except:
                continue
    saveSoapMissingIP()

rawDescription: Skipping a field on save (Django models, Insert and Update)


rawDescription: Breaking out a dataframe into groups, applying a calculation, and reconsolidating to one dataframe


code:
class LDAPUserEx(_LDAPUser):
    def _check_required_group(self):
        pass # Put your implementation here !

rawDescription: Customizing / extending / monkey patching Django Auth Backend


code:
if y is None:
    qs = Model.objects.filter(x=x).filter(z=z)
elif z is None:
    qs = Model.objects.filter(x=x).filter(y=y)
...

rawDescription: Query when parameter is none django

description: Query when parameter is none django


code:
xdata = ...
ydata = ...
xleft, xright = 13.3979400087, 13.414973348
xfill = np.linspace(xleft, xright)
yfill = np.interp(xfill, xdata, ydata)
plt.fill_between(xfill, 0, yfill, color='r')

rawDescription: Matplotlib fill_between() workaround

description: Matplotlib fill_between() workaround


code: {id: 123, first_name: "John", "skill_ids": [1, 2, 3]}

rawDescription: Django Rest update many to many by id

description: Django Rest update many to many by id


code:
def signature_seq(signature, limit):
  products = set((1,))
  for factor in signature:
    new_products = set()
    for prod in products:
      x = factor * prod
      while x <= limit:
        new_products.add(x)
        x *= factor
    products.update(new_products)

  products.remove(1)
  return products

rawDescription: Enumeration of all factor products less than a maximum


code:
for x in range(dimX):
    for y in range(dimY):
        #2 floats, each 4 bytes, is one complex number
        trace=stream.readBytes(8*dimZ)
        a = np.frombuffer(trace,dtype=np.dtype('complex64'))
        data[x][y] = a

rawDescription: Python: unpacking string of floats to complex numbers


rawDescription: how do i create a list of dict in python with the data been read from a text file?

description: Create a list of dict in python with the data been read from a text file


code:
import base64
import pymongo
from pymongo import binary
# if pymongo version >= 1.9, use the following instead
# from bson import binary

con = pymongo.Connection()
b64 = base64.b64encode("ajskldfjaklsdjfklasdjf")
bi = binary.Binary(b64)
con.test.test.insert({'foo': bi})
con.test.test.find_one({'foo': bi})

rawDescription: Python & MongoDB - How to find by BinData type


code:
with open(os.path.join(pathBlackList, 'blacklist.txt')) as file:
    return [line.strip().lower() for line in file]

rawDescription: Applying changes to elements in array

description: Applying changes to elements in array


code: fig, ax = plt.subplots(10, 10)

rawDescription: Large number of subplots with matplotlib


rawDescription: Round pandas data frame/series

description: Round pandas data frame/series


code: event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE,fill = color, width=linesize)

rawDescription: Python tkinter delete event.widget.create_line


rawDescription: Python list of dicts: how to manipulate dynamically?


code:
if nCatSeq not in potBasin:
    potBasin[nCatSeq] = (nBasinSeq,)
else:
    if nBasinSeq not in potBasin[nCatSeq]:
        potBasin[nCatSeq] = potBasin[nCatSeq] + (nBasinSeq,)

rawDescription: Nested dictionary

description: Nested dictionary


code:
my_iterator = [(1, 2), (3, 4)]
df = pd.DataFrame.from_records(my_iterator, columns=['i', 'j'])
df

rawDescription: How can I improve this Pandas DataFrame construction?

description: Improve this Pandas DataFrame construction


code:
if infile:
  data = infile.read(1024)
else:
  data = ''

rawDescription: "Initializing" a constant containing a file in python?


code:
def method1(name):
    def wrapper():
        return 'Hello ' + name
    return wrapper

def method2(method, question):
    output = method()
    return output + ', ' + question

method2(method1(name = 'Sam'), 'How are you?')

rawDescription: What is the best way to pass a method (with parameters) to another method in python


code:
rdd1H.leftOuterJoin(rdd2H).values().collect()
## [(0, 1), (0, 3), (1, 0), (3, None)]

rawDescription: Pyspark: Get indexes of an RDD elements from another RDD


code:
root = Tk()
root.wm_attributes("-topmost", 1)

rawDescription: How to keep a python window on top of all others (python 3.1)

description: Keep a python window on top of all others (python 3.1)


code:
registry = {}

def onEvent(eventname):
    def eventdecorator(func):
        registry.setdefault(eventname, []).append(func)
        return func
    return eventdecorator

rawDescription: Is this possible with decorators?

description: Is this possible with decorators


code:
# You can call whatever vectorized string methods on the RHS
df['bar'] = df['foo']

rawDescription: Efficiently adding a new column to a Pandas DataFrame with values processed from an existing column?


code:
import re

s = "20160204094836A"
result = re.search(r"^(\d{4})(\d{2})(\d{2})", s)
year = int(result.group(1))
day = int(result.group(2))
month = int(result.group(3))

print(year, day, month)

rawDescription: date extraction through regex

description: Date extraction through regex


code: lambda x: x if (x<3) else None

rawDescription: Python lambda with if but without else

description: Python lambda with if but without else


code:
from collections import OrderedDict

# Keep the last copy with a given link
kept_last = OrderedDict((x.link, x) for x in nonuniquelist).values()

# Keep the first copy with a given link (still preserving input order)
kept_first = list(reversed(OrderedDict((x.link, x) for x in reversed(nonuniquelist)).viewvalues()))

rawDescription: It's possibile to use set function on a object basing only one attribute?


code: [(el[0], el[1]) for el in grouper(2, range(10))]

rawDescription: Logical task for Python programmers. Make tuple of lists from list


code:
# this may only be called from the main kivy thread
def set_property(value, *largs):
    self.kivy_property = value

# the second thread does this when it wants to set self.kivy_property to 10
Clock.schedule_once(partial(set_property, 10))

rawDescription: Altering a kivy property from another thread


code:
f = SomeFilter(request.GET)
f = SomeFilter(request.GET, queryset=f.qs)

rawDescription: Hide filter items that produce zero results in django-filter


code:
pat1 = re.compile(regex1)
pat2 = re.compile(regex2)
for para in soup.findAll('p'):
    mat1 = pat1.search(para)
    mat2 = pat2.search(para)
    if not (mat1 or mat2): continue
    # found your match

rawDescription: Check if element are in same paragraph (Beautiful soup)


code:
file2read = netcdf.NetCDFFile(path+'state.nc','r')
temp = file2read.variables[var] # var can be 'Theta', 'S', 'V', 'U' etc..
data = temp[:]*1
file2read.close()

rawDescription: Read .nc (netcdf) files using python

description: Read .nc (netcdf) files using python


rawDescription: How to integrate my python plugin with nagios

description: Integrate my python plugin with nagios


code:
pos = f.find('torrents.humblebundle.com')
end = f.find('.torrent')

rawDescription: Finding links in file, keeps repeating same link


rawDescription: Multiple operators between operands

description: Multiple operators between operands


code: dataframe.loc[dataframe.index < 'date time value'][-n:]

rawDescription: Select row prior as.freq() occurance

description: Select row prior as.freq() occurance


rawDescription: Have user sign up with Google and get redirected back to the site afterwards?


code:
time_coffeeA = coffeeA_df['Epoch'].iloc[0] / 1000
users_df[(users_df['Epoch'] - time_coffeeA).abs() < timeWindow]

rawDescription: In Pandas, how to find occurrence of one value from one dataframe in another dataframe?


code:
import scipy.stats as stats
temp_avg, bin_edges, binnumber = stats.binned_statistic(
    x=lat, values=temp, statistic='mean', bins=grid)

rawDescription: Recursively select elements in numpy array


code: out = [type("Generic", (object,), dict(ll))() for ll in l]

rawDescription: Python create list of objects from list of 2 elements lists


rawDescription: Grouping model objects in Django

description: Grouping model objects in Django


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

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


code:
key = max(d, key=sum)
# (8, 9) is the key with the highest average value

rawDescription: Loop through dictionary with a math function


code:
def body():
  for fileName in fileList:
    # Add boundary and header
    yield('--' + boundary) + '\r\n'
    yield('Content-Disposition: form-data; name={0}; filename=    {0}'.format(fileName)) + '\r\n'

    fileType = mimetypes.guess_type(fileName)[0] or 'application/octet-stream'
    yield('Content-Type: {}'.format(fileType)) + '\r\n'
    yield('\r\n')

    with open(fileName) as f:
        # Bad for large files
        yield f.read()
    yield('--'+boundary+'--') + '\r\n'
    yield('') + '\r\n'

rawDescription: Python - HTTP multipart/form-data POST request


code:
with RetryClient() as rc:
    for inode in os.listdir('.'):
        rc.upload(inode)

rawDescription: Reassign variable in with-block

description: Reassign variable in with-block


rawDescription: Python - sorting incremented files

description: Python - sorting incremented files


code:
c = Cube(['instrument__name', 'firstname'], Musician.objects.all(), len)
#Cube(dimensions, queryset, aggregation_function)
#You can use the Django field-lookup syntax for dates and foreign keys !!!

rawDescription: Python / Django : emulating a multidimensional layer on a MySQL database


code:
def comments_to_dicts(comments):
    results = []  # create list for results
    for comment in comments:  # iterate over comments
        item = {
            "id": comment.id,
            "author": comment.author,
        }  # create dict from comment

        results.append(item)  # add converted item to results
    return results  # return all converted comments

rawDescription: Retrieving a threaded comment list recursively


rawDescription: Detect missing multiplication in math expression


rawDescription: Python: Sorted representation of dict of lists, sorted by number of elements in list, after removing duplicates


code:
df.plot(x='type', y='success', kind='bar')
plt.xticks(rotation=25)

rawDescription: dataframe.plot histogram change label

description: Dataframe.plot histogram change label


code: (c[:,None] < rnd).sum(0)

rawDescription: Numpy operation of arrays with different size


rawDescription: Python dynamic bit manipulation example

description: Python dynamic bit manipulation example


code:
from django.core.management import call_command

fixture = 'initial_data'

def load_fixture(apps, schema_editor):
    call_command('loaddata', fixture, app_label='yourapp')

rawDescription: Loading initial data with Django 1.7 and data migrations


rawDescription: cast from list to numpy array problems in python

description: Cast from list to numpy array problems in python


code:
class ExecutiveAdmin(admin.ModelAdmin):
    list_display = ('Person_Name', 'Person_Link')

rawDescription: Django Admin Panel. Display and Edit Parent Fields in Child's Object (ModelAdmin.inlines reverse)


code: data_list = [[key] + value for key, value in data.items()]

rawDescription: Similarity of lists in Python - comparing customers according to their features


code:
import re

a = [
"items (lcd, cardboard, hats on rack, keyboard cat)",
"items( lcd , cardboard,hats on rack  , keyboard cat)",
"items & descrips: (lcd, cardboard, hats on rack, keyboard cat)",
"descriptions & items: (lcd (for computer), cardboard  {brown & white colored}, hats on rack, keyboard cat[dept. 11])",
"items: (lcd, cardboard, hats on rack, keyboard cat (dept. 11)",
"items: (lcd, cardboard, hats on rack, keyboard cat [dept. 11]",
"item (lcd; cardboard; hats on rack; keyboard cat)",
u"item (lcd\u2122, cardboard)"
]

for i in [re.sub(' *[,;] *', ', ',
          re.sub('\(.+?\)|\[.+?\]|{.+?}', '',
          re.search('\((.*)', i).group(1))).strip()
          for i in a]:

    if i[-1] == ')':
        i = i[:-1]

    if not re.search('[\(\[{}\]\)]', i):
        print(i)

rawDescription: Using python regex to change variations of a string?


code: map(lambda x:x.strip('+-'),x)

rawDescription: Python: remove multiple character in list of string


code: presents = [x.strip() for x in re.findall(r'[^,]*', presents) if x]

rawDescription: re.findall - Getting a list of items from a comma delimited string

description: Re.findall - Getting a list of items from a comma delimited string


code:
class ModelOutputSerializer(serializers.Serializer):
    model1 = Model1Serializer(many=True)
    model2 = Model2Serializer(many=True)

    class Meta:
        fields = ('model1', 'model2')

rawDescription: Django-rest-framework serializing multiple queries without a related field


code:
import re

def remove_commas_from_numbers(n):
    r = re.compile(r'^(\d+(?:,\d+)?.+)*$')
    m = r.match(n)
    if not m:
        return n
    return n.replace(',', '')

remove_commas_from_numbers('1,1.')

rawDescription: Pandas Dataframe column with both Strings and Floats


code:
match = re.search(r'<a href="(.*)">', text)
if match:
    foo = match.group(1)
else:
    foo = None

rawDescription: Filter values from strings using regexp

description: Filter values from strings using regexp


code:
import string

def LetterChanges(s):
    t = string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
                         'bcdEfghIjklmnOpqrstUvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZA')
    return s.translate(t)

rawDescription: How to solve this Python puzzle in a much more elegant manner?

description: Solve this Python puzzle in a much more elegant manner


code:
def manage(func):
    def wrapper(*args, **kw):
        session = Session()
        try:
            logger.debug("BEGIN %s(%s, %s)", (func, args,kw))
            result = func(*args, **kw)
            logger.debug("SUCCEEDED %s(%s, %s)", (func, args,kw))
            # don't you need a session.commit() somewhere ???
            return result

        except Exception as e:
            logger.exception("FAILED %s(%s, %s)", (func, args,kw))

            logger.debug("ROLLINGBACK %s(%s, %s)", (func, args,kw))
            session.rollback()
            logger.debug("ROLLEDBACK %s(%s, %s)", (func, args,kw))

            # if you don't handle exceptions let them propagate, thanks
            raise

        finally:
            logger.debug("CLOSING %s(%s, %s)", (func, args,kw))
            session.close()
            logger.debug("CLOSED %s(%s, %s)", (func, args,kw))

    return wrapper

    @manage
    def func1(*params):
        do_something_with(params)

rawDescription: Decorator to store function name to file and delete if there is no error


code:
desired_result = {
    'x': int(match.group(1)),
    'y': int(match.group(2)),
    'z': int(match.group(3))
}

rawDescription: Dictionary from parsed text. Simpler way to create?


code: padsize = 16 - extra

rawDescription: How to make sure the input is a multiple of 16, and if not add padding to it

description: Make sure the input is a multiple of 16, and if not add padding to it


code:
for contact_dict in list_of_dicts:
    for phone_dict in contact_dict['phoneNumbers']:
        phone_dict['phone'] = phone_dict['phone'].replace('-', '')

rawDescription: Updating a value in a dictionary inside a dictionary


code:
boundary = set()
for edge in g.es[crossing_edges]:
    boundary.update(edge.tuple)

rawDescription: A scalable function for get boundary vertices in a graph


code: {{ include_file('file.txt') }}

rawDescription: Insert static files literally into Jinja templates without parsing them


code: self.text_area.get(0, "end")

rawDescription: Tkinter Class method

description: Tkinter Class method


code:
from collections import defaultdict

l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}]
l2 = [{"index":1, "c":4}, {"index":2, "c":5}]

d = defaultdict(dict)
for l in (l1, l2):
    for elem in l:
        d[elem['index']].update(elem)
l3 = d.values()

# l3 is now:

[{'b': 2, 'c': 4, 'index': 1},
 {'b': 3, 'c': 5, 'index': 2},
 {'green': 'eggs', 'index': 3}]

rawDescription: join two lists of dictionaries on a single key

description: Join two lists of dictionaries on a single key


code:
for i in outer:           # used once, okay to be a generator or return a list
    for j in inner:       # used multiple times, reusing a list is better
         ...

rawDescription: When is not a good time to use python generators?


code: plt.savefig('/tmp/test.png', dpi = 200)

rawDescription: matplotlib savefig image size with bbox_inches='tight'

description: Matplotlib savefig image size with bbox_inches='tight'


code:
def baseMultiply(data, colToMul, baseCol='Base Days', convFactor=24, preTreat=None):
    col_data = data[colToMult]
    if preTreat is not None:
        col_data = preTreat(col_data)
    return data[baseCol] * col_data * convFactor

rawDescription: Refactoring a bad 'code smell' in multiplication of columns in a dataframe


code:
def f(x):
    pass
print(f(20))

rawDescription: Why does my python function return None?

description: Why does my python function return None


code:
result = []
for x in seq:
  if x not in seen:
    result.append(x)
    seen.add(x)
return result

rawDescription: does adding element to a set return true if it is successful in python?

description: Does adding element to a set return true if it is successful in python


code:
with open('datas.txt') as f:
    n = 8
    for line in f:
        a = float(line[line.index('[')+1:line.index(']')].split(',')[n])
        do_something_with(a)

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

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


code:
import sys
current_module = sys.modules[__name__]

rawDescription: How can I get a list of all classes within current module in Python?

description: Get a list of all classes within current module in Python


rawDescription: python re match digits or digits followed by characters

description: Python re match digits or digits followed by characters


code:
history/models.py
class ArchivePostModel(CommonPostModel):
    pass

rawDescription: Reusing django models

description: Reusing django models


code:
from lxml import objectify, etree

root = objectify.parse("input.xml").getroot()
elems = root.xpath("//object_header")

for elem in elems:
    header = elem.text
    objectDetails = ''
    for sibling in elem.xpath("following-sibling::*"):
        if sibling.tag == 'object_header':
            break

        objectDetails += str(etree.tostring(sibling))

    print(header, objectDetails)

rawDescription: Elegant Python loop for parsing flat XML


code:
class YourRSS2Item(PyRSS2Gen.RSSItem):
    def publish_extensions(self, handler):
        handler.startElement("show_id")
        handler.endElement("show_id")

rawDescription: How can I generate RSS with arbitrary tags and enclosures

description: Generate RSS with arbitrary tags and enclosures


code:
import csv
with open('data.txt') as f:
    groups = {}
    for item in list(csv.reader(f, delimiter=',')):
        n = int(item[2]) // 10
        group = "%d-%d" % (n*10, n*10+9)
        groups.setdefault(group, []).append(item[:2])

rawDescription: How to cluster (or group) the data from a CSV file?

description: Cluster (or group) the data from a CSV file


code:
import sys

if sys.version_info[0] < 3:
    sys.stderr.write('Requires Python 3 or up\n')
    sys.exit(1)

rawDescription: How to label a Python package as version 3 only?

description: Label a Python package as version 3 only


code:
sortedY = [y for x,y in sorted(zip(X,Y))]
print(sortedY)

# Output
['S', 'S', 'C', 'S', 'S', 'S', 'C']

rawDescription: zipped array returns as <zip object at 0x02B6F198>

description: Zipped array returns as <zip object at 0x02B6F198>


code:
lowerb = np.array([lH, lS, lV], np.uint8)
upperb = np.array([uH, uS, uV], np.uint8)

rawDescription: Why doesn't OpenCV's inRange function convert my HSV image to Binary?


code:
intervals = [(6,1),(2,20),(8,7)]
in_interval(intervals)
intervals = [(6,1),(2,20),(4,9)]
in_interval(intervals)

rawDescription: overlapping of 3 intervals: what is the fastest way

description: Overlapping of 3 intervals: what is the fastest way


code:
from collections import Counter
from nltk.corpus import brown
texts = brown.words()[:10000]
word_counts = Counter(texts)
word_counts['dollar']
word_counts['dollars']

rawDescription: How to check if a word is more common in its plural form rather than in it's singular form in an array of words (with Python/NLTK)?

description: Check if a word is more common in its plural form rather than in it's singular form in an array of words (with Python/NLTK)


code: string = ''.join('[{0}{1}]'.format(x[1:], self.obj[x]) for x in self.obj)

rawDescription: Simplification of iterating

description: Simplification of iterating


code:
import collections
import os.path

sites = collections.defaultdict(list)

for index in indexes:
    root, ext = os.path.splitext(index)
    sites[ext].append(index)

for site_key, devices in sites.iteritems():
    ...

rawDescription: How to create a dict equivalent in Python from Perl hash?

description: Create a dict equivalent in Python from Perl hash


code:
def my_run(num):
    run(num, "ns", blocking=True)

rawDescription: How to avoid typing the arguments to run() all the time

description: Avoid typing the arguments to run() all the time


code:
class CursesWindow(object):
    def __enter__(self):
        curses.initscr()

    def __exit__(self):
        curses.endwin()

def main():
    with CursesWindow():
        curses.cbreak()
        for i in range(3):
            time.sleep(1)
            curses.flash()
            pass
        print( "Hello World" )

rawDescription: Python curses dilemma

description: Python curses dilemma


code:
from django.db import models

class ItemGroup(models.Model):
    group = models.CharField(max_length=100)
    code = models.CharField(max_length=20)

class ItemType(models.Model):
    item_group = models.ForeignKey(ItemGroup)
    type = models.CharField(max_length=100)

class Store(models.Model):
    name = models.CharField(max_length=150)
    item_type = models.ManyToManyField(ItemType, related_name="store")

# admin
from django.contrib import admin

class StoreAdmin(admin.ModelAdmin):
    list_display=('name', 'item_type',)
    list_editable=('item_type',)

for model in [(Store, StoreAdmin), (ItemGroup,), (ItemType,)]:
    admin.site.register(*model)

rawDescription: What's the straightforward way to implement one to many editing in list_editable in django admin?


rawDescription: How to access private variable of Python module from class

description: Access private variable of Python module from class


code: np.arange(n) - np.repeat(csum - occupations, occupations)

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
df.convert_objects(convert_numeric=True).plot()
# the converts change "0.97" -> 0.97 so it's plottable

rawDescription: writing "dictionary of dictionaries" to .csv file in a particular format

description: Writing "dictionary of dictionaries" to .csv file in a particular format


code: [list(islice(accumulate(col), 1, None)) for col in cols]

rawDescription: Cumulative addition whilst looping over a list


rawDescription: Pandas: index data by a histogram result


rawDescription: plot a 3d surface plot using matplotlib

description: Plot a 3d surface plot using matplotlib


code:
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field

class MyItem(Item):
    url= Field()

class MySpider(CrawlSpider):
    name = 'twitter.com'
    allowed_domains = ['twitter.com']
    start_urls = ['http://www.twitter.com']

    rules = (Rule(SgmlLinkExtractor(), callback='parse_url', follow=False), )

    def parse_url(self, response):
        item = MyItem()
        item['url'] = response.url
        return item

rawDescription: Scrapy XPath all the links on the page

description: Scrapy XPath all the links on the page


rawDescription: configobj multiple configurations

description: Configobj multiple configurations


code:
pt0 = contour[i][j][0] # that's what you need to replace pt0 = contours[i][j];
# pt0 = [x, y], where pt0[0] = x, pt0[1] = y

rawDescription: How to access opencv contour point indexes in python?

description: Access opencv contour point indexes in python


rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


code:
def testSomething(self):
    if not self.preconditions():
        self.fail('Preconditions failed')

    _s = CulebraTests.sleep
    _v = CulebraTests.verbose

    self.vc.dump(window=-1)
    if not self.vc.findViewWithText(u'Pick a Daily Goal'):
        self.vc.findViewWithTextOrRaise(u'GET STARTED').touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
        self.vc.findViewWithTextOrRaise(u'Spanish', root=self.vc.findViewByIdOrRaise('id/no_id/5')).touch()
        self.vc.sleep(_s)
        self.vc.dump(window=-1)
    self.vc.writeImageToFile('/tmp/${serialno}-${focusedwindowname}-${timestamp}.png', 'PNG', 'None', False, False)

rawDescription: Error of Script with MonkeyRunner and AndroidViewClient (Touch)


code:
import json

with open(data_file, 'wb') as dump:
    dump.write(json.dumps(arbitrary_data))

rawDescription: Convert a list to a string and back

description: Convert a list to a string and back


code:
import sys

lo,hi = sys.maxint,-sys.maxint-1
for x in (item['the_key'] for item in dict_list):
    lo,hi = min(x,lo),max(x,hi)

rawDescription: In List of Dicts, find min() value of a common Dict field


code:
words = set()
word = input('Word: ')
while word != '':
    words.add(word)
    word = input('Word: ')
print("You know "+ str(len(words)), "unique word(s)!")

rawDescription: How to not count the duplicates from an user input?

description: Not count the duplicates from an user input


code:
sys.stdout.write(" [ ] {0}/{1} progress left\r".format(i+1, len(names)))
sys.stdout.flush()

rawDescription: Sys.stdout.write not working as expected


code:
import sys, os
from PyQt4 import QtGui, QtCore, uic

DIRPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)))

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        uic.loadUi(os.path.join(DIRPATH, 'helloworld.ui'), self)
        self.button.clicked.connect(self.handleButton)

    def handleButton(self):
        print('Hello World')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Hello world in pyqt?

description: Hello world in pyqt


code: [bisect.bisect(a, x) for x in b]

rawDescription: Check between which floats in a list a given float falls


code:
for multiple in to:
    for single in fro:
        pairs = ",".join(single + multiple)

rawDescription: How to add two odd lists into one list in python?

description: Add two odd lists into one list in python


code:
some_child = YourModel.objects.get(...)
siblings = some_child.siblings()
parent = some_child.parent()
children = parent.children.all()

rawDescription: Making portable Nodes in Django and using them to make Trees


code: set([u'PLAN_B', u'PLAN_C', u'PLAN_A', u'PLAN_F', u'PLAN_G', u'PLAN_D', u'PLAN_E'])

rawDescription: generate html table with potentially expanding columns and need to reordering columns, using django

description: Generate html table with potentially expanding columns and need to reordering columns, using django


rawDescription: How can I use Python 2.6 in Ubuntu 11.10?

description: Use Python 2.6 in Ubuntu 11.10


code:
def vendors(request):
    items = Itemo.objects.all()
    var_2 = request.GET.get("q")
    if var_2:
        items = items.filter(Vendor_Name__icontains=var_2)

    return render(request, 'vendor_db/vendors.html', {'items': items})

rawDescription: Issue using Messages in Django Template

description: Issue using Messages in Django Template


code:
import pygame, sys
from pygame.locals import *

pygame.init()
width, height = 40, 40
clock = pygame.time.Clock()
DRAWSURF = pygame.display.set_mode((width, height))
pygame.display.set_caption("Matt's Minesweeper")
background = pygame.Surface(DRAWSURF.get_size())
DRAWSURF.blit(background, (0, 0))
pygame.display.flip()
size = [255, 255]
screen = pygame.display.set_mode(size)

margin = 5

from collections import OrderedDict
from random import sample

class DrawBoard():
    def __init__(self, grid, mines):
        self.grid_size = grid
        self.board = OrderedDict(((i, j), False) for i in range(grid) for j in range(grid))
        self.mines = mines
        samp = sample(list(self.board), self.mines)
        for k in samp:
            self.board[k] = True

    def draw(self):
        for i, j in self.board:
            x = 100 + i * 60
            y = 0 + 60 * j
            pygame.draw.rect(DRAWSURF,(0,0,0), (x, y, 60, 60), margin)

game = DrawBoard(5, 5)
game.draw()

def game_over():
    font = pygame.font.SysFont(None, 50)
    text = font.render('Game over!', True, (255, 0, 0), (255, 255, 255))
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery
    screen.blit(text, text_rect)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

user_won = False
user_lost = False

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # get mouse pos
            pos = pygame.mouse.get_pos()
            # change to grid coordinates
            column = pos[0] // (width + margin)
            row = pos[1] // (height + margin)
            print(game.board[row, column])
            if game.board[row, column]:
                user_lost = True
            else:
                game.board[row, column] = "picked"

    if user_lost:
        game_over()

    screen.fill((0, 0, 0))
    for row, column in game.board:
        color = (255, 255, 255)
        if game.board[row, column] == "picked":
            color = (0, 255, 0)
        pygame.draw.rect(screen,
                         color,
                         [(margin + width) * column + margin,
                          (margin + height) * row + margin,
                          width,
                          height])

    pygame.display.flip()
    clock.tick(30)

    pygame.display.update()

rawDescription: Python/PyGame Select a Random Boolean From List


code:
def ntuples():
    list_of_names = df.columns.values
    list_of_names_dict = {x:x for x in list_of_names}

    Varnames = namedtuple('Varnames', list_of_names)
    return Varnames(**list_of_names_dict)

var = ntuples()

rawDescription: IPython Notebook and Pandas autocomplete


rawDescription: Matplotlib continuing line into infinity


code:
from my_dict import dict2
print(dict2[2])
# Output: val2

rawDescription: Outputting a dictionary to file exactly as defined in variable


code: Z = np.reshape(Z_approx, (3, 3))

rawDescription: Matplotlib- meshgrid

description: Matplotlib- meshgrid


code: word = re.findall("start;([^;]+);", string)

rawDescription: regex, how to exlude search in match

description: Regex, how to exlude search in match


code:
TL;DR - codes
import win32security
import ntsecuritycon as con

FILENAME = r'D:\tmp\acc_test'

userx, domain, type = win32security.LookupAccountName ("", "your.user")
usery, domain, type = win32security.LookupAccountName ("", "other.user")

sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()

ace_count = dacl.GetAceCount()
print('Ace count:', ace_count)

# Listing
for i in range(0, ace_count):
    rev, access, usersid = dacl.GetAce(i)
    user, group, type  = win32security.LookupAccountSid('', usersid)

    print('User: {}/{}'.format(group, user), rev, access)

# Removing the old ones
for i in range(0, ace_count):
    dacl.DeleteAce(0)

# Add full control for user x
dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION,
    con.OBJECT_INHERIT_ACE|con.CONTAINER_INHERIT_ACE, con.FILE_ALL_ACCESS, userx)

# Add read only access for user y
dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION,
    con.OBJECT_INHERIT_ACE|con.CONTAINER_INHERIT_ACE, con.FILE_GENERIC_READ, usery)

sd.SetSecurityDescriptorDacl(1, dacl, 0)   # may not be necessary
win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)

rawDescription: How to authorize/deny write access to a directory on Windows using Python?

description: Authorize/deny write access to a directory on Windows using Python


code:
ts = ts.stack()
ts = ts.swaplevel(0,1)

rawDescription: Making missing time slots and filling in 0 values in a Pandas series?


code:
def rabbit(rocks, prev=0):
    if rocks[0] - prev > 50:
        return -1
    p = rocks[0]
    for i, x in enumerate(rocks):
        if x - prev > 50:
            ret = rabbit(rocks[i:], p)
            if ret >= 0:
                ret += 1
            return ret
        p = x
    return 1

rawDescription: Recursive function for tuple

description: Recursive function for tuple


code:
def regress(df):
    slope, intercept, r_value, p_value, std_err = stats.linregress(df['p_rel'], df['y_BET'])

    if r_value ** 2 < 0.995:
        return regress(df.iloc[:-1, :])  # call again and regress with last row removed
    else:
        return slope, intercept, r_value, p_value, std_err

# call like so:
slope, intercept, r_value, p_value, std_err = regress(df)

# use the results here

rawDescription: Changing pandas dataframe based on linear reggression R^2 values


code:
class StatModel(object):
    '''parent class - starting point to add abstraction'''
    def load(self, fn):
        self.model.load(fn)
    def save(self, fn):
        self.model.save(fn)

rawDescription: Python OpenCV SVM implementation

description: Python OpenCV SVM implementation


code: np.diff(index)/np.timedelta64(1, 's')

rawDescription: getting seconds from numpy timedelta64

description: Getting seconds from numpy timedelta64


code:
def use_from(step_todo, *args):
    use_all(step_todo, *args)

rawDescription: Python: Using defined arguments with *args


code:
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt1.x = 2.0

rawDescription: What are "named tuples" in Python?

description: What are "named tuples" in Python


code:
def serialize_custom_object(o):
    res = o.__dict__.copy()
    res['machines'] = res['_machines']
    del res['_machines']
    return res

json.dumps(object, sort_keys=True,indent=4, separators=(',', ': '),
           default=serialize_custom_object)

rawDescription: json.dump object rename attribute before the dump

description: Json.dump object rename attribute before the dump


code:
import string
b = [4, 2, 4, 7, 3, 1, 5]
[char * count for char, count in zip(string.ascii_lowercase, b)]
[char * count for char, count in zip(string.ascii_lowercase, b + [3])]
[char * count for char, count in zip(string.ascii_lowercase, b + [3, 7])]

rawDescription: python list comprehension alphabet generation

description: Python list comprehension alphabet generation


rawDescription: Matrix in Python Changing some Values

description: Matrix in Python Changing some Values


code: result = newline #you lose the newline here

rawDescription: Replace a whole line in a file

description: Replace a whole line in a file


code: del Files[5:]

rawDescription: Python looping to read and parse all in a directory


code:
#!python

from ctypes import *
from os import path

SPI_SETDESKWALLPAPER = 0x14
SPIF_UPDATEINIFILE   = 0x1

lpszImage = path.join(path.dirname(path.realpath(__file__)), 'your_image.jpg')

SystemParametersInfo = windll.user32.SystemParametersInfoA

SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, lpszImage, SPIF_UPDATEINIFILE)

rawDescription: Change wallpaper in Python for user while being system


code: phrase = "".join(c for c in phrase if c.isalpha())

rawDescription: Ignoring noncharacters in cypher text

description: Ignoring noncharacters in cypher text


rawDescription: Python - filling a list of tuples with zeros in places of missing indexes


rawDescription: Boolean indexing to find character

description: Boolean indexing to find character


code:
chart_row = 1
chart_col = 3
chart_offset = 0;

worksheet.insert_chart(chart_row + chart_offset, chart_col, chart1)

# Later...

chart_offset += 15
worksheet.insert_chart(chart_row + chart_offset, chart_col, chart2)

rawDescription: Calculate relative positions using xlsxwriter


code:
def initialer(name):
    space_pos = name.find(' ')
    if space_pos == -1:
        return name[0]
    else:
        return name[0] + initialer(name[space_pos + 1:])

rawDescription: How can i use "str.find" (python) to locate the next character after a space or " "?

description: Use "str.find" (python) to locate the next character after a space or " "


rawDescription: How can I store the historical stock prices (using an array)?

description: Store the historical stock prices (using an array)


rawDescription: Selecting items from an array

description: Selecting items from an array


rawDescription: Why does id(id) and id(id(id)) always return the same value, while id(id(id(id))) "loops" over 3 values?


code: instanceList = map(MyClass, args)

rawDescription: Rapid Class Declaration

description: Rapid Class Declaration


code:
zipped = zip(list1, list2, list3, list4)

with open('in.csv', 'rb') as infile, open('out.csv' 'wb') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for i, row in enumerate(reader):
        row.extend(zipped[i])
        writer.writerow(row)

rawDescription: Adding python lists as new columns to a csv file


code:
linenum2sample = dict([(x, 0) for x in s0]+[(x, 1) for x in s1]+[(x, 2) for x in s2])

outfile = [open("-".join(x, filename), "w") for x in ["2000", "1000", "500"]]

try:
    with open(filename, "r") as f:
        for linenum, line in enumerate(f):
            s = linenum2sample.get(linenum)
            if s is not None:
                outfile[s].write(line)
finally:
    for f in outfile:
        f.close()

rawDescription: python file manipulations (bash script porting)

description: Python file manipulations (bash script porting)


code:
import itertools

history = []

with open('sample.txt') as f:
    group = []
    for line in f:
        line = line.strip()
        if 'Block' in line:
            if group:
                history.append(group)
                group = []
        elif line:
            group.append(float(line.split()[2]))

    history.append(group)

with open('output.txt', 'w') as f:
    for i in range(len(history)):
        l = list(itertools.chain(*history[:i+1]))
        print(sum(l) / len(l), file=f)

rawDescription: Running average issue

description: Running average issue


code:
from collections import defaultdict

with open('datafile.csv') as f:
    d = defaultdict(list)
    next(f)    # skip first header line
    next(f)    # skip second header line
    for line in f:
        id_, value, amount = line.split()
        d[id_].append((int(value), int(amount)))

# sum and average of column Value by ID
for id_ in d:
    total = sum(t[0] for t in d[id_])
    average = total / float(len(d[id_]))
    print('{}: sum = {}, avg = {:.2f}'.format(id_, total, average))

rawDescription: get value of one column by another column in csv file python

description: Get value of one column by another column in csv file python


code:
def is_permuation_matrix(x):
    x = np.asanyarray(x)
    return (x.ndim == 2 and x.shape[0] == x.shape[1] and
            (x.sum(axis=0) == 1).all() and
            (x.sum(axis=1) == 1).all() and
            ((x == 1) | (x == 0)).all())

rawDescription: How to quickly determine if a matrix is a permutation matrix

description: Quickly determine if a matrix is a permutation matrix


code:
list((x - y).elements())
list((y - x).elements())

rawDescription: Looking for more pythonic list comparison solution


code:
R23 = stepconv(pulse(7),3)
R23
len(R23)

rawDescription: Create constrained random numbers?

description: Create constrained random numbers


code:
lines ="""apple boy 'cat'
dog, egg fin
goat hat ice!"""

out = []
for line in lines.splitlines():
    temp = ""
    for ch in line:
        if ch.isalnum():
            temp+= ch
        else:
            temp += " {} ".format(ch)
    out.extend(temp.split())
print(out)

rawDescription: Splitting strings at multiple delimiters in python


code:
from collections import Counter
x = Counter(['abc','abc','def','jkl'])
total = sum(x.values(), 0.0)
for key in x:
    x[key] /= total

x
y = Counter(['abc','def','def','pqr', 'pr', 'foo', 'bar'])
total = sum(y.values(), 0.0)
for key in y:
    y[key] /= total

y

rawDescription: How to normalize a Counter and combine 2 normalized Counters? - python

description: Normalize a Counter and combine 2 normalized Counters? - python


code: layout = BoxLayout(size_hint=(0.5, None), height=50, pos_hint={'top': 1})

rawDescription: python kivy boxlayout set position

description: Python kivy boxlayout set position


code: soup = bs.BeautifulSoup(html, convertEntities=bs.BeautifulSoup.HTML_ENTITIES)

rawDescription: How to extract tags from HTML using Beautifulsoup in Python

description: Extract tags from HTML using Beautifulsoup in Python


code:
import unittest

class UnitTestExamples(unittest.TestCase):

    def testsum(self):
        a = 10
        b = 42
        self.assertEqual(a+b,52)

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

rawDescription: python Unitest sample Application

description: Python Unitest sample Application


code:
# build a table mapping lead byte to expected follow-byte count
# bytes 00-BF have 0 follow bytes, F5-FF is not legal UTF8
# C0-DF: 1, E0-EF: 2 and F0-F4: 3 follow bytes.
# leave F5-FF set to 0 to minimize reading broken data.
_lead_byte_to_count = []
for i in range(256):
    _lead_byte_to_count.append(
        1 + (i >= 0xe0) + (i >= 0xf0) if 0xbf < i < 0xf5 else 0)

def readUTF8(f, count):
    """Read `count` UTF-8 bytes from file `f`, return as unicode"""
    # Assumes UTF-8 data is valid; leaves it up to the `.decode()` call to validate
    res = []
    while count:
        count -= 1
        lead = f.read(1)
        res.append(lead)
        readcount = _lead_byte_to_count[ord(lead)]
        if readcount:
            res.append(f.read(readcount))
    return (''.join(res)).decode('utf8')

rawDescription: Reading UTF-8 strings from a binary file


code:
import multiprocessing as mp
import logging

logger = mp.log_to_stderr(logging.DEBUG)

def do_stuff(text):
    logger.info('Received {}'.format(text))
    return text

if __name__ == '__main__':
    p = mp.Pool(4)
    tasks = ['str{}'.format(i) for i in range(2000)]
    results = p.map(do_stuff, tasks)
    p.close()

    logger.info(results)

rawDescription: Python multiprocessing.Pool.map dying silently


code:
eventsdb_subset = self.eventsdb_subset
self.eventsdb_subset = sqldf('SELECT * from eventsdb_subset WHERE %s' % filterstring,locals())
self.db_info_string.set('Number of events: ' +str(len(eventsdb_subset)))

rawDescription: Updating Tkinter label from a StringVar happens on a delay


code:
''''echo hello from bash
exit
'''

print('hello from python')

rawDescription: embedding Bash Script in python without using subprocess call

description: Embedding Bash Script in python without using subprocess call


rawDescription: IPython Notebook/Matplotlib: Interactive show/hide graphs on a plot, is it possible?


rawDescription: search for any string value in an ordered dictionary

description: Search for any string value in an ordered dictionary


rawDescription: Python AST: How to get the children of a node


code: return render(request, 'my-template.html', json.loads(data))

rawDescription: Django : Parsing Json data to template

description: Django : Parsing Json data to template


code:
swapped_lut = np.rollaxis(lut, -1)
cmyk = swapped_lut[:, rgb[0], rgb[1], rgb[2]].copy()

rawDescription: Fancier Fancy Indexing in NumPy?

description: Fancier Fancy Indexing in NumPy


code: can.coords(oval1, *(moveLeft() + addThirty(moveLeft())))

rawDescription: Passing function returns as method parameters in Python


code:
import numpy as np

desc = np.dtype([('letter', 'S1'), ('v1', float), ('v2', float),
                 ('v3', float), ('v4', float)])

rawDescription: importing an array from a .dat file in python

description: Importing an array from a .dat file in python


code: self.tc = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER, size=(200,100))

rawDescription: Enter key in wx.TextCtrl on Mac has no effect


code:
import itertools

def pairwise(input):
    for values in input.itervalues():
        for pair in itertools.combinations(values.iteritems(), 2):
            yield dict(pair)

rawDescription: Pair combinations of elements in dictionary without repetition


code: set(genre for d in list_of_dicts for genre in d['genres'])

rawDescription: Remove inner list in list of lists

description: Remove inner list in list of lists


code:
from FunctionLibrary import foo, bar as fl_bar
foo()
fl_bar()

rawDescription: Difference in ways of importing modules

description: Difference in ways of importing modules


code: Df['Description'].str.replace('macbook air 11.*' , 'macbook air 11')

rawDescription: How to replace all words in a series with a few specified words in Pandas,Python?

description: Replace all words in a series with a few specified words in Pandas,Python


rawDescription: Accents/special characters (e.g., ñ) in verbose_name or help_text ?


code:
#!/bin/bash
#/path/to/run-monthly
run-parts /path/to/monthly/jobs

rawDescription: Cronjobs per package

description: Cronjobs per package


rawDescription: Scrapy hxs.select() not selecting all results


code:
import sympy as sy

f = sy.Function('f')
g = sy.Function('g')

a = f(3) + g(5) + 1.0

print(a)
# f(3) + g(5) + 1.0
print(a.atoms(sy.Function))

rawDescription: Check if sympy expression contains function


code:
import pandas as pd
from itertools import dropwhile
import csv
with open("in.csv") as f:
    f = dropwhile(lambda x: x.startswith("#!!"), f)
    r = csv.reader(f)
    df = pd.DataFrame().from_records(r)

rawDescription: Python convert comma separated list to pandas dataframe


code:
import random
coins = 1000
wager = 0
while True: #main loop
    print('you have {} coins'.format(coins))
    if coins == 0: #stops the game if the player is out of money
        print('You are out of money! Scram, deadbeat!')
        break
    while wager > coins or wager == 0: #loops until player enters a non-zero wager that is less then the total amount of coins
        wager = int(input('Please enter your bet (enter -1 to exit): '))
    if wager < 0: # exits the game if the player enters a negative
        break
    print('All bets are in!')
    x = random.randint(0,10)
    y = random.randint(0,10)
    z = random.randint(0,10)
    print(x,y,z) #displays all the random ints
    if x + y +z > 10: #victory condition, adds coins for win
        print('You win! You won {} coins.'.format(wager))
        coins += wager
    else: #loss and deduct coins
        print('You lost! You lose {} coins'.format(wager))
        coins -= wager
    wager = 0 # sets wager back to 0 so our while loop for the wager validation will work

rawDescription: Infinite Loop Error in Python

description: Infinite Loop Error in Python


code:
def func():
    return x**2

rawDescription: How to bring variables into functions - Python

description: Bring variables into functions - Python


code: currencies

rawDescription: python scraping exchange rate data

description: Python scraping exchange rate data


rawDescription: Understanding performance difference

description: Understanding performance difference


rawDescription: Applying circular mask with periodic boundary conditions in python


code:
mergedf = df.shift(1).reset_index().rename(columns={'coulmnis':'newcol'})
newdf = df.merge(mergedf).set_index('timestmp')
df['count'] = newdf.apply((lambda x: len(x['coulmnis'] & x['newcol']) if pd.notnull(x['newcol']) else 0),axis=1)

rawDescription: Pandas dataframe column containing list, Get intersection of two consecutive rows


code:
with open('this.txt') as f, open('that.txt', 'w') as g:
    text = f.read()
    matches = re.findall('', text) # do some re matching here
    g.write("\n".join(i[0] for i in matches))

rawDescription: Writing items to file on separate lines without blank line at the end


rawDescription: How to get (childless) “tabs” in a pygtk application

description: Get (childless) “tabs” in a pygtk application


code:
import json, dateutil.parser, bson.json_util

a = """{
    "mydate": {"$isodate": "2012-11-01T20:19:55.782Z"}
}"""

def my_hook(dct):
    if '$isodate' in dct:
        return dateutil.parser.parse(dct['$isodate'])
    return bson.json_util.object_hook(dct)

obj = json.loads(a, object_hook=my_hook)

rawDescription: What should be the format of "Date" in text file to be read as Json and then inserted into MongoDB using Python?


code:
import win32com.client
conn = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/path/to/my.mdb;'
conn.Open(DSN)
conn.Execute("ALTER TABLE my_table ADD COLUMN my_column INTEGER;")
conn.Close()

rawDescription: Add new field to access table using python


code:
filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
mydict={}
for i,j in zip(filtered_symbolic_path,filtered_symbolic_path_times):
    mydict.setdefault(i,0)
    mydict[i]=j+mydict[i]

rawDescription: How to add repeating occurences of elements in two lists in python

description: Add repeating occurences of elements in two lists in python


code:
from myapp.models import Post, PostImage
from django.forms import inlineformset_factory
PostImageFormSet = inlineformset_factory(Post, PostImage, fields=('image',))
post = Post.objects.get(id=13)
formset = PostImageFormSet(instance=post)

rawDescription: What is the right way to attach multiple images to a post? [Django]