code:
from lxml import objectify
import json

def xml_to_json(f_xml, f_json, indent=4):
    def tree_to_dict(tree, tree_dict):
        _dict = {}
        if tree.attrib:
            # store attrib in dictionary
            _dict.update(tree.attrib)
        elif tree.text:
            _dict = tree.text
        # loop through all the children nodes
        for node in tree.iterchildren():
            node_dict, node_list, _d = {}, [], {}
            # if nested, do a recursion
            node_dict = tree_to_dict(node, _d)
            if not node.tag in _dict:
                _dict.update(node_dict)
                continue
            # use list to append all same name's children node
            if isinstance(_dict[node.tag], list):
                _dict[node.tag].append(node_dict[node.tag])
                continue
            node_list.append(_dict[node.tag])
            _dict[node.tag] = node_list
            _dict[node.tag].append(node_dict[node.tag])
        if not _dict:
            _dict = None
        tree_dict[tree.tag] = _dict
        return tree_dict
    # parse your xml file here, getroot() return the root element
    root = objectify.parse(f_xml).getroot()
    root_dict = {}
    # make use of json module and parse the result dictionary to file
    with open(f_json, 'w') as f:
        json.dump(tree_to_dict(root, root_dict), f, indent=indent)

rawDescription: XML conversion fails to JSON return object


code:
import collections
def condense(l):
    outp = [l[0]]
    for x in l[1:]:
        if isinstance(x,collections.Sequence) \
            and not isinstance(x,basestring) and x[0]==l[0]:
            outp += x[1:]
        else:
            outp.append(x)
    return outp
def condense_r(l):
    outp = [l[0]]
    for x in l[1:]:
        if isinstance(x,collections.Sequence) and not isinstance(x,basestring):
            z = condense_r(x)
            if z[0]==l[0]:
                outp += z[1:]
            else:
                outp.append(z)
        else:
            outp.append(x)
    return outp

rawDescription: Python : Iterate through list and sublists and match first elements and do some more manipulations


code:
def end_of_quiz():
    global score
    if  score > 0:
        print("Well Done, Your score is:")
        print(score)
    else:
        print("Sorry, you didn't get any points, you shall try again!")

rawDescription: Check if user collected any points from my quiz


code:
from itertools import combinations

# Assume input is a list of strings called input_list
input_list = ['OG_1: A|1 A|3 B|1 C|2','OG_2: A|4 B|6','OG_3: C|8 B|9 A|10']

# Create a dict to store relationships and a list to store OGs
rels = {}
species = set()

# Populate the dict
for item in input_list:
    params = item.split(': ')
    og = params[0]
    raw_species = params[1].split()
    s = [rs.split('|')[0] for rs in raw_species]
    rels[og] = s

    for item in s:
        species.add(item)

# Get the possible combinations of species:
combos = [c for limit in range(1, len(l)-1) for c in combinations(species,limit)]

def combo_in_og(combo, og):
    for item in combo:
        if item not in rels[og]:
            return False
    return True

# Loop over the combinations and print
for combo in combos:
    valid_ogs = []
    for og in ogs:
        if combo_in_og(combo, og):
            valid_ogs.append(og)
    print('(species) ' + ','.join(combo) + ' (are in groups) ' + ', '.join(valid_ogs))

rawDescription: modify range in every loop of the range

description: Modify range in every loop of the range


code:
import io
import pandas as pd

text = '''\
Time stamp                   SOG    Altitude
2015-03-11T08:49:53.000Z        0   20
2015-03-11T08:49:42.000Z        0   19
2015-03-11T08:49:32.000Z        0   24'''

df = pd.read_table(io.BytesIO(text), sep='\s{2,}')
df['Time stamp'] = pd.to_datetime(df['Time stamp'])
df = df.set_index(['Time stamp'])
df.between_time('8:49:32', '8:49:52')

rawDescription: Python Pandas ix timestamp

description: Python Pandas ix timestamp


code:
# just to 0 at the start of w
# (or calculate first slice by hand and use out=... keyword argument to avoid even
# this copy.
w = np.concatenate(([0], w))
max_x = np.fmin.reduceat(r_x, w)
return ids, max_x

rawDescription: How to speed up a loop in python

description: Speed up a loop in python


code:
from PIL import Image

im = Image.fromarray(img_array)
# this might fail if `img_array` contains a data type that is not supported by PIL,
# in which case you could try casting it to a different dtype e.g.:
# im = Image.fromarray(img_array.astype(np.uint8))

im.show()

rawDescription: Viewing .npy images

description: Viewing .npy images


rawDescription: Ideal data structure with fast lookup, fast update and easy comparison/sorting


code: vars(testobj).update(d) # No (explicit) loop

rawDescription: How to modify class object parameters in code

description: Modify class object parameters in code


code: {{ url_for('custom_static', filename='foo') }}

rawDescription: More than one static path in local Flask instance


rawDescription: python multiple list, AND func, then create new list

description: Python multiple list, AND func, then create new list


code:
import sys
from PyQt4 import QtCore, QtGui

class Main(QtGui.QMainWindow):
    def __init__(self,parent = None):
        QtGui.QMainWindow.__init__(self,parent)
        self.init_ui()

        self.disable_edit_text_timer = QtCore.QTimer(self)
        self.disable_edit_text_timer.timeout.connect(self.disable_edit_text)
        self.disable_edit_text_timer.setSingleShot(True)
        self.disable_edit_text_timer.start(2000)

    def init_ui(self):
        self.text = QtGui.QTextEdit(self)
        self.setCentralWidget(self.text)
        self.statusbar = self.statusBar()
        self.setGeometry(100,100,1080,720)
        self.setWindowTitle("Text Editor")

    def disable_edit_text(self):
        self.text.setReadOnly(True)

def main():
    app = QtGui.QApplication(sys.argv)
    main = Main()
    main.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

rawDescription: Background Timer in PyQt Python Applicatiion


rawDescription: Spark Window Functions - rangeBetween dates


code: print(infile.read() % tuple(words))

rawDescription: Python: Interpolate array of unknown size into string


code:
@patch('__builtin__.open', new_callable=mock_open, read_data="aa\nbb")
def test_interface_mapping_new(self, mo):
    handlers = (mo.return_value,mock_open(read_data="AA\nBB").return_value,)
    mo.side_effect = handlers
    with open("ppp") as f:
        self.assertEqual("aa\nbb",f.read())
    with open("ppp") as f:
        self.assertEqual("AA\nBB",f.read())

rawDescription: Python mock builtin 'open' in a class using two different files


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.colors as colors
import math

fig = plt.figure()
ax = fig.add_subplot(111)

ratio = 1.0 / 3.0
count = math.ceil(math.sqrt(len(colors.cnames)))
x_count = count * ratio
y_count = count / ratio
x = 0
y = 0
w = 1 / x_count
h = 1 / y_count

for c in colors.cnames:
    pos = (x / x_count, y / y_count)
    ax.add_patch(patches.Rectangle(pos, w, h, color=c))
    ax.annotate(c, xy=pos)
    if y >= y_count-1:
        x += 1
        y = 0
    else:
        y += 1

plt.show()

rawDescription: Named colors in matplotlib

description: Named colors in matplotlib


code:
@withrepr(lambda x: "<Func: %s>" % x.__name__)
def mul42(y):
    return y*42

rawDescription: Possible to change a function's repr in python?


code: y['user']='guest'

rawDescription: Shallow copy: why is list changing but not a string?


rawDescription: In Python 2.* division which has more overhead?


code:
def firstTwoWords(strings):
    return [(s[0], s[1]) for s in (s.split() for s in strings)]

rawDescription: Eliminating redundant function calls in comprehensions from within the comprehension


rawDescription: check membership of a set in python

description: Check membership of a set in python


rawDescription: Python string formatting

description: Python string formatting


code:
import numpy as np
import sk_calc

class MyDia(QtGui.QDialog, Dlg):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.buttonOPLOT.clicked.connect(self.onPLOT)
        self.buttonPRED.clicked.connect(self.onPRED)

    def onPRED(self):
        if self.button_1.isChecked():
            a = 1
        elif self.button_2.isChecked():
            a = 2
        else:
            a = 0
        query = np.zeros((1,18))
        # ... etc

        # when user has made his choices the data goes do this

        # create an instance of the Calc class, passing in
        # parameters from the gui
        calc = sk_calc.Calc(a)

        # call methods of the instance, passing in parameters
        # from the gui, and receiving returned values
        prediction = calc.pred(query)

        # calc.plot() ... etc

rawDescription: Subprogram which takes all the predefined variables from a "main program"


code:
def __eval(self, expr, eval_globals=None, eval_locals=None):
    if eval_globals is None:
        eval_globals = globals()
    if eval_locals is None:
        eval_locals = eval_globals()

rawDescription: Is it possible to get locals() and globals() from an upper stack frame?


rawDescription: Call Python From Bat File And Get Return Code


rawDescription: python 3, unicode conversion, two \u0000 as one character

description: Python 3, unicode conversion, two \u0000 as one character


code:
class UrlData(object):
    def __init__(self, num_of_urls, url_pattern):
        self.num_of_urls = num_of_urls
        self.url_pattern = url_pattern

    def url_list(self):
        # Returns a list of strings that represent the urls you want based on num_of_urls
        # e.g. asite.com/?search?start=10
        urls = []
        for i in xrange(self.num_of_urls):
            urls.append(self.url_pattern + 'start=' + str((i + 1) * 10))
        return urls

rawDescription: Foreach loop to get next page of links with BeautifulSoup/Mechanize/Python


code:
# Make the plot of all the points together
plt.plot(x_data_plot,y_data_plot)
plt.show()

rawDescription: Plotting within a for loop, with 'hold on' effect in matplotlib?


code:
import csv
with open('products.txt') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')

rawDescription: Read txt file into list Python

description: Read txt file into list Python


code:
contents = ["IL-2", "CD-28","IL2","25"]
import re
[re.sub(r'\d','',i) for i in contents]

rawDescription: how to identify that anystring of list contains digits or not in python

description: Identify that anystring of list contains digits or not in python


code:
def delistify(x):
    try:
        return x[0]
    except TypeError:
        return x

rawDescription: How to convert some items in a tuple from list to float?

description: Convert some items in a tuple from list to float


code: testvar = 1 if x == 'dog' else (2 if x == 'cat' else (0 if x.isspace() else None))

rawDescription: possible to set variable with multiple if statments?

description: Possible to set variable with multiple if statments


code:
from datetime import datetime
from time import mktime

YOUR_FORMAT = """your format"""

date_string = 'Tue, 17-Oct-45 11:54:07 GMT'

# strip off the timezone here with split or regex, whatever you like

p = datetime.strptime(date_string, YOUR_FORMAT)
floating_number = mktime(p.timetuple())

rawDescription: how to convert cookie's GMT formated expires to float in Python http.cookiejar.Cookie method?

description: Convert cookie's GMT formated expires to float in Python http.cookiejar.Cookie method


rawDescription: Astropy Units equivalencies - interferometry baselines


code: row[0:0] = [str(delta)]

rawDescription: Need to do a math operation on every line in several CSV files in Python


code:
'x' in locals() or 'x' in globals()
x = None
'x' in locals() or 'x' in globals()
del x
'x' in locals() or 'x' in globals()

rawDescription: pythonic way to check if something exists?

description: Pythonic way to check if something exists


code: sym = [x for x in list if x not in no_sym and not no_sym.append(switch(i))]

rawDescription: Python: Finding symmetries in list of lists


code: target_dir = SECdownload(someYear, someMonth)

rawDescription: Python GUI cannot see global variable

description: Python GUI cannot see global variable


code:
total_elements = len(used_bytes)
mean = statistics.mean(used_bytes)

rawDescription: Pythonic way to aggregate object properties in memory efficient way?


code:
eng1 = Engine(1)
eng2 = Engine(2)
eng1 == eng2
eng1 == eng1
eng1 == Engine(1)
engines = set([eng1, eng2])
engines
engines.add(Engine(1))
engines

rawDescription: are user defined classes mutable

description: Are user defined classes mutable


code:
new_arr = np.array([1,2,3])
new_result_array = np.array([result_array * x for x in new_arr])
new_result_array

rawDescription: Arrays generation from different arrays and arrays/numpy modules?


rawDescription: Most efficient way to loop through multiple csv files and calculate NYSE tick


code:
import collections
d=collections.OrderedDict()
for e in dates:
    d.setdefault(e.strftime('%Y%m%d'),collections.OrderedDict()).setdefault(e.strftime('%H'), []).append(e.strftime('%H%M%S'))

rawDescription: Extract days, hours and seconds from a list of datetimes


code:
g = lambda x: x + 5
g(123)

rawDescription: How to sort a Python dict by value

description: Sort a Python dict by value


code:
img1 = np.array([[1, 2], [3, 4]])
img2 = np.array([[10, 6], [1, 0]])
img3 = np.array([[8, 1], [0, 4]])
images = np.zeros(shape=img1.shape + (3,))
images[:,:,0] = img1
images[:,:,1] = img2
images[:,:,2] = img3
images
images[:,:,0]
np.median(images, axis=2)

rawDescription: Temporal median image of multiple images


code: password = password.join(thelist[0])

rawDescription: Strings not joining in Python

description: Strings not joining in Python


code:
LPAR,RPAR = map(Suppress, '()')
expr = Forward()
operand = real | integer
factor = operand | Group(LPAR + expr + RPAR)
term = factor + ZeroOrMore( oneOf('* /') + factor )
expr = term + ZeroOrMore( oneOf('+ -') + term )

rawDescription: Parse mathematical expressions with pyparsing


code:
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, key)
# the command like likes pem format
cert_pem = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)

# the bundle that you created from the zip extraction
certificate_bundle = 'verisign-root-bundle.pem'

# Pipe the cert to the openssl verify command and check the return code
# a return code of 0 is successful verify
import subprocess
p = subprocess.Popen(['openssl', 'verify', '-CAfile', certificate_bundle],
                     stdin=subprocess.PIPE)
p.communicate(input=cert_pem)
p.wait()
if (p.returncode == 0):
    print('Certificate Verified.')
else:
    print('Problem with certificate')

rawDescription: How to authenticate a public key with certificate authority using Python?

description: Authenticate a public key with certificate authority using Python


code:
c = [7, 8, 9]
prod = itertools.product(a, b, c)
triplets = set()
for p in prod:
    f = frozenset(p)
    if len(f) == 3:
        triplets.add(f)

triplets

rawDescription: Heterogeneous combinations between two lists


code:
def func(input):
    # do calculation on input
    return result

s = "hello goodbye"
res = func(s)       # res now a result dictionary

rawDescription: Python Newbie: Returning Multiple Int/String Results in Python


code:
test = [3, 5, 2]
result = [[v+1 if i==j else v for j, v in enumerate(test)] for i in range(len(test))]

rawDescription: Pythonic way to generate a list of possible arrays


code:
from tkinter import *
from tkinter import ttk

root_window = Tk()

estyle = ttk.Style()
estyle.element_create("plain.field", "from", "clam")
estyle.layout("EntryStyle.TEntry",
                   [('Entry.plain.field', {'children': [(
                       'Entry.background', {'children': [(
                           'Entry.padding', {'children': [(
                               'Entry.textarea', {'sticky': 'nswe'})],
                      'sticky': 'nswe'})], 'sticky': 'nswe'})],
                      'border':'2', 'sticky': 'nswe'})])
estyle.configure("EntryStyle.TEntry",
                 background="green",
                 foreground="grey",
                 fieldbackground="black")
entry_v = StringVar()
entry = ttk.Entry(root_window, style="EntryStyle.TEntry", textvariable=entry_v)
entry.pack(padx=10, pady=10)

rawDescription: ttk Entry background colour

description: Ttk Entry background colour


code:
b = bigrams("This is a test".split(' '))
b
Counter(b)

rawDescription: Can't Import Bigrams From NLTK Library

description: Can't Import Bigrams From NLTK Library


code:
js = json.loads(soup.select_one("script[type=application/ld+json]").text)
all_urls = [dct["url"] for dct in js["itemListElement"]]
print(all_urls)

rawDescription: Parsing html for specific script type

description: Parsing html for specific script type


code: list3 = merged.items()

rawDescription: What is the Pythonic way to merge 2 lists of tuples and add the nonunique values in the tuples?


rawDescription: With Python, what is the most efficient way to remove all char from string except a-z, A-Z, 0-9, _, and -?


code: self.column1.add_attribute( self.renderer1, "visible", 2)

rawDescription: How to remove Parent checkbox in pygtk

description: Remove Parent checkbox in pygtk


rawDescription: Slicing numpy recarray at "empty" rows

description: Slicing numpy recarray at "empty" rows


code:
import re

onclick = soup.select_one("td.identityColumn[onclick]")["onclick"]

match = re.search(r"fundview\('(.*?)'\);", onclick)
if match:
    print(match.group(1))

rawDescription: Use Beautiful Soup findall to extract text between single quotations


code: str.count('/home/usr/music', '/')

rawDescription: how to compare a string with each element of a list in python

description: Compare a string with each element of a list in python


code: myListComp = [d[:1] + d[1] for d in myList]

rawDescription: List comprehension with nested lists (sublists)


code:
# Vectorized versions of c,d,e
c_vect = (a-AM)*(b-BM)
d_vect = (a-AM)**2
e_vect = (b-BM)**2

# Finally get r using those vectorized versions
r_out = np.sum(c_vect)/float(np.sqrt(np.sum(d_vect)*np.sum(e_vect)))

rawDescription: Matlab corr2 equivalent in python - performance issue


code: Refactoring

rawDescription: How are you using IronPython?

description: How are you using IronPython


code:
import numpy as np
from scipy.spatial.distance import pdist

dm = pdist(X, lambda u, v: np.sqrt(((u-v)**2).sum()))

rawDescription: Use pdist() in python with a custom distance function defined by you


code:
it = (r[i:].sum() for r, i in zip(data, start_indices))
np.fromiter(it, data.dtype)

rawDescription: Sum rows of numpy array where start index of each sum comes from another array


code:
x = pd.date_range('2000-1-1', periods=N, freq='T')
x - np.array(frame['seconds'], dtype='timedelta64[s]')

rawDescription: Apply time shift on Pandas DataFrame from another column


code:
class TestBase(object):
    def __init__(self):
        self.foo = 1

    def foo_printer(self):
        print(self.foo)

class TestChild(TestBase):
    def __init__(self):
        super(TestChild, self).__init__()
        print(hasattr(super(TestChild, self), 'foo_printer'))

test = TestChild()

rawDescription: How to test if python class parent has method defined?

description: Test if python class parent has method defined


code: [{value: index} for index, value in enumerate(a)]

rawDescription: Finding Index in string with recurring chars


code:
import string
instring = 'ABCD'
instring.translate(string.maketrans('ACac','gtgt'))

rawDescription: Wanting to Change specific Characters from TextFile into Other Characters. Not trying to Write, only wanting to print out into the console


rawDescription: Is it possible to insert specific sections of one list into a specific location in another list?


code: wtr.writerow([row[i] for i in cmdargs])

rawDescription: Specifying columns though command line to copy columns from csv file in python


code:
chars = set('0123456789$,')
if any((c in chars) for c in s):
    print('Found')
else:
    print('Not Found')

rawDescription: How to check a string for specific characters?

description: Check a string for specific characters


code:
from dulwich.repo import Repo
r = Repo("/path/to/repo")
tags = r.refs.as_dict("refs/tags")

rawDescription: How to get a list of tags and create new tags with python and dulwich in git?

description: Get a list of tags and create new tags with python and dulwich in git


code:
import subprocess
with open('CONTENT','w') as f1:
  p1 = subprocess.Popen(["sort", "CONTENT1"], stdout=subprocess.PIPE)
  p2 = subprocess.Popen(["uniq"], stdin=subprocess.PIPE, stdout=f1)
  p1_out = p1.communicate()[0] # catch output
  p2.communicate(p1_out)       # pass input

rawDescription: Redirecting Output of PIPE to a FILE in python


code:
avg = y.mean(axis=(1, 3))
avg

rawDescription: How can I vectorize the averaging of 2x2 sub-arrays of numpy array?

description: Vectorize the averaging of 2x2 sub-arrays of numpy array


code:
lib_path = os.path.join(os.path.dirname(__file__), 'libeay32.dll')
lib = CDLL(lib_path)

rawDescription: How can I make a Python Wheel from an existing native library?

description: Make a Python Wheel from an existing native library


code:
x.py
from ctypes import *
x = CDLL('x')
x.read.argtypes = [POINTER(c_int16)]
x.read.restype = None
p = (c_int16*5)()
x.read(p,len(p))
print(list(p))

rawDescription: passing arrays with ctypes

description: Passing arrays with ctypes


code:
items= [['F','G'], ['B','C'], ['A','B'], ['C','D'], ['E','F']]
mydict = dict(items)
for prev,next in items:
    if next in mydict:
        mydict[prev] = mydict[next]
        del mydict[next]
print(list(mydict.items()))

rawDescription: How merge prev/next lists in python?

description: How merge prev/next lists in python


code: soup.find_all(['a', 'div'])

rawDescription: Beautiful Soup Using Regex to Find Tags?

description: Beautiful Soup Using Regex to Find Tags


code:
def registered_monster(cls):
    Monster.monsters.append(cls)
    return cls

class Monster(object):
    monsters = []

@registered_monster
class Lochness(Monster):
    pass

@registered_monster
class Yeti(Monster):
    pass

rawDescription: Executing code after construction of class object


code: my_obj = MyClass.load_from_db(number)

rawDescription: Exit and delete a class instance python

description: Exit and delete a class instance python


code:
# assumes Python 2.x
def get_int(prompt):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError:
            pass

def get_one_of(prompt, values):
    while True:
        result = raw_input(prompt).strip()
        if result in values:
            return result
        else:
            print("  (must enter one of [{}])".format(", ".join(values)))

class Node(object):
    node_type_values = {"pale": 1.1, "normal": 1.3, "bright": 1.5}
    node_types = sorted(node_type_values.keys())

    node_feature_values = {"normal": 2.5, "sinister": 3, "pure": 4, "hungry": 5}
    node_features = sorted(node_feature_values.keys())

    @classmethod
    def from_prompt(cls):
        capacity     = get_int("Enter the node's capacity: ")
        node_type    = get_one_of("Enter the node's type: ", cls.node_types)
        node_feature = get_one_of("Enter the node's feature: ", cls.node_features)
        num_aspects  = get_int("Enter the node's aspect count: ")
        return cls(capacity, node_type, node_feature, num_aspects)

    def __init__(self, capacity, node_type, node_feature, num_aspects):
        self.capacity = capacity
        self.node_type = node_type
        self.node_feature = node_feature
        self.num_aspects = num_aspects

    def price(self):
        return 4 * self.capacity * Node.node_type_values[self.node_type] * Node.node_feature_values[self.node_feature] * (1. + 0.1 * self.num_aspects)

def main():
    n = Node.from_prompt()
    print("Price is ${:0.2f}.".format(n.price()))

if __name__=="__main__":
    main()

rawDescription: i have a formula, trying to put it into python and this is what i have so far, whats the issue with it?

description: I have a formula, trying to put it into python and this is what i have so far, whats the issue with it


code:
from django.core.mail import EmailMessage
from django.db import models
from django.db.models import signals

class PurchaseOrder(models.Model):
    product = models.CharField(max_length=256)
    vendor = models.CharField(max_length=256)
    dollar_amount = models.FloatField()
    item_number = models.AutoField(primary_key=True)

def send_email_on_new_order(instance, created, raw, **kwargs):
    # Fixtures or updates are not interesting.
    if not created or raw:
        return

    # `instance` is your PurchaseOrder instance.
    email = EmailMessage('Purchase Order System', 'your message here', to=['youremail@gmail.com'])
    email.send()

signals.post_save.connect(send_email_on_new_order, sender=PurchaseOrder, dispatch_uid='send_email_on_new_order')

rawDescription: How can I send an email based on a new primary key being generated through Django?

description: Send an email based on a new primary key being generated through Django


code:
image
np.diff(image, axis=0)

rawDescription: Python - differentiating an image in the X direction


code:
d = {}
for activity in Activities:
    for subactivity in activity:
        for subsubactivity in subactivity:
            d['Activity']['Subactivity']['subsubactivity'] = value

rawDescription: How to create a json tree structure from SQLalchemy model

description: Create a json tree structure from SQLalchemy model


code:
def myfun(x_val):
    return fun0(x_val) if x_val == 0 else fun1(x_val)
x = np.array(map(myfun,x))

rawDescription: How to apply multiple functions to numpy array?

description: Apply multiple functions to numpy array


rawDescription: When oracle virtualbox are set, How to get local ip address in python


code:
import random

def myRand(i, w):
    r = random.uniform(0, sum(w))

    # loop through a list of inputs and max cutoff values, returning
    # the first value for which the random num r is less than the cutoff value
    for n,v in map(None, i,[sum(w[:x+1]) for x in range(len(w))]):
        if r < v:
            return n

rawDescription: Returning a value at random based on a probability weights


code: merge(foo, fundraisers, left_on=['fundraiser ID', 'event'], right_on=['ID', 'event'], how='outer')

rawDescription: python pandas merging data based off 2 keys

description: Python pandas merging data based off 2 keys


code:
def g(n):
    if n <= 3:
        return n
    a, b, c = 1, 2, 3
    while n > 3:
        a, b, c = b, c, c + 2 * b + 3 * a
        n -= 1
    return c

rawDescription: Python: Convert this recursive function to iterative


code: [ p for p in database if p.y == 2 ]

rawDescription: Storing information on points in a 3d space


code:
def pytest_generate_tests(metafunc):
    if 'data' in metafunc.funcargnames:
        metafunc.parametrize('data', [1,2,3,4])

def test_data(data):
    assert data > 0

rawDescription: Paramaterize unit tests in python

description: Paramaterize unit tests in python


rawDescription: Plotting Days of the year Python

description: Plotting Days of the year Python


code:
def insort_left(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the left of the leftmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    a.insert(lo, x)

rawDescription: Python: Using bisect.insort with key

description: Python: Using bisect.insort with key


code:
df
dates

rawDescription: Creating column with difference in two rows in pandas


code:
Value('i', True)
Value('i', False)
bool(Value('i', False).value)
bool(Value('i', 50).value)

rawDescription: Python share values

description: Python share values


code:
from dendropy import Tree as DTree
from ete3 import Tree

#do your Tree generation magic here
DendroTree = DTree.get(data=t.write(format = 9),schema = 'newick')

rawDescription: Using python 3.x how can I pass a Tree object from ete3 to DendroPy without writing to file


code:
class Principal(object):
    ...

rawDescription: How can I acess a metod from an object inside a class in python 2.6?

description: Acess a metod from an object inside a class in python 2.6


code:
outfile = open("outfile", "w")
proc = subprocess.Popen(["./myexe", "arg1", "arg2"],
                        stdout=outfile, stderr=outfile)

rawDescription: Executing and killing a shell process using python script


code:
def myfun():
  myfun.last_called = datetime.now()
  # … do things

rawDescription: Checking if function was not called for x amount of time


code:
try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

rawDescription: What is the best way to handle dependencies based on the Python version?


code:
def strings_in_a_list(n, s):
    if n == 0:
        return []
    else:
        l = strings_in_a_list(n - 1, s)
        l.append(s)
        return l

rawDescription: Create a Python list with a string, s, repeated n times. Uses recursion


code:
timeit.timeit('primes_list(1000)', 'from __main__ import primes_list', number=1000)
timeit.timeit('erat(1000)', 'from __main__ import erat', number=1000)

rawDescription: Is this more efficient than Sieve of Eratosthenes?


code: {{gettext("'message'")|safe}}

rawDescription: serving i18n js using babel, django, & jinja2

description: Serving i18n js using babel, django, & jinja2


code:
from pkg_resources import resource_stream
f = resource_stream('myproject', 'my_csv.csv')

rawDescription: How to code a scrapy to grab differently formatted html tables

description: Code a scrapy to grab differently formatted html tables


code: values[row[0]] = float(row[1]) + float(row[2])

rawDescription: Python: Adding multiple values to a dictionary key


rawDescription: Summation of TFIDF sparse vector values for each document in Spark with Python


code:
import numpy as np
import scipy as sp
import scipy.interpolate
import matplotlib.pyplot as plt

# Mock up an image.
W = 100
x = np.arange(W)
y = np.arange(W)
xx,yy = np.meshgrid(x,y)

image = xx//5*5 + yy//5*5
image = image / np.max(image)  # scale into [0,1]

plt.imshow(image, interpolation='nearest', cmap='gray')
plt.show()

rawDescription: Take data from a circle in python

description: Take data from a circle in python


rawDescription: Create constants for offsets into a list


code:
a = Single.get_instance()
b = Single.get_instance()
a is b
del a
del b
c = Single.get_instance()
del c

rawDescription: How to delete object created by another module?

description: Delete object created by another module


code:
list1, list2 = zip(*source_list)
list(source_list) == zip(list1, list2)

rawDescription: Unpacking a list / tuple of pairs into two lists / tuples


code:
class DragTable(QtGui.QTableView):
    def __init__(self, parent = None):
        super(DragTable, self).__init__(parent)
        self.setDragEnabled(True)
        self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)

rawDescription: Multiple drag and drop in PyQt4

description: Multiple drag and drop in PyQt4


code:
class foo(functions.foo, FooBase): # Methods from functions.foo take precedence
    pass

rawDescription: Import code directly into script with Python?


code:
import kivy
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button

class CalcApp(App):
    def build(self):
        layout = GridLayout(cols=3, row_force_default=True, row_default_height=50,
            pos_hint={'center_x':.5} , size_hint=(None, None))
            # ^ position grid in mid horizontally, ^ make grid use custom
            # size.
        # Bind the size of the gridlayout of to it's minimum_size(calculated
        # by children size)
        layout.bind(minimum_size = layout.setter('size'))
        # bind the top of the grid to it's height'
        layout.bind(height = layout.setter('top'))
        for x in (1, 2, 3, 4, 5, 2, 6, 7, 8, 9, 0):
            layout.add_widget(Button(text=str(x), size_hint_x=None, width=100))
        layout.add_widget(Button(text='Enter', size_hint_x=None, width=100))
        return layout

CalcApp().run()

rawDescription: How can I set the position (x,y coordinates) of a grid layout in kivy?

description: Set the position (x,y coordinates) of a grid layout in kivy


code: dir(content)

rawDescription: How to examine a urllib2 object in Python?

description: Examine a urllib2 object in Python


code:
import decimal
decimal.getcontext()

rawDescription: PHP bcmath versus Python Decimal

description: PHP bcmath versus Python Decimal


code:
from xml.etree import ElementTree as et

tree = et.fromstring(x)

print(sorted({n.get("name") for n in tree.findall(".//record[@name]")}))

rawDescription: Python: Find Unique XML Attributes

description: Python: Find Unique XML Attributes


rawDescription: Python: Length of longest common subsequence of lists


rawDescription: Using django 1.8 duration field to annotate a set of django objects


code:
import csv
with open('large.csv','w') as f1:
    writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
    writer.writerow([''] + range(1000000))
    for i in range(1000000):
        row = [i] + [i + j*0.2 for j in range(i+1)]
        writer.writerow(row)

rawDescription: csv writing within loop

description: Csv writing within loop


code:
twos, threes = countmatching(xrange(1,10),
                             lambda a: a % 2 == 0,
                             lambda a: a % 3 == 0)

rawDescription: Most pythonic way of counting matching elements in something iterable


code:
with open('cities.txt') as cities, open('tests.txt') as tests:
    for c, t in itertools.product(cities.readlines(), tests.readlines()):
        print("{city} {test}".format(city=c,test=t))

rawDescription: Double for Loop Using 2 Lists Compared to Double Loop Using 2 Text Files - Different Outcome


code: json.dumps(p, default=default)

rawDescription: Retrieve the object from dict to that it can easily be dumped via json.dumps()


code:
m1
m2
np.concatenate((m1,m2)).T.reshape(-1,m1.shape[0]).T
np.dstack((m1,m2)).reshape(m1.shape[0],-1)

rawDescription: merge identity matrices in specific way

description: Merge identity matrices in specific way


code:
df['new_val'] = df.apply(lambda row: sum(row[lf[i]]*co[i] for i in range(len(lf)))+5, axis=1)
df

rawDescription: How to calculate a new field in python using a linear relationship

description: Calculate a new field in python using a linear relationship


code: c = [x | y for x, y in zip(a, b)]

rawDescription: is there a binary OR operator in python that works on arrays?

description: Is there a binary OR operator in python that works on arrays


code:
import numpy.distutils.system_info as sysinfo
sysinfo.platform_bits

rawDescription: Do I have Numpy 32 bit or 64 bit?

description: Do I have Numpy 32 bit or 64 bit


rawDescription: Python regex for a complex string

description: Python regex for a complex string


code:
import string

alphabet = set(string.ascii_lowercase)

def ispangram(input_string):
    return set(input_string.lower()) >= alphabet

rawDescription: How do I check if a string contains ALL letters of the alphabet in python?

description: Check if a string contains ALL letters of the alphabet in python


code:
# check that a string is all 0 or all 1
def check_string(s):
    size = len(s)
    return s in ('0'*size, '1'*size)

# check that a list contains only strings that satisfy check_string
def check_list(l):
    return all(check_string(s) for s in l)

lst = [["111","101","000"],["1001","1100","1111"],["00","11","00"]]

result = [l for l in lst if not check_list(l)]

rawDescription: Filtering out sublist from list based on contents of entire sublist?


code:
type(a)
type(b)

rawDescription: what is the difference for python between lambda and regular function?

description: What is the difference for python between lambda and regular function


code:
import glob
import numpy as np

path = './file[0-9]*'
filenames = glob.glob(path)
files = [open(i, "r") for i in filenames]
output_file = open('output_file', mode = 'a')

# last_ids[i] = last id number read from files[i]
# I choose np.array because of function np.argmin
last_ids = np.ones(shape = len(files)) * np.inf
last_items = [None] *len(files)

# Note: When we hit EOF in a file, the corresponding entries from "files", "last_items", and "last_ids" will be deleted

for i in range(len(files)):
    line = files[i].readline()
    if line:
        item = line.strip().split()
        last_ids[i] = int(item[1])
        last_items[i] = item

# Find an item with the smallest id
pos = np.argmin(last_ids)
current_item = last_items[pos]
# Inverting positions, so that id is first
current_item[0], current_item[1] = current_item[1], current_item[0]

while True:
    # Read next item from the corresponding file
    line = files[pos].readline()
    if line:
        item = line.strip().split()
        last_ids[pos] = int(item[1])
        last_items[pos] = item
    else:
        # EOF in files[pos], so delete it from the lists
        files[pos].close()
        del(files[pos])
        del(last_items[pos])
        last_ids = np.delete(last_ids, pos)
        if last_ids.size == 0:
            # No more files to read from
            break

    # Find an item with the smallest id
    pos = np.argmin(last_ids)
    if last_items[pos][1] == current_item[0]:
        # combine:
        current_item.append(last_items[pos][2])
    else:
        # write current to file and replace:
        output_file.write(' '.join(current_item) + '\n')
        current_item = last_items[pos]
        current_item[0], current_item[1] = current_item[1], current_item[0]

# The last item to write:
output_file.write(' '.join(current_item) + '\n')
output_file.close()

rawDescription: merge multiple files by reading them simultaneously line by line?

description: Merge multiple files by reading them simultaneously line by line


rawDescription: Clearing a QWebView widget PyQt

description: Clearing a QWebView widget PyQt


code: x = range(100)

rawDescription: What does list[x::y] do?

description: What does list[x::y] do


rawDescription: Extend index on business day range

description: Extend index on business day range


code:
s = "{} {}".format('foo', 'bar')
if something:
    do_something('{} {} {}'.format(1, 2, 3))

rawDescription: String formatting without index in python2.6


rawDescription: Iterating through permutations that fit a specific key


code:
def clicked(self, arg):
    proxyModel=self.tableview.model()
    self.tableview.clearSelection()
    proxyModel.filterActive = True
    proxyModel.invalidateFilter()

rawDescription: How to select QTableView index or row from inside of Model

description: Select QTableView index or row from inside of Model


code:
for f in lst:
    f("event_info")

rawDescription: What is the idiomatic way of invoking a list of functions in Python?


code:
def nanmean_reduceat(x, indices):
    mask = np.isnan(x)
    # use try-finally to make sure x is reset
    # to its original state even if an error is raised.
    try:
        x[mask] = 0
        return np.add.reduceat(x, indices) / np.add.reduceat(~mask, indices)
    finally:
        x[mask] = np.nan

rawDescription: numpy.nanmean of subsets of elements

description: Numpy.nanmean of subsets of elements


code:
django_app/monkey/tastypie.py
from __future__ import absolute_import

from django.core.exceptions import ObjectDoesNotExist
from tastypie.bundle import Bundle
from tastypie.exceptions import ApiFieldError

def dehydrate(self, bundle, for_list=True):
    if not bundle.obj or not bundle.obj.pk:
        if not self.null:
            raise ApiFieldError(
                "The model '%r' does not have a primary key and can not be used in a ToMany context." % bundle.obj)

        return []

    the_m2ms = None
    previous_obj = bundle.obj
    attr = self.attribute

    if isinstance(self.attribute, basestring):
        attrs = self.attribute.split('__')
        the_m2ms = bundle.obj

        for attr in attrs:
            previous_obj = the_m2ms
            try:
                the_m2ms = getattr(the_m2ms, attr, None)
            except ObjectDoesNotExist:
                the_m2ms = None

            if not the_m2ms:
                break

    elif callable(self.attribute):
        the_m2ms = self.attribute(bundle)

    if not the_m2ms:
        if not self.null:
            raise ApiFieldError(
                "The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (previous_obj, attr))

        return []

    self.m2m_resources = []
    m2m_dehydrated = []

    # TODO: Also model-specific and leaky. Relies on there being a
    # ``Manager`` there.
    m2ms = the_m2ms.all() if for_list else the_m2ms.get_query_set().all()
    for m2m in m2ms:
        m2m_resource = self.get_related_resource(m2m)
        m2m_bundle = Bundle(obj=m2m, request=bundle.request)
        self.m2m_resources.append(m2m_resource)
        m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource, for_list=for_list))

    return m2m_dehydrated

def _build_reverse_url(self, name, args=None, kwargs=None):
    return kwargs.get('pk')

def get_via_uri(self, uri, request=None):
    bundle = self.build_bundle(request=request)
    return self.obj_get(bundle=bundle, pk=uri)

def build_related_resource(self, value, request=None, related_obj=None, related_name=None):
    """
    Returns a bundle of data built by the related resource, usually via
    ``hydrate`` with the data provided.

    Accepts either a URI, a data dictionary (or dictionary-like structure)
    or an object with a ``pk``.
    """
    self.fk_resource = self.to_class()
    kwargs = {
        'request': request,
        'related_obj': related_obj,
        'related_name': related_name,
    }

    if isinstance(value, Bundle):
        # Already hydrated, probably nested bundles. Just return.
        return value
    elif isinstance(value, (basestring, int)):
        # We got a URI. Load the object and assign it.
        return self.resource_from_uri(self.fk_resource, value, **kwargs)
    elif isinstance(value, Bundle):
        # We got a valid bundle object, the RelatedField had full=True
        return value
    elif hasattr(value, 'items'):
        # We've got a data dictionary.
        # Since this leads to creation, this is the only one of these
        # methods that might care about "parent" data.
        return self.resource_from_data(self.fk_resource, value, **kwargs)
    elif hasattr(value, 'pk'):
        # We've got an object with a primary key.
        return self.resource_from_pk(self.fk_resource, value, **kwargs)
    else:
        raise ApiFieldError("The '%s' field was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: %s." % (self.instance_name, value))

rawDescription: Django Tastypie Postgres slow server response


rawDescription: Create model for MySQL view and join on it


code: self.bnext = Button(...)

rawDescription: matplotlib, plt.show() in a different method = no on_clicked

description: Matplotlib, plt.show() in a different method = no on_clicked


code:
from mystuff.customs import MyFileStorage

mfs = MyFileStorage()

class SomeModel(model.Model):
   my_file = model.FileField(storage=mfs)

rawDescription: Set Django's FileField to an existing file


code: [ ''.join(x) for x in itertools.product( *[(c, d.get(c)) if d.get(c) else c for c in s] ) ]

rawDescription: Get ALL results of a word mapping with a dictionary


code: b[:len(a)] = a

rawDescription: inserting numpy data into a bigger array of zeros

description: Inserting numpy data into a bigger array of zeros


code: ls = [item for item in ls if all(tuple[1] != m for tuple in item)]

rawDescription: Delete item from list upon a condition

description: Delete item from list upon a condition


code:
server_list, good_email = ["gmail.com", "yahoo.com"], []
if all(not emailaddress.endswith(server) for server in server_list):
    good_email.append(emailaddress)

rawDescription: Python: check if string is in any items in a list?


code:
@register.simple_tag()
def multiply(qty, unit_price, *args, **kwargs):
    # you would need to do any localization of the result here
    return qty * unit_price

rawDescription: Multiply in django template

description: Multiply in django template


code:
import netCDF4
import numpy as np

yindexlist = [1,2,3]
xindexlist = [4,5,6]
ngridcell = len(xidx)
ntimestep = 58400

# Define an empty 2D array to store time series of precip for a set of grid cells
timeseries_per_grid_cell = np.zeros([ngridcell, ntimestep])

ncfile = netCDF4.Dataset('path/to/file/precip_all.nc', 'r')

# Note that precip is 3D, so need to read in all dimensions
precip = ncfile.variables['precip'][:,:,:]

for i in range(ngridcell):
     timeseries_per_grid_cell[i,:] = precip[:, yindexlist[i], xindexlist[i]]

ncfile.close()

rawDescription: Combine multiple NetCDF files into timeseries multidimensional array python


code:
class Document(object):

    def __init__(self, index, label, bowdict):
        self.index = index
        self.label = label
        self.bowdict = bowdict

rawDescription: I need a neat data structure suggestion to store a very large dataset (to train Naive Bayes in Python)


rawDescription: Generate repeated elements in a list based on elements of another list


rawDescription: find neighbours in np array in python

description: Find neighbours in np array in python


code:
sq = [['welcome'], ['we', 'are'], ['the', 'champions']]
sl = [['we', 'are', 'rainbow', 'while', 'to', 'and', 'do', 'welcome', 'while', 'cant', 'did'], ['are', 'time', 'to', 'do', 'the', 'champions', 'while', 'am']]

_flat = sum(sq, [])
test = []

for i, nested_list in enumerate(sl):
    test.append([])
    for item in nested_list:
        test[i].append(1 if item in _flat else 0)
print(test)

rawDescription: Taking two lists and comparing for similarities


code:
def chunks(f):
    while True:
        data = f.read(8192)
        if not data:
            break
        yield data

rawDescription: Process large data in python

description: Process large data in python


code:
arr = (c_double * 4 * 2 * 3)()

for i, row in enumerate(list3d):
    for j, col in enumerate(row):
        arr[i][j][:] = col

rawDescription: How do I convert a Python list of lists of lists into a C array by using ctypes?

description: Convert a Python list of lists of lists into a C array by using ctypes


code:
foo = bar = None
type(foo); type(bar)
foo = bar = "1Value4All"
type(foo); type(bar)

rawDescription: Python: Set many variables to the same value – with automatic count of number of variables


code:
from pyspark.sql.functions import col

s = (
    '{"quantity": 1, "name": "product_id", "price": 12}\n'
    '{"quantity": 3, "name": "product_id2", "price": 5}'
)

with open('/tmp/test.jsonl', 'w') as fw:
  fw.write(s)

df = sqlContext.read.json('/tmp/test.jsonl')
df.withColumn('total', col('price') * col('quantity'))

rawDescription: How can I map a spark RDD of json objects to another RDD which contains objects with only selected set of attributes

description: Map a spark RDD of json objects to another RDD which contains objects with only selected set of attributes


code:
numbers = input("Enter your numbers followed by commas: ")
numbers
numbers = numbers.split(',')
numbers
numbers = [ x for x in map(int,numbers) ]
numbers  = [ int(x) for x in numbers ]
numbers

rawDescription: Sum function prob TypeError: unsupported operand type(s) for +: 'int' and 'str'


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

n = 14
X = np.random.rand(20)
Y = np.random.rand(20)
Z = np.random.randint(low=0,high=n,size=X.shape)

plt.figure()
plt.scatter(X,Y,c=Z,cmap=cm.hot)
plt.colorbar()

plt.figure()
plt.scatter(X,Y,c=Z,cmap=cm.get_cmap('hot',n))
plt.colorbar()

rawDescription: Discrete pyplot scatter colobar

description: Discrete pyplot scatter colobar


code:
all_params = get_params(some_stuff_here, and_another_stuff)
for param_one, param_two, param_three, param_four, param_five in all_params:
    pass

rawDescription: proper formatting of python multiline [ for in ] statement

description: Proper formatting of python multiline [ for in ] statement


code:
import numpy as np
import pylab as P

mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)

P.hist(x, 50)
P.show()

rawDescription: Bar charts with xaxis bins using Plotly or Matplotlib?


code: urllib.quote_plus(url, safe=':')

rawDescription: percent encoding URL with python

description: Percent encoding URL with python


code:
seq="----AB--C-D-----"
newseq="--A--BC---D-"
seq=list(seq) #changing maaster sequence from string to list
newseq=list(newseq) #changing new sequence from string to list
n=len(seq) #obtaining length of master sequence
newseq.extend('.') #adding a tag to end of new sequence to account for terminal gaps

print(seq, newseq,n) #verification of sequences in list form and length
for i in range(len(seq)):
    if seq[i]!=newseq[i]:
       if seq[i]=='-':
           newseq.insert(i,'-')

       elif newseq[i]=='-':
           newseq.insert(i,seq[i])
       else:
           newseq.insert(i,seq[i])

else:
    newseq=newseq[0:len(seq)]

old=''.join(seq) #changing list to string
new=''.join(newseq) #changing list to string
new=new.strip('.') #removing tag

print(old) #verification of master-sequence fidelity
print(new) #verification of matching sequence

rawDescription: Protein sequence pattern-matching python


code:
data = np.loadtxt(r'dataa.txt')

a = [data[:,0]]
b = [data[:,1]]
n = [data[:,2]]

x = np.asarray(a)
y = np.asarray(b)
z = np.asarray(n)

rawDescription: Contour plot in Python importing txt table file


code: values = {chr(i): i + 1 for i in range(ord("a"), ord("a") + 26)}

rawDescription: python: How do I assign values to letters?

description: Python: How do I assign values to letters


code:
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon, QTextEdit, QTextDocumentFragment

def main():

    app = QtGui.QApplication(sys.argv)
    window = QDialog()

    list = QListWidget( window )

    textEditor = QTextEdit( window );
    textEditor.setReadOnly( True )
    tick_icon = QTextDocumentFragment.fromHtml(r"<img src='tick.png'>");

    textEditor.insertPlainText ( " ValiumKnight writes: " )
    textEditor.textCursor().insertFragment(tick_icon);
    textEditor.insertPlainText ( " Hello World " )
    textEditor.textCursor().insertFragment(tick_icon);
    textEditor.textCursor().insertFragment(tick_icon);
    textEditor.textCursor().insertFragment(tick_icon);

    window.show( )
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: how to add image with text in qlistwidget pyqt4 python?

description: Add image with text in qlistwidget pyqt4 python


rawDescription: using a variable keyword for an optional argument name with python argparse

description: Using a variable keyword for an optional argument name with python argparse


rawDescription: Perl or Python: Convert date from dd/mm/yyyy to yyyy-mm-dd


code: variables = {mod_name: getattr(import_module(mod_name), 'var') for mod_name in module_list}

rawDescription: Importing same variable from multiple libraries


code:
def my_func_vec(a, b):
    a = np.array(a, copy=False, ndmin=2)
    b = np.array(b, copy=False, ndmin=2)
    a = a[..., np.newaxis, :]
    b = b[..., np.newaxis, :, :]
    distance = np.sqrt(np.sum((a[..., 1:] - b[..., 1:])**2, axis=-1))
    rate = np.exp(-2*distance / loclength)
    mask = a[..., 0] < b[..., 0]
    rate[mask] *= np.exp((a[..., 0] - b[..., 0])[mask] / kT)
    mask = rate <= cutoff
    rate[mask] = 0
    return rate

rawDescription: vectorize a function for numpy, that correlates each element of one vector with each element of another

description: Vectorize a function for numpy, that correlates each element of one vector with each element of another


code:
S = 1000 # Size of the matrices
N = 10 # Number of matrices

L = [np.random.standard_normal(size=(np.random.randint(S//2, S*2), S)).astype(np.float32) for _ in range(N)]

rawDescription: Speedup for the reduce operation in Theano


code:
from dir1 import execute as execute1
from dir2 import execute as execute2

rawDescription: Structure for a test suite

description: Structure for a test suite


code:
# EXPLANATION OF THE REGEX.
# Finds segments of strings that:
#     [x-z]    start with a letter x,y, or z
#     [1]      followed by the number 1
#     =        followed by the equals sign
#
#     But dont return any of that section of the string, only use that
#     information to then extract the following values that we do actually want
#
#     (        Return the parts of the string that have the following pattern,
#              given that they were preceded by the previous pattern
#
#     [\d]     contain only a numeric digit
#     *        keep proceeding forward if the current character is a digit
#     )        end of the pattern, now we can return the substring.

rawDescription: Extracting xyz coordinate values from a string into lists


rawDescription: Most pythonic way to delete text between two delimiters


code: G

rawDescription: iterating over lists finding standard deviation of each point

description: Iterating over lists finding standard deviation of each point


code:
from scipy.spatial.distance import cdist

N = (cdist(A,B,'sqeuclidean') <= dSquared).astype(int)

rawDescription: Vectorize mask of squared euclidean distance in Python


A Caption

picture: PICTUREURL

source: PICTUREURL

rawDescription: "Easy" Access to Facebook Profile Photo via Graph API


code:
list_a = [0 for k in range(10)]
list_b = list_a[:]

rawDescription: Functioning of list values in Python

description: Functioning of list values in Python


rawDescription: Specify join condition in SQLalchemy ORM without foreign key


code: print (c_time_converted + timedelta(hours=1)).time() # prints 00:13:57

rawDescription: having issues with python time object

description: Having issues with python time object


rawDescription: Python itertools.combinations continue from certain value?


rawDescription: How can I build a python datastructure by reading it from a file

description: Build a python datastructure by reading it from a file


rawDescription: trying to mask 2D numpy arrays based on values in one column

description: Trying to mask 2D numpy arrays based on values in one column


code:
a = 'b\n'
a.strip()

rawDescription: Importing file as list. \n after every item


rawDescription: python 3: subprocessing a python script that uses argparse

description: Python 3: subprocessing a python script that uses argparse


code:
rows = incorrect
cols = [[row[i] for i in range(len(rows[0]))] for row in rows]
cols = [[row[i] for row in rows] for i in range(len(row))]
cols
rows

rawDescription: Made typo, Python function still works. Why?


rawDescription: How to merge two columns together in Pandas

description: Merge two columns together in Pandas


code:
import os
import urllib2
import sys
d = urllib2.urlopen(sys.argv[0])
o = open('image.%s' % d.info().gettype(), 'w')
o.write(d.read())

rawDescription: how can i download the images with no extension on linux

description: Download the images with no extension on linux


code: regex.findall("dont capture{START}capture me 1{END}dont capture{END}dont capture{START}dont capture{START}capture me 2{END}dont capture")

rawDescription: python regex to match all minimal strings between specified start and end tokens

description: Python regex to match all minimal strings between specified start and end tokens


rawDescription: matrix using python

description: Matrix using python


rawDescription: looping over keys and values, process the key values and store them back another dictinory in Python

description: Looping over keys and values, process the key values and store them back another dictinory in Python


rawDescription: How do I get the first timestamp (index) of a group when applying groupby to a python pandas dataframe?

description: Get the first timestamp (index) of a group when applying groupby to a python pandas dataframe


code:
from pyspark import SparkContext, SparkFiles

sc = SparkContext()
sc.addFile("config")

from envvariables import EnvVariables

rawDescription: Python Spark, Accessing Class Static Variables from Executor


code:
import xml.dom.minidom as minidom
doc = minidom.Document()
foo = doc.createElement("foo")
doc.appendChild(foo)
print(foo.__class__)
# xml.dom.minidom.Element

print(foo.toprettyxml(indent = '  '))
# <foo/>

rawDescription: Pretty print Python xml.dom.Element object


code:
def search_list(thedict, thelist):
    return any(x["class"] == thedict["class"]
               and x["parameter"] == thedict["parameter"]
               for x in thelist)

rawDescription: Search in python list of dict

description: Search in python list of dict


code:
np.mgrid[-1:1:0.5]  # values starting at -1, using 0.5 as step, up to 1 (not included)
np.mgrid[-1:1:4j]  # values starting at -1 up to +1, 4 values requested
np.mgrid[-1:1:1+4j]  # ???

rawDescription: Streamplot mgrid - Python

description: Streamplot mgrid - Python


code:
import os
from django.db.models.loading import AppCache
cache = AppCache()

curdir = os.getcwd()

for app in cache.get_apps():
    f = app.__file__
    if f.startswith(curdir) and f.endswith('.pyc'):
        os.remove(f)
    __import__(app.__name__)
    reload(app)

from django.utils.datastructures import SortedDict
cache.app_store = SortedDict()
cache.app_models = SortedDict()
cache.app_errors = {}
cache.handled = {}
cache.loaded = False

rawDescription: How do you reload a Django model module using the interactive interpreter via "manage.py shell"?

description: Reload a Django model module using the interactive interpreter via "manage.py shell"


code: tn = None

rawDescription: Find and remove a Python object from locals() or globals()


code:
import operator

def test(arg1, arg2, compare_function):

    if compare_function(arg1, arg2):
        print("condition is true")
    else:
        print("condition is false")

rawDescription: Is there a way to swap between logical operators on the basis of some boolean?


code:
import commands
commands.getoutput("cp file.mp3 /Users/<your_username>/Music/iTunes/iTunes Media/Automatically Add to iTunes")

rawDescription: Programatically add songs to iTunes

description: Programatically add songs to iTunes


rawDescription: How to get the mean over time value

description: Get the mean over time value


code:
get_meridiem = lambda tm: 'AM' if tm.tm_hour < 12 else 'PM'
get_meridiem(time.strptime('9:00 AM', '%I:%M %p'))
get_meridiem(time.strptime('9:00 PM', '%I:%M %p'))
get_meridiem(time.strptime('12:00 PM', '%I:%M %p'))
get_meridiem(time.strptime('11:59 AM', '%I:%M %p'))

rawDescription: How to access meridiem of a time in Python?

description: Access meridiem of a time in Python


code:
from lxml import etree
city='Boston'
country='USA'
info = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+city +','+ country +'&mode=xml')
doc = etree.fromstring(info.text)
doc.find('city').find('coord').get('lon')
doc.xpath('/current/city/coord/@lon')[0]

rawDescription: How to extract information out of an api in python

description: Extract information out of an api in python


code:
class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def printLabel(self, str):
        print(str)

    def logLabel(self, str):
        '''log to a file'''
        pass

    @QtCore.pyqtSlot(int)
    def on_sld_valueChanged(self, value):
        self.lcd.display(value)
        self.printLabel(value)
        self.logLabel(value)

    def initUI(self):

        self.lcd = QLCDNumber(self)
        self.sld = QSlider(Qt.Horizontal, self)

        vbox = QVBoxLayout()
        vbox.addWidget(self.lcd)
        vbox.addWidget(self.sld)

        self.setLayout(vbox)
        self.sld.valueChanged.connect(self.on_sld_valueChanged)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Signal & slot')

rawDescription: PyQt proper use of emit() and pyqtSignal()


rawDescription: order of parameters of function call of python

description: Order of parameters of function call of python


code:
def apicall(color=None, size=None):
    pass # Do stuff

color = request.GET.get('color')
size = request.GET.get('size')
apicall(color, size)

rawDescription: Python -- Only pass arguments if the variable exists


code:
overhead =  df.loc[df['Exercise 2'] == 'Overhead press', 'Weight(LB)2']
bench =  df.loc[df['Exercise 2'] != 'Overhead press', 'Weight(LB)2']
# etc...

rawDescription: Access column in data frame that shares a name with other columns


code:
import numpy as np
storageMatrix=np.empty((4,9),dtype='object')

rawDescription: Simple question: In numpy how do you make a multidimensional array of arrays?


code: profile.run('runCombinationCheckingMethod(triadicIteractionFirstPrinciple, [], {"signsQty" : 15})')

rawDescription: Why is triadic iteration 2 times slower than the recursion?


code: ['"5" is a magic number.', '"6" is a magic number.', '"7" is a magic number.', '"8" is a magic number.']

rawDescription: What‘s the best way to pick out string of a specific pattern in python?


code:
if __name__ == '__main__':
    procs = []
    for i in range(4):
        p = multiprocessing.Process(target=worker, args=(i,))
        p.start()
        procs.append(p)
    for p in procs:
        p.join()

rawDescription: Multiprocessing, how to run processes in parallel without creating zombies?


code:
from mpl_toolkits.mplot3d import art3d
from mpl_toolkits.mplot3d import proj3d
from mpl_toolkits.mplot3d import axis3d

rawDescription: How to update 3D arrow animation in matplotlib

description: Update 3D arrow animation in matplotlib


rawDescription: matrix array plotting opposite of what i want matplotlib

description: Matrix array plotting opposite of what i want matplotlib


code: proc = subprocess.Popen('echo "$MY_ENV_VAR"', env=environ, shell=True)

rawDescription: How to get PID via subprocess.Popen with custom environment variable?

description: Get PID via subprocess.Popen with custom environment variable


rawDescription: How to detect identical part(s) inside string?

description: Detect identical part(s) inside string


rawDescription: How to kill a terminal after completion of process

description: Kill a terminal after completion of process


code:
with open('text.txt') as f:
    data = [line.split() for line in f.readlines()]
    out = [(float(k), float(v)) for k, v in data]

rawDescription: I need to read in a text file with data into python and assign the data the variables


code: [line.rstrip('\n') for line in file]

rawDescription: Reading a file without newlines

description: Reading a file without newlines


code:
slices = {
    'a': 10,
    'b': 10,
    'c': 20
}

dct = {k: sorted(l, reverse=True)[:slices[k]]
    for k, l in dct.items()}

rawDescription: Slicing a dictionary of list

description: Slicing a dictionary of list


code: #define Py_SIZE(ob)     (((PyVarObject*)(ob))->ob_size)

rawDescription: Get index of recently appended item

description: Get index of recently appended item


code: print(mergesort(ent))

rawDescription: Python - Merge Sort Recursive Algorithm

description: Python - Merge Sort Recursive Algorithm


rawDescription: Python: find area of polygon from xyz coordinates


code: map(lambda n: (lambda f, *a: f(f, *a))(lambda rec, n: 1 if n == 0 else n*rec(rec, n-1), n), range(10))

rawDescription: Can a lambda function call itself recursively in Python?


code:
@celery.task
def fetch(url):
    # fetch url
    return html

@celery.task
def parse(html):
    pass

rawDescription: What is the proper way to shedule Celery tasks to maximize worker productivity?


rawDescription: Reading comma-separated words into pandas


code:
b=np.array([np.datetime64(x.isoformat(),'s') for x in a])
b

rawDescription: Select specified month date from numpy array (datetime object)


code: [keys, values] = zip(*[(k, v) for k, vs in d.items() for v in vs])

rawDescription: From dictionary of lists to two lists of same length


code:
len(syllables)
gibberish(4)
gibberish(5)
gibberish(10)

rawDescription: Any Python password-generators that are readable and pronounceable?


code:
a = dict((hash_counting_int(x), []) for x in range(10))
[x.count for x in a.keys()]
b = dict(a)
[x.count for x in a.keys()]
for n, v in enumerate(b.itervalues()):
    v.append(n)

[x.count for x in a.keys()]
b

rawDescription: How to avoid rehashing dict keys?

description: Avoid rehashing dict keys


rawDescription: Run multiple subprocesses in foreach loop? One at the time?


rawDescription: How should I grab pairs from a list in python?


code: url(r'^index', PostListView.as_view())

rawDescription: Django pass parameter to web page via ListView class


code:
a()
a

rawDescription: Can I add function references to a list, and iterate over this list calling each in succession?

description: Add function references to a list, and iterate over this list calling each in succession


rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
def removeLine(n, file):
    f = open(file,"r+")
    d = f.readlines()
    f.seek(0)
    for i in range(len(d)):
        if i > n:
            f.write(d[i].replace(d[i].split(",")[0],str(i -1)))
        elif i != n:
            f.write(d[i])
    f.truncate()
    f.close()

rawDescription: python delete specific line and re-assign the line number

description: Python delete specific line and re-assign the line number


code:
class A(object):
  _class_path = 'mymodule.A'
  class B(object):
    _class_path = 'mymodule.A.B'
    ...

rawDescription: getting the class path or name space of a class in python even if it is nested

description: Getting the class path or name space of a class in python even if it is nested


rawDescription: Check if the Main Thread is still alive from another thread


code:
def consolidate(sets):
    # http://rosettacode.org/wiki/Set_consolidation#Python:_Iterative
    setlist = [s for s in sets if s]
    for i, s1 in enumerate(setlist):
        if s1:
            for s2 in setlist[i+1:]:
                intersection = s1.intersection(s2)
                if intersection:
                    s2.update(s1)
                    s1.clear()
                    s1 = s2
    return [s for s in setlist if s]

def group_ids(pairs):
    groups = consolidate(map(set, pairs))
    d = {}
    for i, group in enumerate(sorted(groups)):
        for elem in group:
            d[elem] = i
    return d

rawDescription: Grouping Data into Clusters Based on DataFrame Columns


code:
class Range:
  '''
  Represents a range, in the spirit of Guava's Range class.
  Endpoints can be absent, and (presently) all ranges are openClosed.
  There's little reason to use this class directly, as the range()
  builtin provides this behavior for integers.
  '''
  def __init__(self, start, end, increment=1):
    if start and end and end < start:
      raise ValueError("End date cannot be before start date, %s:%s" % (start,end))
    self.start = start
    self.end = end
    self.increment = increment

  def __repr__(self):
    return '[%s\u2025%s)' % (
      self.start or '-\u221E',
      self.end   or '+\u221E'
    )

  def __eq__(self, other):
    return self.start == other.start and self.end == other.end

  def __hash__(self):
    return 31*hash(self.start) + hash(self.end)

  def __iter__(self):
    cur = self.start
    while cur < self.end:
      yield cur
      cur = cur + self.increment

  def __contains__(self, elem):
    ret = True
    if self.start:
      ret = ret and self.start <= elem
    if self.end:
      ret = ret and elem < self.end
    return ret

class DateRange(Range):
  '''A range of dates'''
  one_day = timedelta(days=1)

  @staticmethod
  def parse(daterange):
    '''Parses a string into a DateRange, useful for
    parsing command line arguments and similar user input.
    *Not* the inverse of str(range).'''
    start, colon, end = daterange.partition(':')
    if colon:
      start = strToDate(start) if start else None
      end = strToDate(end) if end else None
    else:
      start = strToDate(start)
      end = start + DateRange.one_day
    return DateRange(start, end)

  def __init__(self, start, end):
    Range.__init__(self, start, end, DateRange.one_day)

def strToDate(date_str):
  '''Parses an ISO date string, such as 2014-2-20'''
  return datetime.datetime.strptime(date_str, '%Y-%m-%d').date()

rawDescription: Representing a Range of values as a Python Sequence Type


code: split_string("Before the rain ... there was lightning and thunder.", " .")

rawDescription: Splitting Strings in Python with Separator variable


code: filter(lambda d: None not in d.values(), ToD)

rawDescription: How should I remove all dicts from a list that have None as one of their values?


rawDescription: Regex to match MAC address and also extract it's values


code:
import timeit, random
testset = {random.randrange(50000) for _ in xrange(1000)}
tests = [random.randrange(5000) for _ in xrange(500)]
timeit.timeit('for i in tests: i in s',
              'from __main__ import testset as s, tests',
              number=100000)
timeit.timeit('for i in tests: s.__contains__(i)',
              'from __main__ import testset as s, tests',
              number=100000)

rawDescription: python 2.7 writing "x in set" vs "set.__contains__(x)"

description: Python 2.7 writing "x in set" vs "set.__contains__(x)"


code:
# scan.py
import functools
from scipy.optimize import minimize
import random, my_model

for i in range(5):
    m = random.randint(0,10)
    k = random.randint(0,10)
    minimize(functools.partial(my_model.V, m, k), 0)

rawDescription: Python structuring - Do I really need a class?


code:
res = []
for animal in your_list:
    res.append(animal in animal_list)

rawDescription: List of Elements to Boolean Array

description: List of Elements to Boolean Array


code:
def foo(a, b):
    return locals()
foo(1, 2)
def foo(a, b, c, d, e):
    return locals()
foo(1, 2, 3, 4, 5)

rawDescription: packing named arguments into a dict

description: Packing named arguments into a dict


code: reduce(lambda x, y: x[y], index[:-1], array)[index[-1]] = new_value

rawDescription: Indexing into a nested array of arbitrary dimension?


code:
class DBTask(Task):
    _session = None

    def after_return(self, *args, **kwargs):
        if self._session is not None:
            self._session.remove()

    @property
    def session(self):
        if self._session is None:
            _, self._session = _get_engine_session(self.conf['db_uri'],
                                                   verbose=False)

        return self._session

rawDescription: how to setup sqlalchemy session in celery tasks with no global variable

description: Setup sqlalchemy session in celery tasks with no global variable


code:
FIRST_ROW_NUM = 1  # or 0
ROWS_TO_DELETE = {1, 3}

with open('infile.csv', 'rt') as infile, open('outfile.csv', 'wt') as outfile:
    outfile.writelines(row for row_num, row in enumerate(infile, FIRST_ROW_NUM)
                        if row_num not in ROWS_TO_DELETE)

rawDescription: Select row to be deleted in csv file in python


code:
#!/usr/bin/env python
import time
import logging
import threading
from gi.repository import Gtk

class Worker(threading.Thread):
    should_record = False
    quit = False

    def run(self):
        while not self.quit:
            if self.should_record:
                logging.warn("recording...")
                # cpu-intensive code here
            else:
                time.sleep(0.1)

class MainWindow(Gtk.Window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.worker = Worker()
        self.worker.start()
        hb = Gtk.Box()
        self.add(hb)
        record = Gtk.Button("Record")
        stop = Gtk.Button("Stop")
        hb.add(record)
        hb.add(stop)

        def command(arg):
            self.worker.should_record = arg

        record.connect("clicked", lambda _b: command(True))
        stop.connect("clicked", lambda _b: command(False))
        # optional, if you want to quit the app on stop as well
        stop.connect("clicked", lambda _b: Gtk.main_quit())

if __name__ == "__main__":
    main = MainWindow()
    try:
        # optional, if you want to support close window to quit app
        main.connect("delete-event", Gtk.main_quit)
        main.show_all()
        Gtk.main()
    finally:
        main.worker.quit = True
        main.worker.join()

rawDescription: gtk infinite loop exit

description: Gtk infinite loop exit


code:
fv = open("filename.txt", 'w') # 'w' for write
for monster in monlist:
    print(monster, file=fv)
fv.close() # close the file

rawDescription: Dictionary creator (Python 3.x)

description: Dictionary creator (Python 3.x)


code:
for i in test[:]:
    if i not in ["C","D"]:
        test.remove(i)

rawDescription: How can I loop through a list of strings?

description: Loop through a list of strings


code: number = int(''.join(str(number) for number in numbers))

rawDescription: Convert an int list into an int number

description: Convert an int list into an int number


code:
import subprocess
import shlex

proc = subprocess.Popen(shlex.split('animate animation.gif'))
proc.communicate()

rawDescription: How to display an animated gif with Linux?

description: Display an animated gif with Linux


code: df['Valid_Quarters'] = df.apply(check_quarters, axis = 1)

rawDescription: Detect errant data over consecutive rows of a Python Pandas DataFrame


code:
from subprocess import check_output

out = check_output(["ls", "-al"])

rawDescription: Read stdout from subprocess until there is nothing left


code:
RunSer2Command(lines2[21])
time.sleep(1)
ls_output = subprocess.Popen(['tcpclient.exe','192.168.4.110','8000','10000','1400'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,bufsize=3)
time.sleep(2)
RunSer2Command(lines2[22])
RunSer2Command(lines2[23])
time.sleep(1)
ls_output.communicate(input = '3')
ls_output.wait()
RunSer2Command(lines2[24])

rawDescription: Using multiple programs simultaneously in Python


rawDescription: pandas count true values in multi-index frame

description: Pandas count true values in multi-index frame


code:
len('asdf')
import sys
sys.getsizeof('asdf')

rawDescription: Python line read size in bytes

description: Python line read size in bytes


rawDescription: Accessing elements in a list of arrays in python


code:
soup = BeautifulSoup(html)

a_tags = soup.select("a[href^=http]")
from pprint import pprint as pp
paired = dict((a.text, a["href"]) for a in a_tags)

pp(paired)

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


code:
def clean_in_place(lst):
    if lst.count(lst[0]) == len(lst):
        lst[:] = [lst[0]]

rawDescription: remove duplicate list elements

description: Remove duplicate list elements


rawDescription: Python: transform a list of lists of tuples


code: [' List2 Element1', ' List2 Element2', ' List2 Element3']

rawDescription: Getting list based on text lxml

description: Getting list based on text lxml


code: install.sh -n

rawDescription: Where is mininet installed to?

description: Where is mininet installed to


rawDescription: Count by > DATE

description: Count by > DATE


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

text = ax.annotate("TESTING", xy=(.5, .5), xytext=(.5, .5),
                  )

text.set_alpha(.4)

plt.show()

rawDescription: Matplotlib text transparency

description: Matplotlib text transparency


code: plt.imshow(Z, extent=(X.min(), X.max(), Y.min(), Y.max()), origin='lower', cmap=cm.RdBu)

rawDescription: How can I plot implicit functions in python?

description: Plot implicit functions in python


code:
d0
d1
d2
d3

rawDescription: Array building in Python

description: Array building in Python


code:
for p in bets.keys():
    if bets[p][0] == TEAM_BLUE:
        payout = total * bets[p][1] / wtotal

rawDescription: Algorithm for betting and particularly winning the bet?


code:
from Bio.Blast.NCBIWWW import qblast
results = qblast("blastn",
                 "nr",
                 "".join(seq),
                 entrez_query='Thermofilum_pendens_Hrk_5')

rawDescription: How do I extract a sequence from a genome based on homologues with a sequence?

description: Extract a sequence from a genome based on homologues with a sequence


rawDescription: Dict merge in a dict comprehension

description: Dict merge in a dict comprehension


code: os.popen('cat /etc/services').read()

rawDescription: Assign output of os.system to a variable and prevent it from being displayed on the screen


code: subprocess.call([ 'ssh', 'localhost', 'echo "one   two"; echo three'])

rawDescription: How to escape ssh quoted shell commands in Python

description: Escape ssh quoted shell commands in Python


code:
#!python3

import os

def isPDFfile(fname):
    name, ext = os.path.splitext(fname)
    return ext.lower() == '.pdf'

if __name__ == '__main__':
    for fname in os.listdir('.'):
        if isPDFfile(fname):
            print(fname, 'is PDF file.')
        else:
            print(fname, 'is not PDF file.')

rawDescription: How to distinguish a PDF file from other files?

description: Distinguish a PDF file from other files


code:
import ansible.runner

runner = ansible.runner.Runner(
   module_name='setup',
   module_args='',
   pattern='dbservers',
)
dbservers_get_facts = runner.run()

rawDescription: Running ansible-playbook using Python API


code:
lookup = defaultdict(list)
wholelookup = defaultdict(list)

mydata = open('summaryfile.txt')
for line in csv.reader(mydata, delimiter='\t'):
    code = re.match('[a-z](\d+)[a-z]', line[-1], re.I)
    if code:
        lookup[line[-2]].append(code.group(1))
        wholelookup[line[-2]].append(code.group(0))

rawDescription: Is there way to use dictionary in python to print 2 outputs: one as string of whole token and one as number


code: list(combiner(13, 2))

rawDescription: generating all permutations of 2 ones and 3 zeroes with itertools

description: Generating all permutations of 2 ones and 3 zeroes with itertools


code:
import matplotlib.pyplot as plt

fig = plt.figure()
fig.add_axes([0.1,0.1,0.5,0.5])
plt.show()

rawDescription: How to set graph (and not figure !) size in matplotlib

description: Set graph (and not figure !) size in matplotlib


rawDescription: Print csv input file into a table of columns/rows


code: desired_output_df = pd.DataFrame(_, columns=['a'])

rawDescription: How to shift entire groups in pandas groupby

description: Shift entire groups in pandas groupby


code:
import regex # $ pip install regex

chars = regex.compile(r"\X").findall # get all characters

def match(word, letters):
    return sorted(chars(word)) == sorted(letters)

words = ["cat", "dog", "tack", "coat"]

print(" ".join(get_words(['o', 'c', 'a', 't'])))
# -> coat
print(" ".join(get_words(['k', 'c', 't', 'a'])))
# -> tack

rawDescription: Regex to get list of all words with specific letters (unicode graphemes)


code:
first_num
first_arr

rawDescription: Unpack a given number of items in Python?


code:
for ip in range(0, 256):
    pool.apply_async(ping, (ip,))

pool.close()
pool.join()

rawDescription: Speed up Python script's for loop

description: Speed up Python script's for loop


rawDescription: python using argparse.ArgumentParser method

description: Python using argparse.ArgumentParser method


code:
t=lambda x:exec(x)
t("print('hello')")

rawDescription: Can I write a lambda function in python of more than one line, and call other functions?

description: Write a lambda function in python of more than one line, and call other functions


code:
a,b = triup(5,5),trido(5,5)
print(a)
print(b)
print(b+a)
print(a + b)

rawDescription: Defining a rhomb by two triangles

description: Defining a rhomb by two triangles


code:
def html_comment(text):
    return '<!-- ' + text.replace('--', '- - ') + ' -->'

rawDescription: Convert text to HTML comment in Python

description: Convert text to HTML comment in Python


rawDescription: Python itertools.combinations' results

description: Python itertools.combinations' results


rawDescription: Superimpose 2 plots in matplotlib - empty plot


code:
user = User.objects.create_user(username, email, password)
user.first_name = firstname
user.last_name = lastname
user.save()

user_profile, created = UserProfile.objects.create_or_create(user=user, role=role)

rawDescription: How to save data in models with oneToOne relationship

description: Save data in models with oneToOne relationship


rawDescription: find all files indirectory and sub-directories and provide the path from directory

description: Find all files indirectory and sub-directories and provide the path from directory


code:
class Foo(date):
    def __new__(cls, year, month=1, day=1):
        return super(Foo, cls).__new__(cls, year, month, day)

rawDescription: Inherit from a built-in class, can't change args of __init__


code:
from datetime import datetime as dt
import datetime

input_date = '2015-11-16'
# convert string to datetime
from_date = dt.strptime(input_date, '%Y-%m-%d').date()
# combine `from_date` with min time value (00:00)
from_date = datetime.datetime.combine(from_date, datetime.time.min)
# combine `from_date` with max time value (23:59:99) to have end date
to_date = datetime.datetime.combine(from_date, datetime.time.max)
posts = Post.objects.filter(created_time__range=(from_date, to_date))

rawDescription: Filter objects with a datetime range (00:00 to 23:59:99) in Django


rawDescription: Convert string to nested structures like list


code:
reads_array = []
for x in Bio.SeqIO.parse("inp.fastq", "fastq"):
    reads_array.append(x)

df = pd.DataFrame(np.zeros((len(reads_array), 2)), columns=["read_id", "score"])

for index, x in enumerate(reads_array):
    alignments = pairwise2.align.globalms("ACTTGAT", str(x.seq), 2, -1, -.5, -.1)
    sorted_alignments = sorted(alignments, key=operator.itemgetter(2), reverse=True)
    read_id = x.name
    score = sorted_alignments[0][2]
    df.loc[index, 'read_id'] = read_id
    df.loc[index, 'score'] = score

rawDescription: appending to a pandas dataframe

description: Appending to a pandas dataframe


rawDescription: Pandas DataFrame.unstack() Changes Order of Row and Column Headers


code:
execfile('parameters.dat')

var_par = 'B'
array = [1.4, 2.6, 4.8, 5.6]

for I in array: # Start choosing the values in array

    if var_par in params: params[var_par][0] = I

    f = open('params_temp.dat', 'w')
    print >> f, 'params = {'
    for p in params:
        if type(params[p][0]) == str:
            print >> f, ''.join(map(str,['"', p,'"',':'])), '\t',
            print >> f, ''.join(map(str,['[', '"', params[p][0], '"', ','])), '\t', ''.join(map(str,['"', params[p][1], '"', ']', ',']))
        else:
            print >> f, ''.join(map(str,['"', p,'"',':'])), '\t',
            print >> f, ''.join(map(str,['[', params[p][0], ','])), '\t', ''.join(map(str,['"', params[p][1], '"', ']', ',']))
    print >> f, '}'
    f.close()
    os.remove('parameters.dat')
    os.rename('params_temp.dat', 'parameters.dat')

    execfile('script.py')

rawDescription: Replace dictionary value in a separate file


rawDescription: Convert binary string to int

description: Convert binary string to int


rawDescription: Simplify conditional integrals in SymPy

description: Simplify conditional integrals in SymPy


code:
import pandas as pd

data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)

spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)

rawDescription: Pandas: find column whose name contains a specific string


code:
def new_variable():
    name = input("Give your new variable a name! ")
    value = input("Give your new variable a value! ")
    globals()[name] = value
new_variable()
print(foo)

rawDescription: Why would people use globals() to define variables


rawDescription: How do I specify different date ranges for CustomBusinessDays holidays in Pandas?

description: Specify different date ranges for CustomBusinessDays holidays in Pandas


code:
def foo():
    """sample doc"""
    print(foo.__doc__)

foo()  # prints sample doc

rawDescription: How to print your function's documentation python

description: Print your function's documentation python


code: print("foo")

rawDescription: Overwrite built-in function

description: Overwrite built-in function


code: lister(List1, List2, List3)

rawDescription: How do you make a table out of multiple list in list?

description: Make a table out of multiple list in list


code:
a = np.arange(16).reshape((4, 4))
a
a[0]  # access the first "row" of data
a[0, 2]  # access the 3rd column (index 2) in the first row of the data

rawDescription: Numpy array slicing using commas

description: Numpy array slicing using commas


code: T2 = tuple([(x, y, z) for (x, y), z in d.items()])

rawDescription: Summing similar elements within a tuple-of-tuples


code:
# create the tables
Base.metadata.create_all(engine)

rawDescription: SqlAlchemy filter by time difference

description: SqlAlchemy filter by time difference


code:
x
out
counts

rawDescription: Summation of only consecutive values in a python array


code:
fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "chicken"
for name in fridge:
    if name == food_sought:
        print("I was able to find a something in our list of food: %s : %s" % (food_sought, fridge[food_sought]))
        break
else:
    print("We couldn't find the food you were looking for")

rawDescription: trying to iterating over dictionary but when the element is not found, else statement is not called, last key is printed instead

description: Trying to iterating over dictionary but when the element is not found, else statement is not called, last key is printed instead


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

space = np.zeros((100, 100, 100), dtype=np.uint8)

x, y, z = np.random.randint(100, size=(3, 1000))
space[x, y, z] += 1

space_ps = np.abs(np.fft.fftn(space))
space_ps *= space_ps

space_ac = np.fft.ifftn(space_ps).real.round()
space_ac /= space_ac[0, 0, 0]

rawDescription: Power Spectrum and Autocorrelation of Data in Numpy


rawDescription: Loop Issue with Local Variable

description: Loop Issue with Local Variable


rawDescription: Build diagonal matrix without using for loop


code:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item, Field
import urlparse

class CustomItem(Item):
    image_urls = Field()
    image_names = Field()
    images = Field()

class ImageSpider(BaseSpider):
    name = "customimg"
    allowed_domains = ["www.python.org"]
    start_urls = ['http://www.python.org']

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//img')
        items = []
        for site in sites:
            item = CustomItem()
            item['image_urls'] = [urlparse.urljoin(response.url, u) for u in site.select('@src').extract()]
            # the name information for your image
            item['image_name'] = ['whatever_you_want']
            items.append(item)
        return items

rawDescription: Scrapy: customize Image pipeline with renaming defualt image name


code:
state_abbrs = {}
for name in range(state_sheet.nrows):  #a sheet with state names in col 0, state abrevs in col 1
    state_name = state_sheet.cell_value(name, colx=0)
    state_abrev = state_sheet.cell_value(name, colx=1)
    state_abbrs[state_name.lower()] = state_abbr

rawDescription: best way to check every cell of a spreadsheet against every cell of another?

description: Check every cell of a spreadsheet against every cell of another


code: means = contracts.groupby(['State', 'Year'])['$'].mean()

rawDescription: Pandas Groupby with multiple columns selecting rows with full range of values


rawDescription: Python Sorting Regular Expression

description: Python Sorting Regular Expression


rawDescription: Counting Occurrences Across Dataframe Rows


code:
x=[2,5,7,10]
y=[3.3,5.6,2.1,-.5]
line,= matplotlib.pyplot.plot(x,y)
add_labels(line)

rawDescription: Data value at each marker

description: Data value at each marker


code:
import sys; sys.version_info
string='\x9f'
array=bytearray(string)
array
str(array)

rawDescription: How to convert bytearray with non-ASCII bytes to string in python?

description: Convert bytearray with non-ASCII bytes to string in python


code:
w.writerow(header)
for row in values:
    w.writerow(row)

rawDescription: Write a simple list into a new CSV file

description: Write a simple list into a new CSV file


code:
from cherrypy import config, engine, tree

config.update(configfile)
tree.mount(ShowHTML(htmlfile), '/', configfile)
if hasattr(engine, "signal_handler"):
    engine.signal_handler.subscribe()
if hasattr(engine, "console_control_handler"):
    engine.console_control_handler.subscribe()

engine.start()
webbrowser.open("http://127.0.0.1:8080")
engine.block()

rawDescription: Launching browser within CherryPy

description: Launching browser within CherryPy


code:
import ctypes

def get_display_name():
    GetUserNameEx = ctypes.windll.secur32.GetUserNameExW
    NameDisplay = 3

    size = ctypes.pointer(ctypes.c_ulong(0))
    GetUserNameEx(NameDisplay, None, size)

    nameBuffer = ctypes.create_unicode_buffer(size.contents.value)
    GetUserNameEx(NameDisplay, nameBuffer, size)
    return nameBuffer.value

rawDescription: How to get Windows user's full name in python?

description: Get Windows user's full name in python


code:
from datetime import datetime
from time import mktime

birthdate = time.strptime('6/8/1980', '%m/%d/%Y')
self.d_birthdate = datetime.fromtimestamp(mktime(birthdate))

rawDescription: Python date object for MongoDB

description: Python date object for MongoDB


rawDescription: Cannot update user email addresses via Google Admin Directory API Client Library for Python


code:
for key, const in list_of_constellations.items():
    globals()[const[0]] = v  # set "And" to 0, etc.

rawDescription: Runtime injection of attributes into module namespace


code: re.sub(r'\{cite web.*?[\r\n]+.*?\}\}', lambda m: re.sub('\s*[\r\n]\s*', '', m.group(0)), inputtext, flags=re.DOTALL)

rawDescription: Python regex on wikitext template

description: Python regex on wikitext template


code:
import numpy as np
b = np.arange(5)
b
b.mean()

rawDescription: Mean of object variables in a python array


code:
def testing(n):
   return n
testing = my_dec(100)(testing)

rawDescription: Decorators with arguments

description: Decorators with arguments


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

fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax2 = fig.add_axes([0.2, 0.3, 0.25, 0.3])

#Plot page from a book
im = plt.imread("./book_page.jpg")
implot = ax1.imshow(im, origin='lower')

# Plot a graph and set background to transparent
x = np.linspace(0,4.*np.pi,40)
y = np.sin(x)
ax2.plot(x,y,'-ro',alpha=0.5)
ax2.set_ylim([-1.1,1.1])
ax2.patch.set_alpha(0.0)

from matplotlib import rc
rc('text', usetex=True)
margin = im.shape[0]*0.075
ytext = im.shape[1]/2.+10
ax1.text(margin, ytext, "The following text is an example")
ax1.text(margin, 90, "Figure 1. Showing a sine function")

plt.show()

rawDescription: matplotlib: jpg image special effect/transformation as if its on a page of an open book

description: Matplotlib: jpg image special effect/transformation as if its on a page of an open book


code:
from types import MethodType, FunctionType
methodtypes = set((MethodType, FunctionType, classmethod, staticmethod))

def methods_in_order(cls):
    "Given a class or instance, return its methods in the order they were defined."
    methodnames = (n for n in dir(cls) if type(getattr(cls, n)) in methodtypes)
    return sorted((getattr(cls, n) for n in methodnames),
                  key=lambda f: getattr(f, "__func__", f).func_code.co_firstlineno)

rawDescription: Is there a way to programatically determine the order in which functions are declared in a python module?


rawDescription: Break from array and run another function in python


code:
extruded = np.zeros((N, 10,10))
extruded[range(N), cords[:,2], cords[:,0]] = 1

grid = np.zeros((10,10))
for atom, proj in atom_proj.iteritems():
    centers = extruded[atoms==atom].sum(0)
    projected = nd.convolve(centers, proj)
    grid += projected

rawDescription: Projecting Coordinates in Numpy array

description: Projecting Coordinates in Numpy array


code:
d = {}
for item in search:
    items = item.split('=')
    d[items[0]] = items[1]
results = results.filter(**d)

rawDescription: Arbitrary number of search terms

description: Arbitrary number of search terms


code:
import sched
import time

def print_something(x):
    print(x)

def busy_wait(target):
    while time.monotonic() < target:
        pass

s = sched.scheduler(delayfunc=busy_wait)

s.enter(1, 0, print_something, ['first'])
s.enter(2, 0, print_something, ['second'])
s.run()

rawDescription: How to invoke a function at an exactly given time point in Python?

description: Invoke a function at an exactly given time point in Python


code:
class MySerializer(serializers.Serializer):
    afield = KeyValueField(labels={0:'enum text 0', 1:'enum text 1'})

rawDescription: Serialize and De-serialize a Django Enum field to accept Numerical and Text representation


code:
daily_totals = df.groupby('date').hits.sum()
daily_totals

rawDescription: Reshaping tables in pandas

description: Reshaping tables in pandas


code:
docs = sorted(doc_hash.itervalues(), key=operator.attrgetter('score'), reverse=True)
for i, doc in enumerate(docs):
    doc.rank = i

rawDescription: Python hash table design

description: Python hash table design


code: dates.groupby('client')['date'].apply(lambda x: np.mean([i / np.timedelta64(1, 'D') for i in np.diff([pd.to_datetime(c) for c in x])[0]]))

rawDescription: Finding Date difference in list of dates [Pandas]


code:
num_seqs = 50
max_id_len = 60
numpy.empty((num_seqs, 1), dtype='S{:d}'.format(max_id_len))

rawDescription: Biopython SeqIO to Pandas Dataframe

description: Biopython SeqIO to Pandas Dataframe


code:
lst = ['blabla', 10, 'something']
with open("/path/to/file", "a+") as myfile:
    myfile.write(",".join(map(str, lst)))

rawDescription: Python - how to write strings to file without quotes and spaces?


rawDescription: Pandas recalculate index after a concatenation


rawDescription: python multidimensional list.. how to grab one dimension?

description: Python multidimensional list.. how to grab one dimension


code:
guesses = [['o', 'o', 'o', 'o'], ['r', 'r', 'r', 'r']]
clues = [['b'], ['b', 'b']]
def print_game(Guesses, Clues):
    print("Guesses", "Clues", sep='\t')
    for guess, clue in zip(Guesses, Clues):
        print(' '.join(guess), ' '.join(clue), sep='\t')

print_game(guesses, clues)

rawDescription: Python formatting lists of lists

description: Python formatting lists of lists


code:
from sklearn.externals import joblib
model_clone = joblib.load('my_model.pkl')

rawDescription: Python scikit-learn: exporting trained classifier


rawDescription: Python - using dictionary to count keys and values


rawDescription: Iterating through multi-dimentional lists while remembering indices


code:
from itertools import groupby

len_ab = len(a) + len(b)
groups = groupby(((a[len(a)*i//len_ab], b[len(b)*i//len_ab]) for i in range(len_ab)),
                 key=lambda x:x[0])
[j[i] for k,g in groups for i,j in enumerate(g)]

rawDescription: How to elegantly interleave two lists of uneven length in python?

description: Elegantly interleave two lists of uneven length in python


code:
import csv
my_list = []
with open('Test.csv') as csvfile:
    spamreader = csv.reader(csvfile)
    for row in spamreader:
        my_list.append(row)
print(my_list)

rawDescription: Get row index instead of columns in csv file


code: id_produto = str(ID+'*')

rawDescription: Python Find script

description: Python Find script


code:
def byte_offset(a):
    """Returns a 1-d array of the byte offset of every element in `a`.
    Note that these will not in general be in order."""
    stride_offset = np.ix_(*map(range,a.shape))
    element_offset = sum(i*s for i, s in zip(stride_offset,a.strides))
    element_offset = np.asarray(element_offset).ravel()
    return np.concatenate([element_offset + x for x in range(a.itemsize)])

def share_memory(a, b):
    """Returns the number of shared bytes between arrays `a` and `b`."""
    a_low, a_high = np.byte_bounds(a)
    b_low, b_high = np.byte_bounds(b)

    beg, end = max(a_low,b_low), min(a_high,b_high)

    if end - beg > 0:
        # memory overlaps
        amem = a_low + byte_offset(a)
        bmem = b_low + byte_offset(b)

        return np.intersect1d(amem,bmem).size
    else:
        return 0

rawDescription: Is there a way to check if NumPy arrays share the same data?


rawDescription: How to turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)

description: Turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)


code:
import pandas as pd

def strip(text):
    try:
        return text.strip()
    except AttributeError:
        return text

def make_int(text):
    return int(text.strip('" '))

table = pd.read_table("data.csv", sep=r',',
                      names=["Year", "Make", "Model", "Description"],
                      converters = {'Description' : strip,
                                    'Model' : strip,
                                    'Make' : strip,
                                    'Year' : make_int})
print(table)

rawDescription: How can I remove extra whitespace from strings when parsing a csv file in Pandas?

description: Remove extra whitespace from strings when parsing a csv file in Pandas


rawDescription: How to get keyword arguments for a function

description: Get keyword arguments for a function


code: bar.rangeChanged.connect( lambda x,y: bar.setValue( 9999 ) )

rawDescription: pyside - auto scroll down in qscrollarea

description: Pyside - auto scroll down in qscrollarea


rawDescription: python sorting array of XYZ coordinates in table matrix

description: Python sorting array of XYZ coordinates in table matrix