code:
start = dt.datetime(year=2000,month=1,day=1)
time = datalvm['time'][1:]
floatseconds = map(float,time) #str->float

#floats to datetime objects -> this is you timeseries index
datetimes = map(lambda x:dt.timedelta(seconds=x)+start,floatseconds)

#construct the time series
timeseries = dict() #timeseries are collected in a dictionary
for signal in datalabels[1:]:
    data =map(float,datalvm[signal][1:].values)
    t_s = pd.Series(data,index=datetimes,name=signal)
    timeseries[signal] = t_s

#convert timeseries dict to dataframe
dataframe = pd.DataFrame(timeseries)

rawDescription: pandas timeseries with relative time

description: Pandas timeseries with relative time


rawDescription: If I use a for loop with a string, will it check character by character?


code:
n, bins, patches = ax.hist([1,2,3,4])
n
bins
patches

rawDescription: Matplotlib Xticklabels not working

description: Matplotlib Xticklabels not working


rawDescription: float random.uniform to 4 decimal places in python

description: Float random.uniform to 4 decimal places in python


code:
class LabelMapperProxy(object):
    def __init__(self, mapper): self.__dict__['mapper'] = mapper

rawDescription: Proxy class for accessing other class' items as attributes (__getitem__ infinite recursion)


code: vis = np.concatenate((img1, img2), axis=0)

rawDescription: Combining Two Images with OpenCV

description: Combining Two Images with OpenCV


rawDescription: compare if an element exists in two lists

description: Compare if an element exists in two lists


code:
import pandas as pd
def EBIT(t):
    if pd.notnull(df['EBIT'][t]):
        return df['EBIT'][t]

    df['EBIT'][t] = df['revenue'][t] - df['costs'][t]
    ...

rawDescription: Financial modelling with Pandas dataframe


rawDescription: Check if a timestamp string is within a time range


code:
the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length

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

description: Sort by length of string followed by alphabetical order


code:
with mmap.mmap(f.fileno(), access=mmap.ACCESS_READ) as m:
    process(m)

rawDescription: Process large data in python

description: Process large data in python


code:
import scipy.sparse as sparse
import numpy as np
import math

def fCosine(u,v): # u,v CSR vectors, Cosine Dissimilarity
    uData = u.data; vData = v.data
    denominator = np.sqrt(np.sum(uData**2)) * np.sqrt(np.sum(vData**2))
    if denominator>0:
        uCol = u.indices; vCol = v.indices # np array
        intersection = set(np.intersect1d(uCol,vCol))
        uI = np.array([u1 for i,u1 in enumerate(uData) if uCol[i] in intersection])
        vI = np.array([v2 for j,v2 in enumerate(vData) if vCol[j] in intersection])
        return 1-np.dot(uI,vI)/denominator
    else:
        return float("inf")

def alt_fCosine(u,v):
    uData, vData = u.data, v.data
    denominator = math.sqrt(np.sum(uData**2) * np.sum(vData**2))
    if denominator>0:
        uCol, vCol = u.indices, v.indices
        uI = uData[np.in1d(uCol, vCol)]
        vI = vData[np.in1d(vCol, uCol)]
        return 1-np.dot(uI,vI)/denominator
    else:
        return float("inf")

# Check that they return the same result
N = 10**5
u = np.round(10*sparse.random(1, N, density=0.1, format='csr'))
v = np.round(10*sparse.random(1, N, density=0.1, format='csr'))
assert np.allclose(fCosine(u, v), alt_fCosine(u, v))

rawDescription: Faster Python Cosine dissimilarity between Scipy CSR "vectors"


code:
import re
p=re.compile(r'(^.*?)(?:\Ws(?:eason )?(\d{1,2}|[ivxlcdm]{1,5}))?\Wp(?:art )?(\d{1,2}|[ivxlcdm]{1,5})\W(.*$)', re.I)
p.search('miniseries.season 1.part 5.720p.avi').groups()
p.search('miniseries.part 5.720p.avi').groups()
p.search('miniseries.part VII.720p.avi').groups()

rawDescription: python regex optional capture group

description: Python regex optional capture group


code: ((value & 0x1fffff) >> 8).to_bytes(2, byteorder='big')

rawDescription: How to shift bits in a 2-5 byte long bytes object in python?

description: Shift bits in a 2-5 byte long bytes object in python


code:
with open('output.txt', 'w') as f:
    for pair in pairs:
        f.write('%s is paired with %s\n' % pair)

rawDescription: Pairing a name from one text file with a random name from the same text file


code:
test_list = ['a', 'A', 'g', 'G']
precedence_dict = {'A':0, 'a':1, 'G':2,'g':3}
test_list.sort(key=lambda x: precedence_dict[x])
test_list

rawDescription: Rearrange strings in list alphabetically and by case


code:
seen = set()
lis = []

lis
d = {x:i for i,x in enumerate(lis)}

rawDescription: Enumerate unique strings in list

description: Enumerate unique strings in list


rawDescription: Calculating percentage based on python dictionaries


code:
parent = {}
children = {}
with open( 'my.csv', 'rt' ) as fh:
    for line in fh:
        # strip the comments and line endings
        if '#' in line: line = line[ :line.index( '#' ) ]
        line = line.strip()
        if line:
            # record the association
            node, subnode = line.split( ',', 1 )
            parent[ subnode ] = node
            children.setdefault( node, [] ).append( subnode )

rawDescription: Array Associations Python

description: Array Associations Python


code:
PASTEBIN_STORAGE_OPTIONS = {
    'api_dev_key' : '<your_api_dev_key>',
}

rawDescription: Passing an input to a service and saving the result to DB in Django


code:
def dealHand2(n):
    while True:
        candidate = dealHand(n)
        if all(v <= 2 for v in candidate.values()):
            return candidate

rawDescription: random chars for word game python

description: Random chars for word game python


code: {k: [v, v/var1, v/var1+var2] for k, v in band1.iteritems()}

rawDescription: adding arithmetic values to dictionary?

description: Adding arithmetic values to dictionary


code: word = word.rstrip()

rawDescription: Writing tab spaced words to a file in Python


code:
a
[i.split("\n") for i in a]

rawDescription: How do I split a list into a list of lists on a specific character in the elements?

description: Split a list into a list of lists on a specific character in the elements


code:
query_dict = csv.DictReader(query,fieldnames=('ip','na-1','na-2','time', 'zone', 'url', 'refer', 'client'),quotechar='"',delimiter=" ")
veggies = [ x for x in query_dict if re.search('veggies',x['url']) ]
query_dict = csv.DictReader(query,fieldnames=('ip','na-1','na-2','time', 'zone', 'url', 'refer', 'client'),quotechar='"',delimiter=" ")
fruits = [ x for x in query_dict if re.search('fruits',x['url']) ]

rawDescription: Why can't I split this python list?

description: Why can't I split this python list


code:
categories_from_form = request.form.getlist('categories') # ['bar']
# create Category objects with the form data
categories = [Category(title=title) for title in categories_from_form]

post = Post(request.form['title'], request.form['content'], request.form['slug'], request.form['published'])
post.categories = categories # attach the Category objects to the post
...

rawDescription: How to use many-to-many fields in Flask view?

description: Use many-to-many fields in Flask view


code:
results = set()
for node in nodes:
    results.update(foo(node))

rawDescription: Python create union of results from function applied to elements in a set


code:
def my_key_func(x):
    if x=='dev':
        return (1,x)
    else:
        return (0,x)
ls.sort(key=my_key_func)
ls

rawDescription: How to sort a list with user defined condition in python?

description: Sort a list with user defined condition in python


code:
import sqlite3
import csv, codecs, cStringIO

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([unicode(s).encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

conn = sqlite3.connect('yourdb.sqlite')

c = conn.cursor()
c.execute('select * from yourtable')

writer = UnicodeWriter(open("export.csv", "wb"))

writer.writerows(c)

rawDescription: It is possible export table sqlite3 table to csv or similiar?


code: from urllib.parse import urlparse

rawDescription: python 2 and 3 extract domain from url

description: Python 2 and 3 extract domain from url


code:
def selectAll(self):
    """Select all data in both tables"""

    for table in [self._header_table, self._data_table]:
        for row in xrange(table.rowCount()):
            for col in xrange(table.columnCount()):
                item = table.item(row, col)
                table.setItemSelected(item, True)

rawDescription: Create QTableWidget with 2 or more header rows


code:
# For lists
self.items = list(temporary_list)
# For sets
self.items = set(temporary_list)
# And so on...

rawDescription: Adding an element to a collection type without changing the collection type in Python


code:
reg = re.compile('\w*?(\d+)\\n')
lst.sort(key=lambda s: int(reg.match(s).group(1)))

rawDescription: Sort strings accompanied by integers in list


rawDescription: Python 3.4 Import a list to function

description: Python 3.4 Import a list to function


code:
for x in soup.find_all('a'):
    for k, v in categories.iteritems():
        if v in x['href']:
            return k

rawDescription: Making multiple if statements less verbose


code:
def yield_adjacent(lst):
    it = iter(lst)
    sub = [next(it)]
    for n in it:
        if n - sub[-1] == 1:
            sub.append(n)
        else:
            yield tuple(sub)
            sub = [n]
    yield tuple(sub)

rawDescription: Create a list of tuples containing adjacent numbers?


code:
m,n = M.size, N.size    # Size parameters

X = np.zeros((m,n),dtype=N.dtype)
Y = np.zeros((m,n),dtype=M.dtype)

X += N
Y += M[::-1,None]

rawDescription: Repeating rows and columns in Python

description: Repeating rows and columns in Python


code:
import pprint
pprint.pprint(c.configure())
{'background': ('background',
                'background',
                'Background',
                'SystemButtonFace',
                'SystemButtonFace'),
 'bd': ('bd', 'borderWidth'),
 'bg': ('bg', 'background'),
 'borderwidth': ('borderwidth', 'borderWidth', 'BorderWidth', '0', '0'),
 'closeenough': ('closeenough', 'closeEnough', 'CloseEnough', '1', '1.0'),
 'confine': ('confine', 'confine', 'Confine', '1', '1'),
 'cursor': ('cursor', 'cursor', 'Cursor', '', ''),
 'height': ('height', 'height', 'Height', '7c', '100'),
 'highlightbackground': ('highlightbackground',
                         'highlightBackground',
                         'HighlightBackground',
                         'SystemButtonFace',
                         'SystemButtonFace'),
 'highlightcolor': ('highlightcolor',
                    'highlightColor',
                    'HighlightColor',
                    'SystemWindowFrame',
                    'SystemWindowFrame'),
 'highlightthickness': ('highlightthickness',
                        'highlightThickness',
                        'HighlightThickness',
                        '2',
                        '0'),
 'insertbackground': ('insertbackground',
                      'insertBackground',
                      'Foreground',
                      'SystemButtonText',
                      'SystemButtonText'),
 'insertborderwidth': ('insertborderwidth',
                       'insertBorderWidth',
                       'BorderWidth',
                       '0',
                       '0'),
 'insertofftime': ('insertofftime', 'insertOffTime', 'OffTime', '300', '300'),
 'insertontime': ('insertontime', 'insertOnTime', 'OnTime', '600', '600'),
 'insertwidth': ('insertwidth', 'insertWidth', 'InsertWidth', '2', '2'),
 'offset': ('offset', 'offset', 'Offset', '0,0', '0,0'),
 'relief': ('relief', 'relief', 'Relief', 'flat', 'flat'),
 'scrollregion': ('scrollregion', 'scrollRegion', 'ScrollRegion', '', ''),
 'selectbackground': ('selectbackground',
                      'selectBackground',
                      'Foreground',
                      'SystemHighlight',
                      'SystemHighlight'),
 'selectborderwidth': ('selectborderwidth',
                       'selectBorderWidth',
                       'BorderWidth',
                       '1',
                       '1'),
 'selectforeground': ('selectforeground',
                      'selectForeground',
                      'Background',
                      'SystemHighlightText',
                      'SystemHighlightText'),
 'state': ('state', 'state', 'State', 'normal', 'normal'),
 'takefocus': ('takefocus', 'takeFocus', 'TakeFocus', '', ''),
 'width': ('width', 'width', 'Width', '10c', '100'),
 'xscrollcommand': ('xscrollcommand',
                    'xScrollCommand',
                    'ScrollCommand',
                    '',
                    ''),
 'xscrollincrement': ('xscrollincrement',
                      'xScrollIncrement',
                      'ScrollIncrement',
                      '0',
                      '0'),
 'yscrollcommand': ('yscrollcommand',
                    'yScrollCommand',
                    'ScrollCommand',
                    '',
                    ''),
 'yscrollincrement': ('yscrollincrement',
                      'yScrollIncrement',
                      'ScrollIncrement',
                      '0',
                      '0')}

rawDescription: Why does the Tkinter canvas request 4 extra pixels for the width and height?


code:
from datetime import datetime
import time
d = datetime.strptime('2014-07-16 16:10:22.380059', '%Y-%m-%d %H:%M:%S.%f')
time.mktime(d.timetuple())

rawDescription: How to obtain and then compare two timestamp values from postgreSQL via python?

description: Obtain and then compare two timestamp values from postgreSQL via python


code:
r = requests.get(link, timeout=10, headers={'User-Agent': 'Mozilla/5.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'}, verify=False)
r.headers

rawDescription: requests: cannot download zip file properly with verify is False

description: Requests: cannot download zip file properly with verify is False


rawDescription: How to correctly call variables from a txt file into my python code?

description: Correctly call variables from a txt file into my python code


code:
def checkSolution(problem, solution):
    return re.match("^" + ".".join(map(re.escape, problem.split("#"))) + "$",
                    solution)

rawDescription: Comparing similarity of two strings in Python


code:
def handle_wait(self, event):
    # cancel the old job
    if self._after_id is not None:
        self.after_cancel(self._after_id)

    # create a new job
    self.after(1000, self.change_color)

rawDescription: Wait until user stopped typing in Tkinter


code: datetime.datetime.now().replace(day=1, hour=0, minute=0, second=0).timetuple()

rawDescription: Python parsedatetime: get current month / first of the month


code:
import json

my_dict = {'name': 'georgi',\
        'famili': 'ivanov',\
        'drinks': json.dumps([\
           {"breakfast": "milk", "lunch": "beer",},\
           {"breakfast": "tea", "lunch":"vodka"}])};

ddict = json.loads(my_dict["drinks"]) # json str to python data types

seen = {}; # store the items already seen

# for each dictionary object in key3
for d in range(0,len(ddict)):
    for k in ddict[d]:
        if k in seen:
            # update the value to the one already seen
            ddict[d][k] = seen[k];

        if k == "lunch" and (ddict[d] == "" or ddict[d] is None):
            ddict[d] = alternative_lunch_value;

        else:
            seen[k] = ddict[d][k];

my_dict["drinks"] = json.dumps(ddict);

print(my_dict);

rawDescription: Change json.dumps dictionary values in python


code:
from cPickle import Unpickler

up = Unpickler(open('data.pkl', 'r'))
lst = up.load()

rawDescription: Storing a list, then reading it as integer


code:
import subprocess
import os
import sys
import time
import random
import gc  # This is just to test the hypothesis that garbage collection of p=Popen() causing the problem.

# This spawns many (3) children in quick succession
# and then reports as each child finishes.
if __name__=='__main__':
    N=3
    if len(sys.argv)>1:
        x=random.randint(1,10)
        print('{p} sleeping for {x} sec'.format(p=os.getpid(),x=x))
        time.sleep(x)
    else:
        for script in xrange(N):
            args=['test.py','sleep']
            p = subprocess.Popen(args)
        gc.collect()
        for i in range(N):
            pid,retval=os.wait()
            print('{p} finished'.format(p=pid))

rawDescription: Why do I have to use .wait() with python's subprocess module?


code: known[res] = n

rawDescription: Memos in python (Think Python exercise 11.6)


code: from your_app.models import *

rawDescription: Using Django database layer outside of Django?


rawDescription: Remove white spaces from dict : Python

description: Remove white spaces from dict : Python


code:
a = b'Path\xc3\xa9'
a
print(a)
sys.getdefaultencoding()
hash('Pathé')
hash(b'Path\xc3\xa9')

rawDescription: Accentuation in python: structure and for loop


code:
with open('ofile.txt','w+') as f:
    max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))
    for line in zip(COLUMN_1,COLUMN_2):
        f.write(','.join(('{:<%s}' % (max_len)).format(e) for e in line)+'\n')

rawDescription: How to center align columns of different lengths using numpy.savetxt in Python?

description: Center align columns of different lengths using numpy.savetxt in Python


code:
np.array(a) # 9.92ms
np.fromiter(a, dtype=np.float) # 5.19ms

rawDescription: fastest way to populate a 1D numpy array

description: Fastest way to populate a 1D numpy array


rawDescription: Suppose I have a dictionary. How do I strip out all the keys? Edit: This is a nested dictionary


code:
df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 0])
df
df[[0]]  # ambiguous

rawDescription: Python pandas: Keep selected column as DataFrame instead of Series


code:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

x = np.arange(0, 10, 0.2)
y = [2.5, 3, 1.5, ... , 7, 9]
ax.plot(x, y)
plt.show()

rawDescription: Python Pyplot: How to scale x-axis independant from number of list-elements?


code:
t = tuple(map(d.get, df1.index.names))
t
df1.loc[t]

rawDescription: Is it possible to explicitly to refer to indexes by their name in pandas data frame?


code:
for count,i in enumerate(I_phase):
    F = sum(m*np.cos(2*np.pi*l*x/D) for m,l in zip(i,n))
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title(titlelist[count])
    ax.plot(x,F)
    fig.savefig(str(count)+'.png')

rawDescription: Giving different titles to plots in for-loop


code:
A = la.inv(np.dot(np.dot(points.T, np.diag(u)), points)
           - np.dot(c[:, np.newaxis], c[np.newaxis, :]))/d

rawDescription: Port MATLAB bounding ellipsoid code to Python


rawDescription: Efficiently build a graph of words with given Hamming distance


code: lazy_function = lazy(f, type)

rawDescription: How do I use django @lazy decorator?

description: Use django @lazy decorator


code:
from collections import defaultdict
doc_words = defaultdict(list)
for d, w in doc_has_word:
    doc_words[tuple(d.items())].append(w)

rawDescription: Searching a normal query in an inverted index


rawDescription: Converting a list of tuples into a simple flat list


code: sum(k*v for k,v in a.items())

rawDescription: Multiply keys*values in a dict?

description: Multiply keys*values in a dict


rawDescription: How do binary operations with XOR in python work?


rawDescription: Rounding a number in python but keeping ending zeros


code: print ()

rawDescription: How to print a list of integers in 10 columns?

description: Print a list of integers in 10 columns


code:
a = numpy.zeros((3, 3, 3))
a += numpy.array((1, 3, 2)).reshape((3, 1, 1))
b = numpy.arange(3*3*3).reshape((3, 3, 3))
c = numpy.array(zip(a.flatten(), b.flatten()), dtype=[('f', float), ('i', int)]).reshape(3, 3, 3)
c.sort(axis=0)
c['i']

rawDescription: Sort a numpy array by another array, along a particular axis, using less memory


code:
@pyqtSlot(int)
def on_my_signal_int(self, value):
    assert isinstance(value, int)

@pyqtSlot(str)
def on_my_signal_str(self, value):
    assert isinstance(value, str)

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


code:
def do_with_line(line):
    return line

with open("filename") as f:
    process = [do_with_line(line) for line in f]

rawDescription: Preferred file line by line read idiom in Python


code:
my_list.sort() # sort list in place
new_list = sorted(my_list)

rawDescription: Is it legal to define two methods with the same name but different returning types?


code:
f=open( 'myfile.txt', 'r')
for line in f.readlines():
    # suppose line is '["a","b","c"]'
    a = line.split( ',' )
    # a is now the list [ '["a"', '"b"', '"c"]' ]

    # To strip away the brackets use this instead:
    a = line.strip('[]').split( '[]' )
    # a is now the list [ '"a"', '"b"', '"c"' ]

    # To strip away the spurious quote marks use this instead:
    a = [ s.strip('"') for s in line.strip('[]').split(',') ]
    # a is now the list [ 'a', 'b', 'c' ]

rawDescription: Python how to read multiple inputs in a same line


code:
def calculate_distance(l, start_pos=[0,0]):
    curr = start_pos[:]
    for coord in l:
        direction, dist = coord.split()
        dist = float(dist)
        if direction == 'UP':
            curr[1] += dist
        elif direction == 'DOWN':
            curr[1] -= dist
        elif direction == 'LEFT':
            curr[0] -= dist
        elif direction == 'RIGHT':
            curr[0] += dist
    d = (curr[0] - start_pos[0])**2 + (curr[1] - start_pos[1])**2
    d = d**(.5)
    return d

rawDescription: Function that calculates distance based on a set of instructions


rawDescription: Split lines into paragraphs

description: Split lines into paragraphs


rawDescription: Create complicated conditional column (geometric mean) Python


code: image_array = cv2.imread('image.png')

rawDescription: Change a pixel value

description: Change a pixel value


code:
for line in mylog:
    list1.append(line)

rawDescription: Python: take the content of a list and append it to another list


code:
# Python sequences are zero-based
model.rx2("coefficients").rx2("fixed")[1]

rawDescription: extract coefficients from R lme model in rpy2

description: Extract coefficients from R lme model in rpy2


code:
datetime.datetime.now()
datetime.datetime.now() - datetime.timedelta(minutes=1)

rawDescription: GAE datastore - count records between one minute ago and two minutes ago?


code:
data = {}
person_1 = {'name': 'lisa', 'age': 17}
person_2 = {'name': 'tom', 'age': 20}
data['people'] = [person_1, person_2]
data

rawDescription: dict.update overwrites existing keys, how to avoid?

description: Dict.update overwrites existing keys, how to avoid


code:
import argparse
parser = argparse.ArgumentParser(prog='script.py')
sp = parser.add_subparsers(dest='cmd')
for cmd in ['START', 'STOP', 'STATUS']:
    sp.add_parser(cmd)
for cmd in ['MOVEABS', 'MOVEREL']:
    spp = sp.add_parser(cmd)
    spp.add_argument('x', type=float)
    spp.add_argument('y', type=float)
parser.print_help()
args = parser.parse_args()
print(args)

rawDescription: optional python arguments without dashes but with additional parameters?

description: Optional python arguments without dashes but with additional parameters


code:
import json
inputstring = r'''[["Acct-Input-Octets", "47762756"], ["NAS-Port-Type", "Ethernet"], ["Acct-Session-Id", "\"8172fde7\""], ["Acct-Output-Gigawords", "0"], ["Service-Type", "Framed-User"], ["Acct-Unique-Session-Id", "\"f55597d3cc05fe3a\""], ["Called-Station-Id", "\"myhome\""], ["Acct-Authentic", "RADIUS"], ["Acct-Status-Type", "Interim-Update"], ["Acct-Output-Packets", "698213"], ["NAS-IP-Address", "192.168.100.100"], ["NAS-Port-Id", "\"vlan555\""], ["Acct-Output-Octets", "379021490"], ["Acct-Session-Time", "33900"], ["Calling-Station-Id", "\"A0:CC:DD:9F:F2:09\""], ["Framed-Protocol", "PPP"], ["User-Name", "\"testing\""], ["NAS-Identifier", "\"testing_radius\""], ["Event-Timestamp", "\"Sep 6 2014 02:09:40 PKT\""], ["Acct-Input-Gigawords", "0"], ["Framed-IP-Address", "172.16.100.100"], ["Acct-Input-Packets", "622069"], ["NAS-Port", "467422"], ["Acct-Delay-Time", "0"]]'''
dict(json.loads(inputstring))
pprint(_)
dict((k, int(v) if v.isdigit() else v) for k, v in json.loads(inputstring))
pprint(_)

rawDescription: Python string to dict

description: Python string to dict


code: set_option("verbose", 10)

rawDescription: z3 pseudo-randomly hangs while parsing through a SAT Model

description: Z3 pseudo-randomly hangs while parsing through a SAT Model


rawDescription: Python for loop with a tuple in it

description: Python for loop with a tuple in it


rawDescription: How to combine try/except in python into a pretty one liner?

description: Combine try/except in python into a pretty one liner


code: re.findall(r'\w+|[^\w\s]+', 'month/year/day T hour:minute')

rawDescription: parsing dates and times

description: Parsing dates and times


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

n_points = 10
aa = np.linspace(-5, 5, n_points)
bb = np.linspace(-1.5, 1.5, n_points)

def cost(a, b):
    return a + b

z = []
for a in aa:
    for b in bb:
        z.append(cost(a, b))

z = np.reshape(z, [len(aa), len(bb)])

fig, ax = plt.subplots()
im = ax.pcolormesh(aa, bb, z)
fig.colorbar(im)

ax.axis('tight')
plt.show()

rawDescription: heat map using matplotlib

description: Heat map using matplotlib


code:
class I18NString(TranslatableModel):
    key = models.SlugField(unique = True)
    translations = TranslatedFields(
        text = models.TextField(),
    )

rawDescription: Django Application Layout: Internationalization


code:
tweet_sample = [{'contributers': None, 'truncated': False, 'text': 'foo'}, {'contributers': None, 'truncated': True, 'text': 'bar'}]
df = pd.DataFrame(tweet_sample)
df

rawDescription: Python: Import Tweet unicode data to pandas data frame object


code: packages = ['Django<=1.6',]

rawDescription: How do I update Django on Openshift?

description: Update Django on Openshift


code:
import re
def split_string(source,separators):
    return re.split('[{0}]'.format(re.escape(separators)),source)

split_string("the;foo: went to the store",':;')

rawDescription: Splitting Strings in Python with Separator variable


code:
def setCustAttr(self, name, value):
    setattr(self, name, value)

rawDescription: Set a custom object attribute

description: Set a custom object attribute


rawDescription: Count and sum all previous like terms

description: Count and sum all previous like terms


code:
import cgi
form = cgi.FieldStorage()
files_types = {};
if form.type == 'multipart/form-data':
    for part in form.keys():
        files_types[form[part].filename] = form[part].type
else:
    files_types[form.filename] = form.type

rawDescription: How do I find mime-type in Python

description: Find mime-type in Python


code:
def iter_with_list(l):
    for element in l:
        yield (l, element)

rawDescription: Python: list comprehension which references an internally generated list


code: ''.join(elem.rjust(8) for elem in (i,j))

rawDescription: Python - Writing white space to imported CSV data


code:
def splitList (lst, n):
    it = iter(lst)
    new = [[next(it) for _ in range(n)] for _ in range(len(lst) // n)]

    for i, x in enumerate(it):
        new[i].append(x)

    return new

rawDescription: Split a list into n items in a sublist with remainder being added


rawDescription: Complex comparisons on yesno filter?

description: Complex comparisons on yesno filter


rawDescription: pandas count true values in multi-index frame

description: Pandas count true values in multi-index frame


code:
import chardet
chardet.detect(html)

rawDescription: how to decode and encode web page with python?

description: Decode and encode web page with python


rawDescription: semantics of generating symmetric matrices in numpy

description: Semantics of generating symmetric matrices in numpy


code: my_f = lambda x: 1.0*len(x.unique())/len(x)

rawDescription: Pandas - Identify % of unique entries per column


code:
import csv
lst = [('Endurance', 112, 150, 121, 136), ('Tempo', 152, 190, 138, 142),
       ('Threshold', 192, 210, 144, 150), ('VO2', 212, 240, 152, 155),
       ('Anaerobic', 242, 300, 156, 161)]

def write_csv(lst):

    with open('tz.csv', 'wb') as myfile:
        wr = csv.writer(myfile, delimiter = ',', quoting=csv.QUOTE_ALL)
        wr.writerows(lst)

write_csv(lst)

rawDescription: Separate items in tuples in list when writing to csv


code: df3.apply(lambda x: None)

rawDescription: How to apply a concat function to a group by data frame using pandas?

description: Apply a concat function to a group by data frame using pandas


code:
import re

dtpattern = re.compile(r'(?<=\s)\d{2}\.\d{2}\.(?:\d{2}|\d{4})\s+\d{2}:\d{2}(?=|)')
date = dtpattern.search(name_date).group()

rawDescription: How to split() a string before date

description: Split() a string before date


rawDescription: Using matplotlib, how do I whiten the background of the axis label?


rawDescription: How to figure out if a word in spelled in alphabetical order in Python

description: Figure out if a word in spelled in alphabetical order in Python


code:
lst1 = [1, 5, 1, 1, 3]
def remove_extra(lst):
    lst[:] = set(lst)
    return lst

lst1 = [1, 5, 1, 1, 3]
result1 = remove_extra(lst1)
result1 is lst1
lst1
lst2 = [2, 2, 2, 1, 5, 4, 4]
result2 = remove_extra(lst2)
result2 is lst2

rawDescription: Remove duplicates in a list and check whether it's the same as another list


code: os.system("taskset -p 0xff %d" % os.getpid())

rawDescription: Why does multiprocessing use only a single core after I import numpy?


code:
# change the fill into a blueish color with opacity .3
l.set_facecolors([[.5,.5,.8,.3]])

# change the edge color (bluish and transparentish) and thickness
l.set_edgecolors([[0, 0, .5, .3]])
l.set_linewidths([3])

# add more ticks
ax.set_xticks(np.arange(25))
# remove tick marks
ax.xaxis.set_tick_params(size=0)
ax.yaxis.set_tick_params(size=0)

# change the color of the top and right spines to opaque gray
ax.spines['right'].set_color((.8,.8,.8))
ax.spines['top'].set_color((.8,.8,.8))

# tweak the axis labels
xlab = ax.xaxis.get_label()
ylab = ax.yaxis.get_label()

xlab.set_style('italic')
xlab.set_size(10)
ylab.set_style('italic')
ylab.set_size(10)

# tweak the title
ttl = ax.title
ttl.set_weight('bold')

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

description: Make matplotlib graphs look professionally done like this


code:
from distutils.core import setup
from distutils.command.bdist_dumb import bdist_dumb

class custom_bdist_dumb(bdist_dumb):

    def reinitialize_command(self, name, **kw):
        cmd = bdist_dumb.reinitialize_command(self, name, **kw)
        if name == 'install':
            cmd.install_lib = '/'
        return cmd

if __name__ == '__main__':
    setup(
        # our custom class override
        cmdclass = {'bdist_dumb': custom_bdist_dumb},
        name='my_package',
        py_modules = ['__main__'],
        packages = ['module1', 'module2'],
        package_dir = {'': 'src'}
    )

rawDescription: how to use distutils to create executable .zip file?

description: Use distutils to create executable .zip file


code:
dy, dx = np.gradient(x)
edges = np.abs(dx) > 0

rawDescription: Find adjacent elements in a 2D numpy grid


code:
from collections import defaultdict
from itertools import groupby
from operator import itemgetter

def yield_d(data,k, keys):
    for k,v in groupby(data, key=itemgetter(k)):
        d = defaultdict(lambda: dict.fromkeys(keys, 0))
        for dct in v:
            for _k in dct.keys() & keys:
                d[k][_k] += dct[_k]
        yield d

rawDescription: slow python code seems like a suitable fit for itertools: how to optimize?

description: Slow python code seems like a suitable fit for itertools: how to optimize


code: f = np.multiply.outer(a, b)

rawDescription: Vector-vector multiplication to create a matrix


code:
# remove original file
os.remove('csvpatpos.csv')

# rename temp file to original file name
os.rename('csvtemp.csv','csvpatpos.csv')

rawDescription: python: adding a zero if my value is less then 3 digits long

description: Python: adding a zero if my value is less then 3 digits long


code: btn_new.connect("clicked", self.comboprint, combobox1, combobox2)

rawDescription: How do I add additional arguments to button.connect in PyGTK?

description: Add additional arguments to button.connect in PyGTK


code:
flat_array = np.asarray(g).flatten()
flat_array

rawDescription: Numpy: Transform sparse matrix to ndarray


code:
import os,sys
apache_configuration = os.path.dirname(__file__)
project = os.path.dirname(apache_configuration)
workspace = os.path.dirname(project)
sys.path.append(workspace)
sys.path.append('PATH TO YOUR PROJECT ROOT')

os.environ['DJANGO_SETTINGS_MODULE'] = 'mideastinfo.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

rawDescription: Cannot deploy django on Apache with mod-wsgi


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

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


code: arr = np.empty((0,3), int)

rawDescription: How to add a new row to an empty numpy array

description: Add a new row to an empty numpy array


code:
stuffs = [i['dbtype'] + '@' + i['host'] for i in stuff]
result = ', '.join(stuffs)

rawDescription: how to join an django model object response

description: Join an django model object response


code: listboxInventory.bind('<<ListboxSelect>>', lambda _: delete_item(listboxInventory))

rawDescription: Python 3.4.2, Using listbox for an inventory


code:
for c in xrange(sys.maxunicode+1):
    u = unichr(c)
    if unicodedata.category(u) == 'Zs':
        sys.stdout.write("U+{:04X} {}\n".format(c, unicodedata.name(u)))

rawDescription: How can I get all whitespaces in UTF-8 in Python?

description: Get all whitespaces in UTF-8 in Python


code:
db = sqlite3.connect('test.db.temp')
db.begin_transaction()
db.executescript('CREATE TABLE foo (bar);')
db.commit()
os.rename('test.db.temp', 'test.db')

rawDescription: WindowsError moving sqlite3 database after closing


code:
from Tkinter import *
import ttk

# In Python 3.x
#from tkinter import *
#from tkinter import ttk

root = Tk()

upper_container = Frame(root)
upper_container.pack()

left_tree = ttk.Treeview(upper_container)
left_tree.pack(side=LEFT)
right_tree = ttk.Treeview(upper_container)
right_tree.pack(side=LEFT)

lower_tree = ttk.Treeview(root)
lower_tree.pack()

root.mainloop()

rawDescription: Python multiple treeviews

description: Python multiple treeviews


code:
def get_merge_fields(self, obj):
    serializer = MergeSerializer(obj)
    return serializer.data;

rawDescription: Make serializer for nested values in Django rest serializer


code:
import json
json.dumps(d)

rawDescription: How do I deserialise (deserialize) HTML fragments in JSON from simplejson.dumps?

description: Deserialise (deserialize) HTML fragments in JSON from simplejson.dumps


code:
task_graph = construct_task_graph(deps, ["a", "d"])
task_graph.nodes()
task_graph.edges()

rawDescription: How can I implement "weak" edges with NetworkX?

description: Implement "weak" edges with NetworkX


code:
from fileheader import FileHeader, Frame
from echogram import QEchogram
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import os, sys

class MainWindow(QWidget):

    def __init__(self, filename, parent=None):
        super(MainWindow, self).__init__(parent)
        # here we are loading file
        # now self.fileheader contains attributes
        self.fileheader = FileHeader(filename)
        self.fileheader_table = QTableWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.fileheader_table)
        self.setLayout(layout)
        self.populate()

    def populate(self):
        self.fileheader_table.setRowCount(len(self.fileheader.fileheader_fields))
        self.fileheader_table.sestColumnCount(2)
        self.fileheader_table.setHorizontalHeaderLabels(['name','value'])
        for i,field in enumerate(self.fileheader.fileheader_fields):
            name=QTableWidgetItem(field)
            value=QTableWidgetItem(getattr(self.fileheader, field))
            self.fileheader_table.setItem(i,0,name)
            self.fileheader_table.setItem(i,1,value)

    if __name__=="__main__":
        app=QApplication(sys.argv)
        filename=str(QFileDialog.getOpenFileName(None,"open  file","C:/vprice/DIDSON/DIDSON  Data","*.ddf"))
        wnd=MainWindow(filename)
        wnd.resize(640,480)
        wnd.show()
        #echoGram=QEchogram()
        #echoGram.initFromFile(filename)
        #fileName="test.png"
        #echoGram.processEchogram()
        #dataH=echoGram.data
        #print "Horizontal data", dataH

rawDescription: Populating a table in PyQt with file attributes


code:
prj_files = [
  line,
  line,
  etc
]

prj_files_2 = [
  line,
  etc
]

rawDescription: Python extracting blocks of text from a file


code:
import os
import time
import flask
import json

application = flask.Flask(__name__)
start_time = time.time()

counter_file = '/tmp/worker_role.tmp'

@application.route('/', methods=['GET', 'POST'])
def hello_world():
   if flask.request.method == 'POST':
        with open(counter_file, 'a') as f:
            f.write(flask.request.data + "\n")
        return flask.Response(status=200)

if __name__ == '__main__':
    application.run(host='0.0.0.0', debug=True)

rawDescription: Print to file Beanstalk Worker Tier (Python)


code:
attribute = '10'
element = root.find('.//switch[@id="%s"]' % attribute)
element.items()

rawDescription: How to parse an XML file using Python?

description: Parse an XML file using Python


code:
x = itertools.count(3, 5)
next(x)
next(x)
next(x)

rawDescription: Native infinite range?

description: Native infinite range


rawDescription: Accessing text in html using BeautifulSoup


code:
my_list = ['Hey','Lol (First)','Dasd','Go (First)','Asd']
[x for x in my_list if 'First' in x] + [x for x in my_list if 'First' not in x]
[x for x in my_list if 'First' not in x] + [x for x in my_list if 'First' in x]

rawDescription: Words to append first

description: Words to append first


code:
masterSet = set()
for setA in iterable:
    masterSet = masterSet.union(setA)

rawDescription: Quick way to extend a set if we know elements are unique


code:
result = np.zeros_list(input_data)
for i in range(input_data.shape[0]):
    result[i] = processing_funcs(input_data[i])

rawDescription: Numpy matrices - how to handle arbitrary size


code:
import configparser

config = configparser.ConfigParser()
config.read('path/to/config.ini')

sections = config.sections()  # does not include defaults!
for section in sections:
    items = config.items(section)
    # items == [("somekey", "val"),
    #           ("anotherkey", "val"),
    #           ("wedontknowthesekeys", "val"),
    #           ...]

rawDescription: Read all the name and value pair in a section


code:
class h(Function):
    @classmethod
    def eval(cls, x, k):
        if k.is_Integer and k.is_positive:
            if k == 1:
                return f(x)/g(x)
            else:
                return diff(h(x, k - 1), x)/g(x)

rawDescription: Define functions recursively with derivative in Python


code:
from collections import defaultdict

T1 = (('a', 'b', 2),
 ('a', 'c', 4),
 ('b', 'c', 1),
 ('a', 'b', 8),)

d = defaultdict(int)

for x, y, z in T1:
    d[(x, y)] += z

T2 = tuple([(*k, v) for k, v in d.items()])

print(T2)

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


code:
A
np.concatenate(A)

rawDescription: Unwrapping Numpy "object" dtypes

description: Unwrapping Numpy "object" dtypes


rawDescription: How to return data from python script

description: Return data from python script


code:
term_regexes = []
term_tags = []

for term in term_file:
    term_matchers = [term] + term.split()
    term_regexes.append('|'.join(term_matchers))
    term_tags.append(term)

rawDescription: Regex Python firstname lastname tag the keywords in json dump


code:
import pytest
...
while True:
    import my_nifty_app
    my_nifty_app.be_nifty()
    pytest.main()

rawDescription: Running pytest from inside a module, seems to cache tests


rawDescription: Insert data from one sorted array into another sorted array


code: 'C:/dir\\file.txt'.replace('\\', '/')

rawDescription: How to replace all recurrences of something in a list with something else

description: Replace all recurrences of something in a list with something else


code:
import pandas as pd
import io

temp=u"""[02/Jan/2012:09:07:32] "GET /click?id=162&prod=5475 HTTP/1.1" 200 4352
[02/Jan/2012:09:07:32] "GET /click?id=162&prod=5475 HTTP/1.1" 200 4352
[02/Jan/2012:09:07:32] "GET /click?id=162&prod=5475 HTTP/1.1" 200 4352
[02/Jan/2012:09:07:32] "GET /click?id=162&prod=5475 HTTP/1.1" 200 4352
[02/Jan/2012:09:07:32] "GET /click?id=162&prod=5475 HTTP/1.1" 200 4352"""

#change io.StringIO(temp) to 'filename.csv'
df = pd.read_csv(io.StringIO(temp), sep="\s*", engine='python', header=None,
                                    names=['date','get','data','http','no1','no2'])

#format - http://strftime.org/
df['date'] = pd.to_datetime(df['date'].str.strip('[]'), format="%d/%b/%Y:%H:%M:%S")

#split Dataframe
df1 = pd.DataFrame([ x.split('=') for x in df['data'].tolist() ], columns=['c','id','prod'])

#split Dataframe
df2 = pd.DataFrame([ x.split('&') for x in df1['id'].tolist() ], columns=['id', 'no3'])

rawDescription: Parsing large log file

description: Parsing large log file


rawDescription: How does vary the brightness of markers on a Matplotlib basemap?


code:
x = np.array((((1,2), (3,4) ), ((5,6),(7,8))))
x
x.shape # dimensions of the array
x.sum(axis=0)
x.sum(axis=1)
x.sum(axis=2) # [1, 2] = 3 [3, 4] = 7 [5, 6] = 11 [7, 8] = 15
x.ndim # number of dimensions of the array

rawDescription: Axis in numpy multidimensional array

description: Axis in numpy multidimensional array


code:
import matplotlib.pyplot as plt  #making toy data
x = np.arange(0, 2, .05)

s = []
s.append(np.sin(x*3))
s.append(np.cos(x*4+0.3))
s.append(np.sin(x)*np.exp(2-x)*-1)
plt.clf()
plt.plot(x, s[0], x, s[1], x, s[2])
plt.show()
plt.clf()

rawDescription: align three time series in python

description: Align three time series in python


code:
import ast
d = ["'WORKSHOP'", "'KIDS'", "'EXHIBITION'", "'FANTASY'", "'FESTIVAL'"]
result = [ast.literal_eval(i) for i in d]
result

rawDescription: using ast_literal_eval in python

description: Using ast_literal_eval in python


code:
author_form = AuthorForm(request.POST)
if author_form.is_valid():
    author = author_form.save()
    story_form = StoryForm(request.POST)
    if story_form.is_valid():
        story = story_form.save(commit=False)
        story.author = author
        story.save()

rawDescription: Django inlineformsets and general noobishness


code:
import json

def iload_json(buff, decoder=None, _w=json.decoder.WHITESPACE.match):
    # found at http://www.benweaver.com/blog/decode-multiple-json-objects-in-python.html
    """Generate a sequence of top-level JSON values declared in the
    buffer.

    >>> list(iload_json('[1, 2] "a" { "c": 3 }'))
    [[1, 2], u'a', {u'c': 3}]
    """
    decoder = decoder or json._default_decoder
    idx = _w(buff, 0).end()
    end = len(buff)
    try:
        while idx != end:
            (val, idx) = decoder.raw_decode(buff, idx=idx)
            yield val
            idx = _w(buff, idx).end()
    except ValueError as exc:
        raise ValueError('%s (%r at position %d).' % (exc, buff[idx:], idx))

rawDescription: Prossing Very Ugly Multi-line Json Object with Python


code:
with open('path/to/file.txt') as f:
    result = [line.split() for line in f]

rawDescription: how to write the contents of a file into lists in python?

description: Write the contents of a file into lists in python


code:
unique_sets = set(frozenset(d.items()) for d in list_of_dicts)
unique_dicts = [dict(s) for s in unique_sets]

rawDescription: How to remove duplicate dictionaries from a list in Python?

description: Remove duplicate dictionaries from a list in Python


code:
from datetime import timedelta

start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())

YouTubeVideo("Pi9NpxAvYSs", start=start, autoplay=1, theme="light", color="red")

rawDescription: Can the ipython notebook YouTubeVideo class play from time offset


rawDescription: Python selenium didn't find css element

description: Python selenium didn't find css element


code:
{'de': {'essen': '', 'fressen': 'for animals'},
 'fr': {'bouffer': 'slang', 'manger': ''}}

rawDescription: Transform dictionaries to a list of dictionaries according to their values


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

def dostuff(x):
    print("x is %s" % x)

class MyButton(Button):
    def on_press(self):
        dostuff(22)

class MyApp(App):

    def build(self):
        return MyButton()

MyApp().run()

rawDescription: Can someone tell me where I'm going wrong with this structure?


code:
text = str(row[0])
for pattern, replacement in REPLACEMENTS:
    text = pattern.sub(replacement, text)

rawDescription: List of compiled regexes in Python

description: List of compiled regexes in Python


code:
s = 'abc{0}efg'.format('d')
s

rawDescription: Alternative to python string item assignment


code:
import numpy
np_array = numpy.array(r_tot)

rawDescription: Create a matrix with solution arrays in it


code:
output_lines = []
for u in li:
    z = u[1]
    A = z.count('A')
    C = z.count('C')
    G = z.count('G')
    T = z.count('T')
    sumbases = "A,C,G,T" # I suppose you format it here differently
    y = sumbases.replace("\n"," ")  # not sure why you need this

    # print(y) # don't print now, print later...
    output_lines.append(y)

print(','.join(output_lines))

rawDescription: print formatting in python 3

description: Print formatting in python 3


rawDescription: Filter numpy ndarray (matrix) according to column values


rawDescription: Create hourly/minutely time range using pandas


code:
from Tkinter import *

def toplevelwin():
    def clear(): return
    select = unselect = done = enter = clear
    window = Toplevel()

    frame0 = Frame(window)
    frame0.grid(row=0, column=0, sticky='WE', padx=5, pady=5, columnspan=3)
    frame0.grid_columnconfigure(0, weight=1)
    lblentry = Label(frame0, text="Entry Box:")
    lblentry.grid(row=0, column=0, sticky='W')
    entrybx = Entry(frame0)
    entrybx.grid(row=1, column=0, sticky='NSEW', columnspan=2)
    entrybt = Button(frame0, text=' Enter ', command=enter)
    entrybt.grid(row=1, column=2, sticky='NW', padx=3)

    frame1 = Frame(window)
    frame1.grid(row=1, column=0, sticky='EW', padx=5, pady=5)
    lblshow_lst = Label(frame1, text="List Box 1:")
    lblshow_lst.grid(row=0, sticky='W')
    show_lst = Listbox(frame1)
    show_lst.grid(row=1, sticky='W')

    frame2 = Frame(window)
    frame2.grid(row=1, column=1, sticky='W')
    selbtn = Button(frame2, text='Select', command=select)
    selbtn.grid(row=0, padx=5, sticky='EW')
    uselbtn = Button(frame2, text='Unselect', command=unselect)
    uselbtn.grid(row=1, padx=5, sticky='EW')

    frame3 = Frame(window)
    frame3.grid(row=1, column=2, sticky='W', padx=5, pady=5)
    lblsel_lst = Label(frame3, text="List Box 2:")
    lblsel_lst.grid(row=0, sticky='W')
    sel_lst = Listbox(frame3)
    sel_lst.grid(row=1, column=0, sticky='W')

    frame4 = Frame(window)
    frame4.grid(row=2, column=0, sticky='WE', padx=5, pady=5, columnspan=3)
    frame4.grid_columnconfigure(0, weight=1)
    Button(frame4, text=' Done ', command=done).grid(
        row=0, column=0, padx=7, pady=2, sticky='E')
    Button(frame4, text='Clear', command=clear).grid(
        row=0, column=1, padx=7, pady=2, sticky='E')

    window.wait_window(window)

root = Tk()
toplevelwin()
root.mainloop()

rawDescription: How to expand widgets size in a frame with respect to other frames in Tkinter (Help on:Tkinter grid management)

description: Expand widgets size in a frame with respect to other frames in Tkinter (Help on:Tkinter grid management)


code:
module = imp.load_source("test", "testdir/test.py")
module.assertAndTerminate = assertionFunction

rawDescription: Python: setting __globals__ for modules and their imports


code:
def consecutive_values(arr, val=1, cnt=3):
    def comparator(pos):
        return arr[pos] == val
    if len < cnt:
        return []
    else:
        return [p for p, x in  enumerate(arr[:1-cnt])
                     if all(map(comparator, xrange(p, p+cnt, 1)))]

rawDescription: How can I get step jump in for loop when it has a while conditioned on the for loop's variable

description: Get step jump in for loop when it has a while conditioned on the for loop's variable


code:
from collections import defaultdict
list1 = ['a: xyz', 'b:123']
list2 = ['a: dupe', 'c:456']
d = defaultdict(list)
for item in list1 + list2:
    k,v = item.split(':')
    d[k].append(v)

d
['{}:{}'.format(k,d[k][0]) for k in d if len(d[k]) == 1]

rawDescription: Compare lines of 2 input files, and output third file with differences


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtGui
from Ui_MyWidget import Ui_MainWindow

class MyWidget(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
       super(MyWidget, self).__init__(parent)

       self.setupUi(self)

    @QtCore.pyqtSlot()
    def on_pushButton_clicked(self):
        self.lineEdit.setText("A Qt standalone app!")

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)
    window = MyWidget()
    window.resize(300, 30)
    window.show()
    sys.exit(app.exec_())

rawDescription: How to save a form from Qt Designer as a standalone app?

description: Save a form from Qt Designer as a standalone app


code: {{ jsonstring|regex }}

rawDescription: Using regex in jinja

description: Using regex in jinja


code:
cut_weight = 2
partitions[0] = set([0, 1])
partitions[1] = set([2, 3, 4])
edge_cut_list = [(0, 2), (1, 3)]

rawDescription: Minimum s-t Edge cut which takes edge weight into consideration


rawDescription: Given a List of Matrices, Sum Them but Ignore Some Matrix's Rows


code:
import numpy as np

#n = 1000000
n = 1000
a = np.random.rand(n,100)  ## This needs to be in memory
b = np.random.rand(1,100)
c = a-b  # this need to be in code in order to perform next operation
d = np.linalg.norm(np.asarray(c), axis=1)

batch_size = 300
# Preallocate the result.
d2 = np.empty(n)
for start in range(0, n, batch_size):
    end = min(start + batch_size, n)
    c2 = a[start:end] - b
    d2[start:end] = np.linalg.norm(c2, axis=1)

rawDescription: NUMPY Operations: Memory Efficiency: PYTHON


rawDescription: ValueError: invalid literal for int() with base 10: '0.00'


code:
for item in list:
    href, text = item.xpath("@href|text()")
    print(href, text)

rawDescription: Get value to 2 attribute from a xpath node for anchor tag


rawDescription: Turning a list of lists into a dictionary of lists


code:
lst =  ["comp1", "comp2", "comp1", "mycomp", "mycomp"]
d = {}
for i in lst:
    d[i] = d.get(i, 0) +1
print (d)

rawDescription: python: convert list to dictionary

description: Python: convert list to dictionary


code:
b = blist([None])
b *= 5000
import random
for i in range(100):b[random.randint(0, 4999)] = i

b.__sizeof__()

rawDescription: Better to use dict of integer keys or a very long list?


code:
while True:
    #internally process pygame event handlers
    pygame.event.pump()
    keypressed = pygame.key.get_pressed()

    time.sleep(5)
    print("5 seconds later")

    if keypressed[pygame.K_w]:
        print("it worked")
    else:
        print("It didn't work")

rawDescription: Why is pygame.key.get_pressed not working as expected?


rawDescription: How to get the 'cardinal' day of the year in Pandas?

description: Get the 'cardinal' day of the year in Pandas


code: Author: {{ aitem.get_authors|join:", " }}

rawDescription: How can I distinguish lists from strings in django templates

description: Distinguish lists from strings in django templates


code:
for result in cursor.fetchall():
    if any(field is None for field in result):
        print(result)
        break  # break once we meet a row with None value

rawDescription: How to check if a sql returns NonType data in python

description: Check if a sql returns NonType data in python


rawDescription: Apply multiple functions to the same argument in functional Python


rawDescription: Tkinter widgets not appearing

description: Tkinter widgets not appearing


code:
from tkinter import * # I use python 3
import tkinter.scrolledtext as tkst
from file2 import *
from file2 import Hero#importing the oth

class Application(Frame):
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.output_text = tkst.ScrolledText(self, width = 100, height = 20,
                                wrap = WORD, bd=0)
        self.output_text.grid(row = 9, column = 0, columnspan = 5, sticky="nsew")

root = Tk()
root.title("Game")
app = Application(root)
center(root)

h = Hero()
h.attack(enemy, damage, app) #passing as third argument)

root.mainloop()

rawDescription: Connecting a method of an imported class with a class of the main script


code:
def abc(host, protocol):
    ...

abc("10.1.0.100", "http")
abc(host="10.1.0.100", protocol="http")

rawDescription: What is the best way to pass multiple parameters to class init in python?


code:
import sys
sys.path.append("C:/")

from hello import function_to_call
function_to_call()

rawDescription: How to execute a python program by a button click on html page generated by django

description: Execute a python program by a button click on html page generated by django


code:
from base64 import b64decode
from Crypto.Cipher import AES
[...]
iv = 'asdfasdfasdfasdf'
key = 'asdfasdfasdfasdfasdfasdfasdfasdf'
encoded = b64decode('my_encrypted_string')

dec = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
value = dec.decrypt(encoded)

rawDescription: AES - Encryption with Crypto (node-js) / decryption with Pycrypto (python)


code:
import random
letters = [random.choice('BCDFGHJKMPQRTVWXYZ') for x in range(18)]
numbers = [random.choice('2346789') for x in range(7)]
s = letters + numbers
random.shuffle(s)
s

rawDescription: Alphanumeric generator with restrictions


code:
for index, content in enumerate(Window.list_2):
  if content == item_selected:
      del Window.list_2[index]
      # must break out of the for loop,
      # as the original list now has changed:
      break

rawDescription: delete items from 3 different lists

description: Delete items from 3 different lists


code:
cols = [x for x in df.columns if 'abc' in x]
cols
df['newcol'] = (df[cols] == 'r').any(axis=1).map({True:'r',False:'np.nan'})
df

rawDescription: pandas dataframe: return column that is a compression of other columns

description: Pandas dataframe: return column that is a compression of other columns


code:
words = ["Games","Development","Keyboard","Speed","Typer","Anything","Alpha","Zealous","Accurate","Basics","Shortcut","Purpose","Window","Counter","Fortress","Modification","Computer","Science","History","Football","Basketball","Solid","Phantom","Battlefield","Advanced","Warfare","Download","Upload","Antidisestablishmentarianism","Supercalifragilisticexpialidocious","Discombobulation","Liberated","Assassin","Brotherhood","Revelation","Unity","Syndicate","Victory"]

import random
while words:
    random_word = random.choice(words)
    print(random_word)
    words.remove(random_word)

rawDescription: How to make random.shuffle truly random?

description: Make random.shuffle truly random


code: bookmark_par = get_bookmark_par_element(doc, 'insertion_point')

rawDescription: python-docx insertion point

description: Python-docx insertion point


code:
def myfunc(a,b):
    if (a>b): return a
    else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)
# [[7 4 5]
#  [7 6 9]]

rawDescription: Function application over numpy's matrix row/column


code:
from subprocess import Popen, PIPE
p = Popen(['python test_enter.py'], stdin=PIPE, shell=True)
p.communicate(input='\n')

rawDescription: How to make python script press 'enter' when prompted on Shell

description: Make python script press 'enter' when prompted on Shell


code:
import re
import sys
import urllib
import urlparse
from BeautifulSoup import BeautifulSoup

class MyOpener(urllib.FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15'

def process(url):
    myopener = MyOpener()
    #page = urllib.urlopen(url)
    page = myopener.open(url)

    text = page.read()
    page.close()

    soup = BeautifulSoup(text)

    print(soup)

    for tag in soup.findAll('img'):
        print (tag)
# process(url)

def main():
    url = "https://www.organicfacts.net/health-benefits/fruit/health-benefits-of-grapes.html"
    process(url)

if __name__ == "__main__":
    main()

rawDescription: Parsing txt file, to web scrape an image from each link on each line, with python


header: First Story

author: Tim

team: department one

paragraphs:
First para
Second para

header: Second Story

author: Steven

team: department two

header: Third Story

author: Bob

team: department three

header: Fourth Story

author: John

team: department four

rawDescription: Python: How do I make changes and add onto in json


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

y, x = np.ogrid[-1:2:100j, -1:1:100j]
plt.contour(x.ravel(), y.ravel(), x**2 + (y-((x**2)**(1.0/3)))**2, [1])
plt.axis('equal')
plt.show()

rawDescription: Plotting function that returns complex values using pyplot


code:
# create a user
u = User(name='davidism')
db.session.add(u)
db.session.commit()

# query all users
users = User.query.all()

# update a user
u = User.query.filter_by(name='davidism').one()
u.active = False
db.session.commit()

# check if a user is active like Flask-Login
print(u.is_active)

rawDescription: How do I define and create a User model for use with Flask-Login?

description: Define and create a User model for use with Flask-Login


code:
class Node:
  def __init__(self, cargo=None, next=None):
    self.car = cargo
    self.cdr = next
  def __str__(self):
    return str(self.car)

def display(lst):
  if lst:
    w("%s " % lst)
    display(lst.cdr)
  else:
    w("nil\n")

rawDescription: Python Linked List

description: Python Linked List


code:
class MemorySavingQuerysetIterator(object):

    def __init__(self,queryset,max_obj_num=1000):
        self._base_queryset = queryset
        self._generator = self._setup()
        self.max_obj_num = max_obj_num

    def _setup(self):
        for i in xrange(0,self._base_queryset.count(),self.max_obj_num):
            # By making a copy of of the queryset and using that to actually access
            # the objects we ensure that there are only `max_obj_num` objects in
            # memory at any given time
            smaller_queryset = copy.deepcopy(self._base_queryset)[i:i+self.max_obj_num]
            logger.debug('Grabbing next %s objects from DB' % self.max_obj_num)
            for obj in smaller_queryset.iterator():
                yield obj

    def __iter__(self):
        return self

    def next(self):
        return self._generator.next()

rawDescription: Limiting Memory Use in a *Large* Django QuerySet


code:
from BeautifulSoup import BeautifulSoup

html = '
Chinese New Year Sale
February 8, 2013 - February 10, 2013
'
date = BeautifulSoup(test).findAll('h2', {'class' : 'pointer'})[0].findAll('span')[0]
date = date.findAll(text=True)[0]

rawDescription: How to parse html using beautifulsoap/python?

description: Parse html using beautifulsoap/python


code: getattr(module, class_name)

rawDescription: Python dynamic instantiation from string name of a class in dynamically imported module


code: vars(Foo(2, 3))

rawDescription: Extend python's dict functionality to user created classes


rawDescription: Copied dictionary via numpy.copy. Now is ndarray; how to recover the original dictionary?


code:
def sort_lists_by(lists, key_list=0, desc=False):
    return izip(*sorted(izip(*lists), reverse=desc,
                 key=lambda x: x[key_list]))

rawDescription: sorting multiple lists in python based on sorting of a single list

description: Sorting multiple lists in python based on sorting of a single list


code: a < d or (a == d and b < e) or (a == d and b == e and c < f)

rawDescription: Tuple comparison in Python

description: Tuple comparison in Python


code:
frame = leg.get_frame()
frame.set_height(frame.get_height()+20)

rawDescription: offset one of matplotlib's legend items

description: Offset one of matplotlib's legend items


code:
mask = np.zeros(img.shape,np.uint8)
mask[y:y+h,x:x+w] = img[y:y+h,x:x+w]

rawDescription: OpenCV via python: Is there a fast way to zero pixels outside a set of rectangles?


code:
a = "hello {}"
a
a.format("dave")

rawDescription: Is there a good standard for adding data to a string if already saved as a str object


code: FormSet = inlineformset_factory(Foo, Bar, form=BarForm, formset=forms.BaseBarFormSet) # notice formset=forms.BaseBarFormSet

rawDescription: Change queryset of model field in inlineformset of non parent model


code:
s = np.cumsum(np.concatenate(([0], a)))
print (s[3:] - s[:-3]) / 3

rawDescription: Fast 1D convolution with finite filter and sum of dirac deltas in python


code:
from time import strptime
sorted(d, key = lambda i: strptime(i.split('@')[0], '%d-%m-%Y'))

rawDescription: Sort by Date Python List

description: Sort by Date Python List


code:
from collections import Counter
listA = ['a', 'b', 'c', 'a', 'c']
listB = [('a', 5), ('b', 10), ('c', 0)]

rawDescription: Comparing a list to a tuple

description: Comparing a list to a tuple


code:
def some_callback(event):
    event.widget.delete(0, "end")
    return None

rawDescription: Entry box text clear when pressed Tkinter


code:
with open('file.txt') as f:
    data = f.readlines()
    items = list(zip(data[0::2], data[1::2]))  # A list of items like ('Water', '100ml')

rawDescription: Python - How can I separate characters and integers from a string into sub-strings?


rawDescription: Update list to include new elements of another list (primefactor computation)


code:
def select_subprofile(request):
   if request.method == 'POST':
      form = SubProfileSelectForm(request)
      if form.is_valid():
          subprofile = form.cleaned_data['subprofile']
          url = '%s?subprofile' % (reverse('homepage'), subprofile)
          return redirect(url)  # the redirect is something like '/homepage?subprofile=123'
   else:
      form = SubProfileSelectForm()
   return render(request, 'myapp/subprofile_select.html', {'form':form})

rawDescription: Python: How to "fork" a session in django


code: "\n".join([" ".join(row) for row in map_])

rawDescription: Python: How to return a string with a certain formatting for a nested list


code:
servdict = dict([(d['scheme'],d['url']) for d in serv])
url = servdict['urn:x-esri:specification:ServiceType:WMS']

rawDescription: Find value matching value in a list of dicts


code:
startApplication("exampleapp") # Launch application binary 'exampleapp'
snooze(10) # Let it start

root = findRoot()
page = findFlat(root, "page", 1, True, False)
foobar = findFlat(page, "foobar", 1, True, False)

# Also just: foobar = findRecursive(root, "foobar", 1)

if foobar.text == "ipsum":
    test.passes("text is ok")
else:
    test.fail("Incorrect foobar text: " + foobar.text)

rawDescription: Get QML element in Squish by id or objectName using findObject() or waitForObject() without object map


code: pos = emcee.utils.sample_ball(mean, np.sqrt(np.diag(C)), size=Nwalkers)

rawDescription: Truncated multivariate normal in SciPy?

description: Truncated multivariate normal in SciPy


code: '2' > '10'  #strings are compared lexicographically

rawDescription: How to find the average of values in a .txt file

description: Find the average of values in a .txt file


code:
class State(models.Model):
    name = models.CharField(max_length=255)
    # id from external source, e.g. 5 from your example
    external_id = models.IntegerField()

    def fetch_cities_from_network(self):
        # Fetching data
        resp = requests.get(
            'http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/'
            'api.php?type=getCities&stateId=%d' % self.external_id
        )

        # Get dictionary with cities
        cities_dict = resp.json()['result']

        # Get dictionary values (city names) and save them into the db
        for city in cities_dict.values():
            City.objects.create(state=self, name=city)

class City(models.Model):
    state = models.ForeignKey(State)
    name = models.CharField(max_length=255)

rawDescription: how can i save data, retrieved from a url into my database

description: Save data, retrieved from a url into my database


code:
def orderby(table, column): return sorted(table, key=itemgetter(column))
[p['age'] for p in orderby(people, 'first') if p['last'] == 'Smith']

rawDescription: Are there a tools that can help to treat files as tables in a database?


code:
curve = plotItem.plot(data)
data = np.roll(data, 1)  # scroll data
curve.setData(data)      # re-plot

rawDescription: Live Data Monitor: PyQtGraph

description: Live Data Monitor: PyQtGraph


code:
def sdist(p,q):
    return (p[0]-q[0])**2 + (p[1]-q[1])**2

def closestPoint(p,points):
    candidate = points[0]
    currentMin = sdist(p,candidate)
    for q in points[1:]:
        d = sdist(p,q)
        if d == 0: return q
        if d < currentMin:
            currentMin = d
            candidate = q
    return candidate

def closestPoints(pointsA,pointsB):
    return [(p,closestPoint(p,pointsB)) for p in pointsA]

rawDescription: How to find the point pairs in two point lists with min distance in a efficent way?

description: Find the point pairs in two point lists with min distance in a efficent way


rawDescription: Convert a binary to an array with each binary number


code: print(A)

rawDescription: Convert triplets to matrix/dataframe in python


rawDescription: How to save pictures with lower resolution in python?

description: Save pictures with lower resolution in python


code:
for i in range(100):
     login()

rawDescription: Creating a dictionary to store pass and user


rawDescription: Is it possible to write a combination function with recursion technique?


code:
numList = []

while len(numList) <= 1000:
    numList.append(1)

for i in range(0, 1000):
    numList[i] = 0

print(numList)

rawDescription: Create a loop to change ints in a list to another int?


rawDescription: How to combine/merge mostly identical sublists into one, and append the non-identical part to the end of the list?

description: Combine/merge mostly identical sublists into one, and append the non-identical part to the end of the list


code:
class SomeFileType(object):
    _filename = None
    _client = None

    def __init__(self, path):
        self._path = path

    @property
    def path(self):
        return self._path

    @path.setter
    def path(self, value):
        # clear all private instance attributes
        for key in [k for k in vars(self) if k[0] == '_']:
            delattr(self, key)
        self._path = value

    @property
    def filename(self):
        if self._filename is None:
            filename = os.path.basename(self.path)
            self._filename = os.path.splitext(filename)[0]
        return self._filename

    @property
    def client(self):
        '''Returns client name associated with file'''
        if self._client is None:
            client = self.filename.split()
            self._client = client[1] # Assuming filename is formatted "date client - docTitle"
        return self._client

rawDescription: Python class __init__ layout?

description: Python class __init__ layout


code:
def collector(_device, _data1, _data2, _loc):
    global session
    global metadata
    Records = Table(_loc, metadata,
        Column('device', String(17), primary_key=True),
        Column('data1', Text()),
        Column('location', Text()),
        Column('data2', Text()),
        extend_existing=True
    )
    check = exists().where(Records.c.device==_device)
    if check == True:
        updt = update(Records).where(Records.c.device==_device).values(data1=_data1, location=_loc, data2=_data2)
        session.add(updt)
        session.commit()
    else:
        Create_new_Table(_loc)
        ins = Records.insert().values(debice=_device, data1=_data1, location=_loc, data2=_data2)
        session.execute(ins)
    session.commit()
    session.close()

rawDescription: Python SQLAlchemy create dymanic unknown tables


code:
def __iter__(self):
   return iter(self.__a)

rawDescription: Why yield returns an iterator?

description: Why yield returns an iterator


code:
from functools import partial
def myfunc(arg1, arg2):
    pass

partial(myfunc, arg2=1).func == partial(myfunc, arg2=1).func
partial(myfunc, arg2=1).args == partial(myfunc, arg2=1).args
partial(myfunc, arg2=1).keywords == partial(myfunc, arg2=1).keywords

rawDescription: How to compare wrapped functions with functools.partial?

description: Compare wrapped functions with functools.partial


rawDescription: Add a column to the end of csv using pandas or in general python


rawDescription: All combinations of a mapped list of lists in python


code:
import math

def counter_cosine_similarity(c1, c2):
    terms = set(c1).union(c2)
    dotprod = sum(c1.get(k, 0) * c2.get(k, 0) for k in terms)
    magA = math.sqrt(sum(c1.get(k, 0)**2 for k in terms))
    magB = math.sqrt(sum(c2.get(k, 0)**2 for k in terms))
    return dotprod / (magA * magB)

rawDescription: Compute the similarity between two lists


code:
from itertools import combinations

def prize(L):
    C = 4
    return [(x, y) for x, y in combinations(L, 2) if x + y == C]

lst = [1, 2, 3, 4]

print('Possible', prize(lst))

rawDescription: How to find the sum of each element in a list with each other element

description: Find the sum of each element in a list with each other element


code: df['path'] = df['origin'] + '-' + df['node name']

rawDescription: How to Efficiently Process Time-Series Data in Pandas


rawDescription: Dynamically calculated zero padding in format string in python


code:
merged = []
for l1,l2 in zip(get_part(list1),get_part(list2)):
    merged.extend(l1)
    merged.extend(l2)
    merged.append(';')

rawDescription: Conditionally merge lists

description: Conditionally merge lists


code:
import re
import sys
import ConfigParser
inputfile = raw_input("Enter config file: ")
scanfile = raw_input("Enter name of file to scan through: ")
searchfile = open(scanfile,'r')
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read(inputfile)
for ch in config.sections():
  keys = set(config.options(ch))
  person = ch
  for line in searchfile: # iterate over file object not the string
      if any(k in keys for k in line.split()):
         outfile = open(person,'w')
         print >> outfile,line
searchfile.close()
outfile.close()

rawDescription: Is there a way to have ConfigParser 'not' return a list


code:
from request_cache import RequestCache
cache = RequestCache()
cache.get(key)
cache.set(key, value)

rawDescription: django: how to memoize model manager methods?

description: Django: how to memoize model manager methods


code: table[hashes] = xrange(len(hashes))

rawDescription: Higher-performance method do this type of insert from python?


code: icon = pygame.image.load('image.png')

rawDescription: How to change the icon in the pygame window?

description: Change the icon in the pygame window


rawDescription: Moving x-axis to the top of a plot in matplotlib


rawDescription: How to make a free hand shape(random) on an image in python using opencv

description: Make a free hand shape(random) on an image in python using opencv


code:
sampling_rate = 2
wave_data = np.array([1, 3, 5, 2, 8, 10])
sampling_rate * (wave_data[1:] - wave_data[:-1])

rawDescription: Mapping a numpy array pairwise

description: Mapping a numpy array pairwise


code:
def sh(dir):
    a = xlwt.Workbook()
    sheet = a.add_sheet('sheet1')
    n = 0
    for f in glob.glob(os.path.join(dir, '*.xml')):
        dom = parse(os.path.join(dir, f))
        name = dom.getElementsByTagName('rev')
        title = dom.getElementsByTagName('title')
        sheet.write(n, 0, f)
        sheet.write(n, 1, title[0].firstChild.nodeValue)
        sheet.write(n, 2, name[0].firstChild.nodeValue)
        n += 1
    a.save('sha.xls')

rawDescription: Printing the output in Excel

description: Printing the output in Excel


rawDescription: Grouping python list into timeslots of 3 hours


rawDescription: How do I create a pandas dataframe in python from a csv with additional delimiters?

description: Create a pandas dataframe in python from a csv with additional delimiters


code:
try:
    cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
except sqlite3.IntegrityError as err:
    print(err)
    # sqlite3.IntegrityError: column bar is not unique

rawDescription: Basic pySQLite example?

description: Basic pySQLite example


code:
import tkinter
import random

class Main(tkinter.Tk):

    def __init__(self, screenName=None, baseName=None, className='Tk',
                 useTk=1, sync=0, use=None):
        super().__init__(screenName, baseName, className,
                         useTk, sync, use)
        frame = Application(self)
        frame.grid()
        self.mainloop()

class Application(tkinter.Frame):

    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.w = tkinter.Label(self, text='Hello, world!')
        self.w.grid()
        self.v = tkinter.Button(self, text='Press Me', command=self.click)
        self.v.grid()
        self.u = tkinter.Button(self, text='Me Too!',
                                command=lambda: external_mutator(self.w))
        self.u.grid()

    def click(self):
        self.w['text'] = external_function(3)

def external_function(ndigits):
    return round(random.random(), ndigits)

def external_mutator(widget):
    widget['text'] = external_function(6)
    print('Hello to you too!')  # shown on console if present

if __name__ == '__main__':
    Main()

rawDescription: is this bad programming practice in tkinter?

description: Is this bad programming practice in tkinter


code:
info = "test:1;xxx:4;yyy:12"
dict(item.split(':', 1) for item in info.split(';'))

rawDescription: Python split and manipulate results

description: Python split and manipulate results


code:
def foo():
    ...

rawDescription: Python dummy statement for nothing or nop when indent expected


code:
a = 1234
b = a
b is a
b = 1234
b is a

rawDescription: How to create a new data object in memory, rather than pointing to one? (in Python 3)

description: Create a new data object in memory, rather than pointing to one? (in Python 3)


code: a.sort(order=['fr', 'to', 'time'])

rawDescription: Sorting a record array in numpy

description: Sorting a record array in numpy


code:
x, y = np.genfromtxt('tmp.txt', unpack=True, delimiter=',')

pw0 = (.02, 30, .2, -2000) # a guess for slope, intercept, slope, intercept
pw, cov = curve_fit(two_lines, x, y, pw0)
crossover = (pw[3] - pw[1]) / (pw[0] - pw[2])

plt.plot(x, y, 'o', x, two_lines(x, *pw), '-')

rawDescription: Fit a curve for data made up of two distinct regimes


code:
def countVowels(s):
    s = s.lower()
    vowels = {'a':0,'e':0,'i':0,'o':0,'u':0}
    for char in s:
        if char in vowels:
            vowels[char]+=1
    return vowels

rawDescription: Function that takes a string as input and counts the number of times the vowel occurs in the string


code:
final_score =  defaultdict(int)

with open('score.txt','r') as f: # with will automatically close your file
    for line in f: # iterate over file object
        # split once on whitespace from right side of string, separating name from score
        name, score = line.rsplit(None,1)  # unpack
        # use our defaultdict to increment the score
        final_score[name] += int(score)

# just call sorted on .items()
print(sorted(final_score.items(), key=lambda score: score[1], reverse=True))

rawDescription: How do I create a dictionary where I add points to names form a text file?

description: Create a dictionary where I add points to names form a text file


code:
from sympy.abc import x,y
g = sympy.sin('y')
f = g.subs({'y':h})

rawDescription: How to do function composition in Sympy?

description: Do function composition in Sympy


code: red

rawDescription: OpenCV: setting all pixels of specific BGR value to another BGR value


code: (element,) = myset

rawDescription: How to extract the member from single-member set in python?

description: Extract the member from single-member set in python


code: [dt.date() for dt in query.values_list('time_finished', flat=True)]

rawDescription: django convert .values_list('datetimefield') to date

description: Django convert .values_list('datetimefield') to date


code:
class BlogFilter(django_filters.FilterSet):
    entry__headline = django_filters.CharFilter(grouped=True)
    entry__pub_date = django_filters.CharFilter(grouped=True)

    class Meta:
        model = Blog
        fields = ['entry__headline', 'entry__pub_date', ]

rawDescription: Combine several filters into one filter() with django-filters


code:
do_not_read_cols = [3, 4, 9]
data = np.loadtxt('filename')
data = np.delete(data, do_read_cols, axis=1)

rawDescription: numpy.loadtxt - negated usecols?

description: Numpy.loadtxt - negated usecols


code:
for i in range(len(somelist)):
   something( somelist[i] )

rawDescription: Cleaning up nested for loops in python

description: Cleaning up nested for loops in python


code:
data_slices = ndimage.find_objects(labmat)
# [(slice(0L, 1L, None), slice(4L, 5L, None), slice(28L, 29L, None)),
#  (slice(0L, 1L, None), slice(25L, 26L, None), slice(19L, 20L, None)),
#  (slice(0L, 1L, None), slice(27L, 28L, None), slice(10L, 11L, None)),
#  (slice(0L, 1L, None), slice(28L, 29L, None), slice(7L, 8L, None)),
# ...

rawDescription: Objects' sizes along dimension?

description: Objects' sizes along dimension


code:
from itertools import count
KS = count()

rawDescription: Python: Optimizing, or at least getting fresh ideas for a tree generator


code:
def __call__(cls, *args, **kwargs):
    instance = self.__new__(cls, *args, **kwargs)
    instance.__init__(*args, **kwargs)
    return instance

rawDescription: Python Class Fields

description: Python Class Fields


code:
for xx in range(0, width, block_size):
    for yy in range(0, height, block_size):
        ...

rawDescription: Python nested while-loop doesn't increment as expected


code:
lst = []
news = [(str(i), str(i)) for i in range(10)]
import random
random.shuffle(news)
for new in news:
    print(lst)
    lst.insert(determine_points(lst, new), new)
print(lst)

rawDescription: Correct implementation of determining position in the list


code: dictionary_with_temporal_distribution["{}".format(k)] = v * cap_medium_demand

rawDescription: Subdivide nested dictionary, while applying percentage from values in Python


code:
class SomeAbstraction( object ):
    pass # lots of stuff - but missing something

class Mixin1( object ):
    def something( self ):
        pass # one implementation

class Mixin2( object ):
    def something( self ):
        pass # another

class Concrete1( SomeAbstraction, Mixin1 ):
    pass

class Concrete2( SomeAbstraction, Mixin2 ):
    pass

rawDescription: Difference between abstract class and interface in Python


rawDescription: How to restore a builtin that I overwrote by accident?

description: Restore a builtin that I overwrote by accident


code: x = EqM_list(bah*2 for bah in buh)

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


rawDescription: Parsing "Return-Path:" in Python

description: Parsing "Return-Path:" in Python


code:
def do_hard_work(hash):
    time.sleep(1)
def Run(data_pipe):
   while True:
       while data_pipe.poll():
            hash = data_pipe.recv()
            if hash == "QUIT":
                  break
            threading.Thread(target=do_hard_work,args=(hash)).start()
            time.sleep(1)

local,remote = multiprocessing.Pipe()
worker_process = multiprocessing.Process(target=run,args=(local,))
worker_process.start()
while True:
    remote.send(random.getrandbits(128))
    time.sleep(1)
    if some_condition:
         remote.send("QUIT")
         break

rawDescription: Calling a function and each call works simultaneously and not in a queue


code:
key, val = height_by_gender_and_agegroup(person)
gender, age = key

rawDescription: returning multiple values in python

description: Returning multiple values in python


code:
from OpenSSL import crypto as c
cert = c.load_certificate(c.FILETYPE_PEM, file('server.pem').read())
cert.get_extension_count()
ext = cert.get_extension(0)
ext.get_short_name()
ext.get_data()

rawDescription: Extract the value of a X.509 certificate custom extension using PyOpenSSL


code: df.mycol.get(myIndex, NaN)

rawDescription: return default if pandas dataframe.loc location doesn't exist

description: Return default if pandas dataframe.loc location doesn't exist


code:
def listallcams():
   camtab = SVSIpCamReg.query.filter_by(u_id = current_user.id).all()
   for rec in camtab:
      dkey = rec.key
      bdkey=bytes(dkey)
      f = Fernet(bdkey)
      bcamurl = bytes(rec.camurl_hash)
      camurl =f.decrypt(bcamurl)
      rec.camurl = camurl
   return render_template('cam/viewallcam.html',allcam = camtab)

rawDescription: How to loop through object return by SQLALchemy and process each row and display it to HTML

description: Loop through object return by SQLALchemy and process each row and display it to HTML


code: models.PointField: {'widget': Textarea }

rawDescription: Disabling Openlayers map in GeoDjango Admin


code: list(filter(lambda item: item % 2 != 0, a))

rawDescription: python for loop with "reducing" list

description: Python for loop with "reducing" list


rawDescription: Django: How to override authenticate() method?


rawDescription: Python - convert <type 'instance'> to <type 'str'>?


code:
def read(fileName):
    list2 =[]
    infile = open(fileName, "r")
    for line in infile:
        words = line.split()
        words[2] = float(words[2])
        if words[3] == "mi":
            words[2] = words[2] / 0.62137
            words[3] = "km"
            words[2] = float("{0:.1f}".format(words[2]))
        else:
            pass
        list2.append(words[:2])
    maximum = max(list2,key=lambda x:x[2])
    infile.close()
    return maximum

def rinter(fileName, maximum):
    infile = open(fileName, "r")
    infile.write(' '.join(maximum))
    print('winner is :'+' '.join(maximum))

maximum = read("distances.txt")
newcode = rinter("winner.txt",maximum)

rawDescription: What am I doing wrong? Python Reading and Distinguishing


code:
from itertools import accumulate
list(accumulate([1,2,3,4,5]))

rawDescription: Elegant pythonic cumsum

description: Elegant pythonic cumsum


code:
import urllib

urllib.urlretrieve('ftp://server/path/to/file', 'file')

rawDescription: Python Script Uploading files via FTP

description: Python Script Uploading files via FTP


rawDescription: how to use Pi3d to draw an array

description: Use Pi3d to draw an array


code:
emails = [
    (u'Subject', u'Dear {}, Message.'.format(name), u'from@example.com', [address])
    for name, address in recipients
]

rawDescription: Looping through to create a tuple

description: Looping through to create a tuple


code:
mat = [[0]*2 for x in xrange(3)]
mat[0][0] = 1
mat

rawDescription: Creating lists of lists in a pythonic way


code:
i = np.argpartition(a.ravel(), -5)[-5:] # argpartition(a.ravel(), 5)[:5] for smallest
i

rawDescription: Get max or min n-elements out of numpy array? (preferably not flattened)


code:
def grabber3(datafile):
    with open(datafile, 'rb') as f:
        r =csv.DictReader(f)
        for line in r:
            del line['thisthing']
            yield line

rawDescription: Returning elements from a loop, one at a time


code:
import logging

from datetime import (
    datetime,
    timedelta
)
from requests.exceptions import (
    ConnectionError,
    Timeout,
)
from requests_cache.core import (
    dispatch_hook,
    CachedSession,
)

log = logging.getLogger(__name__)
# Stop logging from complaining if no logging has been configured.
log.addHandler(logging.NullHandler())

class FallbackCachedSession(CachedSession):
    """Cached session that'll reuse expired cache data on timeouts

    This allows survival in case the backend is down, living of stale
    data until it comes back.

    """

    def send(self, request, **kwargs):
        # this *bypasses* CachedSession.send; we want to call the method
        # CachedSession.send() would have delegated to!
        session_send = super(CachedSession, self).send
        if (self._is_cache_disabled or
                request.method not in self._cache_allowable_methods):
            response = session_send(request, **kwargs)
            response.from_cache = False
            return response

        cache_key = self.cache.create_key(request)

        def send_request_and_cache_response(stale=None):
            try:
                response = session_send(request, **kwargs)
            except (Timeout, ConnectionError):
                if stale is None:
                    raise
                log.warning('No response received, reusing stale response for '
                            '%s', request.url)
                return stale

            if stale is not None and response.status_code == 500:
                log.warning('Response gave 500 error, reusing stale response '
                            'for %s', request.url)
                return stale

            if response.status_code in self._cache_allowable_codes:
                self.cache.save_response(cache_key, response)
            response.from_cache = False
            return response

        response, timestamp = self.cache.get_response_and_time(cache_key)
        if response is None:
            return send_request_and_cache_response()

        if self._cache_expire_after is not None:
            is_expired = datetime.utcnow() - timestamp > self._cache_expire_after
            if is_expired:
                self.cache.delete(cache_key)
                # try and get a fresh response, but if that fails reuse the
                # stale one
                return send_request_and_cache_response(stale=response)

        # dispatch hook here, because we've removed it before pickling
        response.from_cache = True
        response = dispatch_hook('response', request.hooks, response, **kwargs)
        return response

def basecache_delete(self, key):
    # We don't really delete; we instead set the timestamp to
    # datetime.min. This way we can re-use stale values if the backend
    # fails
    try:
        if key not in self.responses:
            key = self.keys_map[key]
        self.responses[key] = self.responses[key][0], datetime.min
    except KeyError:
        return

from requests_cache.backends.base import BaseCache
BaseCache.delete = basecache_delete

rawDescription: Does requests_cache automatically update cache on update of info?


code:
from rest_framework import filters
queryset = filters.OrderingFilter().filter_queryset(self.request, queryset, self)

rawDescription: Ordering lost when returning self.get_queryset() in GET method of ListAPIView in Django REST Framework


code:
value = 0
def default():
    global value
    value = 1

rawDescription: Python global variable scoping

description: Python global variable scoping


code:
newfiles = []

while True:
    process(newfiles)
    newfiles = check_for_new_files()
    time.sleep(pollinterval)

rawDescription: How do you check when a file is done being copied in Python?

description: Check when a file is done being copied in Python


code:
class QPythonBinding(QQuickItem):
    def __init__(self, parent=None):
        super(QPythonBinding, self).__init__(parent)

    addElement = pyqtSignal(str, str)   #you call it like this  - addElement.emit("name", "value")

if __name__ == '__main__':
    import sys
    app = QGuiApplication(sys.argv)

    qmlRegisterType(QPythonBinding, "MyApplication", 1, 0, "QPythonBinding")
    view = QQuickView()

    view.show()
    app.exec_()

rawDescription: How to Add Dynamic Data to a QML Table

description: Add Dynamic Data to a QML Table


code:
import re
test = "blade, coffeen,    , cardiac"
re.search('blade[, ]*?coffeen[, ]*?cardiac', test)
re.search('blade[, ]*coffeen[, ]*cardiac', test)

rawDescription: using non-greedy qualifiers in regular expression '*?'

description: Using non-greedy qualifiers in regular expression '*?'


code:
pipelines.py
from mybot.utils import connect_url_database

class DedupPipeline(object):

    def __init__(self):
        self.db = connect_url_database()

    def process_item(self, item, spider):
        url = item['url']
        self.db.insert(url)
        yield item

rawDescription: avoid scrapy revisit on a different run

description: Avoid scrapy revisit on a different run


code:
class YourForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(YourForm, self).__init__(*args, **kwargs)

    # ... use self.request in clean etc

rawDescription: Setting a form field's default value from a request variable


code:
from importlib import import_module
OtherLongName = import_module('some.very.long.package.name.LongName')

rawDescription: multiline import from X import Y as Z

description: Multiline import from X import Y as Z


code:
root = tree.getroot()  # now get the root
keeper_data = ['06354237', '87654321']  # your list that you will apparently get from a file?
instances = root.findall('Instance')

rawDescription: Python: In an xml, How to delete nodes within a parent node


rawDescription: Assigning the inputs, with respect to its len()


code:
funclist = [f,g,h]
somelist+=[[x+f(x) for x,f in zip(somelist[-1],funclist)]]

rawDescription: Loop over time and over list elements with python -- one-dimensional lake temperature model simulation


code:
def __init__(self):
    self.callbacks_status = CallbackList()
    self.callbacks_conn = CallbackList()
    self.callbacks_angle = CallbackList()
    self.callbacks_brake = CallbackList()

rawDescription: More pythonic way to manage a list of callbacks


code:
# urls.py
urlpatterns = patterns('',
    url(r'^photo/(?P<pk>\d+)/$', 'render_image_with_watermark', name='render_image_with_watermark'),
    ...
)

rawDescription: image watermark using PIL in django

description: Image watermark using PIL in django


code:
df2 = df1.groupby(['abs_a','a']).count()
df3 = df2.groupby(level=0).min()

rawDescription: How to return all opposite pairs in a Pandas DataFrame?

description: Return all opposite pairs in a Pandas DataFrame


code:
import dis
dis.dis(lambda x: x.foo)
dis.dis(lambda x: getattr(x, 'foo'))

rawDescription: Is it bad practice to use python's getattr extensively?


code:
def readcountries():
    with open("countries.txt") as fh:
        rows = [[n.strip(), float(a), int(p)]
                for line in fh for n, a, p in (line.split(','),)]

rawDescription: python binary search and file i/o

description: Python binary search and file i/o


code:
class DynamicURLConf(object):
    urlpatterns = None

    def __init__(self, pages):
        self.urlpatterns = patterns('',
                                    url(r'^$', 'app.account.site.views.test'),
                                    url(r'^test/$', 'app.account.site.views.test'),
        )

def page_dispatcher(request, path=None):
    if path is None:
        # Here will be a return a homepage view
        return
    func, args, kwargs = resolve(urlparse("/" + path.strip("/") + "/")[2], DynamicURLConf(pages=None))
    kwargs['request'] = request
    return func(*args, **kwargs)

def test(request):
    return HttpResponse("I am test")

rawDescription: Subdomain-based URL configuration in Django app


code:
from communicate import *
x = 2 + 2
send_and_exit(x)

rawDescription: How to Get Variable from another .py

description: Get Variable from another .py


code:
def main():

    word_set = set()

    while True:
        word = input("Please enter a word: ")

        if word == 'stop': # we're using the word 'stop' to break from the loop
            break          # this of course means that 'stop' should be entered
                           # as an input word unless you want to exit
        word_set.add(word)

    with open('test.txt', 'w') as of:
        of.writelines("{}\n".format(word) for word in word_set)
        # google "generator expressions" if the previous line doesn't
        # make sense to you

    return

if __name__ == "__main__":
    main()

rawDescription: Reading a word from a file in a specific way


code: user = database.get(session['user_id'])

rawDescription: Python Flask: keeping track of user sessions? How to get Session Cookie ID?


code:
import numpy as np
a = np.arange(24).reshape((2,3,4))
a

rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code:
import numpy as np
import math
import random
n=2 #number of elements that can describe each cell
N=2 # number of cells
u=[np.zeros((n,n)) for i in range(N)]
V=2.0
epsilon=2.0

Mx=np.zeros((n,n))
My=np.zeros((n,n))

for x in range (n):
    Mx[x]=x-n/2

for y in range (n):
    My[y]=y-n/2

for i in range(N):
    for x in range(n):
        for y in range(n):
            if (x-n/2)**2+(y-n/2)**2<5: u[i][x,y]=1
lenu = len(u)
for i in range (lenu):
    if (np.sum(u[i])>V):
        print(u[i], i, u, len(u))
        theta=random.uniform(0, 2*math.pi)
        constant = np.tanh((math.cos(theta)*Mx+math.sin(theta)*My)/epsilon)
        u_end = u[i]/2.0*(1 + constant)
        u[i] = u[i]/2.0*(1 - constant)
        u.append(u_end)
        N+=1

rawDescription: change one element of an array into two and then delete the original (cell division simulation)

description: Change one element of an array into two and then delete the original (cell division simulation)


code: resumetext = str(s['resumetext'])

rawDescription: Python program to search for specific strings in hash values (coding help)


code: open('foo.csv').readlines()[1: -1]

rawDescription: Reading a specific number of lines of a .csv in python


code:
def pairs(df, k1,k2, a, b):
    check = df.loc[(df[k1] == a) & (df[k2] == b)]
    return None if check.empty else check.index.tolist()

rawDescription: Is there a way to 'search' in a pandas DataFrame for 2 specific numbers in columns and return the index if it exists?


code:
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
args = parser.parse_args(['--foo', 'BAR'])
vars(args)

rawDescription: Is it possible to reconstruct a command line with Python's argparse?


code:
userinput = create_text()
userinput['Story']

rawDescription: Function that allows the user to specify title and words for a text and keep them also outside the function?


code:
import matplotlib.pyplot as plt

def new_figure():

    fig = plt.figure()
    plt.plot([0, 1], [2, 3])
    plt.close(fig)
    return fig

def show_figure(fig):

    # create a dummy figure and use its
    # manager to display "fig"

    dummy = plt.figure()
    new_manager = dummy.canvas.manager
    new_manager.canvas.figure = fig
    fig.set_canvas(new_manager.canvas)

if __name__ == '__main__':

    fig = new_figure()
    show_figure(fig)

    plt.show()

rawDescription: Matplotlib: how to show a figure that has been closed


code:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'mysite.polls',
    'mysite.myapp',
)

rawDescription: choice_set django tutorial part one

description: Choice_set django tutorial part one


code:
for value in collection:
  ...

rawDescription: Learning Python from Ruby; Differences and Similarities


code: indices = [ ind_dict[x] for x in inter ]

rawDescription: Python: Finding corresponding indices for an intersection of two lists


code:
@app.route('/metering')
@authenticated_resource
def getstats():
    token = session.get("auth_token")
    # you might want to verify that the token was in the session, as such
    if token:
        return render_template('metering.html')
    else:
        abort(403)

rawDescription: Generate auth token in login route and require it in other routes


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1977)

# Generate some interesting-looking random data...
num = 200
grid = np.random.normal(0, 1, (20, num)).cumsum(axis=1).cumsum(axis=0)
x = np.linspace(0, 360, num)
y1 = np.random.normal(0, 1, num).cumsum()
y2 = np.random.normal(0, 1, num).cumsum()

# Plot on three seperate axes
fig, axes = plt.subplots(nrows=3, sharex=True)
axes[0].plot(x, y1)
axes[1].plot(x, y2)
im = axes[2].imshow(grid, extent=[0, 360, 0, 20], aspect='auto')

# Make some room for the colorbar
fig.subplots_adjust(left=0.07, right=0.87)

# Add the colorbar outside...
box = axes[2].get_position()
pad, width = 0.02, 0.02
cax = fig.add_axes([box.xmax + pad, box.ymin, width, box.height])
fig.colorbar(im, cax=cax)

plt.show()

rawDescription: Matplotlib mixed subplots with plot and pcolor(mesh) to have the same x axis length when colorbar is on


code:
class B(file1.B):
    A = A

rawDescription: Python inheritance and scoping question

description: Python inheritance and scoping question


code:
def unpack(stream, fmt):
    size = struct.calcsize(fmt)
    buf = stream.read(size)
    return struct.unpack(fmt, buf)

rawDescription: Idiomatic way to struct.unpack from BytesIO?


code:
print(repr(astr.encode('utf_8')))
# 'e\xcc\x81'
print(repr(combined_astr.encode('utf_8')))
# '\xc3\xa9'

rawDescription: Precompose Unicode Character Sequences in Python