code:
your_array = [[2, 3, 4], [3, 5, 6], [8, 7, 9]]
np.savetxt("filename.txt", your_array, fmt="%d")

rawDescription: Writing numpy arrays to files

description: Writing numpy arrays to files


rawDescription: python using popen without shell, or assert to increase safety

description: Python using popen without shell, or assert to increase safety


path: src

Documentation

path: docs

List

shell_cmd: ls -l

rawDescription: How to make the anaconda plugin use a custom interpreter (virtualenv)?

description: Make the anaconda plugin use a custom interpreter (virtualenv)


code:
unique_id = '11223|14589'
foo.find({'id': unique_id})

rawDescription: Using JSON in Python to send query to MongoDB


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

# generate temperatures
np.random.seed(0)
N, sigma = 1000, 5
trend = np.sin(4 / N * np.arange(N)) * 30
alltemps = np.array([tmp0 + trend + sigma*np.random.randn(N)
                     for tmp0 in [70, 50, 40]])

# generate attitudes:
altitudes = np.array([500, 1500, 4000]).astype(float)
location = np.linspace(altitudes[0], altitudes[-1], N)

def doit():
    """ do the interpolation, improved version for speed """
    AA = np.vstack([np.abs(altitudes-a_i) for a_i in altitudes])
    # This is slighty faster than np.linalg.solve(), because AA is small:
    cc = np.dot(np.linalg.inv(AA), alltemps)

    return (cc[0]*np.abs(location-altitudes[0]) +
            cc[1]*np.abs(location-altitudes[1]) +
            cc[2]*np.abs(location-altitudes[2]))

t_loc = doit()  # call interpolator

# do the plotting:
fg, ax = plt.subplots(num=1)
for alt, t in zip(altitudes, alltemps):
    ax.plot(t, label="%d feet" % alt, alpha=.5)
ax.plot(t_loc, label="Interpolation")
ax.legend(loc="best", title="Altitude:")
ax.set_xlabel("Time")
ax.set_ylabel("Temperature")
fg.canvas.draw()

rawDescription: Fast linear interpolation in Numpy / Scipy "along a path"


code: output = [sub.split('\t') for sub in my_list]

rawDescription: Partitioning elements in list by \t . Python


code:
f=open('C:\\Python33\\text file.txt','r')

for c in iter(lambda: f.read(1),'\n'):
    print(c)

rawDescription: Returning yield of lambda within iter

description: Returning yield of lambda within iter


code:
c = ['nan'] * len(a)
for i, j in zip(aindex, lindex):
    c[j] = al3[i]

c

rawDescription: Python : creating an array from list with given indices


code:
class UserForm(ModelForm):

    enabled = forms.BooleanField(default=True)

    class Meta:
        model = User
        fields = ['name', 'email', ...]

rawDescription: Django : ModelForm with OneToOneField

description: Django : ModelForm with OneToOneField


code:
cols = ['a', 'b', 'c'] # a list of columns to test
df[cols] > 0

rawDescription: making new column in pandas dataframes based on filter

description: Making new column in pandas dataframes based on filter


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

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))
width = 0.65

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(ind+width+0.35, b, 0.45, color='#deb0b0')

ax2 = ax.twinx()
ax2.bar(ind+width, a, width, color='#b0c4de')

ax.set_xticks(ind+width+(width/2))
ax.set_xticklabels(a)

ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

plt.tight_layout()
plt.show()

rawDescription: Two bar charts in matplotlib overlapping the wrong way


code:
from subprocess import STDOUT

output = qx(cmd, stderr=STDOUT)

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


code:
wb = xlwt.Workbook()
for (sheet_number, sublist) in enumerate(lst):
    ws = wb.add_sheet('sheet_%s', sheet_number + 1)
    for (rownum, rowlist) in enumerate(sublist):
        for (colnum, value) in enumerate(rowlist):
            ws.write(rownum, colnum, value)

rawDescription: How to create a tabular data structure from a list of sublists with Gpread or XLWT?

description: Create a tabular data structure from a list of sublists with Gpread or XLWT


code:
from __future__ import print_function
import pandas as pd
import numpy as np

raw_data = [['OCT 27, 2015',2,4,6,8],['NOV 03, 2015',1,5,9,2],['NOV 05, 2015',2,4,6,8]]
pandas_data = pd.DataFrame(raw_data, columns=['Date', 'A', 'B', 'C', 'D'])
pandas_data["Date"] = pd.to_datetime(pandas_data["Date"])
print(pandas_data)
print(pandas_data.mean())

rawDescription: Categorize Data by Day of Week Python

description: Categorize Data by Day of Week Python


code:
a.name: MyClass_0
b.name: MyClass_1
c.name: MyClass_2

rawDescription: Ensure uniqueness of instance attribute in python


rawDescription: recursively traverse multidimensional dictionary, dimension unknown

description: Recursively traverse multidimensional dictionary, dimension unknown


code: {k: sum(i for i in v if isinstance(i, int)) for k, v in d.items()}

rawDescription: Python how to get sum of numbers in a list that has strings in it as well


code:
from matplotlib import pyplot as plt
from adjustText import adjust_text
import numpy as np

np.random.seed(2016)
xs = np.arange(10, step=0.1)+np.random.random(100)*3
ys = np.arange(10, step=0.1)+np.random.random(100)*3
labels = np.arange(100)

f = plt.figure()
scatter = plt.scatter(xs, ys, s=15, c='r', edgecolors='w')
texts = []
for x, y, s in zip(xs, ys, labels):
    texts.append(plt.text(x, y, s, bbox={'pad':0, 'alpha':0}))

#plt.show()

rawDescription: "Repel" annotations in matplotlib?

description: "Repel" annotations in matplotlib


code:
def parse_shot_success(string):
    pp = re.compile("(scores|misses|blocks)")
    match = pp.search(string)

    if not match:
        # https://docs.python.org/dev/library/re.html#re.search
        # "Return None if no position in the string matches the pattern"
        return "not a shot"
    elif match.group(1) == "scores":
        return "scores"
    elif match.group(1) in ("blocks", "misses"):
        return "misses"
    else:
        raise AssertionError

rawDescription: Searching fro string and converting it to another string python


code:
from functools import partial

foo = Foo()
integrand_func = partial(Foo._integrand, foo)

rawDescription: Use a class method as an integrand to GSL QAGS


code:
import json
with open("logfile.json", "r") as logfile:
    records = json.load(logfile)

rawDescription: How to categorize and count imported data

description: Categorize and count imported data


code:
def main(filename):
    print(filename)

if __name__ == "__main__":
    import sys
    main(sys.argv[1])

rawDescription: Equivalent of Ipython run command in normal python


code:
class C(A, B):
    _x = None

    @property
    def x(self):
        if self._x is not None:
            return self._x
        return self.a + self.y

    @x.setter
    def x(self, val):
        self._x = val

rawDescription: Override a field in parent class with property in child class


code:
twython/streaming/api.py._request
if self.retry_count and (self.retry_count - retry_counter) > 0:
    time.sleep(self.retry_in)
    retry_counter += 1
    _send(retry_counter)

rawDescription: How to disconnect the streaming on the exact date & time

description: Disconnect the streaming on the exact date & time


code: np.sum(A, axis=2)

rawDescription: Python 2.7: looping over 1D fibers in a multidimensional Numpy array


code:
object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rdiv__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)

rawDescription: Handle operation by object on right side (__r*__ methods)


code:
keys = {}
keys.update(dict.fromkeys('qwertyuiop', 1))
keys.update(dict.fromkeys('asdfghjkl', 2))
keys.update(dict.fromkeys('zxcvbnm,', 3))

rawDescription: What's the most pythonic way to build this dictionary?


code:
from Tkinter import *
import pickle

root=Tk()
dic={}

class Launch(object):
    def __init__(self, root):
        self.load()  # <-- load
        root.title("Choose Client")
        self.row = 3
        for key in dic:
            Label(root, text=key).grid(row=self.row, column=0)
            self.row += 1
        l3=Label(root, text="Client Name")
        l3.grid(row=0, column=0)
        self.e1=Entry(root)
        self.e1.grid(row=0, column=1)
        l4=Label(root, text="Client age")
        l4.grid(row=1, column=0)
        self.e2=Entry(root)
        self.e2.grid(row=1, column=1)
        b3=Button(root, text="Create client", command=self.add)
        b3.grid(row=2)

    def add(self):
        client=self.e1.get()
        age=self.e2.get()
        dic[client]=age
        Label(root, text=client).grid(row=self.row)
        self.row += 1  # <--- increase row count
        with open("data", "wb") as f:
            pickle.dump(dic, f)

    def load(self):
        # should be declared, otherwise, will create local variable
        global dic
        try:
            dic = pickle.load(open("data", "rb"))
        except IOError:  # if file does not exist.
            pass

app = Launch(root)
root.mainloop()

rawDescription: Pickling dictionary data then loading it doesn't work


code:
class Reader (object):
    def __init__(self):
        self.files = []

    def add(self, src):
        self.files.append(src)

    def read(self, nbytes=0):
        if not len(self.files):
            return bytes()

        data = bytes()
        while True:
            data = data + self.files[0].read(nbytes - len(data))
            if len(data) == nbytes:
                break

            self.files[0].close()
            self.files.pop(0)
            if not len(self.files):
                break

        return data

rawDescription: Parse large split XML file(s) with Python


rawDescription: Group by multiple keys and summarize/average values of a list of dictionaries


code:
from flask import Response, json, render_template, jsonify
from app import app
from motifs import get_motif, get_motif_list

@app.route('/ajax')
def ajax() :
    motifs = get_motif_list(10)
    return Response(json.dumps(motifs), mimetype='application/json')

@app.route("/")
def index():
     return render_template("index.html")

rawDescription: JSON passed from Python (Flask) into JavaScript is displaying on screen


rawDescription: How to pickle individual steps in sklearn's Pipeline?

description: Pickle individual steps in sklearn's Pipeline


code:
start_value = 10;
end_value = 20;
for i in range(start_value, end_value):
  print(i)

rawDescription: How to write a special for loop case of C++ in Python?

description: Write a special for loop case of C++ in Python


code:
from sys import argv as v
v=__import__('sys').argv

rawDescription: What is the shortest way to get argument passed into program?


code: B

rawDescription: How to create equal spaced values in between unequal spaced values in Python?

description: Create equal spaced values in between unequal spaced values in Python


code:
import scipy as sp

interpolator = sp.interpolate.interp1d(origdata['time'], origdata['vals'], kind='zero')

filledOutData2 = {}
filledOutData2['time'] = range(origdata['time'][0],origdata['time'][-1])
filledOutData2['vals'] = interpolator(filledOutData2['time'])

rawDescription: Function that copies last value for each second until next datapoint in Python 2.7, piecewise constant interpolation (Solved)


code:
mat = np.random.randn(2,3)
mat

rawDescription: Storing these vectors but which data structure to use in Python


code:
with open('somefilename') as f:
    tokenized = read_by_tokens(f)

    # read first two tokens separately
    first_token = next(tokenized)
    second_token = next(tokenized)

    for token in tokenized:
        # loops over all tokens *except the first two*
        print(token)

rawDescription: Python: Read whitespace separated strings from file similar to readline


rawDescription: pandas: groupby and unstack to create feature vector for classification

description: Pandas: groupby and unstack to create feature vector for classification


code:
class MySerializer(serializers.ModelSerializer):

    def to_internal_value(self, data):
       if 'member_profile' not in data:
           data['member_profile'] = {}
       return super(MySerializer,self).to_internal_value(data)

rawDescription: Overriding Django-Rest-Framework serializer is_valid method


rawDescription: Python: Math expression parsing

description: Python: Math expression parsing


rawDescription: Can argparse in python 2.7 be told to require a minimum of TWO arguments?


code: step1 = sorted(start) #if you have duplicates, sorted(set(start)) to uniquify

rawDescription: Python reduce a list by order

description: Python reduce a list by order


code:
coalesce = (g for key, g in groupby(f, key=lambda x: x[:1] == "A") if key)
runs = [[res.partition(':')[-1].strip() for res in group] for group in coalesce]

rawDescription: Using `itertools.groupby()` to get lists of runs of strings that start with `A`?


code:
a = [1, 2, 3]
a.append(4)
a
print(a.append(5))
a

rawDescription: type of variable through indentation of loops Python

description: Type of variable through indentation of loops Python


code: re.split(r'$\n\n', 'Cool\n\nNew paragraph\nruns here\n\nAnother paragraph?', flags=re.MULTILINE)

rawDescription: Splitting paragraphs that begin as indents


code:
import Tkinter as tki
class App(object):
     def __init__(self,root):
         self.root = root

         self.txt_frm = tki.Frame(self.root, width=900, height=900)
         self.txt_frm.pack(fill="both", expand=True)
         button3 = tki.Button(self.txt_frm,text="CLICK 1", command = self.retrieve_inpu)
         button3.grid(column=0,row=2)
         self.entry = tki.Entry(self.txt_frm)
         self.entry.grid(column=1,row=0)

         #create label in init
         self.label = tki.Label(self.txt_frm)
         self.label.grid(column=0,row=3)

     def retrieve_inpu(self):
        ent = self.entry.get()

        #treat label properties as a dict for tkinter
        #assign a new text value
        self.label['text'] = ent

root = tki.Tk()
app = App(root)
root.mainloop()

rawDescription: tkinter Display current label,deleting the previous

description: Tkinter Display current label,deleting the previous


rawDescription: Difference between numpy.array shape (R, 1) and (R,)


rawDescription: python: flatten to a list of lists but no more

description: Python: flatten to a list of lists but no more


code:
s = "my name is Alex and you're Alex too."
re.search(r'my.*?Alex', s).group()

rawDescription: Grep a range of words from a text file python


code: verboseprint = print if verbose else lambda *a, **k: None

rawDescription: How to implement the --verbose or -v option into a script?

description: Implement the --verbose or -v option into a script


code: res = (lambda x, y: x * y)(*map(int, s.split('x')))

rawDescription: Resolve variables from a string

description: Resolve variables from a string


rawDescription: Find first element of numpy ndarray of unknown shape


rawDescription: Matching substring in pattern in Python

description: Matching substring in pattern in Python


rawDescription: Find the network distance between two IPv4 addresses (not geographic distance)


code: B,G,R = cv2.split(img)

rawDescription: Extracting individual frames from an image


code: [dictionary[k] for k in sorted(dictionary)]

rawDescription: python : list of dictionary values by alphabetical order of keys

description: Python : list of dictionary values by alphabetical order of keys


code: a = int(input('Enter number for factorial operation: '))

rawDescription: Python 3 factorial

description: Python 3 factorial


rawDescription: Regex to ignore unwanted matched quotes

description: Regex to ignore unwanted matched quotes


code:
def f2(a, b) :
    a, b = 2 * a, 3 * b
    return ne.evaluate('2*a + 3*b + c',
                       global_dict= {'c' : np.arange(30, 40)})
f2(a, b)
4 * a + 9 * b + np.arange(30, 40)

rawDescription: Numexpr: How to use "local_dict" and "global_dict"?


code:
self.tabWidget.setStyleSheet("background-color: rgb(255, 255, 255);\n"
                                    "border:1px solid rgb(255, 170, 255);")

rawDescription: PySide custom Tab

description: PySide custom Tab


code: [random.choice(colors) for i in range(10)] #xrange for python2 compatability

rawDescription: Returning N random items from smaller original list


code:
import csv

file1 = 'C:/Users/Me/Desktop/file1'
file2 = 'C:/Users/Me/Desktop/file2'

reader1 = csv.reader(open(file1))
reader2 = csv.reader(open(file2))

F1 = set(''.join(row1[0].strip().split()[1:6]) for row1 in reader1)
F2 = set(''.join(row2[0].strip().split()) for row2 in reader2)

for sequence in F1.intersection(F2):
    print(sequence[:-4]),
    print('\t'),
    print(sequence[-4:])

rawDescription: How to compare columns from two CSV in python?

description: Compare columns from two CSV in python


code:
import pandas as pd
import numpy as np

df = pd.read_table('data', sep='\s{2,}', parse_dates=[0])

print(df.dtypes)
# Time    datetime64[ns]  # It is important that Time has dtype datetime64[ns]
# Bid              int64
# dtype: object

df['group'] = (df['Time'].diff() > np.timedelta64(60,'s')).cumsum()
print(df)

rawDescription: pandas quick way to break dataframe by timeindex

description: Pandas quick way to break dataframe by timeindex


code:
tempDF
tempDF['date'].dt.normalize() + datetime.timedelta(hours=12)

rawDescription: Changing time components of pandas datetime64 column


code:
last_day = datetime(2014, 12, 31, 23, 45)
last_day + timedelta(hours=1)

rawDescription: How to naturally roll-over to the next day when adding hours to a datetime

description: Naturally roll-over to the next day when adding hours to a datetime


code: 'Repr:%r Str:%s' % ('foo','foo')

rawDescription: Why would I ever use anything else than %r in Python string formatting?


code:
def __setitem__(self, key, item):
    putenv(key, item)
    self.data[key.upper()] = item

rawDescription: python environment case senstivity - os.environ[...]

description: Python environment case senstivity - os.environ[...]


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

def sortpts_clockwise(A):
    # Sort A based on Y(col-2) coordinates
    sortedAc2 = A[np.argsort(A[:,1]),:]

    # Get top two and bottom two points
    top2 = sortedAc2[0:2,:]
    bottom2 = sortedAc2[2:,:]

    # Sort top2 points to have the first row as the top-left one
    sortedtop2c1 = top2[np.argsort(top2[:,0]),:]
    top_left = sortedtop2c1[0,:]

    # Use top left point as pivot & calculate sq-euclidean dist against
    # bottom2 points & thus get bottom-right, bottom-left sequentially
    sqdists = distance.cdist(top_left[None], bottom2, 'sqeuclidean')
    rest2 = bottom2[np.argsort(np.max(sqdists,0))[::-1],:]

    # Concatenate all these points for the final output
    return np.concatenate((sortedtop2c1,rest2),axis =0)

rawDescription: (4,1,2) Numpy Array Sort Clockwise

description: (4,1,2) Numpy Array Sort Clockwise


code:
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]

rawDescription: Loops in django 1.8 views

description: Loops in django 1.8 views


code: x = np.arange(15).reshape(5, 3)

rawDescription: Unpack NumPy array by column

description: Unpack NumPy array by column


code:
import mechanize
br = mechanize.Browser()
br.get('http://www.imdb.com/title/tt0108778/')
br.title()

rawDescription: How to get page title in requests

description: Get page title in requests


code:
df.groupby("name")["date"].transform(lambda x: df2a.loc[x.name, "datemax"])
df["date"] < df.groupby("name")["date"].transform(lambda x: df2a.loc[x.name, "datemax"])
df_old = df[df["date"] < df.groupby("name")["date"].transform(lambda x: df2a.loc[x.name, "datemax"])]
df_old

rawDescription: Pandas dataframe random row selection per group with a boolean condition


code:
def getDummyData(reactor, x):
    """returns a deferred object that will have a value in some random seconds
    sets up a callLater on the reactor to trgger the callback of d"""
    pause = random.randint(1,10)
    return deferLater(reactor, pause, lambda: (x, pause))

rawDescription: stop a twisted reactor after a gatherResults has finished

description: Stop a twisted reactor after a gatherResults has finished


code:
import ctypes
import unittest

class FooLibTestCase(unittest.TestCase):
    def setUp(self):
        self.foolib = ctypes.CDLL('/full/path/to/foolib.so')

    def test_01a(self):
        """ Test in an easy way"""
        self.failUnlessEqual(4, foolib.my_sum(2, 2))

rawDescription: Is it possible to use Python based Unit Test frameworks and runners, to test C Code


code: string2 = filter(lambda x: x not in ";,.:", string1)

rawDescription: Removing many types of chars from a Python string


code:
import re
no_percentage = re.compile(r'^(?:[^%]|.{2,})$')
no_percentage.search('')
no_percentage.search('%')
no_percentage.search('%1')
no_percentage.search('1')

rawDescription: Python regex for matching all strings except a given string


code:
import yaml
fname = "data.yaml"
with open(fname) as f:
    cfg = yaml.load(f)
cfg

rawDescription: Python array from CSV file

description: Python array from CSV file


code: revDct = dict((val, key) for (key, val) in tuples)

rawDescription: iterating quickly through list of tuples

description: Iterating quickly through list of tuples


code:
def read_chunk(file, buffer):
    return [file.readline() for _ in xrange(buffer)]
    # or, "more" equivalent to using islice
    #return [line for i,line in itertools.izip(xrange(buffer), file)]

def read(from_filename, buffer, process_queue):
  file = open(from_filename, 'r')

  for to_process in iter(lambda: read_chunk(file, buffer), []):
    process_queue.put(to_process)
  process_queue.put('kill')

rawDescription: Process not ending in python

description: Process not ending in python


code: logger.handlers = []

rawDescription: How to avoid duplicate outputs using logging module

description: Avoid duplicate outputs using logging module


code:
def unpack_bytes(raw, zero_replacement=ord("\n")):
    # use - 1 to ignore leading bit
    num_bytes, remainder = divmod(len(raw) * 8 - 1, 7)

    i = int.from_bytes(raw, byteorder="big")
    # i = int(raw.encode("hex"), 16) # python 2
    if remainder:
        # remainder means there are unused trailing bits, so remove these
        i >>= remainder

    msg = []
    for _ in range(num_bytes):
        byte = i & 127
        if not byte:
            msg.append(zero_replacement)
        elif 32 <= byte <= 126:
            msg.append(byte)
        i >>= 7
    msg.reverse()

    return bytes(msg)
    # return b"".join(chr(c) for c in msg) # python 2

rawDescription: Ascii string of bytes packed into bitmap/bitstring back to string?


code:
from django.core.urlresolvers import reverse
url = reverse('pay', args=[plan.payment_id])

rawDescription: Django urlresolvers reverse for dynamically generated ids


code:
from django.contrib.auth.models import User

class UserProfile(models.Model):
    # This field is required.
    user = models.OneToOneField(User)

    # Other fields here
    accepted_eula = models.BooleanField()
    favorite_animal = models.CharField(max_length=20, default="Dragons.")

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

rawDescription: get user profile in django

description: Get user profile in django


code: {a[i]:a[i+1] for i in range(0,len(a)-1,2) if a[i+1].startswith('$')}

rawDescription: From array create tuples on if condition python


rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


rawDescription: Python: Removing random whitespace from a string of numbers


code:
def indexOf(self, term):
    """ Returns the index of the input term. """
    return hash(term) % self.numFeatures

rawDescription: What hashing function does Spark use for HashingTF and how do I duplicate it?


code: fig.canvas.toolbar.update = lambda: None

rawDescription: updating colorbar without resetting zoom history in matplotlib user interface

description: Updating colorbar without resetting zoom history in matplotlib user interface


code:
fig, ax = plt.subplots(1, 3, figsize=(10, 4), sharex=True, sharey=True)
norm = plt.Normalize(0, A.max())
ax[0].imshow(A, norm=norm)
ax[0].set_title('Original', fontsize='x-large')
ax[1].imshow(edges)
ax[1].set_title('Edges', fontsize='x-large')
ax[2].imshow(A_new, norm=norm)
ax[2].set_title('Averaged', fontsize='x-large')
for aa in ax:
    aa.set_axis_off()
ax[0].set_xlim(20, 50)
ax[0].set_ylim(50, 80)
fig.tight_layout()
plt.show()

rawDescription: border/edge operations on numpy arrays

description: Border/edge operations on numpy arrays


code:
def sum_until_found(lst, num):
    index = 0
    res = 0
    if num in lst:
        while index < lst.index(num):
            res += lst[index]
            index += 1
    else:
        return "The number is not in the list!"
    return res

rawDescription: Sum a list of numbers until a number X is found


code:
addresses = []
for emails in staffList:
    addresses.append(str(emails.getEmail()))
print(';'.join(addresses))

rawDescription: Python 3 Joining elements of different strings in a List


rawDescription: Pyplot: Shared axes and no space between subplots


code: year_month = data.index.to_period('M')

rawDescription: Isolating/manipulating data in a pandas Dataframe


code:
from nltk.stem.wordnet import WordNetLemmatizer
lmtzr = WordNetLemmatizer()
lmtzr.lemmatize('apples')
lmtzr.lemmatize('tennis')
lmtzr.lemmatize('process')
lmtzr.lemmatize('processes')

rawDescription: Regex to get rid of the last term with conditions


code:
from sklearn.metrics import silhouette_samples

...

#s = silhouette(X, cIDX)
s = silhouette_samples(X, cIDX)    # <-- scikit-learn function

...

rawDescription: Equivalent of Matlab's cluster quality function?


code:
import cv2

img = cv2.imread("sample_frame.jpg") #Loading an image in RGB mode.

height, width, channels = img.shape

rawDescription: Detect if image has border using PIL

description: Detect if image has border using PIL


code:
from dateutil.parser import parse
parse('Mon, 29 Oct 2012 13:07:07 GMT')
parse('2012-10-29 12:57:08')

rawDescription: Parsing the string to Dates in python

description: Parsing the string to Dates in python


rawDescription: How to turn a iterative DFS into a recursive DFS?

description: Turn a iterative DFS into a recursive DFS


code: {n:[nested_dicts[i][n] for i in range(1,301)] for n in ["name1","name2","name3"]}

rawDescription: Python dictionaries: changing the order of nesting


rawDescription: str.replace issue

description: Str.replace issue


rawDescription: python decimals - rounding to nearest whole dollar (no cents) - with ROUND_HALF_UP

description: Python decimals - rounding to nearest whole dollar (no cents) - with ROUND_HALF_UP


code:
import random
words = ['correct', 'horse', 'battery', 'staple']
[" ".join(random.choice(words) for _ in range(3)) for _ in range(5)]

rawDescription: Using Random in Python's list comprehension


code:
import string

# mapping to remove punctuation with str.translate()
remove_punctuation = {ord(c): None for c in string.punctuation}

listOfSentences = ['mary had a little lamb.',
                   'she also had a little pram.',
                   'bam bam bam she also loves ham.',
                   'she ate the lamb.']

keyWords= [('bam', 3), ('lamb', 2), ('ate', 1)]
keyWords = dict(keyWords)

keySentences = []
for sentence in listOfSentences:
    score = sum(keyWords.get(word, 0) for word in sentence.translate(remove_punctuation).split())
    if score > 0:
        keySentences.append((score, sentence))

keySentences = [sentence for score, sentence in sorted(keySentences, reverse=True)]
print(keySentences)

rawDescription: comparing sub elements in a list with another

description: Comparing sub elements in a list with another


code:
def create_button(self, info, boom, posit):
    ...
    self.button = Button(root)
    self.button.config(command=boom)
    ...

rawDescription: How to determine which button is pressed on a single tkinter object?

description: Determine which button is pressed on a single tkinter object


code:
class Scraper:
    def __init__(self,url):
        self.start_page = url

    def parse_html(self):
        pass

    def get_all_links(self):
        pass

    @classmethod
    def run(cls, url):
        instance = cls(url)
        #parse html, get all links, parse them and when done...
        return links

rawDescription: How to present a class as a function?

description: Present a class as a function


rawDescription: python+win32: detect window drag

description: Python+win32: detect window drag


code:
a = "somedir.somefile"
b = "someclass"

module = __import__(a, globals(), locals(), [b], -1)
clazz = getattr(module, b)

rawDescription: How to make from var_str import var_str in python

description: Make from var_str import var_str in python


code:
self.num_load = tokens.network.loads
self.num_generator = tokens.network.generators
self.num_transformer = tokens.network.transformers
self.num_line = tokens.network.lines
self.num_bus = tokens.network.buses
self.power_rate = tokens.soln.rate

rawDescription: How should I organise my functions with pyparsing?


code:
args = [expected_conditions.visibility_of_element_located((By.ID, id_))
        for id_ in element_id]

rawDescription: Iterating through list length and creating list of functions


code:
ACCESS_TOKEN = 'some_value'
SOME_OTHER_THING = 42

rawDescription: How do I use an access token in modules?

description: Use an access token in modules


rawDescription: Adding duplicate keys to JSON with python


rawDescription: Is there a standard solution for Gauss elimination in Python?


code:
from endless_pagination.templatetags.endless import PAGINATE_EXPRESSION

@register.tag
def paginate(parser, token, paginator_class=None):
    # Validate arguments.
    try:
        tag_name, tag_args = token.contents.split(None, 1)
    except ValueError:
        msg = '%r tag requires arguments' % token.contents.split()[0]
        raise template.TemplateSyntaxError(msg)

    # Use a regexp to catch args.
    match = PAGINATE_EXPRESSION.match(tag_args)
    if match is None:
        msg = 'Invalid arguments for %r tag' % tag_name
        raise template.TemplateSyntaxError(msg)

    # Retrieve objects.
    kwargs = match.groupdict()
    objects = kwargs.pop('objects')

    # The variable name must be present if a nested context variable is passed.
    if '.' in objects and kwargs['var_name'] is None:
        msg = (
            '%(tag)r tag requires a variable name `as` argumnent if the '
            'queryset is provided as a nested context variable (%(objects)s). '
            'You must either pass a direct queryset (e.g. taking advantage '
            'of the `with` template tag) or provide a new variable name to '
            'store the resulting queryset (e.g. `%(tag)s %(objects)s as '
            'objects`).'
        ) % {'tag': tag_name, 'objects': objects}
        raise template.TemplateSyntaxError(msg)

    # Call the node.
    return CustomPaginateNode(paginator_class, objects, **kwargs)

rawDescription: How to do result post-processing before rendering with django endless-pagination?

description: Do result post-processing before rendering with django endless-pagination


code: currentFrame = instructions

rawDescription: Having trouble with packing and unpacking frames in Tkinter


code:
import numpy as np
def unique_order_preserving_numpy(seq):
    u, ind = np.unique(seq, return_index=True)
    return u[np.argsort(ind)]

rawDescription: Proper Usage of list.append in Python

description: Proper Usage of list.append in Python


code:
n = 5
lists = [[] for _ in range(n)]
lists

rawDescription: How can I make multiple empty arrays in python?

description: Make multiple empty arrays in python


code:
f = io.open('/tmp/test.txt', 'rb')
alphafile = AlphaPeekReader(f)
alphafile.readalpha(3)
alphafile.readalpha(3)
alphafile.readalpha(3)
alphafile.readalpha(10)
alphafile.readalpha(10)

rawDescription: character reading in a variety way

description: Character reading in a variety way


code:
import sys
from logic import MyUi

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

    #create a new object
    my_interface = MyUi()
    my_interface.show()
    sys.exit(app.exec_())

    if __name__ == '__main__': main()

rawDescription: How do i connect from main window to next window in pyqt?

description: Connect from main window to next window in pyqt


rawDescription: Insert 0s into 2d array

description: Insert 0s into 2d array


code: total = recAnswer(x, y, z - 1)

rawDescription: Permutation of phone numbers starting at button x, ending at button y, and z numbers long


code: {{ expense.vendor_name }}

rawDescription: Google App Engine Datastore modeling issue


code:
@conditional_decorator(timeit, doing_performance_analysis)
def foo():
    time.sleep(2)

rawDescription: how to do a conditional decorator in python 2.6

description: Do a conditional decorator in python 2.6


rawDescription: How do you subtract list a from list b in Python?

description: Subtract list a from list b in Python


code:
[options]
day = monday,tuesday,wednesday
month = jan,feb,march,april
holiday = thanksgiving,christmas

rawDescription: Python String to list processing

description: Python String to list processing


code:
def filename_minus_extension(self):
    basename, extension = os.path.splitext(os.path.basename(self.file.name))
    return basename

rawDescription: Returning a file path in Django without the file extension


code:
finalKilo.config(text = "")
finalMile.config(text = "")

rawDescription: Why can't I get my labels to clear when the "Reset" button is pressed?


code:
@classmethod
def cmd(cls, argv=None):
    " Executes the command. "
    if argv is None:
        argv = sys.argv

rawDescription: Avoid expansion of sys.argv keyword argument in Sphinx documentation


code:
def teste(molecules):
    P = np.array([Psat(molecule) for molecule in molecules])
    f1 = lambda x: np.sum(x) - 1
    f2 = lambda x: np.dot(x, P) - 760
    return f1, f2

rawDescription: Dynamically build a lambda function in python


code:
def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

rawDescription: Closing pyplot windows

description: Closing pyplot windows


code: df

rawDescription: Pandas: Change dates in dataframe to same date format


rawDescription: Getting data from a list on a specific line in a file (python)


rawDescription: Iterator for each item in a 2D Python list and its immediate m by n neighbourhood


rawDescription: How to use collections.defaultdict, to ensure a straightforward comparison of values in Python

description: Use collections.defaultdict, to ensure a straightforward comparison of values in Python


code:
# add a child
child = Child()
session.add(child)
session.commit()

# find the Child you want to delete by its primary key
child = session.query(Child).get(child_id)
# OR: find it by other filters
child = session.query(Child).filter(...).first()

# mark it for deletion
session.delete(child)
# SA will delete all properly
session.commit()

rawDescription: One-to-one delete for SQLAlchemy classes with inheritance


rawDescription: Sorting 10k data set to the dict by child basis


code: 'Dougherty & Co.',

rawDescription: replacing quotes inside a pandas df to count unique terms

description: Replacing quotes inside a pandas df to count unique terms


rawDescription: Numpy indexing multidimensional arrays with array and slice


code: x[abs(x-x.mean()) > x.std()]

rawDescription: Numpy way to determine the value(s) in an array which is causing a high variance


rawDescription: BeautifulSoup Python is stripping my HTML comments


code:
import pandas as pd
dataframes = [pd.read_csv(p) for p in ("data1.csv", "data2.csv")]
merged_dataframe = pd.concat(dataframes, axis=1)
merged_dataframe.to_csv("merged.csv", index=False)

rawDescription: How to copy columns from several csv files into a single csv file with python?

description: Copy columns from several csv files into a single csv file with python


code:
urllib.quote(json_encoded)
# produces just the part following "&attachment="

rawDescription: urllib's urlencode returning weird encoded results

description: Urllib's urlencode returning weird encoded results


rawDescription: Composite Index updates for Numpy Matrices


code: format(value, '.6f')

rawDescription: Add zeros to a float after the decimal point in Python


code:
from itertools import groupby

grouped = groupby(rooms, type)
rooms = {}
for key, grp in grouped:
    roomname = 'room{}'.format(next(grp))
    rooms[roomname] = list(next(grouped)[1])

rawDescription: Construct dictionary from mixed type list


code:
class NewBookWizard(SessionWizardView):
    form_list = [BookFormStep1, BookFormStep2]
    template_name = 'add_book_wizard.html'

    def done(self, form_list, **kwargs):

        book = Books()
        data = Files()

        file_form, book_form = form_list

        data.file = file_form.cleaned_data['file']
        data.save()

        book.user = self.request.user
        book.title = book_form.cleaned_data['book_title']
        book.save()

        data.book = book
        data.save()

        return render(request, 'thank-you.html')

rawDescription: How can I create a two step form or wizard, where the model has a foreign key, but the foreign key is selected at the second step?

description: Create a two step form or wizard, where the model has a foreign key, but the foreign key is selected at the second step


code:
from os import listdir
from os.path import isfile, join

IMAGE_PATH = "/images"
images_dict = dict()

images = [ f for f in listdir(IMAGE_PATH) if isfile(join(IMAGE_PATH,f)) and f.endswith('png') ]

for filename in images:
    images_dict[os.path.splitext(filename)[0]] = pygame.image.load(join(IMAGE_PATH,filename))

rawDescription: Loading pygame images as a module

description: Loading pygame images as a module


rawDescription: how to get sums in CSV file python

description: Get sums in CSV file python


code:
cities = [
    'Belin (*) 9',
    'München 12',
    'Los Angeles 9'
]
[re.sub('\s*\(\*\)|\s*\d+', '', city) for city in cities]

rawDescription: How to strip noisy pattern at the end of string?

description: Strip noisy pattern at the end of string


rawDescription: Python: 3D list, sum columns

description: Python: 3D list, sum columns


code:
func_l = ((x, func(y)) for x, y in l)
result = dict((key, value) for key, value in func_l if isinstance(value, int))

rawDescription: Is comprehension possible here?

description: Is comprehension possible here


code:
keywords = ['key1', 'key2', 'key3', ...]
number_of_keywords = len(keywords)

for i, doc_id in enumerate(sim_doc_ids):
    # Generate keyword Counter (counter) for doc_id
    for j, key in enumerate(keywords):
        doc_cluster_key_freq.loc[i * number_of_keywords + j] = [doc_id, key, counter[key]]

rawDescription: Inserting counter objects into Dataframe python


code:
def shift_char(ch,shift):
    if not ch.isalpha():
        return ch   # return non-alphabetic characters as is
    if ch.isupper():
        base_a = 'A'
    else:
        base_a = 'a'
    return chr(ord(base_a) + (ord(ch)-ord(base_a)+shift)%26)

def shift_string(s,shift):
    return ''.join(shift_char(i,r) for i in s)

rawDescription: How to change random letter using number in Python

description: Change random letter using number in Python


code:
current = timestamps[0]
count = 0
res = []
for t in timestamps:
    if (t - current) <=  timedelta(minutes= 2):
         count = count + 1
    else:
         res.append((current,count))
         current = t
         count = 1
res.append(current,count) #add last tuple

rawDescription: How would you group timestamps by chunks of given duration?


rawDescription: Advice on a simple algebra solver(python)


rawDescription: Averaging along DataFrame columns with some missing rows


rawDescription: Relative frequencies of a list of numbers


code:
import sqlite3

with sqlite3.connect('apr.sqlite') as connection:
    cursor = connection.cursor()
    cursor.execute('''CREATE TABLE aprtable
                      (id INTEGER PRIMARY KEY AUTOINCREMENT,
                      neighborhood TEXT,
                      income INTEGER,
                      risk_factor INTEGER,
                      apr FLOAT)''')

rawDescription: Dynamically fill a python dictionary

description: Dynamically fill a python dictionary


code:
pattern(9)
pattern(6)

rawDescription: Number patterns in Python3x

description: Number patterns in Python3x


code: df[df.index.levels[1] <= cutoff].groupby(level=[0]).apply(lambda x: x.index.levels[1].asof(cutoff))

rawDescription: pandas index.asof with multiindex

description: Pandas index.asof with multiindex


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

fig, ax = plt.subplots()

x = np.linspace(0, 2, 1000)
y = x**2
ax.plot(x, y)

x0, y0 = 1.0, 1.0
dx, dy = 1, 2

length = 1.25 # in inches
dx, dy = length * np.array([dx, dy]) / np.hypot(dx, dy)

ax.quiver(x0, y0, dx, dy, units='inches', angles='xy', scale=1,
          scale_units='inches', color='red')

ax.axis((0, 2, 0, 2))
plt.show()

rawDescription: Arrow direction set by data, but length set by figure size


rawDescription: Python: "Try" inside shortened for...loop


code:
b = B()
b.f is b.f

rawDescription: Python classmethods: what's the difference between a member of an instance and a member of the class?


code:
def categorize(sText):
    import numpy as np
    aTokens = np.array([d['lsTokens'] for d in dTrainingData.values()], str)
    lCats = [d['lsCats'] for d in dTrainingData.values()]

    print("creating binary cats")

    from sklearn import preprocessing
    oBinarizer = preprocessing.MultiLabelBinarizer()
    aBinaryCats = oBinarizer.fit_transform(lCats)

    from sklearn.multiclass import OneVsRestClassifier
    from sklearn.feature_extraction.text import TfidfTransformer
    from sklearn.svm import LinearSVC
    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.pipeline import Pipeline

    oClassfier = Pipeline([
        ('vectorizer', CountVectorizer()),
        ('tfidf', TfidfTransformer()),
        ('clf', OneVsRestClassifier(LinearSVC()))])

    print("fitting data to classifier...")
    oClassfier.fit(aTokens, aBinaryCats)
    oClassfier = oClassfier

    aText = np.array([sText])

    aPredicted = oClassfier.predict(aText)
    lAllCats = oBinarizer.inverse_transform(aPredicted)

rawDescription: Twitter/ general categorisation training corpus


code:
with open("rs.txt") as inf, open("new.txt", "w") as outf:
    for line in inf:
        line = line.split("(", 1)[0].rstrip() + "\n"
        outf.write(line)

rawDescription: remove the numbers from txt file

description: Remove the numbers from txt file


code:
class CustomWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(CustomWidget, self).__init__(parent)
        layout = QtGui.QVBoxLayout(self)
        self.title_label = QtGui.QLabel("Select full files path:")
        self.simoderev_widget = QtGui.QWidget()
        simoderev_layout = QtGui.QHBoxLayout(self.simoderev_widget)
        self.simoderev_checkbox = QtGui.QCheckBox("use simoderev as base: ")
        self.simoderev_combobox = QtGui.QComboBox()
        self.simoderev_widget.setMaximumWidth(250)
        simoderev_layout.addWidget(self.simoderev_checkbox)
        simoderev_layout.addWidget(self.simoderev_combobox)
        simoderev_layout.setContentsMargins(0,0,0,0)
        self.paths_label = QtGui.QLabel("paths:")
        layout.addWidget(self.title_label)
        layout.addWidget(self.simoderev_widget)
        layout.addWidget(self.paths_label)

rawDescription: Is there any way to show widget it two different tabs?


Numpy.bitwise_and.reduce behaving unexpectedly


code:
from lmfit import minimize, Parameters, Parameter, report_fit
import numpy as np

x=np.array([1,2,3,4,5,6,7,8,9,10]  )
y=np.array([7.2489, 7.0123, 7.0006, 7.0003, 7, 7, 7, 7, 7, 7])

def f_theory1(params, x, data):
    a = params['a'].value
    b = params['b'].value
    c = params['c'].value
    d = params['d'].value

    model = a * np.exp(b*(x**c)) + d # now b can become negative; in your definition it could not

    return model - data #that's what you want to minimize

# create a set of Parameters
#'value' is the initial condition
#'min' and 'max' define your boundaries
params = Parameters()
params.add('a', value= 40, min=-10, max=10000)
params.add('b', value= -0.005, min=-10, max=200)
params.add('c', value= .03, min=-10, max=400)
params.add('d', value= 40.0, min=-10, max=400)

# do fit, here with leastsq model
result = minimize(f_theory1, params, args=(x, y))

# calculate final result
final = y + result.residual

# write error report
report_fit(params)

#plot results
try:
    import matplotlib.pyplot as plt
    plt.plot(x, y, 'k+')
    plt.plot(x, final, 'r')
    plt.ylim([6.95, 7.3])
    plt.show()
except:
    pass

rawDescription: Reg: Error in stretched exponential function fitting


rawDescription: Flask-Paginate with CouchDB

description: Flask-Paginate with CouchDB


rawDescription: How to modify a numpy array inplace without hidden additional memory allocation?

description: Modify a numpy array inplace without hidden additional memory allocation


code: pd.concat(frames, axis=1)

rawDescription: Merge of more than 2 python pandas data frames


code:
from django import forms

class ContactForm(forms.Form):

    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea)

rawDescription: Python Django e-mail form example

description: Python Django e-mail form example


rawDescription: Python regex, how to search for multiple strings?


code:
import os

def paths(filename):
    dirList = ['c:\\', 'y:\\', 'z:\\']
    complete = [os.path.join(s, filename) for s in dirList]
    return complete

def fileWrite():
    for each_file in paths('c:\\peter.txt'):
        text = 'Hello World'
        file = open(each_file, 'w')
        file.write(text)
        file.close()

rawDescription: Utilizing objects in another class in Python


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


code:
from tastypie import fields

class UserResource(ModelResource):
    # ...
    website = fields.CharField(attribute = 'profile__website' )
    description = fields.CharField(attribute = 'profile__description' )
    full_name = fields.CharField(attribute = 'profile__full_name' )
    # ...

rawDescription: Combine Related Resources With TastyPie

description: Combine Related Resources With TastyPie


code:
urls = (
  '/', 'index'
)

rawDescription: LearnPythonTheHardWay Exercise 50

description: LearnPythonTheHardWay Exercise 50


rawDescription: Converting 32-bit integer into array of four 8-bit integers in Python


code:
results = []
with open('myfile.txt', 'r') as f:
    for line in f:
        results.append(processing_func(line))
results = np.array(results)

rawDescription: Appending arrays in numpy

description: Appending arrays in numpy


rawDescription: Do you change variables AFTER you run a function in python?


code: [x for x in A if not any([set(y).issubset(set(x)) for y in B])]

rawDescription: Python - check for combination of items in list of tuples


code:
class C(A, B):
    def another(): pass

class D(C): pass

rawDescription: How would I find where a function originates in source code?


code:
import numpy as np

mask = np.random.randint(2, size=(500,500))
array = np.random.randint(500, size=(4, 2000))

xarr, yarr = array[0, :], array[1, :]
idx = mask[xarr, yarr].astype(bool)
result = array[:, idx]

cols = []
for i in range(2000):
    current = array[:, i]
    if mask[current[0], current[1]] > 0:
        cols.append(i)
expected = array[:, cols]

assert np.allclose(result, expected)

rawDescription: removing entries from a numpy array

description: Removing entries from a numpy array


code:
class PostMessageForm(Form):
    message = TextAreaField(validators=[DataRequired()])

class CreateTopicForm(PostMessageForm):
    topic = TextField(validators=[DataRequired()])

rawDescription: What's the best practice in WTForms, using one form class or multiple ones?


code:
def get_process(name):
    return next((p for p in multiprocessing.active_children() if p.name == name), None)

rawDescription: Process identification using python multiprocessing library


code:
X = np.tile(np.arange(0,n,0.1).astype(int)[None,None,:,None], [n, n, 1, n])
a,b,c,d = np.ogrid[:n,:n,:100,:n]
argmaxD = F[a,b,c,d,X].argmax(axis=-1)

rawDescription: Evaluate array at specific subarray

description: Evaluate array at specific subarray


code:
byte1, byte2 = twobytes[:2]  # will split out to integers
newbyte = bytes([((byte1 & 0x0F) << 4) | (byte2 & 0x0F)])

rawDescription: how to join two bites together (the last 4 bits of each) for a whole file

description: Join two bites together (the last 4 bits of each) for a whole file


code:
from pprint import pprint
pprint(data.items())

rawDescription: Python - iterate text file and create dictionary of dictionary


code:
def index():
    return render_template('index.html',
                            title='test home title')
index = login_required(index)

rawDescription: I need help following along this decorator. And confirmation if I'm correct


code: gridIndexes, dis = getStationIndices(longitude,latitude,st_lon,st_lat,numberOfPoints)

rawDescription: Select gridded data from input array python


code: scores

rawDescription: Recognition of elements in a list - machine learning


code:
def build_insert_statement(table_name, col_names, values, where_clause):
    return ('insert into ' +
            table_name +
            ' ( ' +
            ', '.join(col_names) +
            ' ) values ( ' +
            ', '.join(values) +
            ' ) where ' +
            where_clause +
            ';')

rawDescription: string_builder decorator in python 2.7 - how to do it and should I?

description: String_builder decorator in python 2.7 - how to do it and should I


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

    def __call__(func, self):
        # This is the actual function
        pass

    def __get__(func, instance=None, type_=None):
        class CustomMethod(object):
            def __init__(self, instance, type_):
                self.im_self = instance
                self.im_class = type_
            def __call__(self, *args, **kw):
                return func(self.im_self, *args, **kw)
            def __str__(self):
                return '{} in the instance {} you Dope!'.format(func.name, self.im_self)

        return CustomMethod(instance, type_)

rawDescription: Possible to change a Python method's __str__() attribute?


code:
time = numpy.arange(0, 30, 0.2)
blank = numpy.zeros_like(time)

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


rawDescription: pandas groupby - return min() along with time where min() occurs

description: Pandas groupby - return min() along with time where min() occurs


code: rdd.flatMap(lambda kv: ((kv[0], v) for v in kv[1]))

rawDescription: Spark: how to generate several elements in map (python)?


code:
if message.startswith("!songrequest"):
    song = message.split(' ', 1)[1]   # Add max=1 to split()
    message = request_song(song)
    sendMessage(s, message)
    break

rawDescription: Python - Add multiple values to text file from same variable


code:
field_names = ['status', 'assigned', 'requestor']
if form.validate_on_submit():
    requestlist = models.Request.query

    for field in field_names:
        f_value = getattr(form, field).data
        if f_value != 'No Filter':
            requestlist = requestlist.filter(getattr(models.Request, field).like(f_value))

    return requestlist.all()

rawDescription: smarter sqlalchemy wtf dynamic filter in a flask app

description: Smarter sqlalchemy wtf dynamic filter in a flask app


rawDescription: Converting week numbers to dates

description: Converting week numbers to dates


code:
def switch(lst, i):
  lst[0], lst[i] = lst[i], lst[0]

rawDescription: How to switch nodes at an index with the head of a list?

description: Switch nodes at an index with the head of a list


code:
file = '/var/log/test.txt'
path, file_name = os.path.split(file)

rawDescription: most efficient way to substring path and file out of a string

description: Most efficient way to substring path and file out of a string


code: s = SomeClass(bar=1, foo=0)

rawDescription: Builder pattern equivalent in Python

description: Builder pattern equivalent in Python


code:
first = itemgetter(0)
s = sorted(d, key=first)

rawDescription: Is there a "get first item" function, for use in higher-ordered functions?


code:
import inspect
inspect.getmro(Derive)

rawDescription: How do I get the instance method's next-in-line parent class from `super()` in Python

description: Get the instance method's next-in-line parent class from `super()` in Python


code: heapq.nsmallest(10, (funcx() for i in range(2000000)) )

rawDescription: How do you iterate and keep the top 10 max? Python

description: Iterate and keep the top 10 max? Python


code:
* PATH_MAX (defined in limits.h)
* FILENAME_MAX (defined in stdio.h)

rawDescription: How do I get in python the maximum filesystem path length in unix?

description: Get in python the maximum filesystem path length in unix


code:
def __str__(self):
    return "{0} - ({1} -> {2})".format(
        self.id,
        format_date(self.date_v_debut),
        format_date(self.date_v_fin),
    )

rawDescription: Django one line datetime if null

description: Django one line datetime if null


rawDescription: Learning loops and lists

description: Learning loops and lists


code:
from operator import itemgetter
from itertools import groupby

score_list = score()
score_list.sort(key=itemgetter(2), reversed=True)
rank = 1 # counter for the rank
for group in groupby(score_list):
    current_rank = rank # save the rank
    for item in group:
        print(item, current_rank)
        rank += 1 # rank increment in inner loop

rawDescription: sorting a list in python

description: Sorting a list in python


rawDescription: going through a dictionary and printing its values in sequence

description: Going through a dictionary and printing its values in sequence


code:
cv.CreateImageHeader()
cv.SetData()

rawDescription: Pass python IplImage object as simple struct to shared C library using ctypes


code:
(df2 == "up").all(axis=1)
both_up = df2[(df2 == "up").all(axis=1)]
both_up

rawDescription: Detection of concurrent event appearances - pandas and DataFrame, but possibly pure-python related


code:
sentimentDict = {}

def loadSentiment():
    with open('Sentiment/positive_words.txt', 'r') as f:
        sentimentDict['positive'] = {line.strip() for line in f}

    with open('Sentiment/negative_words.txt', 'r') as f:
        sentimentDict['negative'] = {line.strip() for line in f}

rawDescription: What is this dictionary assignment doing?


code:
class BasicFactory(factory.DjangoModelFactory):

    country = factory.SubFactory(CountryFactory)
    code = factory.Sequence(lambda n: 'unit%d' % n)
    name = factory.Sequence(lambda n: 'Unit %d' % n)
    full_name = factory.Sequence(lambda n: 'Unit %d, etc.' % n)
    unit_type = factory.SubFactory(GeographicUnitTypeFactory)

    class Meta:
        model = 'spatial.GeographicUnit'

class BasicFactoryWithExtraRelatedFactories(BasicFactory):
    season = factory.RelatedFactory(SeasonFactory, 'geographicunit')

class BasicFactoryWithExtraPostGeneration(BasicFactory):

    @factory.post_generation
    def post(self, create, extracted, **kwargs):
        """
        A replacement post_generation method
        """
        self.name = self.name + ' after post'

class ExtraRelatedAndExtraPostGenerationFactory(BasicFactoryWithExtraRelatedFactories, BasicFactoryWithExtraPostGeneration):
    """
    This seems to inherit the extra RelatedFactories, but not the extra post_generation method.
    """

class ExtraPostGenerationAndExtraRelatedFactory(BasicFactoryWithExtraPostGeneration, BasicFactoryWithExtraRelatedFactories):
    """
    This seems to inherit the extra post_generation method, but not the extra RelatedFactories.
    """

from django.test import TestCase

class MyTestCase(TestCase):

    def test_extrarelated(self):
        obj = ExtraRelatedAndExtraPostGenerationFactory()
        self.assertTrue(obj.name.endswith(' after post'))
        self.assertEqual(Season.objects.filter(geographicunit=obj).count(), 1)

    def test_extrapostgeneration(self):
        obj = ExtraPostGenerationAndExtraRelatedFactory()
        self.assertTrue(obj.name.endswith(' after post'))
        self.assertEqual(Season.objects.filter(geographicunit=obj).count(), 1)

rawDescription: Multiple inheritance of factory_boy factories - only seems to inherit the first parent


code: function_that_uses_dict(ChainMap({1001 : "1001"}, big_dict))

rawDescription: How to pass in a dictionary with additional elements in python?

description: Pass in a dictionary with additional elements in python


code:
import csv

with open(filename) as infile:
    for row in csv.reader(infile):
        instance, ts, data = row[:3]
        # or if row can have even less than 3 items
        # instance, ts, data = row[:3] + [None]*(3 - len(row))

rawDescription: How to read multiple values from a line in python when the # of values could change

description: Read multiple values from a line in python when the # of values could change


code: plt.imshow(bg, cmap = plt.get_cmap('gray'), vmin = 0, vmax = 255)

rawDescription: imshow(img, cmap=cm.gray) shows a white for 128 value

description: Imshow(img, cmap=cm.gray) shows a white for 128 value


code:
from math import pi

for n in xrange(100000):
    total = 0.

    binom = 1
    binom_mul = n
    binom_div = 1

    power = -0.05 * n
    for k in xrange(1, n // 2 + 1):
        binom = binom * binom_mul / binom_div
        binom_mul -= 1
        binom_div += 1

        total += binom * (pi * k) ** power

    print(total)

rawDescription: Calculate sums with large binomial coefficients


code:
def my_check_correct_type(value):
    assert isinstance(value, collections.MutableSequence)

third_party_library.check_correct_type = my_check_correct_type

rawDescription: MutableSequence to pass as a list in isinstance() check


rawDescription: Python: convert a dot separated hex values to string?


code:
c['schedulers'].append(SingleBranchScheduler(
    name="foo",
    change_filter=filter.ChangeFilter(project="foo", branch="master",
                                      repository=url),
    treeStableTimer=300,
    fileIsImportant=fileIsImportant,
    builderNames=["foo-build"]))

rawDescription: How can I arbitrarily tell Buildbot to not schedule a build for a given change?

description: Arbitrarily tell Buildbot to not schedule a build for a given change


code: ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']

rawDescription: All possible ways to interleave two strings


code:
def reverse_numeric(x, y):
    return y - x
sorted([3,4,7,2,1], cmp=reverse_numeric)

rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code: max(xrange(len(ld)), key=lambda index: ld[index]['size'])

rawDescription: Python list of dicts, get max value index


code:
allele_freqs = ((20, ('A', 'A')),
                (30, ('A', 'a')),
                (44, ('a', 'a')))

population = [a for n, a in allele_freqs for _ in range(n)]

rawDescription: Populate list with tuples

description: Populate list with tuples


code:
NS = "{http://webservices.amazon.com/AWSECommerceService/2010-11-01}"
doc = ET.fromstring(XML)
items = doc[1]                           # Items element

first_item = items.find(NS + 'Item')     # First direct Item child
all_items =  items.findall(NS + 'Item')  # List of all direct Item children

rawDescription: Parsing xml with etree

description: Parsing xml with etree


code:
import string
letterGoodness = dict(zip(string.ascii_uppercase,letterGoodness))

rawDescription: A value in a list, python

description: A value in a list, python


code:
from django.contrib import admin
from myapp.models import City, Shop

class ShopInline(admin.TabularInline):
    formfield_overrides = {
        models.PointField: {'widget': Textarea},
    }
    model = Shop

class CityAdmin(admin.ModelAdmin):
    inlines = [ShopInline,]

rawDescription: Modifying spatial widget formsets on Django admin


rawDescription: Register username and password

description: Register username and password


code:
f1 = open('yourBigFile.txt', 'r')
f2 = open('yourBigFile.txt.tmp', 'w')
for line in f1:
    f2.write(line.replace(';', ' '))
f1.close()
f2.close()

rawDescription: find and replace within a text file

description: Find and replace within a text file


rawDescription: Getting rows from a data frame which satisfy a condition in pandas


code:
def byte_array(n):
    for i in range(2**(8*n)):
        yield [[i>>k&1 for k in range(j, j-8, -1)] for j in range(8*n-1, 0, -8)]

rawDescription: Python : efficient bytearray incrementation


code:
chained = itertools.chain.from_iterable(sixbit)
list(chained)

rawDescription: iterating over list of string and combining string values Python

description: Iterating over list of string and combining string values Python


code:
p = {"var": ["value", "value2"], "var2": ["yetanothervalue"]}
urlencode([(k, v) for k, vs in p.items() for v in vs])

rawDescription: Python urllib2 sending POST data

description: Python urllib2 sending POST data


code:
mydata = np.fromfile(fp, sep=" ", dtype=int, count=number_of_elements)
mydata.shape = (100000, 3)    # Reshape it to the desired shape as fromfile
                              # returns a 1D array.

rawDescription: Reading large formatted text file with NumPy


code: [m.span() for m in re.finditer('(?=aa)', 'aaadaa')]

rawDescription: Python regular expressions lookahead

description: Python regular expressions lookahead


code:
import urllib2
import csv
import lxml.html

URL = "http://www.ncbi.nlm.nih.gov/pubmed/"

# read IDs from the input csv file
with open('input.csv', 'r') as csvfile:
    numbers = [row[0] for row in csv.reader(csvfile)]

# get the article and collect it's title for each ID
output = []
for number in numbers:
    response = urllib2.urlopen(URL + number)
    html = response.read()

    tree = lxml.html.document_fromstring(html)
    output.append(tree.xpath('//div[@class="rprt abstract"]/h1')[0].text)

# write article titles to the output csv
with open('output.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile)
    for row in output:
        csvwriter.writerow([row])

rawDescription: How to parse data by subtituting part of a url

description: Parse data by subtituting part of a url


code: data = np.asarray([d.flatten() for d in data.swapaxes(0, 1)])

rawDescription: Python eliminate Tuples after zipping list of list of lists


code:
import numpy as np

data = np.genfromtxt(source,delimiter=" ").flatten()

rawDescription: coordinates (str) to list

description: Coordinates (str) to list


code:
i1 = len('VCALogParser_output_')
i2 = len ('.log')

'\n{}, {}\n'.format(s1[i1:-i2], s2[i1:-i2])

rawDescription: how to split the text using python?

description: Split the text using python


code:
def icount(alist):
    adic = {}
    for i in alist:
        adic[i] = adic.get(i, 0) + 1
    return adic

rawDescription: Count occurence in a list with time complexity of O(nlogn)


code:
iframe = driver.find_element_by_css_selector("#mainContent iframe")
driver.switch_to.frame(iframe)

rawDescription: Web scraping with Selenium

description: Web scraping with Selenium


code: pylab.text(0.6, 0.75, 'using axis coords', transform=ax.transAxes)

rawDescription: Matplotlib, adding text with more than one line. Adding text that can follow the curve


rawDescription: Creating a variable inside of a for loop


rawDescription: Why use curses.ascii.islower?

description: Why use curses.ascii.islower


code:
def dict_filter(it, *keys):
    for d in it:
        yield dict((k, d[k]) for k in keys)

rawDescription: Python CSV DictReader ignore columns?

description: Python CSV DictReader ignore columns


code:
from collections import defaultdict

brand2items = defaultdict(list)

for item in items:
    brand2items[item["brand"]].append(item)

pprint(brand2items)
#>>> {'acer': [{'brand': 'acer', 'id': 7},
#>>>           {'brand': 'acer', 'id': 8},
#>>>           {'brand': 'acer', 'id': 9},
#>>>           {'brand': 'acer', 'id': 10}],
#>>>  'apple': [{'brand': 'apple', 'id': 11}, {'brand': 'apple', 'id': 12}],
#>>>  'ibm': [{'brand': 'ibm', 'id': 1},
#>>>          {'brand': 'ibm', 'id': 2},
#>>>          {'brand': 'ibm', 'id': 3},
#>>>          {'brand': 'ibm', 'id': 4},
#>>>          {'brand': 'ibm', 'id': 5},
#>>>          {'brand': 'ibm', 'id': 6}]}

rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


rawDescription: Efficiently Searching Nested Lists

description: Efficiently Searching Nested Lists


code: ["".join(x) for _, x in itertools.groupby("dfsd98sd8f68as7df56", key=str.isdigit)]

rawDescription: Splitting a string where it switches between numeric and alphabetic characters


code:
def group(elements, comp_func):
    groups = {}
    for x in elements:
        for y in groups:
            if comp_func(x, y):
                groups[y].append(x)
                break
        else:
            groups[x] = [x]
    return groups

rawDescription: Gather elements from list into lists of lists of equal elements?


code: new['d'] = pd.to_datetime(new['d'].str[1:].astype(int), unit='s')

rawDescription: Plot with pandas seems not to work well as I change the index of a DataFrame


code:
import threading, Queue

def ftp_chunk_iterator(FTP, command):
    # Set maxsize to limit the number of chunks kept in memory at once.
    queue = Queue.Queue(maxsize=some_appropriate_size)

    def ftp_thread_target():
        FTP.retrbinary(command, callback=queue.put)
        queue.put(None)

    ftp_thread = threading.Thread(target=ftp_thread_target)
    ftp_thread.start()

    while True:
        chunk = queue.get()
        if chunk is not None:
            yield chunk
        else:
            return

rawDescription: Python FTP "chunk" iterator (without loading entire file into memory)


code:
class Library():
    def __init__(self):
        self.shelves = []
        self.shelf = self.Shelf()
    class Shelf():
        def __init__(self):
            self.books = []
        def __repr__(self):
            return str(vars(self))

rawDescription: Python: Printing nested classes

description: Python: Printing nested classes


code:
inputlist = [{'permission': 'full',
  'permission_type': 'allow',
  'trustee': {'id': 'SID:S-1-5-32-545',
              'name': 'Users',
              'type': 'group'}},
 {'permission': 'full',
  'permission_type': 'allow',
  'trustee': {'id': 'SID:S-1-5-32-545',
              'name': 'Users',
              'type': 'group'}},
 {'permission': 'full',
  'permission_type': 'allow',
  'trustee': {'id': 'SID:S-1-5-32-544',
              'name': 'Administrators',
              'type': 'group'}}]
def set_from_dict(d):
    return frozenset(
        (k, set_from_dict(v) if isinstance(v, dict) else v)
        for k, v in d.iteritems())

seen = set()
result = []
for d in inputlist:
    representation = set_from_dict(d)
    if representation in seen:
        continue
    result.append(d)
    seen.add(representation)

from pprint import pprint
pprint(result)

rawDescription: How make unique a list of nested dictionaries in python


rawDescription: How to implement command line switches to my script?

description: Implement command line switches to my script


code: values = [(int(x), int(y)) for x,y in values]

rawDescription: how to add and sort multidimentional array in python?

description: Add and sort multidimentional array in python


code:
f = And(z,Eq(x,y))                     # z ∧ (x = y)
simplify(f)

rawDescription: Simplify removes relational term in Sympy?


rawDescription: Why does python 2.6 not update my numpy array?


code:
def f(seq):
    # http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3383106#3383106
    #non-lambda version by Tony Veijalainen
    return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]

def g(seq):
    # http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3383106#3383106
    #lambda version by Tony Veijalainen
    return [x for x,y in sorted(enumerate(seq), key = lambda x: x[1])]

def h(seq):
    #http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3382369#3382369
    #by unutbu
    return sorted(range(len(seq)), key=seq.__getitem__)

rawDescription: Equivalent of Numpy.argsort() in basic python?


code: complete -r

rawDescription: Bash tab completion with argparse does not show all the files in the directory


code:
from scrapy.item import Item, Field

class DemoItem(Item):
    page = Field()
    urls = Field()
    pageurl = Field()
    title = Field()

rawDescription: selenium ajax dynamic pagination base spider

description: Selenium ajax dynamic pagination base spider


rawDescription: Add a HyperLink in django-rest-framework to a ModelViewSet


rawDescription: How to query a couchdb view using a composite key?

description: Query a couchdb view using a composite key


code:
def homogeneous_type(seq):
    iseq = iter(seq)
    first_type = type(next(iseq))
    return first_type if all( (type(x) is first_type) for x in iseq ) else False

rawDescription: Python check if all elements of a list are the same type


rawDescription: How can I pass union/intersection methods as a parameter in Python?

description: Pass union/intersection methods as a parameter in Python


code:
import MyClass
instance = MyClass.MyClass.getInstance()
#and then use all MyClass methods via instance, ex: instance.SomeMethod()

rawDescription: Using C++ DLLs in Python

description: Using C++ DLLs in Python


code:
class B(Base):
    # ...
    a = relationship(A, backref="b_s")

rawDescription: SQLAlchemy, select such A that has at least one B with raised flag


rawDescription: Applying different formula to each value in the list using if.. else


code: _.name = 'Count'

rawDescription: Need to aggregate count(rowid, colid) on dataframe in pandas


code:
def split_ip(ip):
    """Split a IP address given as string into a 4-tuple of integers."""
    return tuple(int(part) for part in ip.split('.'))

def my_key(item):
    return split_ip(item[0])

items = sorted(ipCount.items(), key=my_key)

rawDescription: How to sort IP addresses stored in dictionary in Python?

description: Sort IP addresses stored in dictionary in Python


rawDescription: Create parser with subcommands in argparse, customize positional argument(s)


code:
x=5
exec("x+=1")
print(x)

rawDescription: using exec() with python 3.2

description: Using exec() with python 3.2


code:
l1 = set(l1)
d2 = {}
for k, v in d1.iteritems():
    v = [s for s in v if s in l1]
    if v:
        d2[k] = v

rawDescription: Python dictionary comprehension very slow


code:
def onchange_casier_judiciare(self, cr, uid, ids, casier_judiciare, certificat_qual, extrait_role, reference_pro, context=None):
    if casier_judiciare and certificat_qual and extrait_role and reference_pro: # if they're all True (that means they're all checked):
        values = {'value': {'etat_dos': 'complet'}} #set the value of etat_dos field

        return values

rawDescription: How to Chage selection field automaticaly in odoo


code:
from gi.repository import Gtk
import sys

class Handler(object):
    def __init__(self, builder):
        self.builder = builder
        self.window = builder.get_object("window1")
        self.window.show_all()

    def on_window1_destroy(self, *args):
        Gtk.main_quit()

    def on_button1_clicked(self, button):
        print("Hello World!")

builder = Gtk.Builder()
builder.add_from_file("somegui.glade")
hdlr = Handler(builder)
builder.connect_signals(hdlr)
Gtk.main()

rawDescription: Closing the GUI window does not end the program


code:
date = data['Date'] # data is just the variable I am using to hold the csv file.
# The above line is just pulling the date column into it's own variable.

x1 = [dt.datetime.strptime(d, '%m/%d/%Y').date() for d in date]

rawDescription: show date on axis of a plot in matplotlib

description: Show date on axis of a plot in matplotlib


rawDescription: Python transform current list into 2d

description: Python transform current list into 2d


code:
# path to first file is ~/classes.csv
# path to second file is ~/abbr.csv

import csv

with open("~/classes.csv", 'rU') as classes_csv,\
     open("~/abbr.csv", 'rU') as abbr_csv:
    classes = csv.reader(classes_csv, delimiter='|')
    abbr = csv.reader(abbr_csv, delimiter=',')
    header = next(classes)

    abbr_dict = {line[1].strip():line[0].strip() for line in abbr}
    # create a lookup dictionary for your tags -> names

    class_tags = (line[2].strip("0123456789 ") for line in classes)
    # create a genexp for all the extant tags in ~/classes.csv

    result = {tag:abbr_dict[tag] for tag in class_tags if tag in abbr_dict}

rawDescription: Search and Find through a list Python

description: Search and Find through a list Python


code: from tensorflow.python.ops import control_flow_ops

rawDescription: TensorFlow Resize image tensor to dynamic shape


code:
# The complex numbers in "mgrid" give the number of increments
# mgrid[min:max:num*1j, min:max:num*1j] is similar to
# meshgrid(linspace(min, max, num), linspace(min, max, num))
y, x = np.mgrid[-5:5:100j, -5:5:100j]

# Our "inverted cone" is just the distance from 0
r = np.hypot(x, y)

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
sql = '''SELECT MAX(app_book.pub_date)
         FROM app_book
         WHERE app_book.author_id=app_author.id'''
latest = Author.objects.extra(
                select={'latest': sql},
                order_by=['-latest'])[:5].values_list('latest')
books = Book.objects.filter(pub_date__in=[x[0] for x in latest]).order_by('-pub_date')

rawDescription: How to retrieve the first X objects with unique attribute value

description: Retrieve the first X objects with unique attribute value


rawDescription: python leave-one-out estimation

description: Python leave-one-out estimation


code:
for name in expr2:
    try:
        expr1.remove(name)
    except ValueError:
        print('{n} is not in expr1'.format(n = name))

rawDescription: Different results achieved using Python's os.walk function and ls command


code:
def my_raw_input(stdscr, r, c, prompt_string):
    curses.echo()
    stdscr.addstr(r, c, prompt_string)
    stdscr.refresh()
    input = stdscr.getstr(r + 1, c, 20)
    return input  #       ^^^^  reading input at next line

rawDescription: How to input a word in ncurses screen?

description: Input a word in ncurses screen


code:
Lv = []
last, lastG = 0, 0
for g in num:
  Lval,x = quad(L, lastG, g)
  last, lastG = last + Lval, g
  Lv.append(last)
Lv = np.array(Lv)

rawDescription: How to make my python integration faster?

description: Make my python integration faster


code: re.findall( r'(viewAllLimiter =) (\w+)', txt )

rawDescription: Search string with re module in html page


code:
def f(foo, bar):
    for x in foo:
        do_something(bar, x)

f(bar=fubar, foo=(arg1, arg2, arg3))
f((arg1, arg2, arg3), bar=fubar) # same as previous line
f((arg1, arg2, arg3), fubar) # same as previous line

rawDescription: Python - Sending multiple values for one argument to a function


rawDescription: Working of Enumerate in Python

description: Working of Enumerate in Python


code:
aplogger = logging.getLogger('apscheduler')
aplogger.propagate = False
aplogger.setLevel(logging.WARNING)    # or whatever
aphandler = logging.FileHandler(...)  # as per what you want
aplogger.addHandler(aphandler)

rawDescription: How do I define a different logger for an imported module in Python?

description: Define a different logger for an imported module in Python


code:
import numpy as np
x, y, z = np.random.multivariate_normal(np.array([0,0,0]), np.eye(3), 200).transpose()
trace1 = dict(
    type = 'scatter3d',
    x=x,
    y=y,
    z=z,
    mode='markers',
    marker=dict(
        size=12,
        line=dict(
            color='rgba(217, 217, 217, 0.14)',
            width=0.5
        ),
        opacity=0.8
    )
)
layout = dict(
    margin=dict(
        l=0,
        r=0,
        b=0,
        t=0
    )
)
fig = dict(data = [trace1], layout = layout)

rawDescription: Plot 3D plots using plotly

description: Plot 3D plots using plotly


rawDescription: Better binning in pandas

description: Better binning in pandas


rawDescription: enumerating all possible strings of length K from an alphabet in Python

description: Enumerating all possible strings of length K from an alphabet in Python


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

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


rawDescription: In Python 3, how to copy a key-value mapping from one dict to another, including remove if necessary?


code:
class MyClass(object):
    def post(self, first_argument=None):
        # do stuff
        self.cleanup()

@settings.scheduler.interval_schedule(hours=2)
def my_job(first_argument=None):
    my_class = MyClass()
    my_class.post(first_argument)

rawDescription: passing current object to python apscheduler method

description: Passing current object to python apscheduler method


code:
@login_manager.unauthorized_handler
def handle_needs_login():
    flash("You have to be logged in to access this page.")
    return redirect(url_for('account.login', next=request.endpoint))

rawDescription: How do I pass through the "next" URL with Flask and Flask-login?

description: Pass through the "next" URL with Flask and Flask-login


code:
fig, ax = plt.subplots()
acorr(data)
plt.show()

rawDescription: bug of autocorrelation plot in matplotlib‘s plt.acorr?

description: Bug of autocorrelation plot in matplotlib‘s plt.acorr


code:
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

rawDescription: Asynchronous method call in Python?

description: Asynchronous method call in Python


code: df = pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000)

rawDescription: python - Using pandas structures with large csv(iterate and chunksize)

description: Python - Using pandas structures with large csv(iterate and chunksize)


code: df['itp'] = interpolate.UnivariateSpline(x, y, k=3)(df.index)

rawDescription: How to use `Series.interpolate` in pandas with the old values modified

description: Use `Series.interpolate` in pandas with the old values modified


code:
from bs4 import UnicodeDammit

dammit = UnicodeDammit(b"Sacr\xc3\xa9 bleu!")
print(dammit.unicode_markup)
# -> Sacré bleu!
print(dammit.original_encoding)
# -> utf-8

rawDescription: A good way to get the charset/encoding of an HTTP response in Python


code: [list(i) + j for i, j in dict([(tuple(x[:2]), x[2:]) for x in sorted(thing, key=lambda x:len(x))]).items()]

rawDescription: Unique items in a list with condition

description: Unique items in a list with condition


code:
from os import urandom

from zope.interface import implements

from twisted.internet.interfaces import IPullProducer

class RandomProducer(object):
    implements(IPullProducer)

    def __init__(self, consumer):
        self.consumer = consumer

    def resumeProducing(self):
        self.consumer.write(urandom(2 ** 16))

    def stopProducing(self):
        pass

rawDescription: sending random data with Twisted

description: Sending random data with Twisted


code: wButton = Button(self, text='text', command = self.OnButtonClick)

rawDescription: Python GUI code to click a button to open another window breaks


code:
import os
import sys

sys.argv[1]
fp = r'c:\test'
os.makedirs(os.path.join(fp,sys.argv[1]))

rawDescription: Pass argument from command button on Access form to python script


code:
my_string = '1: foo bar baz'
num_string, word_string = my_string.split(':')
num = int(num_string)
words = word_string.strip().split(' ')

print(num)
print(words)

rawDescription: Capture all repetitions of a group using Python regular expression


code:
'{:<20} {}'.format(*'{0} <COMMAND>: Help for <command>'.split(': '))
'%-20s %s' % tuple('{0} <COMMAND>: Help for <command>'.split(': '))

rawDescription: How to Left Justify part of a String in python?

description: Left Justify part of a String in python


code:
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt

# Note that the output interpolated coords will be the same dtype as your input
# data.  If we have an array of ints, and we want floating point precision in
# the output interpolated points, we need to cast the array as floats
data = np.arange(40).reshape((8,5)).astype(np.float)

# I'm writing these as row, column pairs for clarity...
coords = np.array([[1.2, 3.5], [6.7, 2.5], [7.9, 3.5], [3.5, 3.5]])
# However, map_coordinates expects the transpose of this
coords = coords.T

# The "mode" kwarg here just controls how the boundaries are treated
# mode='nearest' is _not_ nearest neighbor interpolation, it just uses the
# value of the nearest cell if the point lies outside the grid.  The default is
# to treat the values outside the grid as zero, which can cause some edge
# effects if you're interpolating points near the edge
# The "order" kwarg controls the order of the splines used. The default is
# cubic splines, order=3
zi = ndimage.map_coordinates(data, coords, order=3, mode='nearest')

row, column = coords
nrows, ncols = data.shape
im = plt.imshow(data, interpolation='nearest', extent=[0, ncols, nrows, 0])
plt.colorbar(im)
plt.scatter(column, row, c=zi, vmin=data.min(), vmax=data.max())
for r, c, z in zip(row, column, zi):
    plt.annotate('%0.3f' % z, (c,r), xytext=(-10,10), textcoords='offset points',
            arrowprops=dict(arrowstyle='->'), ha='right')
plt.show()

rawDescription: Multivariate spline interpolation in python/scipy?


rawDescription: getting only integers from a list of tuples python 3

description: Getting only integers from a list of tuples python 3


code:
from blist import sortedlist

l = ['b',"a", 'c', 'e']
b = sortedlist(l)

b.add("f")
print(b)
sortedlist(['a', 'b', 'c', 'e', 'f'])

rawDescription: Python - efficiently find where something would land in a sorted list?


code:
hints = ["a", "b", "c"]
generators = list(map(gen_fun, hints))
for x in zip_longest(*generators):
    for txt in x:
        if txt:
            print(txt)

rawDescription: Transpose nested generators

description: Transpose nested generators


code:
data=np.random.normal(mu,sigma,10000)
normed_data=(data-mu)/sigma
print(stats.kstest(normed_data,'norm'))
# (0.0085805670733036798, 0.45316245879609179)

rawDescription: Implementing a Kolmogorov Smirnov test in python scipy


code:
lines = []
for key, case in self.cases.items():
    a = key, case.color, case.thetype
    lines.append("{0!r}\n".format(a))
return ''.join(lines)

rawDescription: how to return the iterations over keys as a string?

description: Return the iterations over keys as a string


code:
min = 0.1
tol = 0.05
where = np.where((diffs >= min) & (diffs < min + tol))

rawDescription: Algorithm to find indices of two numbers in Series with difference within a specified range


code:
import Image
import numpy as np

im = Image.open('Cam_1.bmp')
#im.show()
r,g,b = im.split()

y = Image.fromarray(np.zeros(im.size[0]*im.size[1]).reshape(im.size[1],im.size[0]).astype('float')).convert("L")

red = Image.merge("RGB",(r,y,y))

green = Image.merge("RGB",(y,g,y))

rawDescription: Why does skimage.imread() not return RGB values for my bmp?


rawDescription: Scipy: Argrelmax Find Maxmima along Dimension in 3d Array


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


code:
from functools import partial
defaultdict(partial(deque, maxlen=10))

rawDescription: Issues with generating a defaultdict with a deque


code:
bw = arr > 0.3
plt.imshow(bw)
plt.show()

rawDescription: Making an image black and white in python without pillow


code:
import MySQLdb
column = str(MySQLdb.escape_string(row[1]))
query = "update myTable set %(column)s = %%s where ID = %%s" % dict(column = column)
cursor2.execute(query, [row[3], row[0]])

rawDescription: What is the best escape character strategy for Python/MySQL combo?


code: [{"param331": [value, value, value], "param332": [value, value, value]}]

rawDescription: How to assign floats to some fields of json dumps using a for loop

description: Assign floats to some fields of json dumps using a for loop


code:
def __radd__(self, other):
    if isinstance(other, C):
        return other.value + self.value
    if isinstance(other, Number):
        return other + self.value
    return NotImplemented

rawDescription: How to get __add__ called

description: Get __add__ called


code:
from django.db import models

class Mall(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return u"%s" % (self.name)

class Shop(models.Model):
    name = models.CharField(max_length=200)
    mall = models.ForeignKey(Mall)

    def __unicode__(self):
        return u"%s" % (self.name)

class Employee(models.Model):
    name = models.CharField(max_length=200)
    hired_by = models.ForeignKey(Shop)

    def __unicode__(self):
        return u"%s" % (self.name)

rawDescription: How do I create this object with the models I have set up?

description: Create this object with the models I have set up


code:
for t in allbinarytrees('1+2-3*4/5'):
    print(t)

rawDescription: What python code generates all possible groupings (trees) for binary operators


code:
alphabet = 'abcdefghijklmnopqrstuvwxyz '
ch = ':;:'.join(''.join(choice(alphabet) for nc in xrange(randrange(0,60)))
                for i in xrange(324000))
with open('fofo.txt','wb') as g:
    g.write(ch)

rawDescription: Special End-line characters/string from lines read from text file, using Python


code:
from links.views import MyRegistrationView

url(r'^register/$', MyRegistrationView.as_view(), name='register'),

rawDescription: Removing second password input from django-registration form


code: series.index = series.index.str.replace('@', '')

rawDescription: Replacing Index values using regex matching


rawDescription: passing dictionaries to other functions

description: Passing dictionaries to other functions


code:
#!/usr/bin/env python3

from gi.repository import Gtk

class Handler:
    def __init__(self, builder):
        self.builder = builder
        self.window = builder.get_object('window1')

    def run(self):
        self.window.show_all()
        Gtk.main()

    def on_app_exit(self, widget, event=None):
        Gtk.main_quit()

    def on_button_show_clicked(self, btn):
        dialog_info = self.builder.get_object('messagedialog_info')
        entry = self.builder.get_object('entry1')
        labels = dialog_info.get_children()[0].get_children()[0].get_children()[1].get_children()
        print(labels)
        # labels[0] is the primary label.
        # labels[1] is the seconary label.
        labels[0].set_text(entry.get_text())

        response = dialog_info.run()
        print('response: ', response)
        dialog_info.hide()

def main():
    builder = Gtk.Builder()
    builder.add_from_file('example.glade')
    handler = Handler(builder)
    builder.connect_signals(handler)
    handler.run()

if __name__ == '__main__':
    main()

rawDescription: How to change primary text in gtk messagedialog in python?

description: Change primary text in gtk messagedialog in python


code:
idx = df.columns.to_series().str.startswith('partial_lab')
df.loc[:,idx]

rawDescription: How to filter pandas dataframe columns by partial label

description: Filter pandas dataframe columns by partial label


code:
from pandas.tools.util import cartesian_product
MultiIndex.from_arrays(cartesian_product([range(3),list('ab')]))

rawDescription: Make a Pandas MultiIndex from a product of iterables?


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

def twinboth(ax):
    # Alternately, we could do `newax = ax._make_twin_axes(frameon=False)`
    newax = ax.figure.add_subplot(ax.get_subplotspec(), frameon=False)
    newax.xaxis.set(label_position='top')
    newax.yaxis.set(label_position='right', offset_position='right')
    newax.yaxis.get_label().set_rotation(-90) # Optional...
    newax.yaxis.tick_right()
    newax.xaxis.tick_top()
    return newax

# Generate random data.
x1 = np.random.randn(50)
y1 = np.linspace(0, 1, 50)
x2 = np.random.randn(20)+15.
y2 = np.linspace(10, 20, 20)

# Plot both curves.
fig, ax1 = plt.subplots()

ax1.set(xlabel='x_1', ylabel='y_1')
ax1.plot(x1, y1, c='r')

ax2 = twinboth(ax1)
ax2.set(xlabel='x_2', ylabel='y_2')
ax2.plot(x2, y2, c='b')

plt.show()

rawDescription: One secondary label missing when plotting x and y secondary axis


rawDescription: How to get a list of the elements in TreeView? PyGtk

description: Get a list of the elements in TreeView? PyGtk


code:
records = od['records']
data = {}

for rec in records:
    for k, v in rec.items():
        if k == 'attributes':
            continue
        data.setdefault(k, []).append(v)

dframe = pandas.DataFrame(data)
print(dframe)

rawDescription: Python: Parsing OrderedDict of OrderedDicts into Pandas Dataframe


code:
#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os

def zipdir(basedir, archivename):
    assert os.path.isdir(basedir)
    with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
        for root, dirs, files in os.walk(basedir):
            #NOTE: ignore empty directories
            for fn in files:
                absfn = os.path.join(root, fn)
                zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
                z.write(absfn, zfn)

if __name__ == '__main__':
    import sys
    basedir = sys.argv[1]
    archivename = sys.argv[2]
    zipdir(basedir, archivename)

rawDescription: How do I zip the contents of a folder using python (version 2.5)?

description: Zip the contents of a folder using python (version 2.5)


code: pd.read_csv('rawdata.txt', converters={'voltage(V)': binary, 'current(A)': binary}, delimiter=" ,", engine='python')

rawDescription: I am trying to get binary data from text and converting to numpy arrays


code: [x._short_opts + x._long_opts for x in parser._get_all_options()]

rawDescription: Python : Not able to get the list of the options that have been added via 'add_option'?


code: help(send)

rawDescription: Scapy send function without output

description: Scapy send function without output


code:
from itertools import product, takewhile
def new(max_len_string, alphabet=range(2)):
    alphabet = list(alphabet)
    zero = alphabet[0]
    for p in product(alphabet, repeat=max_len_string):
        right_zeros = sum(1 for _ in takewhile(lambda x: x==zero, reversed(p)))
        base = p[:-right_zeros]
        yield from filter(None, (base+(zero,)*i for i in range(right_zeros)))
        yield p

rawDescription: Iterator for all lexicographically ordered variable strings up to length n


rawDescription: Python card guessing game

description: Python card guessing game


code:
commands = {
    "view mail": view_mail,
    "send mail": send_mail,
    "logout": lambda u: True
}

rawDescription: Variable scope problems with dictionaries


rawDescription: How to remove the last element in each tuple in a list

description: Remove the last element in each tuple in a list


code:
menubar.Bind(wx.EVT_MENU, onDocClick, documentation)
menubar.Bind(wx.EVT_MENU, onAboutClick, about)

rawDescription: wxPython: MenuBar Bound Events Execute on Init

description: WxPython: MenuBar Bound Events Execute on Init


code:
@route('/')
def index():
    return template('page2')

rawDescription: Return valus from Python file to HTML buy press submit button?


code:
def crunchy_frog():
    '''Only the freshest killed frogs... '''
    # TODO: implement

def anthrax_ripple():
    '''A delightful blend of Anthrax spores... '''
    # TODO: implement

def spring_surprise():
    '''Deploy stainless steel bolts, piercing both cheeks'''
    # TODO: implement

rawDescription: Can I get pip to delete scripts that I installed but no longer want?

description: Get pip to delete scripts that I installed but no longer want


code:
import csv

driver_details = {}

with open('Driver Details.csv') as f_driver_details:
    csv_driver_details = csv.reader(f_driver_details)
    header = next(csv_driver_details)       # skip the header

    for row in csv_driver_details:
        driver_details[row[7]] = row

with open('Standard Reg.csv') as f_standard_reg:
    csv_standard_reg = csv.reader(f_standard_reg)
    header = next(csv_standard_reg)     # skip the header

    for row in csv_standard_reg:
        try:
            driver = driver_details[row[3]]
            print('Match found - {} {}'.format(driver[0], driver[1]))
        except KeyError as e:
            print('No match found')

rawDescription: How to compare two csv files in Python

description: Compare two csv files in Python


code:
import numpy as np
a = np.array(a)
index_0 = np.where(a == 0)[0]
index_1 = np.where(a == 1)[0]

rawDescription: how to find all the index of an element in a list Python

description: Find all the index of an element in a list Python


code: menu=QMenu()

rawDescription: How to apply CSS Style to QMenu via an entire MainWIndow

description: Apply CSS Style to QMenu via an entire MainWIndow


code:
import json
json.loads(my_str)

rawDescription: Python convert string of characters into proper list structure


code:
pot = [2**x for x in range(8)]  # Powers of 2 (bytes with one 1 and seven 0s)
bitvalues = {}
for x in range(256):
    bitvalues[chr(x)] = [(x & y) != 0 for y in pot]

rawDescription: Python: What's the best way to send status bits and timestamps with PySerial


code:
def ifEven(x):
    if isinstance(x, tuple):
        for i in x:
            if i % 2 == 0:
                return True
    return False

rawDescription: Python: Function to find out if a tuple contains even numbers?


code:
DATA = {
0 : ("3", "3", "1"),
1 : ("2", "1", "2"),
2 : ("1", "2", "3")
}

import wx
import wx.lib.mixins.listctrl as listmix
from wx.lib.agw import ultimatelistctrl as ULC

class MyList(ULC.UltimateListCtrl, listmix.ColumnSorterMixin):
    def __init__(self, parent, columns):
        ULC.UltimateListCtrl.__init__(self, parent, agwStyle=ULC.ULC_REPORT | ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)
        self.itemDataMap = DATA
        listmix.ColumnSorterMixin.__init__(self, columns)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumn)

    def OnColumn(self, e):
        self.Refresh()
        e.Skip()

    def GetListCtrl(self):
        return self

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.list = MyList(self, 3)
        self.list.InsertColumn(0, "A")
        self.list.InsertColumn(1, "B")
        self.list.InsertColumn(2, "C")

        items = DATA.items()
        for key, data in items:
            index = self.list.Append(data)
            self.list.SetItemData(index, key)

        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Sort items in UltimateListCtrl

description: Sort items in UltimateListCtrl


code: print('The person %s is %s years old and %s meters tall.' % (splitted_line[0], splitted_line[1], splitted_line[2]))

rawDescription: How to parse csv file and compute stats based on that data

description: Parse csv file and compute stats based on that data


code:
#(Re)Build schedule on screen
def BuildSchedule():
    global widgets
    widgets = {}

    for r in range(1,4):
        label = Label(ScheduleFrame, text=stafflist[r-1].name)
        label.grid(row=r, column=0)
        widgets[(r,0)] = label

    for c in range(1,15):
        label = Label(ScheduleFrame, text=weekdays[(c-1)%7])
        label.grid(row=0, column=c)
        widgets[(0,c)] = label

    for r in range(1,4):
        for c in range(1,15):
            label = Label(ScheduleFrame, text=scheduleDictionary[r-1][c-1])
            label.grid(row=r, column=c)
            widgets[(r,c)] = label

rawDescription: Tkinter label overwrite: update or refresh?


code: print(*result, sep='\n')

rawDescription: Parsing regular strings into a tuple

description: Parsing regular strings into a tuple


code:
def create_entry(key1, key2, value, shelf):
    shelf[(key1, key2)] = value

rawDescription: Python dictionary with two keys with shelve


code:
raw_data = [ 'LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i', 'COMMENT ii',
'COMMENT iii', 'GROUP Y', 'COMMENT iv', 'COMMENT v', 'COMMENT vi', 'LEVEL 2',
'SUBJECT B', 'GROUP Z', 'COMMENT vii', 'COMMENT viii', 'COMMENT ix',
'SUBJECT C', 'GROUP X2', 'COMMENT x', 'COMMENT xi', 'COMMENT xii',
'COMMENT xiii', 'GROUP Y2', 'COMMENT xiv', 'COMMENT xv', 'COMMENT xvi' ]

level, subject, group, comment = '', '', '', ''

result = []

for item in raw_data:

    if item.startswith('COMMENT'):
        comment = item
    elif item.startswith('GROUP'):
        group = item
        comment = ''
    elif item.startswith('SUBJECT'):
        subject = item
        group = ''
    elif item.startswith('LEVEL'):
        level = item
        subject = ''

    if level and subject and group and comment:
        result.append([level, subject, group, comment])

import pprint
pprint.pprint(result)

rawDescription: What is the best way in python to get a denormalized array from this ordered array?


code:
SomeModel.objects.filter(user=some_user)
# where `user` is the name of your foreign key field

rawDescription: How the datas are connected to the specific user ID?


code:
fd = open(filename)
str = ''.join([line.rstrip('\n') for line in fd if not (line.startswith('>from') or line.startswith('*'))])

rawDescription: Explicit line joining in Python

description: Explicit line joining in Python


code:
A * mat(vec)
#ValueError: dimension mismatch

rawDescription: Numpy/Scipy Sparse vs dense multiplication