code:
class SSEHandler(sse.Handler):
    _instances = {}

    @asyncio.coroutine
    def handle_request(self):
        self.send('Working')
        my_future = asyncio.Future()
        SSEHandler._instances[self] = my_future
        yield from my_future

rawDescription: Python - Communicate between asyncio protocol/servers


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)
N = 49999

def chunks(seq, n):
    # http://stackoverflow.com/a/312464/190597 (Ned Batchelder)
    """ Yield successive n-sized chunks from seq."""
    for i in xrange(0, len(seq), n):
        yield seq[i:i + n]

def downsample(seq, n):
    return [sum(chunk)/len(chunk) for chunk in chunks(seq, n)]

x = range(N)
x = downsample(x, 100)
data_dict = {'A' : np.random.random(N), 'B' : np.random.random(N)}
colors = plt.cm.rainbow(np.linspace(0, 1, len(data_dict.keys())))

fig, ax = plt.subplots(dpi=150)
for key,c in zip(data_dict.keys(),colors):
    y = downsample(data_dict[key], 100)
    ax.plot(x,
            y,
            label=key,
            color=c,
            alpha=.5)
    print("%s DONE!" % (key))

ax.axhline(1,color='red',linestyle='--')
ax.grid(True)
ax.set_xlabel("Zeit in ns")
ax.set_ylabel("Distanz in nm")
legend = ax.legend()
print("DONE!")
# plt.show()
plt.savefig('/tmp/test.png')

rawDescription: plotting a graph with matplotlib plot function takes sometimes minutes

description: Plotting a graph with matplotlib plot function takes sometimes minutes


code:
def band_limited_noise(min_freq, max_freq, samples=1024, samplerate=1):
    freqs = np.abs(np.fft.fftfreq(samples, 1/samplerate))
    f = np.zeros(samples)
    idx = np.where(np.logical_and(freqs>=min_freq, freqs<=max_freq))[0]
    f[idx] = 1
    return fftnoise(f)

rawDescription: How to generate noise in frequency range with numpy?

description: Generate noise in frequency range with numpy


code: zip(L,L)

rawDescription: Assorting elements in a list into a list of lists of specific lengths


rawDescription: How can I get the base of a URL in Python?

description: Get the base of a URL in Python


rawDescription: Python regular expression to change date formatting


rawDescription: How do I count the words in a string using only loops and string.strip()?

description: Count the words in a string using only loops and string.strip()


rawDescription: Substitute node labels with emoji using networkX in Python


code:
import lxml.html as LH
code = '......'

doc = LH.fromstring(code)
for text in doc.xpath( "//script[contains(text(), 'document.write') and (contains(text(),'href'))]//text()" ):
    script = LH.fromstring(text)
    print(script.xpath('//a/@href'))

rawDescription: Extract text() and get attributes from it


code: soup = BeautifulSoup(site, "lxml")

rawDescription: Python Beautifulsoup get_text() not getting all text


code: unassigned_items = {k:v for k, v in mydict.viewitems() if v[0] is None}

rawDescription: Checking indexed object value type

description: Checking indexed object value type


code:
def repeat3(fn, n, x):
    if n == 1:
        return fn(x)
    else:
        return fn(repeat3(fn, n-1, x))

def repeat(fn, n):
    return functools.partial(repeat3, fn, n)

rawDescription: Recursive function using lambda expression


code:
pat = re.compile(r' A(\d+)')
lst = re.findall(pat, "= A1 A2 A3 A4")

rawDescription: RegEx in Python matching multiple substrings using one group


code: print(time.time() - start)

rawDescription: Displaying algorithm run time in python

description: Displaying algorithm run time in python


rawDescription: Python - Convert a matrix to edge list/long form


code:
for team, (runs_scored, runs_allowed) in league.iteritems():
    runs_scored = float(runs_scored)
    runs_allowed = float(runs_allowed)

rawDescription: Iterating Over Dictionary Key Values Corresponding to List in Python


code:
from heapq import nsmallest

# Get the 1000th file never storing info on more than 1000 at a time
file1000 = nsmallest(1000, filesonly, key=lambda x: x.stat().st_mtime)[999].path

rawDescription: fastest way to get the filename of a specific file from a directory with python

description: Fastest way to get the filename of a specific file from a directory with python


code: homes, aways = [i.home for i in fixtures[:5]], [i.away for i in fixtures[:5]]

rawDescription: How to slice a list of objects in association of the object attributes

description: Slice a list of objects in association of the object attributes


rawDescription: Looking for a way to shard a MongoDB collection from within Python code


rawDescription: Accessing an attribute of a multiprocessing Proxy of a class


rawDescription: How do I reference a specific value in a nested NumPy array?

description: Reference a specific value in a nested NumPy array


code:
L1 = {'milk', 'butter', 'bread', 'shampoo', 'dog food'}
L2 = {'milk', 'butter', 'shampoo', 'dog food', 'coffee'}
L1 & L2

rawDescription: Compare similarities in a list using hashes?


rawDescription: Capture multiple words in group

description: Capture multiple words in group


code:
from PySide import QtGui, QtCore, QtUiTools

class UiLoader(QtUiTools.QUiLoader):
    _baseinstance = None

    def createWidget(self, classname, parent=None, name=''):
        if parent is None and self._baseinstance is not None:
            widget = self._baseinstance
        else:
            widget = super(UiLoader, self).createWidget(classname, parent, name)
            if self._baseinstance is not None:
                setattr(self._baseinstance, name, widget)
        return widget

    def loadUi(self, uifile, baseinstance=None):
        self._baseinstance = baseinstance
        widget = self.load(uifile)
        QtCore.QMetaObject.connectSlotsByName(widget)
        return widget

rawDescription: How do I load children from .ui file in PySide?

description: Load children from .ui file in PySide


code:
from ctypes import *
file = CDLL('file.dll')
# now it's locked
file.function()
windll.kernel32.FreeLibrary(file._handle)
# not it's unlocked

rawDescription: Can I explicitly close a ctypes CDLL?

description: Explicitly close a ctypes CDLL


rawDescription: Return index values of a sorted row using pandas?


code:
import numpy as np
import timeit

def get_walks_rec(shape,inpath,ij,n):
    # add n more steps to mypath, with dimensions shape
    # procedure: call shorter walks for allowed neighbouring sites

    mypath = inpath[:]
    mypath.append(ij)

    # return if this is the last point
    if n==0:
        return mypath

    i0 = ij[0]
    j0 = ij[1]

    neighbs = [(i,j) for i in (i0-1,i0,i0+1) for j in (j0-1,j0,j0+1) if 0<=i<shape[0] and 0<=j<shape[1] and (i,j)!=(i0,j0)]
    subpaths = [get_walks_rec(shape,mypath,neighb,n-1) for neighb in neighbs]

    # flatten out the sublists for higher levels
    if n>1:
        flatpaths = []
        map(flatpaths.extend,subpaths)
    else:
        flatpaths = subpaths

    return flatpaths

# front-end for recursive function, called only once
def get_walks_rec_caller(mat,n):
    # collect all the paths starting from each point of the matrix

    sh = mat.shape
    imat,jmat = np.meshgrid(np.arange(sh[0]),np.arange(sh[1]))
    tmppaths = [get_walks_rec(sh,[],ij,n-1) for ij in zip(imat.ravel(),jmat.ravel())]

    # flatten the list of lists of paths to a single list of paths
    allpaths = []
    map(allpaths.extend,tmppaths)

    return allpaths

# input
mat = np.random.rand(3,3)
nmax = 3

# original:
walks_old = get_walks(mat,nmax)

# new recursive:
walks_new = get_walks_rec_caller(mat,nmax)

# timing:
number = 1000
print(timeit.timeit('get_walks(mat,nmax)','from __main__ import get_walks,mat,nmax',number=number))
print(timeit.timeit('get_walks_rec_caller(mat,nmax)','from __main__ import get_walks_rec_caller,mat,nmax',number=number))

rawDescription: How to find every walk in a numpy array

description: Find every walk in a numpy array


code:
subprocess.call(['ssh', 'ubuntu@192.168.56.101', 'cat ~/cfg.cfg'])
subprocess.call(['ssh', 'ubuntu@192.168.56.101', '`sed -i -e s/property=\\"true\\"/property=\\"false\\"/g ~/cfg.cfg`'])
subprocess.call(['ssh', 'ubuntu@192.168.56.101', 'cat ~/cfg.cfg'])

rawDescription: How to transport " for remote execution?

description: Transport " for remote execution


code:
from collections import OrderedDict
with open('abc') as f:
    dic = OrderedDict()
    seen = set()
    for line in f:
        spl = line.split() + [""]
        key ,v = spl[:2]
        if v in dic and dic[v] == [""]:
            del dic[v]
        for k1,v1 in dic.items():
            if key in v1:
               dic[k1].append(v)
               break
        else:
             dic[key] = [v]

with open('ouput.txt', 'w') as f:
    for k,v  in dic.items():
        f.write("{} {}\n".format(k," ".join(v)))

rawDescription: for every value which in-turn is a key is put in one-line

description: For every value which in-turn is a key is put in one-line


code:
# We only need row
row, _ = search_in_table(table_name, search_for)

rawDescription: How do I satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function?

description: Satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function


code: sorted(dict1.items(), key=lambda kv: kv[1]['Name'])

rawDescription: Worth using sorted( ,key=) on a nested dictionary?


code:
def count(n):
    sum = 0 #Intializing the return variable
    for i in range(1, n+1):
        sum+=1.0/i #Adding to the return variable
    return sum

rawDescription: Writing a python program takes an int argument and adds 1+1/2+1/3+1/4....1/n


code: pd.crosstab([df.c1,df.c2], [df.c3,df.c4], values=df.val, aggfunc=[len, np.mean])

rawDescription: how to use two different functions within crosstab/pivot_table in pandas?

description: Use two different functions within crosstab/pivot_table in pandas


code:
import itertools

it = iter(someincomingbytedata)
x = bytearray(itertools.islice(it, 10)) # consume the first 10 bytes
inbuffer = bytearray(it)                # consume the rest

rawDescription: Python: Zero Copy while truncating a byte buffer


code: np.vstack([y[1] for y in x])

rawDescription: Recursively defining an N-dimensional numpy array


code:
for fd in source_fds_list:
   with open(destination_url, 'ab') as destn_fd:
       with fd:
           start = fd.read(4)

           if start not in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
               if start[:3] != BOM_UTF8:
                   if start[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
                       # UTF-16 BOM, skip 2 bytes
                       start = start[2:]
               else:
                   # UTF-8 BOM, skip 3 bytes
                   start = start[-1]
               # Not a UTF-32 BOM, write read bytes (minus skipped bytes)
               destn_fd.write(start)

           shutil.copyfileobj(fd, destn_fd)

rawDescription: shutil.copyfileobj method in python copies BOM character also while merging files

description: Shutil.copyfileobj method in python copies BOM character also while merging files


code: 'HELLOWORLD   testing this. {{_thiswillNotMatch}} OKAY'

rawDescription: Python string.replace equivalent (from Javascript)


code:
from sqlalchemy import func
rows = session.query(func.count(Congress.id)).scalar()

rawDescription: Get the number of rows in table using SQLAlchemy


code:
from collections import namedtuple
MyStruct = namedtuple('MyStruct', 'a b d')
s = MyStruct(a=1, b={'c': 2}, d=['hi'])
s
s.a
s.b
s.c
s.d

rawDescription: Convert Python dict to object?

description: Convert Python dict to object


code:
green_box = soup.find("tr", text="GREEN BOX")
for row in green_box.find_next_siblings("tr"):
    print([td.get_text(strip=True) for td in row.find_all("td")])

rawDescription: beautifulsoup table tree: find all tr between two objects?

description: Beautifulsoup table tree: find all tr between two objects


code:
labels[np.array([x[:2] for x in duplicates])]

array([[2, 3],
       [3, 2],
       [0, 0]])

rawDescription: Access 1D array with array of lists or arrays


code:
import json

json.loads(input).encode('utf8')

rawDescription: Unescape unicode-escapes, but not carriage returns and line feeds, in Python


code:
p = (
   Person().setName('Hunter')
           .setAge(24)
           .setSSN('111-22-3333')
)

rawDescription: Calling chains methods with intermediate results


code: CLEANCSS_EXTRA_ARGS = ['--skip-rebase']

rawDescription: How to pass filter specific configuration options in webassets

description: Pass filter specific configuration options in webassets


code: output = data[2] + data[2]

rawDescription: binding local variables in python

description: Binding local variables in python


code:
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7'}
request = urllib2.Request(url, '', headers)
response = urllib2.urlopen(request)

rawDescription: Working with urllib2 in function

description: Working with urllib2 in function


rawDescription: save output values in txt file in columns python

description: Save output values in txt file in columns python


code:
milliseconds = 0
if len(unix_timestamp) == 13:
    milliseconds = int(unix_timestamp[-3:])
    unix_timestamp = float(unix_timestamp[0:-3])

the_date = datetime.fromtimestamp(unix_timestamp)
the_date += timedelta(milliseconds=milliseconds)

rawDescription: Datetime Unix timestamp contains milliseconds


code: z[np.arange(k-i) + i, np.arange(k-i)]

rawDescription: Numpy: Affect diagonal elements of matrix prior to 1.10


code:
connected = {}
accounts = {}

def load_account(acct):
    return db_magic(acct)                             # Grab a dictionary from the DB

def somebody_connected(sck, acct):
    global connected, accounts
    account = load_account(acct)
    connected[sck] = account                          # Now we have it by socket
    accounts[acct["accountid"]] = account             # Now we have it by account ID

rawDescription: Python organizing data with multiple dictionaries


code:
conditions = [
    (np.isnan(x['position'])) & (x['position'].fillna(method='ffill')*x['change']>0),
    (np.isnan(x['position'])) & (x['position'].fillna(method='ffill')*x['change']<=0)]

choices=[x['position'].shift(1),0]
x['position'] = np.select(conditions,choices,default=x['position'])

x['position'] = x['position'].fillna(method='ffill')

rawDescription: Write a user defined fillna function in pandas dataframe to fill np.nan different values with conditions


code:
class TestFoo(unittest.TestCase):

    longMessage = True  # <--

    def test_foo(self):
        self.assertEqual(1+2, 2, 'custom message')

rawDescription: Python: self.assertEqual(a, b, msg) --> I want diff AND msg


code:
q_list = []
for x in fruits:
    q_list.append(Q(fruit_name__contains=x))
q_filter = "|".join(q_list)
r.objects.filter(q_filter)

rawDescription: Django Multiple Filter with list

description: Django Multiple Filter with list


code:
for file in files:
    with open(file, "r") as currentfile, open(file[:-4]+"_RGB_moved.pts", "w") as out:
        firstline = next(currentFile)
        out.write(firstline.split(None, 1)[0])

        for line in currentfile:
            out.write('\n')
            words = line.split()
            newwords = [str(float(words[0])+offsetx), str(float(words[1])+offsety), words[2], str((int(words[3]) + 2050) / 2)]
            out.write(" ".join(newwords))

rawDescription: How can I speed up this really basic python script for offsetting lines of numbers

description: Speed up this really basic python script for offsetting lines of numbers


code: def score(x): sum(x) - max(x)

rawDescription: Python: Sorting list containing tuples

description: Python: Sorting list containing tuples


code: good.write('"' + email.strip() + '"\n')

rawDescription: Surround outputted email addresses in quotation marks in Python3.2


rawDescription: Regex: Get "London, UK" from "Evolution Recruitment (Agency) (London, UK)"


code:
keymap = dict(zip(('key1', 'key2', 'key3'), range(3)))
keymap
arr[:, keymap['key2']]

rawDescription: Python: Pulling data out of dictionary like a 2D array


code:
menu = ['spam', 'ham', 'eggs', 'bacon', 'sausage', 'onions']
# Reversed sequence
for dish in reversed(menu):
    print(dish)

import itertools
# Only every third
for dish in itertools.islice(menu, None, None, 3):
    print(dish)

# In groups of 4
for dish in itertools.izip_longest(*([iter(menu)] * 4)):
    print(dish)

rawDescription: Python - for with counter

description: Python - for with counter


code:
import numpy as np
import matplotlib as plt

xv = np.array(np.linspace(-10,10,200), dtype=np.complex)
plt.plot(xv, np.angle(np.cos(xv)))

rawDescription: Reason for the difference between arg and atan2


rawDescription: PyGobject Application Icon

description: PyGobject Application Icon


rawDescription: Creating a dynamically drawn line in Kivy


code: regex.split('(?=\W)', 'foo/bar spam\neggs', flags=regex.V1)

rawDescription: Python re.split and attaching matched group to either right or left side of the split


code:
def extractText(self):
    [...]
    for operands,operator in content.operations:
        if operator == "Tj":
            _text = operands[0]
            if isinstance(_text, TextStringObject):
                text += _text
        elif operator == "T*":
            text += "\n"
        elif operator == "'":
            text += "\n"
            _text = operands[0]
            if isinstance(_text, TextStringObject):
                text += operands[0]
        elif operator == '"':
            _text = operands[2]
            if isinstance(_text, TextStringObject):
                text += "\n"
                text += _text
        elif operator == "TJ":
            for i in operands[0]:
                if isinstance(i, TextStringObject):
                    text += i

rawDescription: pyPdf ignores newlines in PDF file

description: PyPdf ignores newlines in PDF file


rawDescription: explanation for groupby() in Pandas dataframe object behaviour

description: Explanation for groupby() in Pandas dataframe object behaviour


code:
import os
# f = /home/begueradj/Desktop/metasploitBible.pdf'
os.system('xdg-open path_to_my_filename.pdf')
print("You do not need to close the opened PDF file to run and see this")

rawDescription: LF> os.system(filePath) alternative

description: LF> os.system(filePath) alternative


code: re.split(r'([\s]+)', 'hello world')

rawDescription: What are the empty strings of my readline() after split


code:
for i in range(number_of_cpus):
    label = tk.Label(parent, text="CPU #ts" % i)
    label.pack()

rawDescription: How to create dynamic Labels and populate them in python 3 tkinter/ttk

description: Create dynamic Labels and populate them in python 3 tkinter/ttk


code:
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it:  "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.

import atexit
import os
import readline
import rlcompleter

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)

if os.path.exists(historyPath):
    readline.read_history_file(historyPath)

atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath

rawDescription: Export Python interpreter history to a file?


rawDescription: To print the lists for the code?

description: To print the lists for the code


code: map(f, my_list)

description: Going from (a_1, a_2, ..., a_n) to (f(a_1), f(a_2), ..., f(a_n))


code:
get_diagonal(t, 0, 0)
get_diagonal(t, 19, 19)
get_diagonal(t, 5, 5)
get_diagonal(t, 5, 5, 3)

rawDescription: finding diagonal numbers

description: Finding diagonal numbers


code:
def wrapper_class(cls):
    # do this in a function so we can create it generically as needed
    # for each cython class
    class WrapperClass(object):
        def __init__(self,*args,**kwargs):
            # construct the held class using arguments provided
            self._wrapped = cls(*args,**kwargs)

        def __getattribute__(self,name):
            # intercept all requests for attribute access.
            wrapped = object.__getattribute__(self,"_wrapped")
            update_from = wrapped
            update_to = self
            try:
                o = getattr(wrapped,name)
            except AttributeError:
                # if we can't find it look in this class instead.
                # This is reasonable, because there may be methods defined
                # by sqlalchemy for example
                update_from = self
                update_to = wrapped
                o = object.__getattribute__(self,name)
            if callable(o):
                return FunctionWrapper(o,update_from,update_to)
            else:
                return o

        def __setattr__(self,name,value):
            # intercept all attempt to write to attributes
            # and set it in both this class and the wrapped Cython class
            if name!="_wrapped":
                try:
                    setattr(self._wrapped,name,value)
                except AttributeError:
                    pass # ignore errors... maybe bad!
            object.__setattr__(self,name,value)
    return WrapperClass

class FunctionWrapper(object):
    # a problem we have is if we call a member function.
    # It's possible that the member function may change something
    # and thus we need to ensure that everything is updated appropriately
    # afterwards
    def __init__(self,func,update_from,update_to):
        self.__func = func
        self.__update_from = update_from
        self.__update_to = update_to

    def __call__(self,*args,**kwargs):
        ret_val = self.__func(*args,**kwargs)

        # for both Cython classes and sqlalchemy mappings
        # all the relevant attributes exist in the class dictionary
        for k in self.__update_from.__class__.__dict__.iterkeys():
            if not k.startswith('__'): # ignore private stuff
                try:
                    setattr(self.__update_to,k,getattr(self.__update_from,k))
                except AttributeError:
                    # There may be legitmate cases when this fails
                    # (probably relating to sqlalchemy functions?)
                    # in this case, replace raise with pass
                    raise
        return ret_val

rawDescription: Mixin Cython class and SqlAlchemy

description: Mixin Cython class and SqlAlchemy


code:
import string

def count_letters(line):
    return sum(line.count(x) for x in string.ascii_letters)

jabberwocky = [
"'Twas brillig, and the slithy toves        ",
"       Did gyre and gimble in the wabe;    ",
"    All mimsy were the borogoves,          ",
"       And the mome raths outgrabe.        ",
"                            - Lewis Carroll"]

for line in jabberwocky:
    print(count_letters(line))

rawDescription: Python character count beside each line of a file


code:
df = pd.read_csv('www004.csv')
df1.loc[426178,:]
df2.loc[426178,:]
df3 = df1.combine_first(df2)

rawDescription: In Pandas, how can I patch a dataframe with missing values with values from another dataframe given a similar index?


code:
import itertools
AB = map(sum, itertools.izip_longest(A, B, fillvalue=0))

rawDescription: Finding the sum of matching components in two lists


code:
student_list.sort(key=lambda x: int(x[-1]), reverse=True)

print(student_list)

rawDescription: How to sort a list of strings by highest number

description: Sort a list of strings by highest number


code:
def make_counter(start=0):
    count = start - 1
    def counter():
        nonlocal count  # requires 3.x
        count += 1
        return count
    return counter

rawDescription: state retention for classes and closures

description: State retention for classes and closures


code: re.sub(r'_thing_', temp, template)

rawDescription: regex replace from a list

description: Regex replace from a list


rawDescription: Python: Dynamically adding function to a class, whose name is contained in a string


rawDescription: converting binary to utf-8 in python

description: Converting binary to utf-8 in python


code:
def open_page(self, page_number):
    # enable all except the button for this page.
    for i, button in enumerate(self.buttons):
        if i == page_number:
            button.config(state=DISABLED)
        else:
            button.config(state=ACTIVE)

    self.pages[page_number].lift()

rawDescription: Still struggling with class scope

description: Still struggling with class scope


code:
possibleMatches = parsedHtml.select('select[name=languageid] option')

for match in possibleMatches:
    print(match.text, "-", match.get('value'))

rawDescription: Python 3: Can't properly encode and print a downloaded string with /xXX literals


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

rawDescription: Python set intersection and __eq__

description: Python set intersection and __eq__


code:
for chain in chains:
    for doc in documents:
        doc.list_strippedtext = reduce(lambda data, func: func(data), chain, doc.text)
    bow = createBOW(documents)

rawDescription: Python 3 - cumulative functions alternatives


code:
import re
re.sub(" +"," ","text text                  blabla bla ").strip()

rawDescription: python - remove whitespaces that are not needed

description: Python - remove whitespaces that are not needed


code:
import contextlib

@contextlib.contextmanager
def dbconnect(**kwds):
  dbConnection = MySQLdb.connect(**kwds)
  try:
    yield dbConnection
  finally:
    closeDb(dbConnection)

rawDescription: In Python, how to make sure database connection will always close before leaving a code block?


code:
import numpy as np
def rand_range(a, b, size):
    return a + np.random.random(size) * (b - a)

x = rand_range(-3, 3, (3))
y = rand_range(-3, 3, (3))

rawDescription: Using 'If' to run the loop again?

description: Using 'If' to run the loop again


code:
newest = {}
for entry in entries:
    current = newest.get(entry['remote'])
    if current is None or entry['timestamp'] > current['timestamp']:
        newest[entry['remote']] = entry
entries[:] = newest.values()

rawDescription: How to delete duplicate entries in a nested container

description: Delete duplicate entries in a nested container


code: c = c + x

rawDescription: String Mirror Function

description: String Mirror Function


rawDescription: Performance of multiple iterations

description: Performance of multiple iterations


rawDescription: How to extract only text from the div containing more divs using scrapy

description: Extract only text from the div containing more divs using scrapy


code: s

rawDescription: Python list comprehensions: Is it possible to specify the inclusion of two elements at a time?


rawDescription: numpy: slicing and vectorized looping with 1d and 2d arrays

description: Numpy: slicing and vectorized looping with 1d and 2d arrays


code: json_text += json.dumps(json_data)

rawDescription: Trying to loop through all entries in a datastore object and adding post numbers in dictionary


code:
import json
data1 = json.loads(data)

rawDescription: Parse Json data to Excel

description: Parse Json data to Excel


rawDescription: Time-varying data: list of tuples vs 2D array?


code:
var1=""

def foo():
    global var1
    var1="new_valor"

def bar():
    print(var1)

rawDescription: How to get value from global variable in another module python

description: Get value from global variable in another module python


code:
engine = create_engine(
'mssql+pyodbc://./MyDb',
strategy='mock',
executor= lambda sql, *multiparams, **params: print (sql.compile(dialect=engine.dialect)))

rawDescription: How to generate a file with DDL in the engine's SQL dialect in SQLAlchemy?

description: Generate a file with DDL in the engine's SQL dialect in SQLAlchemy


code:
strPat = r'^(?:((?:January|February|March|April|May|June|July|August|September|October|November|December) \d+ at \d+:\d+[ap]m)|(Yesterday at \d+:\d+[ap]m)|(\d+ hours ago)|(About an hour ago)) \D*?(\d+)?$'
m = re.match(pat1, line, re.M)

rawDescription: Facebook comments regex matching

description: Facebook comments regex matching


code:
np.arange(10) == 4
np.arange(10) * 1
np.arange(10) + 23

rawDescription: How to create in one line a null vector of size 10 but the fifth value being 1 using numpy

description: Create in one line a null vector of size 10 but the fifth value being 1 using numpy


code:
from StringIO import StringIO

import pandas as pd

data = """

            Class
            Fail
            Error
            Skip
            Success
            Total

                Regression_TestCase
                1
                9
                0
                219
                229

            Total
            1
            9
            0
            219
            229

"""

df = pd.read_html(StringIO(data))
print(df)

rawDescription: HTML data from Beautiful Soup needs formatting


code:
import pandas as pd
df = pd.read_csv("ws425.log.test", parse_dates=[0], header=None, usecols=[0, 4])
df
df[0][0]

rawDescription: reading a comma-delimited file with a date object and a float with Python

description: Reading a comma-delimited file with a date object and a float with Python


code: target_list1 = target_list2 = expression

rawDescription: Semantics of 'x = y = z' assignment in Python


code:
options.remove(current_option)
options.append(False)
return options[0]

rawDescription: Python: Pick other value

description: Python: Pick other value


rawDescription: efficient algorithm instead of looping

description: Efficient algorithm instead of looping


code: [[x[0], int(x[1])] for x in csv.reader(data.split('\n')) if len(x) > 1]

rawDescription: shortest Python solution for creating list from csv string

description: Shortest Python solution for creating list from csv string


code:
s = 'this is a sentence sentence sentence this is a sentence where phrases phrases duplicate where phrases duplicate'
while re.search(r'\b(.+)(\s+\1\b)+', s):
  s = re.sub(r'\b(.+)(\s+\1\b)+', r'\1', s)
s

rawDescription: Is there a way to remove duplicate and continuous words/phrases in a string?


code:
from urllib import urlencode, quote
from collections import OrderedDict

initial_url = "http://www.stackoverflow.com"
search = "Generate+value"
query_string = urlencode(OrderedDict(data=initial_url,search=search))

rawDescription: Build query string using urlencode python


code:
from dateutil.parser import parse
parse("Wed, Nov 12")

rawDescription: Python module to extract probable dates from strings?


rawDescription: wxPython align widgets and fitting

description: WxPython align widgets and fitting


code:
client_class = Client(port_push, port_sub)
client_class.start()

rawDescription: ZMQ Poller not working within Class Instance


code: from sympy.simplify.fu import TR8

rawDescription: Python: Importing a module with the same name as a function


code:
from __future__ import print_function

[print(line) for line in results]

rawDescription: Use one line of code to print a for loop


code:
selection = treeView.get_selection()
selections, model = selection.get_selected_rows()

# Note: Must loop through rows in the opposite direction so as not to move a row all the way to the bottom
for i in range(len(selections)-1, -1, -1):
    row = selections[i]
    # Make sure the row we are given is actually selected
    if selection.iter_is_selected(row.iter) and row.next != None:
        self.listData.move_after(row.iter, row.next.iter)

rawDescription: How to move multiple ListStore elements up or down

description: Move multiple ListStore elements up or down


code:
import ctypes

lib = ctypes.cdll.LoadLibrary(LIB_PATH)
lib.hallo.restype = ctypes.c_char_p
lib.hallo.argtypes =[ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]
allocation = ctypes.create_string_buffer(128 * 1024)
j = lib.hallo('my name'.encode(), allocation, 128 * 1024)
if j is not None:
    print('INIT: ' + allocation.value)
else:
    print("Buffer was too small")

rawDescription: CTYPES and PYTHON3: Can't return long string


code:
class A():
    def function(self, *args, bob, sally):
        print(args, bob, sally)

values = [1, 2, 3, 4]
a=A()
a.function(bob="Hi bob", sally="Hello sally", *values)
a.function(*values, bob="Hi bob", sally="Hello sally")
a.function(bob="Hi bob", *values, sally="Hello sally")

rawDescription: In python, can you pass variadic arguments after named parameters?


code: ('caller', 'caller')

rawDescription: Detect method by self.sender() in Python


code:
def consistency(dictionary):

    temp_list_of_values_we_care_about = [(x[0],x[1],x[2]) for x in dictionary.itervalues()]
    temp_dict = {}

    for val in temp_list_of_values_we_care_about:
        if val in temp_dict:
            temp_dict[val] += 1
        else:
            temp_dict[val] = 1

    new_dictionary = {}
    for key in dictionary:

        value = dictionary[key]
        temp = (value[0],value[1],value[2])

        if temp_dict[temp] <=5:
            new_dictionary[key] = value

    return new_dictionary

rawDescription: Python Group by count

description: Python Group by count


code:
from os import listdir,chdir

default_path = r'c:\dev\python'
modules = [ fl for fl in listdir(default_path) if fl.endswith('.py') ]

rawDescription: Fetching all the Module name, class name and method names from directory in python


rawDescription: Reversing the order of values in a single column of a Dataframe


code:
import itertools

x = ['a', 'b', 'c', 'd']
y = [1, 2, 3, 4]

method1 = dict(zip(x, y))
method2 = itertools.izip(x, y)

rawDescription: what is the most efficient way to creating a dict with two lists?

description: What is the most efficient way to creating a dict with two lists


code:
comment_line_regex=re.compile('\s*;.*')
line1='   filename with spaces    crc  '
line2=';  filename with spaces    crc  '
line3='  ;  filename with spaces    crc  '
lines = [line1, line2, line3]

rawDescription: Regular expression to parse sfv-format files


rawDescription: A program to mutate Nested Lists

description: A program to mutate Nested Lists


code:
def process_without_measuring(self):
    self._start = time.time()

    self._k = 0
    while self._k < 100000000:
        self._k = self._k+1

    print (time.time() - self._start)

rawDescription: Python, calculating the status of computation slows down the computation itself


code:
s = ''
for k in range(a.shape[2]):
    s += ' '.join(str(a[i,j,k].real) for j in range(a.shape[1]) for i in range(a.shape[0]))
    s += ' '
    s += ' '.join(str(a[i,j,k].imag) for j in range(a.shape[1]) for i in range(a.shape[0]))
    s += ' '

rawDescription: Pythonic way to print a multidimensional complex numpy array to a string


code: form = TestForm(instance = test_instance)

rawDescription: Auto populate Django ModelForms

description: Auto populate Django ModelForms


code:
for index in sorted(indices_to_delete, reversed=True):
    del oldlist[index]

rawDescription: deleting multiple elements without updating till the end

description: Deleting multiple elements without updating till the end


code:
def f1(f):
    def f2(a):
        return a(a)

    def f3(b):
        def f4(*args):
            return b(b)(*args)

        return f(f4)

    return f2(f3)

rawDescription: Decoding a Cryptic Python statement

description: Decoding a Cryptic Python statement


code:
def print_table(n = 10):
    for i in range(1, n + 1):
        print_multiples(i)

rawDescription: How to generalize a multiplication table for (n * m)

description: Generalize a multiplication table for (n * m)


code: desired_ages = set(desired_ages)

rawDescription: NumPy Array Indexing

description: NumPy Array Indexing


rawDescription: What are the empty strings of my readline() after split


code:
try:
  data = [struct.unpack('<HHL', handle.read(8)) for i in range(PACKETS_PER_TRANSMIT)]
except OSError:
  self.emit(SIGNAL("connectionLost()"))
  self.connected = False

rawDescription: Read latest character sent from Arduino in Python


code:
foo = 'bar'
isinstance(foo, (str, int, float))

rawDescription: assertIsInstance() against multiple class names

description: AssertIsInstance() against multiple class names


code:
lock = threading.Lock()

def your_thread_function():
    do_something_slow()
    with lock:
        subprocess.call(["say", "hello world"])

rawDescription: Check if subprocess currently running in any thread using Python


code:
for i in range(0, num_cols):
    cur_sum = 0
    for j in range(0, num_rows):
            cur_sum += l[j][i]
    cur_sum /= num_rows
    sum_l.append(cur_sum)

rawDescription: Add only the first value in my list of arrays


code:
chars = "ACGT"

def neighbors(pattern, d):
    assert(d <= len(pattern))

    if d == 0:
        return [pattern]

    r2 = neighbors(pattern[1:], d-1)
    r = [c + r3 for r3 in r2 for c in chars if c != pattern[0]]

    if (d < len(pattern)):
        r2 = neighbors(pattern[1:], d)
        r += [pattern[0] + r3 for r3 in r2]

    return r

rawDescription: Implement Neighbors to find the d-neighborhood of a string in Python


rawDescription: Numpy: appending items to matrix-like array


code:
import numpy as np

colorarray = np.random.random_sample((332000000, 4))
colorarray[:, -1] = 0.6
colorarray = np.vstack([colorarray, colorarray])

rawDescription: Python - Fastest way to generate list of random colours with fixed alpha


code: new_list = my_list[:replace_index] + [new_value] + my_list[replace_index+1:]

rawDescription: Replacing a list item and returning a copy of the list (in one line) with Python


code:
for section in config.sections():
    for (key, val) in config.items(section):
        try:
            test={ "%s" % key : "%s" % val }
            s.configure(section, **test)
        except:
            print("Error Parsing Styles Config File:")
            print("   [%s].%s = %s"%(section, key, val))

rawDescription: Reading python ttk Styles from configuration file


code:
def unsignedToHexaString(size, value):
    output = hex(value)
    output = output[2:].zfill(size*2)
    return output.decode('hex')

rawDescription: How to convert unsigned value to byte string

description: Convert unsigned value to byte string


rawDescription: Detecting if a file is a video in Python?


code:
import compiler
ast = compiler.parse("print 'Hello world!'")

rawDescription: Is "safe_eval" really safe?

description: Is "safe_eval" really safe


rawDescription: How read bits in 64 bit data put into corresponding bitfields in python


code:
import tkinter
from tkinter.filedialog import askopenfilename
inputfile = None
def browse():
    global inputfile
    inputfile=askopenfilename()

def fileManipulator(outfile="C:\\out\\File.kml"):
    global inputfile
    if inputfile is None:
        browse()
    #code that manipulates the file here
    file.save(outfile)

root=tkinter.Tk()
browseButton=tkinter.Button(root,text="Browse",command=browse)
browseButton.pack()
fileButton=tkinter.Button(root,text="Manipulate file",command=fileManipulator)
fileButton.pack()
root.mainloop()

rawDescription: Execute function when button is pressed, not when script runs


code:
def repeat_until(fn, x, cond):
    while True:
        yield x
        if cond(x): break
        x = fn(x)

rawDescription: Python repeat: Is there a conditional/lambda based repeat method for python?


code:
import pytz
import datetime as DT
utcnow = DT.datetime.utcnow()

canonical = dict()
for name in pytz.all_timezones:
    tzone = pytz.timezone(name)
    try:
        dstoffset = tzone.dst(utcnow, is_dst=False)
    except TypeError:
        # pytz.utc.dst does not have a is_dst keyword argument
        dstoffset = tzone.dst(utcnow)
    if dstoffset == DT.timedelta(0):
        # utcnow happens to be in a non-DST period
        canonical[name] = tzone.localize(utcnow, is_dst=False).strftime('%z')
    else:
        # step through the transition times until we find a non-DST datetime
        date = utcnow
        while True:
            date = date - DT.timedelta(days=1)
            dstoffset = tzone.dst(date, is_dst=False)
            if dstoffset == DT.timedelta(0):
                canonical[name] = (tzone.localize(date, is_dst=False)
                                   .strftime('%z'))
                break

for name, utcoffset in canonical.iteritems():
    print('{} --> {}'.format(name, utcoffset))

# All timezones have been accounted for
assert len(canonical) == len(pytz.all_timezones)

rawDescription: "Canonical" offset from UTC using pytz?

description: "Canonical" offset from UTC using pytz


code: input_keys = [key for key in request.POST if key.startswith("inputs_")]

rawDescription: Select POST/GET parameters with regular expression


code: parser.unescape(' ')

rawDescription: How to use the python make the Escape Sequence to Character Entities

description: Use the python make the Escape Sequence to Character Entities


code:
items = 100
rpbins, pibins = np.linspace(0, 1, 3), np.linspace(0, 1, 3)
x = np.random.rand(items)
y = np.random.rand(items)
z = np.random.rand(items)

rawDescription: How to vectorize this loop difference in numpy?

description: Vectorize this loop difference in numpy


code:
wordlist = ['fox', 'over', 'lazy']
paragraph = 'A quick brown fox jumps over the lazy fox.'
[word for word in wordlist if word in paragraph]
another_wordlist = ['over', 'foo', 'quick']
[word for word in another_wordlist if word in paragraph]

rawDescription: Python return which list items string contains


code:
def merge_books(books):
    merged = {}

    for book in books:
        authorId = book['authorId']

        # Create article attribute
        book['articles'] = [{
            'articles.id': book['articles.id'],
            'authorId':    book['authorId'],
            'Title':       book['Title'],
        }]

        # Remove redundant information
        del book['articles.id']
        del book['authorId']
        del book['Title']

        if authorId in merged:
            merged[authorId]['articles'].append(book['articles'][0])
        else:
            merged[authorId] = book

    # Convert dict into a tuple, but why not a list?
    return tuple(merged.values())

rawDescription: Combine dict with same keys into one dict with list


code:
zipped = zip(*values)
zipped

rawDescription: How to add elements from a dictonary of lists in python

description: Add elements from a dictonary of lists in python


code:
class Foo(object):
    def __init__(self, l):
        for k, v in l:
            setattr(self, k, v)

rawDescription: Python extremely dynamic class properties


code: l

rawDescription: Python string to list 2D

description: Python string to list 2D


code:
name = 'dog'
df.apply(lambda row: (partial_ratio(row['name'], name) >= 85), axis=1)

rawDescription: Pandas compare each row with all rows in data frame and save results in list for each row


code:
import numpy as np
a = np.arange(1, 5)
[ np.concatenate((a[i:], np.zeros(i))) for i in range(len(a))]

rawDescription: How do I repeatedly shift and pad elements in a list to get a list of lists?

description: Repeatedly shift and pad elements in a list to get a list of lists


code:
from collections import Counter
found = Counter(['CG', 'E6', 'E1', 'E2', 'E4', 'L2', 'E7', 'E5', 'L1', 'E2BS', 'E2BS', 'E2BS', 'E2', 'E1^E4', 'E5'])
expected = Counter(['E1', 'E2', 'E4', 'E1^E4', 'E6', 'E7', 'L1', 'L2', 'CG', 'E2BS', 'E3'])
list((found - expected).elements())
list((expected - found).elements())

rawDescription: in python: difference between two lists

description: In python: difference between two lists


code:
def eval_dottedname(obj, dottedname):
    if dottedname.partition(".")[0] != 'self': # or some other criteria
                                               # to limit the context
        raise ValueError
    return reduce(getattr, dottedname.split('.')[1:], obj)

rawDescription: Tkinter string callbacks

description: Tkinter string callbacks


code:
height = 1.75 # Bob's height in meters.
length = len(sys.modules) # Number of modules imported by program.
area = height * length # What's that supposed to mean???

rawDescription: Python 3 and static typing

description: Python 3 and static typing


code:
def func(x):
    w_evaluator=lambdify(tf,W)
    return w_evaluator(x)

rawDescription: How to use a global variable (derivative expression) inside a function

description: Use a global variable (derivative expression) inside a function


code:
Member.__bases__ = (Adult,)
print(Member.__bases__)
# (<class __main__.Adult at 0xb74a144c>,)

rawDescription: change the superclass of object in Python

description: Change the superclass of object in Python


code:
import mystuff
mystuff.apple()

rawDescription: How to build the nfcpy source code to a python module?

description: Build the nfcpy source code to a python module


code:
from string import Formatter

def no_curly_brackets(fmt):
    try:
        parsed = Formatter().parse(fmt)
        return not any('{' in lt or '}' in lt for lt, _, _, _ in parsed)
    except ValueError:
        return False

rawDescription: Verifying that a string does not contain curly brackets other than those used for formatting


code:
import pandas as pd
import re

A = pd.read_csv('FileA', delimiter = r'\s+')
B = pd.read_csv('FileB', delimiter = r'\s+')
A = A.set_index(['ProbeID'])
B = B.set_index(['ProbeID'])
C = pd.concat([A,B], axis = 1)

idx = C['call'] == 0
C['alleleB'][idx]  = C['alleleA'][idx]
idx = C['call'] == 2
C['alleleA'][idx]  = C['alleleB'][idx]
print(C[['call', 'alleleA', 'alleleB']])

rawDescription: compare text in two files and append text in a field

description: Compare text in two files and append text in a field


code:
class CaseInsensitiveColumnComparator(ColumnProperty.Comparator):
    def __eq__(self, other):
        return func.lower(self.__clause_element__()) == func.lower(other)

rawDescription: What is the correct way to make SQLalchemy store strings as lowercase?


code:
def returnNoneIfEmpty(testText):
    if testText:
        return testText
    else:
        return 'None'

rawDescription: Need help parsing XML with ElementTree

description: Need help parsing XML with ElementTree


code:
import struct
a1, a0, a3, a2 = struct.unpack('cccc', struct.pack('I', 0x12345678))
struct.pack('cccc', a0, a1, a2, a3)

rawDescription: How to pack in a certain order with Python

description: Pack in a certain order with Python


code: important_list = [ord(i) - 64 for i in otp]

rawDescription: Trying to place values of dictionary into a list, but it prints values individually


rawDescription: Subsample pandas dataframe

description: Subsample pandas dataframe


code:
l=[['a', '(junk, b)', '(junk, c)'],
 ['d', '(junk, e)', '(junk, f)'],
 ['g', '(junk, h)', '(junk, i)']]

np.array([[re.search(r'\b[a-z]\b',x).group() for x in i] for i in l])

rawDescription: Replacing specific values in numpy 2D Array


rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


code: list[ (i for i, j in enumerate( list ) if j.startswith( "1" ) ).next() - 2 ]

rawDescription: Python: Locate 3 adjacent list items and determine list index of first of them


code:
for i in range(len(buttons)):
  buttons[i].onclick(lambda i=i: say('button %s', i))

rawDescription: Why are default arguments evaluated at definition time in Python?


rawDescription: how to use user authentication in django

description: Use user authentication in django


rawDescription: easy_install downloading directory

description: Easy_install downloading directory


code:
workers = []
def main():
    while True:
        answer = input("What would you like to do?")
        if answer == "p":
            printAllWorkers()
        elif answer == "a":
            addWorker()
        elif answer == "q":
            return

rawDescription: creating a list containing list of employees

description: Creating a list containing list of employees


rawDescription: How do you write one element of multiple lists to a file before moving on to the next element?

description: Write one element of multiple lists to a file before moving on to the next element


code:
#!/usr/bin/python

from signal import *
from time import sleep

def process_quit(signum, frame):
    # Do your pickle thing here
    print('Exiting...')

signal(SIGQUIT, process_quit)

while 1:
    print('Working hard')
    sleep(0.5)

rawDescription: How can I turn my python script off from the terminal?

description: Turn my python script off from the terminal


code:
def verbose_to_compact(verbose):
    return { item['name']: verbose_to_compact(item['children']) for item in verbose }

def compact_to_verbose(compact):
    return [{'name':key, 'children':compact_to_verbose(value)} for key, value in compact]

rawDescription: Python: tree like implementation of dict datastructure


code:
def most_common_values(counter, count):
    values = set()
    most_common = iter(counter.most_common())
    while len(values) < count:
        key, value = next(most_common)
        values.add(value)
        yield key, value

rawDescription: N biggest values of dict with duplicates


code:
EEG
EEG.shape

rawDescription: Converting matlab code to python

description: Converting matlab code to python


rawDescription: Find matching keywords in nested dictionary


code:
letters = "Cde"
from string import ascii_lowercase
letters.lower() in ascii_lowercase
letters = "Abg"
letters.lower() in ascii_lowercase

rawDescription: how to check if 3 characters are in consecutive alpha order

description: Check if 3 characters are in consecutive alpha order


code: a.append('value') if a<b else b.append('value') if a==b else None

rawDescription: Is there a more elegant pythonic way of expressing the following condional expression?


code:
logdata = np.log(data)
estimated_mu, estimated_sigma = stats.norm.fit(logdata)

rawDescription: A lognormal distribution in python

description: A lognormal distribution in python


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

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^key_auth/$', include('key_auth.urls')),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'views.home_page'),
)

rawDescription: Security issues with a middleware screener page


code: a.write(f, relpath(f, root))

rawDescription: Python zip a sub folder and not the entire folder path


code:
from PySide import QtGui

class Model(object):
    def __init__(self):
        self._update_funcs = []

        # variable placeholders
        self.running = False

    # subscribe a view method for updating
    def subscribe_update_func(self, func):
        if func not in self._update_funcs:
            self._update_funcs.append(func)

    # unsubscribe a view method for updating
    def unsubscribe_update_func(self, func):
        if func in self._update_funcs:
            self._update_funcs.remove(func)

    # update registered view methods
    def announce_update(self):
        for func in self._update_funcs:
            func()

rawDescription: MVC design with QtDesigner and PySide

description: MVC design with QtDesigner and PySide


code:
m = pd.MultiIndex.from_product([[1, 2], [1, 2]], names=['A', 'B'])
s.reindex(m)

rawDescription: Pandas python Initializing groupby object with empty groups


rawDescription: temporary variables in a python expression

description: Temporary variables in a python expression


code:
import dateutil.parser
now = datetime.now(pytz.UTC)
disables = self.sssvc.query("select Name, Project__c, Ownerid, Id, DisableOn__c, User__c from PIXDisableUserTask__c WHERE Status__c = 'Pending'")
for disable in disables[u'records']:
    disable_on = dateutil.parser.parse(disable[u'DisableOn__c'])
    if disable_on < now:
        continue
    else:
        disables.pop(disable)
    print
return disables

rawDescription: Datetime conversions to timestamp

description: Datetime conversions to timestamp


code:
string1 = string1.replace('(', '{').replace(')', '}').format(**word_dict)
string2 = string2.replace('(', '{').replace(')', '}').format(**word_dict)

rawDescription: How to replace parenthesis and text within it in Python string

description: Replace parenthesis and text within it in Python string


code:
import pandas as pd
from datetime import datetime

data = pd.read_csv("Landings.csv")
a=data["year"]
years = [datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year for date in a]

rawDescription: how to get year from a file, column contaning datetime

description: Get year from a file, column contaning datetime


code:
import pandas as pd

df = pd.DataFrame(data={"CommonIdentifier":[1234,1235,1236,1237],
                        "CommonValue":["type1","type2","type1","type1"],
                        "Identifier1":["a","a","b","b"],
                        "Value1":[1,1.5,2,1.3],
                        "Identifier2":["b","b","c","a"],
                         "Value2":[4,2,3.2,1]})

colgroups = [['CommonIdentifier', 'CommonValue', 'Identifier%d'%i, 'Value%d'%i]
        for i in range(1,3)]

colmap = {'{}{}'.format(col,i):'{}Joined'.format(col)
          for i in range(1,3) for col in ('Identifier', 'Value')}

result = pd.concat([df[cols].rename(columns=colmap) for cols in colgroups])
print(result)

rawDescription: Flattening pandas DataFrame

description: Flattening pandas DataFrame


code: B = A[[col1, col2]].iloc[idx]

rawDescription: Using rolling_apply with a function that requires 2 arguments in Pandas


code: goal not in path

rawDescription: endless while loop confusion

description: Endless while loop confusion


code:
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text

rawDescription: Is it possible to post audio files with the python requests library


code: d

rawDescription: Convert content of Object datatype to Date datatype in Python


code: A.date() - B

rawDescription: finding difference in days between two dates

description: Finding difference in days between two dates


code:
x = defaultdict(list)
for word,pos in brown.tagged_words()[1:100]:
    x[pos[:2]].append(word)

x
len(x)

rawDescription: NLTK - Get and Simplify List of Tags

description: NLTK - Get and Simplify List of Tags


code: [list(item) for item in combinations("ABCD", 3)]

rawDescription: What is the best way to write a multiple nested for loops in Python


rawDescription: Adjacency List and Adjacency Matrix in Python


code:
class A1(object):
    def m(self):
        print('Calling method m of class A1')
        self.data *= 2

class A2(object):
    def m(self):
        print('Calling method m of class A2')
        self.data *= 3

class A3(object):
    def m(self):
        print('Calling method m of class A3')
        self.data *= 4

class B(object):
    def m(self, p):
        print('Calling method m of class B')
        for i in range(p):
            # You haven't specified which python you are using so I assume
            # you might need to most explicit variant of super().
            # Python3 also allows just using super().m()
            super(B, self).m()

class C1(B, A1):
    def __init__(self, value):
        self.data = value

rawDescription: Mixin to override inherited method

description: Mixin to override inherited method


rawDescription: how to pack 4 9-bit and 1 4-bit int variable into 5 8-bit variable in python?

description: Pack 4 9-bit and 1 4-bit int variable into 5 8-bit variable in python


code: output = ''.join(next(encode_data[x]) for x in 'aaabbb')

rawDescription: Replacing letters from input with a cycled item in a list


code:
try:
    datetime.datetime.strptime(str, '%Y-%m-%d')
except ValueError:
    raise ValueError("format should be YYYY-MM-DD")

rawDescription: if "it is a date" then "do what I say" -

description: If "it is a date" then "do what I say" -


code:
acceleration = params[['accX', 'accY', 'accZ']].plot(ax=acceleration)
#rest of code

rawDescription: Adding multiple labels at once for matplotlib subplots from pandas dataframe


code:
import functools

def args_as_ints(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args = [int(x) for x in args]
        kwargs = dict((k, int(v)) for k, v in kwargs.items())
        return func(*args, **kwargs)
    return wrapper

@args_as_ints
def funny_function(x, y, z=3):
    """Computes x*y + 2*z"""
    return x*y + 2*z

print(funny_function("3", 4.0, z="5"))
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
#     Computes x*y + 2*z

rawDescription: Preserving signatures of decorated functions


code:
yas = "yas\t\tbs\tcda\t\t"
re.split(r'\t+', yas.rstrip('\t'))

rawDescription: splitting a string based on tab in the file

description: Splitting a string based on tab in the file


rawDescription: Easiest way to serialize a simple class object with simplejson?


code: [item for sublist in row for item in sublist]

rawDescription: Write several list of lists in a csv columns in Python


code:
for file in files(path):
    ...

rawDescription: List only files in a directory?

description: List only files in a directory


code:
from singledispatch import singledispatch

@singledispatch
def translate(txt, inchars=None, outchars=None, deletechars=None):
    raise Exception('Not supported type %s' % (t))

@translate.register(str)
def translate(txt, inchars=None, outchars=None, deletechars=None):
    return str_translate(txt, inchars, outchars, deletechars)

@translate.register(unicode)
def translate(txt, inchars=None, outchars=None, deletechars=None):
    return unicode_translate(txt, inchars, outchars, deletechars)

rawDescription: Transparently doing .translate with str and unicode objects


code:
from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works

rawDescription: Python: importing a sub‑package or sub‑module


code:
import tkinter as tk

# You will need the ttk module for this
from tkinter import ttk

def update_status(step):

    # Step here is how much to increment the progressbar by.
    # It is in relation to the progressbar's length.
    # Since I made the length 100 and I am increasing by 10 each time,
    # there will be 10 times it increases before it restarts
    progress.step(step)

    # You can call 'update_status' whenever you want in your script
    # to increase the progressbar by whatever amount you want.
    root.after(1000, lambda: update_status(10))

root = tk.Tk()

progress = ttk.Progressbar(root, length=100)
progress.pack()

progress.after(1, lambda: update_status(10))

root.mainloop()

rawDescription: Python: Is it possible to create an tkinter label which has a dynamic string when a function is running in background?


code:
# use attributes what you want to build index
indx = pygrib.index(gribfile,'typeOfLevel','level','parameterName')

# important: msg is an array and may have more then one record
# get U wind component on 10 m above ground
msg = indx.select(level = 10, typeOfLevel = "heightAboveGround",
 parameterName = "U U-component of wind m s**-1")
u10 = np.array(msg[0].values)
# get V wind component on 10 m above ground
msg = indx.select(level = 10, typeOfLevel = "heightAboveGround",
 parameterName = "V V-component of wind m s**-1")
v10 = np.array(msg[0].values)

rawDescription: How to iterate over latitude longitude values of a grib2 file?

description: Iterate over latitude longitude values of a grib2 file


code:
def file_reader(func):
    @functools.wraps(func)
    def helper(*args, **kwds):
        return File(func, *args, **kwds)
    return helper

rawDescription: functools.wraps won't let me wrap a function with a class in Python 3

description: Functools.wraps won't let me wrap a function with a class in Python 3


code:
def printStats(self):
    print("Health: " + ...)

rawDescription: Printing in a class python

description: Printing in a class python


code:
r = resource(name="")
a1 = author(name="ninefingers")
a2 = author(name="jon skeet", type="god")
r.authors.add(a1)
r.authors.add(a2)
english = languages.objects.get(iso_lang_code="en-GB")
r.add(english)
r.save()

rawDescription: How do I store multiple copies of the same field in Django?

description: Store multiple copies of the same field in Django


code:
import glob
for f in glob.glob('*-C_'):
    os.system('xRITDecompress {}'.format(f))

rawDescription: apply command to list of files in python

description: Apply command to list of files in python


code:
paired_sorted = sorted(zip(List2,List3,List1),key = lambda x: (x[0],-x[1]))
l2,l3,l1 = zip(*paired_sorted)

rawDescription: Sort List in Python by two other lists

description: Sort List in Python by two other lists


code: datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds = ticks/10)

rawDescription: How does one convert a .NET tick to a python datetime?

description: Convert a .NET tick to a python datetime


code: command,file = raw_input(">").split()

rawDescription: Python: Scanning raw_input

description: Python: Scanning raw_input


code:
@outputSchemaFunction("squareSchema")
def square(num):
  return ((num)*(num))

rawDescription: Is it possible to pass a Python UDF a scalar argument?


code:
[a for i, y in map(lambda l: map(str.strip, l.split(':')), dinner)
 for a in (x+':'+y for x in i.split(','))]

rawDescription: Using Python Higher Order Functions to Manipulate Lists


rawDescription: if statement vs. expression

description: If statement vs. expression


rawDescription: accessing custom python type properties by name

description: Accessing custom python type properties by name


code:
reader = csv.DictReader(open('yourfile.csv', 'rU'), delimiter=',')
entries = [Person(**entry) for entry in reader]

rawDescription: How can I dynamically generate class instances with single attributes read from flat file in Python?

description: Dynamically generate class instances with single attributes read from flat file in Python


code:
from lxml import etree

def preview_key(et):
    major_ordering = ['territories', 'data_file']
    minor_ordering = ['source', 'notes']
    try:
        major = major_ordering.index(et.tag)
    except ValueError:
        major = -1
    try:
        minor = minor_ordering.index(et.get('role', None))
    except ValueError:
        minor = -1
    return major, minor

def data_file_key(et):
    major_ordering = ['locale', 'file_name', 'size', 'checksum', 'attribute']
    minor_ordering = [
            "crop.top",
            "crop.bottom",
            "crop.left",
            "crop.right",
            "image.burned_subtitles.locale",
            "image.textless_master"]
    try:
        major = major_ordering.index(et.tag)
    except ValueError:
        major = -1
    try:
        minor = minor_ordering.index(et.get('name', None))
    except ValueError:
        minor = -1
    return major, minor

with open('input.xml') as input_file:
    parser = etree.XMLParser(remove_blank_text=True)
    tree = etree.parse(input_file, parser)
root = tree.getroot()

for preview in tree.xpath("//asset[@type='preview']"):
    preview[:] = sorted(preview, key=preview_key)

for data_file in tree.xpath("//data_file"):
    data_file[:] = sorted(data_file, key=data_file_key)

with open('output.xml', 'w') as output_file:
    output_file.write(etree.tostring(tree, pretty_print = True))

rawDescription: Python - lxml to re-order xml tags

description: Python - lxml to re-order xml tags


code:
@classmethod
def create(cls, **kwargs):
    return cls(**kwargs)

rawDescription: Return information from dict

description: Return information from dict


rawDescription: Expanding tuple into number repeated X times in a list (python)


rawDescription: How can I create numpy array of views?

description: Create numpy array of views


rawDescription: Convert a 3D array to 2D array based on dictionary


rawDescription: How to obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row

description: Obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row


code:
import a, b
b.Original.name = 'bar'
a.Original.name == 'bar'

rawDescription: How to copy a module

description: Copy a module


code:
output = []
for a, b in zip(L1, L2):
    innerlist = []
    for x, y in zip(a, b):
        innerlist.append(x or y or 0)  # 1 or '' = 1; '' or 2 = 2; etc
    output.append(innerlist)

rawDescription: merging two lists, removing empty strings

description: Merging two lists, removing empty strings


rawDescription: How to write this snippet in Python?

description: Write this snippet in Python


code:
import re
a = 'add {new} sentence {with} this word'
re.findall(r'\{(\w+)\}', a)

rawDescription: Python regex to match all words in {}

description: Python regex to match all words in {}


code:
for o in self.oranges:
    o.draw(self.screen)

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

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


code:
values = np.loadtxt('tmp.txt', dtype=str)
hours= calc_hour( values[:,0] )
degs =  calc_deg( values[:,1] )

rawDescription: Python: Read text file with time in hour, minutes and seconds; and angle in degree, arc minutes and arc seconds


code:
import time
import psutil

for proc in psutil.process_iter():
    if proc.name == 'gnome-panel' and time.time() - proc.create_time > 1:
        if proc.get_cpu_percent() > 80:
            proc.kill()

rawDescription: how to kill specific process using %cpu over given time in python on linux?

description: Kill specific process using %cpu over given time in python on linux


code: resultdict = df.T.to_dict()

rawDescription: Fastest way to store data from Pandas DataFrame


code:
def putFromFileRepository(repoIP, repoUsername, repoPassword, repoPath, putPath):
    from fabric.operations import sudo

    # There are security implications from passing a password as an argument
    # on the command line, namely that command line arguments can be easily seen
    # from anywhere via 'ps -ww -fp <pid>'.
    # Thus scp doesn't allow passwords to be passed on the command line.
    # We'll install expect to make it possible.
    sudo('yum -y install expect')

    repoStr = repoUsername + '@' + repoIP + ':' + repoPath

    # expect has alien syntax - explained inline below.
    # see man expect for more details.
    sudo("expect -c 'spawn scp " + repoStr + ' ' + putPath + '; ' # Run SCP when started.
         + 'expect "*?es??o*" {send "yes\r"; exp_continue} '      # Reply yes to yes/no questions.
         + '"*?assword:" {send "' + repoPassword + '\r"}; '       # Give password when prompted.
         + "interact'")  # Start.

rawDescription: Run SCP From Command Line With Password

description: Run SCP From Command Line With Password


code:
import numpy as np

class MyArray(np.ndarray):

    def __new__(cls, shape, fill_value=0, dtype=float):
        data = np.full(shape, fill_value, dtype)
        obj = np.asarray(data).view(cls)
        obj.fill_value = fill_value
        return obj

    def reset(self, fill_value=None):
        if fill_value is not None:
            self.fill_value = fill_value

        self.fill(self.fill_value)

rawDescription: Overloading the [] operator in python class to refer to a numpy.array data member


code: text.delete("%s-1c" % 'insert', 'insert')

rawDescription: Python - While Loop changing a variable

description: Python - While Loop changing a variable


code:
g = ['abc', 'defg', 'lolololol']
g[:] = (elem[:2] for elem in g)
g

rawDescription: How to truncate all strings in a list to a same length, in some pythonic way?

description: Truncate all strings in a list to a same length, in some pythonic way


code:
def fileOrRandom():
  return raw_input("Would you like to read from file or random list? (A or B): ")

rawDescription: Nested Choices in a python program

description: Nested Choices in a python program


rawDescription: Maximal Growth Period in time series

description: Maximal Growth Period in time series


rawDescription: Sorting a list of names and dates according to birthday


code:
df['wcas'], df['wdiff'] = (df[n] * df['weight'] for n in ('cas', 'diff'))
df.groupby('ind')[['wcas', 'wdiff']].sum()

rawDescription: Calculate weighted average with pandas dataframe


rawDescription: Python scraper (Scraperwiki) only getting half of the table


code:
df.head()
df.tail()

rawDescription: Converting PANDAS dataframe from monthly to daily


code:
import re
from itertools import count
sample = '''\
foo*bar
bar**foo
*hello*world
'''
print(re.sub(r'\*', lambda m, c=count(): str(next(c)), sample))

rawDescription: Replace "*" (asterics) in HTML file with increasing number with python


code:
def selected_genders_labels(self):
    return [label for value, label in self.fields['genders'].choices if value in self['genders'].value()]

rawDescription: Django: Display values of the selected multiple choice field in a template


code: filename, ext = os.path.splitext(base)

rawDescription: Finding full pathname in a Python trace

description: Finding full pathname in a Python trace


code:
counter = 0

def printer(event):
    global counter
    x, y = event.x, event.y
    if event.x in range (130,224) and event.y in range(197,305):
        if counter == 0:
            canvas.create_oval(146, 158, 140, 164, outline="indianred2", fill="red", width=1.5)
        elif counter == 1:
            canvas.create_oval(180.5, 158, 174.5, 164, outline="indianred2", fill="red", width=1.5)
        elif counter == 2:
            canvas.create_oval(209, 158, 215, 164, outline="indianred2", fill="red", width=1.5)
        counter += 1

rawDescription: "If, Then" Statement - registering back-to-back mouse clicks


code:
def updateNgenes(self):
#Updating the number of genes
    self.ngenes = len(self.genes.keys())

rawDescription: optimize python key-searching in hierarchichal dictionary

description: Optimize python key-searching in hierarchichal dictionary


code:
l=[Any(1,3),Any(2,4),Any(1,2),Any(None,6),Any('hello',6), Any(1,'ChuckNorris'),Any(1,2)]
next((i for i, item in enumerate(l) if item.a is None), None)

rawDescription: Python: Find the position in a list of the first object that respect a given condition


code: [('Jack A. Smith', 'Jack', 'A.', 'Smith'), ('Mary B. Miller', 'Mary', 'B.', 'Miller')]

rawDescription: basic regex questions in python to help me learn it

description: Basic regex questions in python to help me learn it


rawDescription: .csv data into a dictionary in Python: Duplicate values


code:
df2.info()
df2.head()

rawDescription: Cythonizing string array comparison function to be applied to pandas DataFrame


rawDescription: Dictionary Creation from DataFrame, Pandas, Python


code:
class MovieCategoryForm(forms.ModelForm):

    class Meta:
        model = MovieCategory
        fields = ['prefix']

    def __init__(self, *args, **kwargs):
        super(MovieCategoryForm, self).__init__(*args, **kwargs)
        self.fields['prefix'].queryset = Prefix.objects.filter(
                                        category_id=self.instance.category.id)

rawDescription: Django ForeignKey limit_choices_to a different ForeignKey id


code: #!/usr/bin/python -u

rawDescription: Output of python scripts displayed only at termination when using SSH?


rawDescription: Python, dictionaries, and chi-square contingency table


code:
import re

SampleString = '''date: 2012-11-25
printer on time:  0800
23.96.82.161 user: pei printer: core 2 pages: 2 code: r n t h p r
28.104.177.80 user: isaac printer: poster pages: 4 code: p h
printer error:  out of paper  time: 1343
180.186.109.129 user: luis printer: core 2 pages: 2 code: k n h
194.96.54.184 user: isaac printer: sally pages: 6 code: p k r p f
122.230.32.236 user: luis printer: hill 3 pages: 8 code: n h n k q
printer off time: 2201'''
print (SampleString)

## Here re.findall()
Regex=re.compile(r'^(?=.*?user:\s+(.*?)\s)(?=.*?pages:\s+(.*?)\s).*?$',re.MULTILINE)
Matches = Regex.findall( SampleString)
Count = 0
for Match in Matches:
    # do something with each found email string
    print("[" + str(Count) + "][0] = " + Match[0])
    print("[" + str(Count) + "][1] = " + Match[1])
    print("")
    Count = Count + 1

rawDescription: re.search python regexpr

description: Re.search python regexpr


code: df = pd.read_fwf('27_35.txt', header=None, widths=[6,4,4,6,6,6,6,6,6], parse_dates=[[0,1,2]], keep_date_col=True)

rawDescription: Create datetime index in pandas dataframe


code: content = dict((key, value) for (key, value) in zip(list2, list1))

rawDescription: Using two lists to define a variable in python


code: string = ' '.join([w.title() if w.islower() else w for w in string.split()])

rawDescription: Python Title Case, but leave pre-existing uppercase


code: total_unique = len(counter.keys())

rawDescription: Counting every word in a text file only once using python


code:
try:
    dictionary = {value: list[0]}
except IndexError:
    dictionary = {value: None}

rawDescription: Python - How to use try/except statement in dictionary


code:
@login_required
def gallery(request):
    url = '/gallery/%s/' % request.user.username
    return HttpResponseRedirect(url)

rawDescription: The "next" parameter, redirect, django.contrib.auth.login


code:
SUBJECT = 'NETHERLANDS MUSIC EPA'
CONTENT = "Michael Buble performs in Amsterdam Canadian singer Michael Buble performs during a concert in Amsterdam, The Netherlands, 30 October 2009. Buble released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK"

rawDescription: How can I parse text in Python?

description: Parse text in Python


code:
from sklearn.svm import LinearSVC
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data
Y = iris.target
svc = LinearSVC()
clf = CalibratedClassifierCV(svc, cv=10)
clf.fit(X, Y)
proba = clf.predict_proba(X)

rawDescription: Multiclass linear SVM in python that return probability


code:
populate_positions = []
for position in positions:
    populate_positions.append(Position.objects.get(label=position))

rawDescription: Improving Python/django view code

description: Improving Python/django view code


code:
sequences = []
with open('protein1.fasta', 'r') as fin:
    sequence = ''
    for line in fin:
        if line.startswith('>'):
            sequences.append(sequence)
            sequence = ''
        else:
            sequence += line.strip()

rawDescription: Trying to find efficient ways to remove headers in fasta files


rawDescription: How do I add, say, n entries of x to a list in one shot?

description: Add, say, n entries of x to a list in one shot


code:
def flatten_combinations(result_tree, current_combo=None, all_combos=None):
    if current_combo is None:
        current_combo = []
    if all_combos is None:
        all_combos = []
    if result_tree is None:
        all_combos.append(current_combo)
        return
    for word in result_tree:
        new_current_combo = current_combo[:]
        new_current_combo.append({'word': word['word']})
        flatten_combinations(word['next'], new_current_combo, all_combos)
    return all_combos

rawDescription: Find all paths through a tree (nested dicts) from top to bottom


code:
def kl(line,pat = pat):
    return time.mktime(time.strptime((pat.search(line).group()),'%d/%m/%y %H:%M:%S'))

output = [ (kl(line),line.rstrip()) for line in output if line.rstrip()]

output.sort()

rawDescription: How to merge only the unique lines from file_a to file_b?

description: Merge only the unique lines from file_a to file_b


rawDescription: What is an efficient way to slice a Pandas Series with a MultiIndex along multiple dimensions?


rawDescription: Trying to grab certain parts of the NFL stats table using BeautifulSoup


code:
from flask import Flask
import redis

r = redis.StrictRedis(host='127.0.0.1', port=6379)
app = Flask(__name__)

@app.route("/")
def hello():
    # send your message to the other process with redis
    r.publish('some-channel', 'some data')
    return "OK"

if __name__ == '__main__':
    app.run(port=4000, debug=True)

rawDescription: Will I get performance boost combining concurrent.futures with Flask


code: self.fields['title'].widget.attrs.update({'placeholder': 'This is a title'})

rawDescription: how to edit {{form|crispy}} with css and move the forms around?

description: Edit {{form|crispy}} with css and move the forms around


code:
del a
b = numpy.memmap('test.mymemmap', dtype='float32', mode='r+', shape=(200000,1000))

rawDescription: Working with big data in python and numpy, not enough ram, how to save partial results on disc?


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart

gs = gridspec.GridSpec(3,1)

if not somecondition:
    ax = plt.subplot(gs[:,:]) #create the first subplot that will ALWAYS be there
    ax.plot(list1) #populate the "main" subplot
else:
    ax = plt.subplot(gs[:2, :])
    ax.plot(list1)
    ax = plt.subplot(gs[2, :]) #create the second subplot, that MIGHT be there
    ax.plot(list2) #populate the second subplot
plt.show()

rawDescription: Python & Matplotlib: creating two subplots with different sizes


code:
index = pd.date_range('2000-1-1', periods=3, freq='D')
index
index.values.tolist()
index.to_pydatetime()

rawDescription: datetime index in python dataframe

description: Datetime index in python dataframe


code:
a = (1,2,3,4)
b = (4,2,3,1)

def children(current):
    for i in range(len(a)-1):
        yield (current[:i] + (current[i+1],current[i]) +
                   current[i+2:])

def dfs(current,path,path_as_set):
    path.append(current)
    path_as_set.add(current)
    if current == b:
        yield path
    else:
        for next_perm in children(current):
            if next_perm in path_as_set:
                continue
            for path in dfs(next_perm,path,path_as_set):
                yield path
    path.pop()
    path_as_set.remove(current)

for path in dfs(a,[],set()):
    print(path)

rawDescription: Lists in python using itertools (moving only 2 items, permutations)


code:
def decorate(function):
    def wrap_function(*args, **kwargs):
        str = 'Hello!'
        return function(str, *args, **kwargs)
    return wrap_function

@decorate
def print_message(str, *args, **kwargs):
    print(str)

rawDescription: How can I pass a variable in a decorator to function's argument in a decorated function?

description: Pass a variable in a decorator to function's argument in a decorated function


code:
player_data = {
 'hearts': 3,
 'coins': 10,
 'items': []
}

rawDescription: Coin count consistency through game

description: Coin count consistency through game


code: os.system('su hadoop -c "bin/hadoop-daemon.sh stop tasktracker"')

rawDescription: Changing user in python

description: Changing user in python


code: sum( [a[i][0]*b[i] for i in range(len(b))] )

rawDescription: What is the pythonic way to calculate dot product?


code:
my_list = [[1], [2], [3]]
my_other_list = my_list[:]
my_other_list[0].append(42)
my_other_list, my_list

rawDescription: python list and quick sort, reference or pointer?

description: Python list and quick sort, reference or pointer


rawDescription: How to append a file with a newline using %%writefile -a command in jupyter?

description: Append a file with a newline using %%writefile -a command in jupyter


code: def f(): return 3

rawDescription: What is function.__code__ behavior across multiple program executions?


code:
base = repo.merge_base(current, master)
base

rawDescription: How do you merge the master branch into a feature branch with GitPython?

description: Merge the master branch into a feature branch with GitPython


code:
df = pd.read_csv("http://real-chart.finance.yahoo.com/table.csv?s=AAPL&d=1&e=16&f=2016&g=d&a=11&b=12&c=2015&ignore=.csv",parse_dates=0)

print(df)

rawDescription: How to import a table with headings to a data frame using pandas module

description: Import a table with headings to a data frame using pandas module


code:
list_name =  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
i = iter(list_name)
dic = OrderedDict(izip(i, i))
dic

rawDescription: Convert a list into a dictionary keeping the sequence intact


code:
num = [elem for elem in xrange(4000, 5001) if not {'7', '8', '9'}.intersection(str(elem))]
choice(num)
choice(num)
choice(num)

rawDescription: Generate random number in range without specific digits


code:
import glob
pathList = glob.glob("C:\SVN\DIR1\DIR2\DIR3\*\data.html")
if pathList:
    path = pathList[0]

rawDescription: Open a file with Python with given name in a folder that change name


code:
import multiprocessing as mp

def print_mynumber(foo):
    """This function is obviously more complicated in my script.
    It should be run as a subprocess."""
    print(foo)

if __name__ == '__main__':
    for foo in [1,2,3]:
        proc = mp.Process(target = print_mynumber, args = (foo, ))
        proc.start()

rawDescription: How do I make functions run as subprocesses in Python?

description: Make functions run as subprocesses in Python


code:
re1 = r'(\d{1,3}[a-zA-Z]?/\d{1,3}[a-zA-Z]?)'
re2 = r'(\babc\b)'
re.findall(re1, text)
re.findall(re2, text)
re1_matches = re.findall(re1, text)
re2_matches = re.findall(re2, text)
rex_nomatch = re.findall('conglomeration_of_sandwiches', text)

rawDescription: Merge several regular expressions into one RE


code: print("foo")

rawDescription: How to initialise long-lived variables?

description: Initialise long-lived variables


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

#Create a figure and axes with room for the table
fig = plt.figure()
ax = plt.axes([0.2, 0.2, 0.7, 0.6])

#Create labels for the rows and columns as tuples
colLabels = ('36', '40', '44', '48', '149', '153', '157', '161', '165')
rowLabels = ('UDL DL', 'UDP UL', 'TCP DL', 'TCP UL')

#Table data as a numpy array
tableData = np.array([[  36.7128,  37.684,   38.283,  48.425,   32.839, 36.424, 34.440, 31.642, 35.710],
        [  36.7128,  37.684,   38.283,  48.425,   32.839, 36.424, 34.440, 31.642, 35.710],
        [  36.7128,  37.684,   38.283,  48.425,   32.839, 36.424, 34.440, 31.642, 35.710],
        [  36.7128,  37.684,   38.283,  48.425,   32.839, 36.424, 34.440, 31.642, 35.710]])

#Get the current color cycle as a list, then reset the cycle to be at the beginning
colors = []
while True:
    colors.append(ax._get_lines.color_cycle.next())
    if colors[0] == colors[-1] and len(colors)>1:
        colors.pop(-1)
        break

for i in xrange(len(colors)-1):
    ax._get_lines.color_cycle.next()

#Show the table
table = plt.table(cellText=tableData,
                  rowLabels=rowLabels, rowColours=colors,
                  colLabels=colLabels,
                  loc='bottom')

#Make some line plots
x = np.linspace(0,10,100)
ax.plot(x,np.sin(x))
ax.plot(x,-1*np.sin(x))
ax.plot(x,np.cos(x))
ax.plot(x,-1*np.cos(x))

#Turn off x-axis ticks and show the plot
plt.xticks([])
plt.show()

rawDescription: python - matplotlib - Create a multiline graph with results summary underneath

description: Python - matplotlib - Create a multiline graph with results summary underneath


code:
with open('FILEPATH') as f:
    lst = [[int(n)] for n in f.read().split()]

lst

rawDescription: Convert plain numbers from file to list of integers


code:
@argument_decorator(True)
def foo(): pass

rawDescription: Python dynamic decorators - why so many wraps?


code:
def lil_repeat(S, repeat):
    # row repeat for lil sparse matrix
    # test for lil type and/or convert
    shape=list(S.shape)
    if isinstance(repeat, int):
        shape[0]=shape[0]*repeat
    else:
        shape[0]=sum(repeat)
    shape = tuple(shape)
    new = sparse.lil_matrix(shape, dtype=S.dtype)
    new.data = S.data.repeat(repeat) # flat repeat
    new.rows = S.rows.repeat(repeat)
    return new

rawDescription: Repeat a scipy csr sparse matrix along axis 0


code: f = float(farenheit)

rawDescription: Simple Python Temperature Converter

description: Simple Python Temperature Converter


code:
grouped = df.groupby(['c1', 'c2'])
mask = grouped['v2'].transform(lambda x: x == x.max()).astype(bool)
df.loc[mask].reset_index(drop=True)

rawDescription: keep dataframe rows meeting a condition into each group of the same dataframe grouped by

description: Keep dataframe rows meeting a condition into each group of the same dataframe grouped by


rawDescription: Make a python nested list for use in Django's unordered_list


code:
def do_POST(self):
    populen(self)
    form = cgi.FieldStorage(fp=self.rfile)
    upfilecontent = form['upfile'].value
    if upfilecontent:
        fout = open(os.path.join('tmp', form['upfile'].filename), 'wb')
        fout.write(upfilecontent)
        fout.close()
    self.do_GET()

rawDescription: how can i find out the uploaded file name in python cgi

description: Find out the uploaded file name in python cgi


code:
def lrcs():
    motions = ["suck his thumb", "tie his shoe", "climb a tree", "shut the door", "take a dive", "pick up sticks", "look up to heaven", "shut the gate", "check the time", "say the end"]

    numbers = ['one','two','three','four','five','six','seven','eight','nine','ten']
    for i in range(10):
        print ("The ants go marching %s by %s, hurrah! Hurrah!\nThe ants go marching %s by %s, hurrah! Hurrah!\nThe ants go marching %s by %s,"%tuple([numbers[i]]*6))

        # antsMotion
        print ("The little one stops to %s," % motions[i])

    print ("And they all go marching down...\nIn the ground...\nTo get out...\nOf the rain./\nBoom! Boom! Boom!")

lrcs ()

rawDescription: Print lyrics by python

description: Print lyrics by python


code: "<option value=\"\">- Pasirinkite -<\/option><option value=\"1088\">-kita-<\/option><option value=\"16230\">208<\/option><option value=\"16231\">246<\/option><option value=\"16232\">250<\/option><option value=\"16233\">275<\/option><option value=\"16234\">288<\/option><option value=\"16235\">308<\/option><option value=\"16236\">328<\/option><option value=\"16237\">330<\/option><option value=\"1093\">348<\/option><option value=\"1089\">360<\/option><option value=\"16238\">365<\/option><option value=\"16239\">400<\/option><option value=\"16240\">412<\/option><option value=\"1086\">456<\/option><option value=\"16229\">458<\/option><option value=\"16245\">512<\/option><option value=\"1085\">550<\/option><option value=\"1084\">575<\/option><option value=\"1092\">599 GTB Fiorano<\/option><option value=\"16246\">612<\/option><option value=\"1090\">612 Scaglietti<\/option><option value=\"16247\">750<\/option><option value=\"1079\">Barchetta<\/option><option value=\"16250\">California<\/option><option value=\"16248\">Daytona<\/option><option value=\"1078\">Enzo<\/option><option value=\"1083\">F 355<\/option><option value=\"18638\">F 360<\/option><option value=\"1087\">F 40<\/option><option value=\"1091\">F 430<\/option><option value=\"1081\">F 50<\/option><option value=\"1080\">F 512<\/option><option value=\"1077\">Maranello<\/option><option value=\"1076\">Mondial<\/option><option value=\"16249\">Superamerica<\/option><option value=\"1075\">Testarossa<\/option>"

rawDescription: Scraping data which loaded when you select something


code:
@register.filter
def get_item(dictionary, key): return dictionary.get(key)

rawDescription: Access a dictionary element in the Django template with a variable


code:
# Fit the features to the response variable
rfecv.fit(X, y)

# Put the best features into new df X_new
X_new = rfecv.transform(X)

rawDescription: Scikit-learn - feature reduction using RFECV and GridSearch. Where are the coefficients stored?


code:
In [10]: "foo".endswith(("o", "r"))
Out[10]: True

In [11]: "bar".endswith(("o", "r"))
Out[11]: True

In [12]: "baz".endswith(("o", "r"))
Out[12]: False

rawDescription: python select files against match list

description: Python select files against match list


code:
import math as m
import functools

def date_support_wrapper(f):
    """ Wraps JD and provides a way to pass a date param

    :param f: the original function
    :return: the wrapper around the original function
    """

    @functools.wraps(f)
    def wrap(*args, **kwargs):
        if 'date' in kwargs:
            d = kwargs['date']
            return f(yr=d.year, mon=d.month, day=d.day, hr=d.hour, min=d.minute, sec=d.second)

        return f(*args, **kwargs)

    return wrap

@date_support_wrapper
def JD(yr, mon, day, hr, min, sec):
    jd = 367.0 * yr - m.floor(
        (7 * (yr + m.floor((mon + 9) / 12.0))) * 0.25) + m.floor(
        275 * mon / 9.0) + day + 1721013.5 + (
                                                 (sec / 60.0 + min) / 60.0 + hr) / 24.0
    return jd

rawDescription: Formatting python datetime object as argument


code: a * b

rawDescription: numpy array that is (n,1) and (n,)

description: Numpy array that is (n,1) and (n,)


rawDescription: How do I use a method outside a class?

description: Use a method outside a class


code:
import binascii

def pairwise(iterable):
    "s -> (s0,s1), (s2,s3), (s4, s5), ..."
    a = iter(iterable)
    return zip(a, a)

hex_encoded = '\\x' + '\\x'.join(pair[0]+pair[1]
                                    for pair in pairwise(binascii.hexlify(data)))
print('data length: {}'.format(len(data)))
print('hex_encoded length: {}, "{}"'.format(len(hex_encoded), hex_encoded))

rawDescription: Convert exe to hex to be run by Python

description: Convert exe to hex to be run by Python


code:
from collections import defaultdict

data = [-2,10,5,50,20,25,40]

target_sum = 100
# T[x, i] is True if 'x' can be solved
# by a linear combination of data[:i+1]
T = defaultdict(bool)           # all values are False by default
T[0, 0] = True                # base case

R=200 # Maximum size of any partial sum
max_percent=0.8 # Maximum weight of any term

for i, x in enumerate(data):    # i is index, x is data[i]
    for s in range(-R,R+1): #set the range of one higher than sum to include sum itself
        max_value = int(abs((target_sum * max_percent)/x))
        for c in range(max_value + 1):
            if T[s - c * x, i]:
                T[s, i+1] = True

coeff = [0]*len(data)
def RecursivelyListAllThatWork(k, sum): # Using last k variables, make sum
    # /* Base case: If we've assigned all the variables correctly, list this
    # * solution.
    # */
    if k == 0:
        # print what we have so far
        print(' + '.join("%2s*%s" % t for t in zip(coeff, data)))
        return
    x_k = data[k-1]
    # /* Recursive step: Try all coefficients, but only if they work. */
    max_value = int(abs((target_sum * max_percent)/x_k))
    for c in range(max_value + 1):
       if T[sum - c * x_k, k - 1]:
           # mark the coefficient of x_k to be c
           coeff[k-1] = c
           RecursivelyListAllThatWork(k - 1, sum - c * x_k)
           # unmark the coefficient of x_k
           coeff[k-1] = 0

RecursivelyListAllThatWork(len(data), target_sum)

rawDescription: Not sure how to integrate negative number function in data generating algorithm?


code:
class CMD_AA:
    ...

rawDescription: Python's equivalence of using namespace

description: Python's equivalence of using namespace


code: orderedlist = sorted(listed, key=sortOnFloat)

rawDescription: Sorting a list containing lists

description: Sorting a list containing lists


code:
def hmm(self):
    return 'ok'
requests.models.Response.hmm = hmm

rawDescription: Python monkey patching

description: Python monkey patching


code:
for value in data:
     print(value)

rawDescription: Stacking multiple columns in a stacked bar plot using matplotlib in python 3


code: print(list(filter(lambda x: isinstance(x, type), (getattr(B, x) for x in B.members))))

rawDescription: Find nested sub-classes in a class in the order they're defined


code:
def on_change_bool1(self, cr, uid, ids, bool1):
    return {'value':{'bool1':bool1,'bool2':False}}

rawDescription: on change in boolean

description: On change in boolean


code:
import json, requests, pprint
headers = {'content-type': 'application/json'}
payload = {"title":"album title"}
pprint.pprint(requests.post('http://httpbin.org/post', payload, headers=headers).json)
pprint.pprint(requests.post('http://httpbin.org/post', json.dumps(payload), headers=headers).json)

rawDescription: requests post to imgur

description: Requests post to imgur


code:
weapon2.accuracy
weapon1.owned

rawDescription: Assigning specific things to a class in Python


code:
if self.steps.current == '6':
    display_image = random.choice(images)
    context.update({'display_image': display_image})
    images.remove(display_image)

rawDescription: Remove value/item from a list but leave index intact


code:
def parse(s):
    d = {}
    lastkey = None
    for fullline in s:
        line = fullline.strip()
        if not line:
            pass
        elif ':' not in line:
            indent = len(fullline) - len(fullline.lstrip())
            if lastindent is None:
                lastindent = indent
            if lastindent == indent:
                lastval.append(line)
        else:
            if lastkey:
                d[lastkey] = lastval
                lastkey = None
            if line.endswith(':'):
                lastkey, lastval, lastindent = key, [], None
            else:
                key, _, value = line.partition(':')
                d[key] = value.strip()
    if lastkey:
        d[lastkey] = lastval
        lastkey = None
    return d

import pprint
pprint(parse(string.splitlines()))

rawDescription: Parsing colon delimited data

description: Parsing colon delimited data


rawDescription: Data processing with adding columns dynamically in Python Pandas Dataframe


code:
row_count = 0
for row in file_reader:
    row_count += 1
    if row_count > 5:
        break

rawDescription: Why is this Python while loop not working?


code: {{ object.M_G|to_kg }}

rawDescription: Django : Manipulate Data in a generic.ListView


code:
class PlayTracker(object):
    def __init__(self):
        self.lst = []
    def play(self, arg):
        if arg:
            self.lst.append(arg)

rawDescription: Keeping track of arguments passed to a function


rawDescription: calculate combinations of letter-pair matches in two lists?

description: Calculate combinations of letter-pair matches in two lists


code:
def numbers(s):
    return (int(match) for match in re.finditer(r"\d+", s))

rawDescription: Filtering text in python for numeric values


rawDescription: Print if origin in tuple is [0] (python)


code:
orders = {'peter': {'food': ['pizza','fries'], 'drink': 'soda'}, 'paul': {'food': ['taco'], 'drink': 'soda'}}
{j for i in orders for j in orders[i]['food']}

rawDescription: Obtaining list (or set) of unique values in nested dictionary


code:
m = np.minimum(m, m.median())
m

rawDescription: Improve code to replace values above the median by the median value itself in a pandas DataFrame


code:
with d3py.NetworkXFigure(G, width=500, height=500) as p:
    p += d3py.ForceLayout()
    p.css['.node'] = {'fill': 'blue', 'stroke': 'magenta'}
    p.css['.link'] = {'stroke': 'red', 'stoke-width': '3px'}
    p.show()

rawDescription: How to plot graphs using networkx and d3py

description: Plot graphs using networkx and d3py


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

fig, axes = plt.subplots(nrows=3)

colors = ('k', 'r', 'b')
for ax, color in zip(axes, colors):
    data = np.random.random(1) * np.random.random(10)
    ax.plot(data, marker='o', linestyle='none', color=color)

plt.show()

rawDescription: matplotlib: overlay plots with different scales?

description: Matplotlib: overlay plots with different scales


rawDescription: Why isn't the shape of the array correct?


code:
from pyspark.sql.functions import broadcast

df1.join(broadcast(df2))

rawDescription: How do you perform basic joins of two RDD tables in Spark using Python?

description: Perform basic joins of two RDD tables in Spark using Python


rawDescription: Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them?


rawDescription: Writing to a csv file in python

description: Writing to a csv file in python


code:
import scrapy
import getpass
from scrapy.spiders.init import InitSpider

class StackOverflowSpider(InitSpider):
    name = 'stackoverflow'
    login_page = 'https://stackoverflow.com/users/login'
    start_urls = ['http://stackoverflow.com/questions/tagged/bigdata+python']

    def parse(self, response):
        ...

    def parse_question(self, response):
        ...

    def init_request(self):
        return scrapy.Request(url=self.login_page, callback=self.login)

    def login(self, response):
        return scrapy.FormRequest.from_response(response,
                    formdata={'email': 'yourEmailHere@foobar.com',
                              'password': getpass.getpass()},
                    callback=self.check_login_response)

    def check_login_response(self, response):
        if "/users/logout" in response.body:
            self.log("Successfully logged in")
            return self.initialized()
        else:
            self.log("Failed login")

rawDescription: Scrapy crawling stackoverflow questions matching multiple tags


code:
['Microsoft Wi-Fi Direct Virtual Adapter',
 'Bluetooth Device (Personal Area Network)',
 'Dell Wireless 1395 WLAN Mini-Card',
 'Broadcom 440x 10/100 Integrated Controller',
 'VirtualBox Host-Only Ethernet Adapter',
 '(unknown)',
 'Microsoft ISATAP Adapter',
 'Microsoft ISATAP Adapter']

rawDescription: How to get meaningful network interface names instead of GUIDs with netifaces under Windows?

description: Get meaningful network interface names instead of GUIDs with netifaces under Windows


code: [reduce(lambda v, f: f(v), fnl, element) for element in content]

rawDescription: Python: apply list of functions to each element in list


code:
from io import StringIO

import matplotlib.pyplot as plt
import pandas

data = StringIO("""\
Region  Q1  Q2  Q3  Q4
West    1   5.2 3.1 2.05
Center  3.1 1.2 1.2 3
East    1.9 4.1 1.1 5.3
""")

df = pandas.read_table(data, sep='\s+')
df = df.set_index('Region')
df.plot(kind='bar')

rawDescription: Use the header as axis and first column as axis


rawDescription: Pandas conditional cumulative sum

description: Pandas conditional cumulative sum


code: {{ items|count_true }}

rawDescription: Django count in template on object attribute