code:
def create_list(tree, templist=[]):
    """
    >>> tree = BinaryTree(2, BinaryTree(29, BinaryTree(26)), BinaryTree(4, None, BinaryTree(2, BinaryTree(9))))
    >>> create_list(tree)
    [2, 29, 4, 26, None, None, 2, None, None, None, None, None, None, 9, None]

    """
    items = []
    queue = [tree]

    while queue:
        copy = queue[:]
        queue = []

        for item in copy:
            if item is None:
                items.append(None)
                queue.append(None)
                queue.append(None)
            else:
                items.append(item.key)
                queue.append(item.left)
                queue.append(item.right)

        if all((x is None for x in queue)):
            break

    return items

rawDescription: python list from python binary tree

description: Python list from python binary tree


code:
from itertools import groupby
from operator import itemgetter

def group_by_start(inputlist, n):
    return [list(g) for k, g in groupby(inputlist, key=itemgetter(slice(n)))]

rawDescription: Python. How to make list from another list by mark?


rawDescription: Rearrange row elements using numpy in Python


code:
import scipy.cluster.vq as vq
import collections
import numpy as np

def auto_cluster(data,threshold=0.1,k=1):
    # There are more sophisticated ways of determining k
    # See http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set
    data=np.asarray(data)
    distortion=1e20
    while distortion>threshold:
        codebook,distortion=vq.kmeans(data,k)
        k+=1
    code,dist=vq.vq(data,codebook)
    groups=collections.defaultdict(list)
    for index,datum in zip(code,data):
        groups[index].append(datum)
    return groups

np.random.seed(784789)
N=20
weights=100*np.random.random(N)
groups=auto_cluster(weights,threshold=1.5,k=N//5)
for index,data in enumerate(sorted(groups.values(),key=lambda d: np.mean(d))):
    print('{i}: {d}'.format(i=index,d=data))

rawDescription: grouping objects to achieve a similar mean property for all groups

description: Grouping objects to achieve a similar mean property for all groups


code:
def add_data(key, value, data):
    if key.startswith('Value('):
        if key.endswith('(int)'):
            value = int(value)
        data['Sequences'][-1].append(value)
    elif key == 'Sequence':
        data['Sequences'].append([])
    else:
        data[key] = value

def parse_lines(lineseq):
    data = {'Sequences':[]}
    for line in lineseq:
        try:
            key, value = [part.strip() for part in line.split(':', 1)]
        except ValueError:
            continue
        add_data(key, value, data)
    return data

lines = proc_stdout.split('\n')
data = parse_lines(lines)

rawDescription: Split string into list, then split list into list of lists


code:
def generate(request):
    if request.method == 'GET':
        val1 = request.GET.get('val1')
        val2 = request.GET.get('val2')
        #futher code

rawDescription: Pass URL parameters to Python

description: Pass URL parameters to Python


code: unique = {id(d): d for d in dictlist}.values()

rawDescription: Is there a python builtin to extract the 'set' of unhashable objects from a list, using 'is' comparison?


rawDescription: Clarification on classes in python

description: Clarification on classes in python


code:
dictionary={'abc','dsw','lol'}
type(dictionary)
dir(dictionary)
dictionary.pop()

rawDescription: how to get the key or values one by one from the dictionary?

description: Get the key or values one by one from the dictionary


code:
# get the number of unique values for each stimulus parameter
params_shape = tuple(np.unique(col).shape[0] for col in stim_params.T)

# get the set of row indices that will sort the stimulus parameters in ascending
# order, starting with the final column
idx = np.lexsort(stim_params[:, ::-1].T)

# sort and reshape the stimulus parameters:
sorted_params = stim_params[idx].T.reshape((5,) + params_shape)

# sort and reshape the output values
sorted_output = output_vals[idx].T.reshape((3,) + params_shape)

rawDescription: Reorganizing an MxN 2D array of datapoints into an N-dimensional array


rawDescription: Remove elements from the array

description: Remove elements from the array


code: sum(dice) - min(dice)

rawDescription: Is there a more efficient way to organize random outcomes by size in Python?


code: most_common(self, n=None)

rawDescription: Selecting all top words in Python list using Counter


rawDescription: PHP post to url

description: PHP post to url


code: BracketedRegex = re.compile(r'\[.*?\]')

rawDescription: Grabbing brackets and everything inside Regex


code:
name2="QW0210"

print("".join(dropwhile(lambda x: not x.isdigit(),name2)))

rawDescription: Python Name Abreviation finding

description: Python Name Abreviation finding


code:
import json
with open('file1.txt') as jdata:
    data = json.load(jdata)
    d = data
d["data"]["Response"]["products"] = d["data"]["Response"]["products"].values()
print(json.dumps(d))

rawDescription: Convert JSONObject into JSONArray using Python


code: [[x[4], x[9]] for x in interaction["input"] for interaction in data["interactions"]]

rawDescription: Python extract values from JSON

description: Python extract values from JSON


code:
parser = argparse.ArgumentParser(prog='tool',
  formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=27))

args = [('-u', '--upf', 'ref. upf', dict(required='True')),
        ('-s', '--skew', 'ref. skew', {}),
        ('-m', '--model', 'ref. model', {})]
for args1, args2, desc, options in args:
     parser.add_argument(args1, args2, help=desc, **options)

parser.print_help()

rawDescription: Control formatting of the argparse help argument list?


code:
class BookForm(ModelForm):
    class Meta:
        model = Book
        fields = ['name']

rawDescription: Django - 'Created by'-Field

description: Django - 'Created by'-Field


rawDescription: How to query pandas dataframe using a specific value?

description: Query pandas dataframe using a specific value


code: tuple(map(next, iterators))

rawDescription: Find changed or new rows in two lists of lists


code:
isinstance(d, collections.MutableMapping)
isinstance(dict(), collections.MutableMapping)

rawDescription: How would I implement a dict with Abstract Base Classes in Python?


code:
def Beta(x: float):
    y = x + 0.5
    return y

rawDescription: Get a python function attribute without running the function


code:
import numpy as np

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

x = np.linspace(1, 4, 1000)

y = x**3

fig, ax = plt.subplots()

ax.loglog(x,y, basex=np.e, basey=np.e)

def ticks(y, pos):
    return r'$e^{:.0f}$'.format(np.log(y))

ax.xaxis.set_major_formatter(mtick.FuncFormatter(ticks))
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))

plt.show()

rawDescription: pyplot: loglog() with base e

description: Pyplot: loglog() with base e


code:
import re
string = r'This a string with ^g\.$s'
pattern = r'^g\.$s'
re.search(re.escape(pattern), re.escape(string))  # nope
re.search(re.escape(pattern), string)  # yep

rawDescription: How can Python's regular expressions work with patterns that have escaped special characters?


code:
while True:
    option = raw_input("What would you like to do?")
    if option == "exit":
        break

rawDescription: How do you define a variable in one function and change it in another with the first function recognizing it

description: Define a variable in one function and change it in another with the first function recognizing it


code: self.fields = list(fields)

rawDescription: python method variables and Objects created in method

description: Python method variables and Objects created in method


code: {w: sum(word_count.get(x, 0) for x in ws) for w, ws in synonyms.items()}

rawDescription: Aggregating and Renaming Keys in Dictionary


code: df.index.get_level_values(0) == 'good'

rawDescription: Get boolean array (or generator) from pandas DataFrame index


code:
class IRSensor:
    def read(self): return {'ir_amplitude': 12}

class UltrasonicSensor:
    def read(self): return {'ultrasonic_amplitude': 63}

class SickLaserSensor:
    def read(self): return {'laser_amplitude': 55}

class CompositeSensor:
    """Wrap multiple component sensors, coalesce the results, and return
    the composite readout.
    """
    component_sensors = []

    def __init__(self, component_sensors=None):
        component_sensors = component_sensors or self.component_sensors
        self.sensors = [cls() for cls in component_sensors]

    def read(self):
        measurements = {}
        for sensor in self.sensors:
            measurements.update(sensor.read())
        return measurements

class MyCompositeSensor(CompositeSensor):
    component_sensors = [UltrasonicSensor, IRSensor]

composite_sensor = MyCompositeSensor()
measurement_map = composite_sensor.read()
assert measurement_map['ultrasonic_amplitude'] == 63
assert measurement_map['ir_amplitude'] == 12

rawDescription: Discussion of multiple inheritance vs Composition for a project (+other things)


code:
import h5py
import contextlib

filename = '/tmp/foo.hdf5'
propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS)
settings = list(propfaid.get_cache())
settings[2] *= 5
propfaid.set_cache(*settings)
with contextlib.closing(h5py.h5f.open(filename, fapl=propfaid)) as fid:
    f = h5py.File(fid)

rawDescription: How to set cache settings while using h5py high level interface?

description: Set cache settings while using h5py high level interface


code:
import glob
json_files = glob.glob("*.json")
for json_file in json_files:
    process_file(json_file)

rawDescription: Error while uploading a JSON file to Amazon SQS


rawDescription: Round pandas data frame/series

description: Round pandas data frame/series


code: XYZ = np.vstack((x,y,z)).T

rawDescription: Summing and removing repeated elements of Numpy Arrays


code:
from threading import Thread, Event
from time import sleep

class PeriodicThread(Thread):

    def __init__(self, interval):
        self.stop_event = Event()
        self.interval = interval
        super(PeriodicThread, self).__init__()

    def run(self):
         while not self.stop_event.is_set():
             self.main()
             # wait self.interval seconds or until the stop_event is set
             self.stop_event.wait(self.interval)

    def terminate(self):
        self.stop_event.set()

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

rawDescription: Python Threading not stopping

description: Python Threading not stopping


code: req = requests.post(url, data=data, headers=headers, stream=True, files=buff, verify=False)

rawDescription: Python equivalent to curls --form: Create multipart form-data post request with data in "form" parameter


code:
import csv
word_features = get_word_features(get_words_in_tweets(tweets))
with open('wordFeatures.csv', 'w') as output:
    writer = csv.writer(output, delimiter=':')
    writer.writerows(enumerate(word_features, 1))

rawDescription: Python export csv data into file

description: Python export csv data into file


code:
list1 = ["Hello", "Goodbye", "Ohai"]
list2 = ["Hello", "Goodbye"]
set(list1) ^ set(list2)

rawDescription: Find the element "left" in a list

description: Find the element "left" in a list


code:
def __iter__(self):
    return iter(self.fetchone, None)

rawDescription: About mysql cursor and iterator

description: About mysql cursor and iterator


code:
schema = Schema({'ID': Use(int, error='ID should be an int'),
                 'FILE': Or(None, Use(open, error='FILE should be readable')),
                 object: object})

rawDescription: docopt + schema validation

description: Docopt + schema validation


code:
from itertools import product

def sublists(lst):
    for doslice in product([True, False], repeat=len(lst) - 1):
        slices = []
        start = 0
        for i, slicehere in enumerate(doslice, 1):
            if slicehere:
                slices.append(lst[start:i])
                start = i
        slices.append(lst[start:])
        yield slices

rawDescription: Python: breaking a list into all possible sublists


code: struct.unpack('<i', bytes + ('\0' if bytes[2] < '\x80' else '\xff'))

rawDescription: How to read integers from a file that are 24bit and little endian using Python?

description: Read integers from a file that are 24bit and little endian using Python


code:
from scipy.spatial.distance import cdist
dist = cdist(precomputed_flat, measured_flat, 'euclidean')

rawDescription: more efficient way to calculate distance in numpy?

description: More efficient way to calculate distance in numpy


code:
with open ("data.txt", "r") as myData:
    data = myData.readlines()

with open ("template.txt", "r") as myTemplate:
    template = myTemplate.read()

file = open("output.txt", "w")

exec(template)
for line in data:
    params = line.split(' ')
    if (params[0].isdigit()):
        for i in range(len(params)):
            params[i] = float(params[i])
        results = [None] * len(headers) #headers from eval'd template
        for i in range(len(headers)):
            # this is where we call our lambdas
            # which will calculate the colums based on the data for this row
            results[i] = str(process[i](params))
        file.write(" ".join(results) + "\n");
    else:
        file.write(" ".join(headers) + "\n")
file.close()

rawDescription: A simple interpreter in python for generating report


code: next(re.finditer(r'\d+$', s)).group(0)

rawDescription: python regex: get end digits from a string

description: Python regex: get end digits from a string


code:
d=collections.defaultdict(list)
for item in lst:
    d[item[1]].append(item)
d[min(key for key in d.keys() if key!=0)]

rawDescription: any python min like function which gives a list as result

description: Any python min like function which gives a list as result


code:
s = 'thumbgreenappleactiveassignmentweeklymetaphor'
print(infer_spaces(s))

rawDescription: How to extract literal words from a consecutive string efficiently?

description: Extract literal words from a consecutive string efficiently


code:
keywords = {}
for url in google.search('sleep', num=2, stop=1):
    article = Article(url)
    article.download()
    article.parse()
    article.nlp()

    keywords[url] = article.keywords

print(keywords)

rawDescription: How to take output from iterating, store that in a dictionary

description: Take output from iterating, store that in a dictionary


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label

class TableHeader(Label):
    pass

class PlayerRecord(Label):
    pass

class MyGrid(GridLayout):

    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.fetch_data_from_database()
        self.display_scores()

    def fetch_data_from_database(self):
        self.data = [
            {'name': 'name', 'score': 'score', 'car': 'car'},
            {'name': 'przyczajony', 'score': '1337', 'car': 'Fiat 126p'},
            {'name': 'Krusader Jake', 'score': '777', 'car': 'Ford'},
            {'name': 'dummy', 'score': '0', 'car': 'none'},
            {'name': 'dummy', 'score': '0', 'car': 'none'},
            {'name': 'dummy', 'score': '0', 'car': 'none'},
            {'name': 'dummy', 'score': '0', 'car': 'none'},
            {'name': 'dummy', 'score': '0', 'car': 'none'},
            {'name': 'dummy', 'score': '0', 'car': 'none'},
            {'name': 'dummy', 'score': '0', 'car': 'none'},
            {'name': 'dummy', 'score': '0', 'car': 'none'}
        ]

    def display_scores(self):
        self.clear_widgets()
        for i in xrange(len(self.data)):
            if i < 1:
                row = self.create_header(i)
            else:
                row = self.create_player_info(i)
            for item in row:
                self.add_widget(item)

    def create_header(self, i):
        first_column = TableHeader(text=self.data[i]['name'])
        second_column = TableHeader(text=self.data[i]['score'])
        third_column = TableHeader(text=self.data[i]['car'])
        return [first_column, second_column, third_column]

    def create_player_info(self, i):
        first_column = PlayerRecord(text=self.data[i]['name'])
        second_column = PlayerRecord(text=self.data[i]['score'])
        third_column = PlayerRecord(text=self.data[i]['car'])
        return [first_column, second_column, third_column]

class Test(App):
    pass

Test().run()

rawDescription: How do I take a Python List of Dictionary Values and display in Kivy UI as a table (Using ListView Widget)?

description: Take a Python List of Dictionary Values and display in Kivy UI as a table (Using ListView Widget)


code:
import sys
from distutils.core import setup
import py2exe

entry_point = sys.argv[1]
sys.argv.pop()
sys.argv.append('py2exe')
sys.argv.append('-q')

opts = {
    'py2exe': {
        'compressed': 1,
        'optimize': 2,
        'bundle_files': 1
    }
}

setup(console=[entry_point], options=opts, zipfile=None)

rawDescription: Can I somehow "compile" a python script to work on PC without Python installed?

description: Somehow "compile" a python script to work on PC without Python installed


code: sorted(b, key=lambda v: a_dict.get(v, float('inf')))

rawDescription: Sort python list with order of another, larger list


code:
S="Hello World"
id(S)
S="Hello Human"
id(S)

rawDescription: What happens to a immutable object in python when its value is changed?


code:
import types

def attach_method(class_instance, name, function):
    if name not in class_instance.__dict__.keys():
        class_instance.__dict__[name] = types.MethodType(function, class_instance)

rawDescription: add method with a specific name to already created class instance

description: Add method with a specific name to already created class instance


code:
# import the modules
import serial
import webbrowser

# open a serial connection to the Arduino to read data from
arduino = serial.Serial('/dev/ttyACM0', 9600)

# we want to read everything the Arduino tells us
while True:

    # read one line (a str) that the Arduino wrote with Serial.println()
    line = arduino.readline()

    # convert the line into a string that contains only the numbers
    # by stripping away the line break characters and spaces
    string_with_number_in_it = line.strip()

    # convert the string into a number that can be compared
    number = float(string_with_number_in_it)

    if number < 36:
        webbrowser.open("/home/path/my-music.mp3")

rawDescription: Issue to play a mp3 file with a Python script from Arduino data


code:
df.index = df.index[0:2].tolist() + [Timestamp('20130101 09:05:00')] + df.index[-2:].tolist()
df
df.index.freq

rawDescription: Python pandas dataframe - any way to set frequency programmatically?


rawDescription: accumulate numpy array for just one column

description: Accumulate numpy array for just one column


code:
cmap = {'a': 'red', 'b': 'blue', 'c': 'yellow'}
df.plot(x='cpu', y='wait', kind='scatter',
        colors=[cmap.get(c, 'black') for c in df.category])

rawDescription: scatter plot by category in pandas

description: Scatter plot by category in pandas


code:
class Color(object):
    ...

rawDescription: How to extend a class in python?

description: Extend a class in python


code:
# content of conftest.py
#
import sys
import pytest

ALL = set("osx linux2 win32".split())

def pytest_runtest_setup(item):
    if isinstance(item, item.Function):
        plat = sys.platform
        if not hasattr(item.obj, plat):
            if ALL.intersection(set(item.obj.__dict__)):
                pytest.skip("cannot run on platform %s" %(plat))

rawDescription: Does pytest support "default" markers?

description: Does pytest support "default" markers


code:
import requests
import sys
from my_module import print_smth

print_smth(requests.get('https://google.com'))
print_smth(sys.version)

rawDescription: Import order coding standard

description: Import order coding standard


code:
class TaskForm(ModelForm):
    class Meta:
       model = Task
       exclude = ['owner']
    def __init__(self, user, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['owner'].queryset = Task.objects.filter(owner=user)

rawDescription: How to get the foreign keys related to drop down only of that user in Django ModelForm

description: Get the foreign keys related to drop down only of that user in Django ModelForm


code:
sorted(d, key=lambda x: d[x][2], reverse=True)[:2]

# b [2, 3, 9]
# c [3, 2, 8]

rawDescription: appropriate data structure for sorting a multi dimensional array in python?

description: Appropriate data structure for sorting a multi dimensional array in python


code:
for i, x in enumerate(l):
    if x >= 1: l[i] = 1

rawDescription: Converting all numbers in a python list to 1 or 0


code: my_bytes = struct.pack('!H', value)

rawDescription: Convert string of 0s and 1s to byte in Python


code:
from json import loads

with open("data.txt", "r") as f:
    data = loads(f.read())

rawDescription: How to read a particular data format

description: Read a particular data format


code:
import test2
test2.pow2(3)   #only need to pass intent(in) parameters :-)

rawDescription: making python and fortran friends

description: Making python and fortran friends


code:
def replacer(matchobj):
    if matchobj.group(1).lstrip() == "":
        return " {}/{}".format(int(matchobj.group(2)) - 11, matchobj.group(2))
    else:
        return "/".join(matchobj.groups())

print(re.sub(r"(\s*\d*)/(\d+)", replacer, data))

rawDescription: Conditional string insertion

description: Conditional string insertion


code:
def miles_to_km(miles):
    return miles * 1.6

def read_miles(prompt):
    miles = float(input(prompt))
    if miles < 0: raise ValueError()
    return miles

def read_miles_retry(prompt, retries = 3):
    while retries > 0:
        try:
            return read_miles(prompt)
        except:
            retries -= 1
            print('Invalid input')

    raise ValueError()

def main():
    try:
        kms = miles_to_km(read_miles_retry('Miles? '))
        print(kms)
    except:
        exit(1)

main()

rawDescription: python 3 - limiting invalid inputs

description: Python 3 - limiting invalid inputs


code:
import pandas
dataf = pandas.DataFrame({'a':(1,2,3), 'b':(4,5,6)})

import sys
def foo(roworcol):
    # current index along the axis
    axis_i = sys._getframe(1).f_locals['i']
    # data frame the function is applied to
    dataf = sys._getframe(1).f_locals['self']
    axis = sys._getframe(1).f_locals['axis']
    # number of elements along the chosen axis
    n = dataf.shape[(1,0)[axis]]
    #  print where we are
    print('index: %i - %i items before, %i items after' % (axis_i,
                                                           axis_i,
                                                           n-axis_i-1))

rawDescription: Apply function over relative rows in Pandas


code:
# Legal, but probably not desirable.
# At the very least, pick one style and be consistent; don't
# use a variety of options like I show here.
return method_returning_json()[
         'LongFieldGroup1'][
         'FieldGroup2'][
         'FieldGroup3'
         ][
         'LongValue'
         ]

rawDescription: pep8 compliance with long json dictionary lookup?

description: Pep8 compliance with long json dictionary lookup


code: locations = dict((s, i) for i, s in enumerate(my_list))

rawDescription: append/insert a value/string to a list element dynamically in Python?

description: Append/insert a value/string to a list element dynamically in Python


rawDescription: Sort a numpy array like a table

description: Sort a numpy array like a table


code:
def parse(self, response):
    for i in range(175):
        url = "http://b2.nourl.com/dp.asp"
        payload = {"AppKey": "94921000e1999f84a518725", "ComparisonType1_1": "LIKE", "Value1_1": "", "MatchNull1_1" : "N", "ComparisonType2_1" : "LIKE", "MatchNull2_1" : "N", "Value2_1" : "", "ComparisonType3_1": "=", "MatchNull3_1" : "N", "Value3_1" : "", "x":"69", "y":"27", "FieldName1" : "County", "Operator1": "OR", "NumCriteriaDetails1": "1", "Operator2" : "OR", "NumCriteriaDetails2" : "1", "FieldName3": "Year", "Operator3" : "OR", "NumCriteriaDetails3": "1", "PageID" : "2", "GlobalOperator": "AND", "NumCriteria" : "3", "Search" : "1", "cpipage": "%i" %i}
        yield FormRequest(url, formdata = payload, callback = self.parse_data)

rawDescription: Python - Scrapy, in a loop

description: Python - Scrapy, in a loop


code: df["grp_idx"] = np.where(df.groupby("id").cumcount()<3, 0, df["grp_idx"])

rawDescription: Pandas: Collapse first n rows in each group by aggregation


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

from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog

appname = "example"

class App(object):
    def __init__(self, root=None):
        if not root:
            root = Tk()
        self.root = root
        self.initUI()

    def initUI(self):
        self.root.title(appname)
        menubar = Menu(self.root)
        self.root.config(menu=menubar)
        fileMenu = Menu(menubar, tearoff=0)
        fileMenu.add_command(label="Open File", command=self.fileOpen)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)
        self.canvas = Canvas(self.root)
        self.canvas.pack(side=LEFT, fill=BOTH)
        self.scrollbar_vert = Scrollbar(self.root)
        self.scrollbar_vert.pack(side=RIGHT, fill=Y)
        self.scrollbar_hor = Scrollbar(self.root)
        self.scrollbar_hor.config(orient=HORIZONTAL)
        self.scrollbar_hor.pack(side=BOTTOM, fill=X)

    def onExit(self):
        self.root.quit()

    def fileOpen(self):
        filename = tkFileDialog.askopenfile(
                parent=self.root,
                mode='rb',
                title='Choose a file',
                filetypes=[ ( "Image files",("*.jpg", "*.jpeg", "*.png", "*.gif") ), ("All files", ("*.*"))] )

        if filename == None:
            return
        self.img = Image.open(filename)
        self.photo_image = ImageTk.PhotoImage(self.img)
        self.canvas.pack_forget()
        self.canvas = Canvas(self.root, width=self.img.size[0], height=self.img.size[1])
        self.canvas.create_image(10, 10, anchor=NW, image=self.photo_image)
        self.canvas.pack(side=LEFT, fill=BOTH)
        self.canvas.config(yscrollcommand=self.scrollbar_vert.set)
        self.canvas.config(xscrollcommand=self.scrollbar_hor.set)
        self.canvas.config(scrollregion=self.canvas.bbox(ALL))
        self.scrollbar_vert.config(command=self.canvas.yview)
        self.scrollbar_hor.config(command=self.canvas.xview)

    def run(self):
        self.root.mainloop()

def main():
    root = Tk()
    root.geometry("250x150+300+300")
    app = App(root)
    app.run()

if __name__ == '__main__':
    main()

rawDescription: Python Tkinter - Image not displaying

description: Python Tkinter - Image not displaying


code:
def make_func(x):
    def func(a, b):
        return a*b*x
    return func

list_of_funcs = [make_func(i) for i in range(10)]

rawDescription: How to create an array of functions which partly depend on outside parameters? (Python)

description: Create an array of functions which partly depend on outside parameters? (Python)


code: sorted(league.items(), key= lambda x: x[1]['totalpts'], reverse=True)

rawDescription: Sort dict in jinja2 loop

description: Sort dict in jinja2 loop


rawDescription: Numpy masked array modification

description: Numpy masked array modification


code: line(Surface, color, (x1,y1), (x2,y2), width)

rawDescription: how can draw a line in python by x,y?

description: How can draw a line in python by x,y


rawDescription: NDB using Users API to form an entity group


code:
from __future__ import print_function
import sys
import inspect
import collections

Record = collections.namedtuple(
    'Record',
    'frame filename line_number function_name lines index')

def myprint(text):
    if text.strip():
        record = Record(*inspect.getouterframes(inspect.currentframe())[1])
        sys.stdout.write('{f} {n}: '.format(f = record.filename, n = record.line_number))
    sys.stdout.write(text + '\n')

def foo():
    print('Hi')

print = myprint
foo()

rawDescription: How do you find where a print statement is located?

description: Find where a print statement is located


code: table = Table(data, colWidths=270, rowHeights=79)

rawDescription: How to make a simple table in ReportLab

description: Make a simple table in ReportLab


code: counts = (entry.get(key, '') for entry in data)

rawDescription: Merge three csv files with same headers in Python


code:
base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]

def genexp():
  return tuple(x for sublist in base_lists for x in sublist)

def listcomp():
  return tuple([x for sublist in base_lists for x in sublist])

def withsum():
  return tuple(sum(base_lists,[]))

import itertools as it

def withit():
  return tuple(it.chain(*base_lists))

rawDescription: Converting a list of lists to a tuple in Python


code:
def flatten(data):
   if isinstance(data, tuple):
      for v in data:
         yield v
   else:
      for k in data:
         for v in flatten(data[k]):
            yield k + '\\' + v

rawDescription: Concatenate sequence from a predefined datastructure


code:
a, b = 1, 2
phi = np.linspace(3, 10, 100)
x = a*phi - b*np.sin(phi)
y = a - b*np.cos(phi)
y_growth_flips = np.where(np.diff(np.diff(y) > 0))[0] + 1

plt.plot(x, y, 'rx')
plt.plot(x[y_growth_flips], y[y_growth_flips], 'bo')
plt.axis([2, 12, -1.5, 3.5])
plt.show()

rawDescription: FInd all intersections of xy data point graph with numpy?


code:
import xml.etree.ElementTree as et
import requests

URL = "http://www.omdbapi.com/?t=True%20Grit&r=XML"

def main():
    pg = requests.get(URL).content
    root = et.fromstring(pg)

    for attr,value in root[0].items():
        print("{:>10}: {}".format(attr, value))

if __name__=="__main__":
    main()

rawDescription: Copy text from a specific point on a web page in Python


code:
from itertools import chain
list(chain(*mayorPowers))

rawDescription: Adding Lists Elements to 'Mega List'

description: Adding Lists Elements to 'Mega List'


code: t = ThreadClass().start()

rawDescription: Global variable in thread class does not update


code:
def float_or_na(value):
    return float(value if value != 'N/A' else 'nan')

rawDescription: Converting string to float python N/A

description: Converting string to float python N/A


code:
o = SomeObj()
'x' in o # This won't work right

rawDescription: Python coroutines on builtin functions

description: Python coroutines on builtin functions


code:
inp = sys.stdin.readline()
integer = int(inp)
sys.stdout.write("%d\n", (integer ** 2,))
sys.stdout.flush()

rawDescription: making python programs "chat" via pipe

description: Making python programs "chat" via pipe


code:
import logging, logging.handlers

handler = logging.handlers.RotatingFileHandler('/tmp/foo.log', 'a', 100000, 10)
logging.getLogger().addHandler(handler)
logging.getLogger('foo').setLevel(logging.DEBUG)

rawDescription: subprocess stdout/stderr to finite size logfile

description: Subprocess stdout/stderr to finite size logfile


code:
from django.contrib.admin.views.main import ChangeList

class ContactChangeList(ChangeList):
    def url_for_result(self, result):
        pk = getattr(result, self.pk_attname)
        # YOU PROBABLY WANT TO CHANGE NEXT LINES!
        return reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name),
                       args=(quote(pk),),
                       current_app=self.model_admin.admin_site.name)

rawDescription: Amending URL for "list_display_links" in Django 1.6 admin change list


rawDescription: Python - alternating lists

description: Python - alternating lists


code: df[ df > 0 ].count(axis=1)

rawDescription: python pandas conditional count across columns

description: Python pandas conditional count across columns


code:
import threading
t = threading.Thread(target=target_function,name=name,args=(args))
t.daemon = True
t.start()

rawDescription: run a python program on a new thread

description: Run a python program on a new thread


rawDescription: Django Piston: How can I exclude nested fields from handler results? Is it even possible?


code:
...
labels = ['New Plan','New Operation','Current Operation']
html_dict['labels_tables'] = zip(label, list_of_tables)

rawDescription: Looping over multiple lists in Django Template


code:
class PluginMetaclass(type):
    def __new__(cls, name, bases, attrs):
        print("Called metaclass: %r" % cls)
        print("Creating class with name: %r" % name)
        newclass = super(PluginMetaclass, cls).__new__(cls, name, bases, attrs)
        print("Registering class: %r" % newclass)
        registry.append((name, newclass))
        return newclass

rawDescription: python 3.2 plugin factory: instantiation from class/metaclass

description: Python 3.2 plugin factory: instantiation from class/metaclass


rawDescription: set value to None zipping two lists into dictionary

description: Set value to None zipping two lists into dictionary


code:
class MyFirstView(TemplateView, BaseContextMixin):
    template_name = "mir/my_first_template.html"

    def get_context_data(self, **kwargs):
        context_data = super(MyFirstView, self).get_context_data(**kwargs)
        context_data["my_special_key"] = my_special_data
        return context_data

class MySecondView(TemplateView, BaseContextMixin):
    template_name = "mir/my_second_template.html"

    def get_context_data(self, **kwargs):
        context_data = super(MySecondView, self).get_context_data(**kwargs)
        context_data["my_special_key_2"] = my_special_data_2
        return context_data

rawDescription: Serving multiple templates from a single view (or should I use multiple views?)


code:
idx = data['event number'] == (data.event.shift(1) == 'event end').cumsum()
data.loc[idx, 'event number'] = np.nan
data

rawDescription: Fill NA Values in pandas Series with a stop


rawDescription: Automatic (whisker-sensitive) ylim in boxplots


code:
sorted("foo bar wibble")
sorted(["foo", "bar", "wibble"])

rawDescription: Why do some arguments need to be defined, and others not? (Learn Python the Hard Way, ex. 25)


code:
current_version_view = couchview.version.CurrentVersion()
result = current_version_view(self.db, key=version_key)

rawDescription: Recommended approach for loading CouchDB design documents in Python?


rawDescription: Create a column with a random number for each exact match of two columns in pandas dataframe


code:
from itertools import compress, tee
seen = set()
f1, f2 = tee(True if x not in seen and not seen.add(x) else False for x in a)
list(compress(a, f1))
list(compress(b, f2))

rawDescription: Remove duplicate from two lists without using loop?


rawDescription: Write value to hidden element with selenium python script


code: np.r_[tuple(slice(s, e) for s, e in zip(start, end))]

rawDescription: Construct Numpy index given list of starting and ending positions


code:
df3 = df2.set_index("Start Date")
df3

rawDescription: How to compare dates from Excel sheets for value filling purposes on python

description: Compare dates from Excel sheets for value filling purposes on python


code: std = np.std(bdict.values())

rawDescription: Perform a Standard Deviation on the values in a dictionary


code:
def generic_get_args(callable):
    if {'args', 'keywords', 'func'}.issubset(dir(callable)):
        # assume a partial object
        spec = getargspec(callable.func).args[len(callable.args):]
        return [var for var in spec if var not in callable.keywords]
    if getattr(callable, '__self__', None) is not None:
        # bound method
        return getargspec(callable).args[1:]
    return getargspec(callable).args

rawDescription: Get argument names of callable objects in the way they are called


code:
import httplib

def getresponse(self,*args,**kwargs):
    response = self._old_getresponse(*args,**kwargs)
    if self.sock:
        response.peer = self.sock.getpeername()
    else:
        response.peer = None
    return response

httplib.HTTPConnection._old_getresponse = httplib.HTTPConnection.getresponse
httplib.HTTPConnection.getresponse = getresponse

import requests

def check_peer(resp):
    orig_resp = resp.raw._original_response
    if hasattr(orig_resp,'peer'):
        return getattr(orig_resp,'peer')

rawDescription: How do I get the IP address from a http request using the requests library?

description: Get the IP address from a http request using the requests library


code:
def mk_func(y):
    def h(x):
        return x * y
    return h

rawDescription: An elegant way to make a list of functions in python


code:
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session

engine = sa.create_engine('sqlite://', echo=True)
session = Session(bind=engine)
Base = declarative_base(bind=engine)

class ThreeWay(Base):
    __tablename__ = 'three_way'

    id = sa.Column(sa.Integer, primary_key=True)
    a = sa.Column(sa.String)
    b = sa.Column(sa.String)

    __mapper_args__ = {
        'polymorphic_on': sa.case(
            (
                (a == sa.literal_column("'X'"), sa.literal_column('1')),
                (b == sa.literal_column("'Y'"), sa.literal_column('2'))
            ),
            else_=sa.literal_column('3')
        )
    }

class X(ThreeWay):
    __mapper_args__ = {
        'polymorphic_identity': 1
    }

    def __init__(self, **kwargs):
        kwargs['a'] = 'X'
        super(X, self).__init__(**kwargs)

class Y(ThreeWay):
    __mapper_args__ = {
        'polymorphic_identity': 2
    }

    def __init__(self, **kwargs):
        kwargs['b'] = 'Y'
        super(Y, self).__init__(**kwargs)

class Z(ThreeWay):
    __mapper_args__ = {
        'polymorphic_identity': 3
    }

Base.metadata.create_all()

session.add_all((X(), Y(), Z()))
session.commit()

print(session.query(ThreeWay).count())  # inserted 3 generic ThreeWay rows
print(session.query(Y).count())  # 1 of them is specifically a Y row

rawDescription: Can polymorhpic_on be used over more than one column?


code: {'hello': 'world'}

rawDescription: How do you read in a text (.txt) file as a .py file in Python 2.7?

description: Read in a text (.txt) file as a .py file in Python 2.7


code:
map(type, [1, 2, 3, 'X'])
list(map(type, [1, 2, 3, 'X']))
# Using `set`, you can get unique types.
set(map(type, [1, 2, 3, 'X']))

rawDescription: Does the list have any numbers?

description: Does the list have any numbers


code:
rows = [[state, count.split()[0]] for state, count in rows]
rows

rawDescription: How to remove extra content in table cell using BeautifulSoup

description: Remove extra content in table cell using BeautifulSoup


code:
def days(amt, day=1):
    new = (amt * .05) + amt - 10

    if amt == 0:
        return day, 0

    elif 0 <= new <= 1000:
        return days(new, day + 1)
    return  day, new

rawDescription: How can I count and display my recursive steps in Python?

description: Count and display my recursive steps in Python


code: form = MiscQuestionForm(request.POST or None, misc=misc_questions)

rawDescription: Can I pass a variable into a form while declaring it in a view in Django

description: Pass a variable into a form while declaring it in a view in Django


rawDescription: One-sided Wilcoxon signed-rank test using scipy


code:
from csv import DictReader, DictWriter

with open('file1') as fil1, open('file2') as fil2, open('file3', 'wb') as fcompout:
    read1 = DictReader(fil1)
    read2 = DictReader(fil2)
    writenum = DictWriter(fcompout, fieldnames=read2.fieldnames)
    writenum.writeheader()

    for num, line in enumerate(read1):
        line['Length'] = len(line['Name']) # Length of Name
        line['Line Num'] = num+1           # Line Numbers
        writenum.writerow(line)            # Write line to new csv

rawDescription: CSV writer will not write first line in file (code contains: dictwriter,numbering lines, values equal to other csv, length of element, etc.)


code:
from datetime import timedelta

CELERYBEAT_SCHEDULE = {
    "runs-every-30-seconds": {
        "task": "tasks.add",
        "schedule": timedelta(seconds=30),
        "args": (16, 16)
    },
}

rawDescription: How to execute a command at exact time once a day in Django?

description: Execute a command at exact time once a day in Django


code: np.einsum('i,j->ji', x, y)

rawDescription: Multiplication of two arrays in numpy

description: Multiplication of two arrays in numpy


rawDescription: Sklearn.KMeans() : Get class centroid labels and reference to a dataset


code:
import urllib2
from base64 import urlsafe_b64encode
PROXY_USERNAME = 'user'
PROXY_PASSWORD = 'password'
req = urllib2.Request('http://www.blah.com')
req.set_proxy('localhost:8888', 'http')
proxy_auth = urlsafe_b64encode('%s:%s' % (PROXY_USERNAME, PROXY_PASSWORD))
req.add_header('Proxy-Authorization', 'Basic %s' % proxy_auth)
f = urllib2.urlopen(req)

rawDescription: What's the format for urllib2 request proxies?


rawDescription: matplotlib gui imshow coordinates

description: Matplotlib gui imshow coordinates


code:
nrows = 10000000
df = pd.concat([DataFrame(randn(int(nrows),34),columns=[ 'f%s' % i for i in range(34) ]),DataFrame(randint(0,10,size=int(nrows*19)).reshape(int(nrows),19),columns=[ 'i%s' % i for i in range(19) ])],axis=1)
df.iloc[1000:10000,0:20] = np.nan
df.info()

rawDescription: pandas: DataFrame.mean() very slow. How can I calculate means of columns faster?

description: Pandas: DataFrame.mean() very slow. How can I calculate means of columns faster


code:
def bigram_db():
    cursr.execute("SELECT * FROM trainedGrammar")
    return "".join([row[0] for row in cursr])

rawDescription: Store output of for loop into single variable


code:
data_dir = os.path.join(sys.prefix, "local/lib/python2.7/dist-package/my_module")
data_files   = [ ("my_module",  [os.path.join(data_dir, "data1"),
                                 os.path.join(data_dir, "data2")])]

rawDescription: setup.py not installing data files

description: Setup.py not installing data files


code:
for i in range(len(new), 4):
    new.append('')
newrow = row[0:4] + new + row[5:]
print('|'.join(newrow))

rawDescription: Splitting a delimited file and storing into new column


code:
Employee(name='Michael Scott', title='Regional Manager', number=3, salary=50000.0)
OrderedDict([('name', 'Michael Scott'), ('title', 'Regional Manager'), ('number', 3), ('salary', 50000.0)])

rawDescription: Python: When printing the contents of a class, I can't understand the order they're being printed in


code:
def img_array_to_single_val(image, color_codes):
    image = image.dot(numpy.array([65536, 256, 1], dtype='int32'))
    result = numpy.ndarray(shape=image.shape, dtype=int)
    result[:,:] = -1
    for rgb, idx in color_codes.items():
        rgb = rgb[0] * 65536 + rgb[1] * 256 + rgb[2]
        result[arr==rgb] = idx
    return result

rawDescription: Replacing RGB values in numpy array by integer is extremely slow


code:
import datetime as dt
import matplotlib.dates as mdates
from matplotlib import pyplot
from random import randint
from matplotlib.ticker import MaxNLocator

dates = ["2014-{month:0>2d}-{day:0>2d}".format(month=m, day=d) for m in [1,5] for d in range(1,10)]
dates = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
freqs = [randint(0,4) for _ in dates]

fig = pyplot.figure()

ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2, sharey=ax1)

ax1.plot_date(dates, freqs, "ro")
ax2.plot_date(dates, freqs, "ro")

#set the upper and lower bounds for the two adjacent plots
ax1.set_xlim(xmax=dt.datetime.strptime("2014-01-11", '%Y-%m-%d').date())
ax2.set_xlim(xmin=dt.datetime.strptime("2014-05-01", '%Y-%m-%d').date())

for ax in [ax1, ax2]:
  _ = ax.get_xticklabels() #For some reason, if i don't do this, then it only prints years for the tick labels. :/
  ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=6))

#Turn off the spines in the middle
ax1.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)

ax1.yaxis.tick_left()

ax2.get_yaxis().set_visible(False)

pyplot.subplots_adjust(wspace=0.1)

fig.autofmt_xdate()

pyplot.show()

rawDescription: How do i get the x axis to only show my data i want to plot? Instead of it including labels with no plots?

description: Get the x axis to only show my data i want to plot? Instead of it including labels with no plots


code: from functools import partial

rawDescription: Kivy - editing label when button clicked


code:
from pydoc import locate
locate('int')
t = locate('int')
t('1')

rawDescription: Lexical cast from string to type

description: Lexical cast from string to type


rawDescription: Subtract List B from List A but keeping the List A index


code: out = open(fname + ".out.csv", "w")

rawDescription: Beginner Python : How to save output in the same location and with a different name?


code:
batch = []
batch.append({'name':'James'})
batch.append({'name':'Julie'})
client.create_vertex(batch)

rawDescription: How to consolidate two Python classes containing methods with identical signatures?

description: Consolidate two Python classes containing methods with identical signatures


code:
import networkx as nx
G = nx.Graph([('A','B'),('C','D'),('B','C'),('D','E')])
path = nx.shortest_path(G, 'A', 'E')

rawDescription: Python Shortest path between 2 points

description: Python Shortest path between 2 points


code:
for i in range(0, 10000):
    print("\rOK", end='')

rawDescription: python print one line same space

description: Python print one line same space


code: indices = [i for i, elem in enumerate(word) if elem == x]

rawDescription: Replace list object based on indexes of another list (Python)


code:
from datetime import datetime

import numpy as np
import pandas as pd

df = pd.DataFrame([[1, '2007-01-01', [.2, .5, .3]],
                   [2, '2007-01-02', [.8, .5, .3]],
                   [3, '2008-01-14', [0.1, 0.2, 0.3]]],
                 columns=['doc_id', 'date', 'topic_dist'])

df.date = pd.to_datetime(df.date)

df = df.set_index('date')

df.topic_dist = df.topic_dist.apply(lambda x: np.array(x))

rawDescription: Summing items in an array -- in a DataFrame -- in a groupby


code:
while repeatchoice == True:
    code = getproductcode()
    product = checkfile(code)
    result,stocklevel = checkstocklevel(code)
    if result:
        quantity = quantityFunction(product)
        checkquantity = isquantityokay(quantity, stocklevel)
        quantity = int(quantity)
        update = updatestocklevel(quantity, stocklevel, code)
        cost = price(product)
        productcost = calculateproductcost(cost, quantity)
        rline = receiptline(product, quantity, productcost)
        addtoreceipt = append(rline)
        addtototal = appendprice(productcost)
    repeatchoice = repeat(username)

rawDescription: How To Skip Functions?

description: How To Skip Functions


code:
class class_or_instance_method(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, cls=None):
        if instance is None:
            return classmethod(self.func).__get__(None, cls)
        return self.func.__get__(instance, cls)

rawDescription: Python method available for both instantiated/uninstantiated class


rawDescription: Sort IP addresses with tuple python

description: Sort IP addresses with tuple python


code:
from itertools import product, islice

def max_sum_n_pow_lower_x(x, n):
    """ returns tuple of number of summand and maximal sum
        of form `n` + `n`**2 + `n`**3  not greater than `x` """
    i, c, s = 1, 0, 0
    while s < x:
       i *= n
       c += 1
       s += i
    return c-1, s-i

def get_nth_pow(iterable, n):
    l = list(iterable)
    repeat, start_from = max_sum_n_pow_lower_x(n, len(l))
    prod = itertools.product(l, repeat=repeat+1)
    return ''.join(list(islice(prod, n-start_from))[-1])

rawDescription: finding nth combination (incremental approach) of letters (list)

description: Finding nth combination (incremental approach) of letters (list)


code:
with open('textfile','w') as f:
    f.write('\n'.join(lines))

rawDescription: Reading lines in text files using python


code:
class Person():
    name = "temp"
    def __init__(self, aname):
        global asd
        print("A Person is created!")
        asd=aname
        self.test()

    def test(self):
        print(asd)
        print(self.name)

p1 = Person("Tim")

rawDescription: Multiple values for same variable when designing Objects (use of self in Python)


code:
import sys

from django.conf import settings
from django.conf.urls import url
from django.core.management import execute_from_command_line
from django.shortcuts import render
from django.views.generic import View

import stripe

settings.configure(
    DEBUG=True,
    ROOT_URLCONF=sys.modules[__name__],
    TEMPLATE_DIRS=['.'],
    STRIPE_SECRET_KEY='sk_test_BQokikJOvBiI2HlWgH4olfQ2',
    STRIPE_PUBLISHABLE_KEY='pk_test_6pRNASCoBOKtIshFeQd4XMUh'
)

stripe.api_key = settings.STRIPE_SECRET_KEY

class StripeView(View):

    @staticmethod
    def get(request):
        return render(request, 'index.html',
                      {
                          'stripe_pub_key': settings.STRIPE_PUBLISHABLE_KEY
                      })

    @staticmethod
    def post(request):
        charge = stripe.Charge.create(
            amount=2000,
            currency="usd",
            source=request.POST['stripeToken'],
            description="Charge for {}".format(request.POST['stripeEmail'])
        )
        return render(request, 'charge.html',
                      {
                          'charge_id': charge.id,
                          'extra_param': request.POST['extraParam2']
                      })

urlpatterns = [
    url(r'^stripe/', StripeView.as_view()),
]

if __name__ == "__main__":
    execute_from_command_line(sys.argv)

rawDescription: Adding extra parameters when sending request with django and stripe


code:
class LocationListAPIView(generics.ListAPIView):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer

class LocationDetailAPIView(generics.RetrieveAPIView):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer

rawDescription: How to get a response of multiple objects using rest_framework and Django

description: Get a response of multiple objects using rest_framework and Django


code: mature = age = (age > 20.0).astype(float)

rawDescription: Assigning numpy array based on condition


rawDescription: Combining multiple timeseries data to one 2d numpy array


code: pip -V

rawDescription: Install python packages on OpenShift

description: Install python packages on OpenShift


code:
import collections
result=collections.defaultdict(list)
with open('data','r') as f:
    for line in f:
        line=line.split()
        key=line[0]
        value=float(line[1])
        result[key].append(value)
for key,values in result.iteritems():
    print(key,sum(values))

rawDescription: Column filtering on trace file

description: Column filtering on trace file


rawDescription: Remove outer list from list of list in python


rawDescription: Using pytz to convert from a known timezone to local


code: df / (df.sum() - df)

rawDescription: In Pandas, is there a way to divide a cell by all other cells in a column?


rawDescription: Splitting a string and adding the digits inside of the string


code:
params = ",".join(["?"+str(i+2) for i in range(len(my_list))])
statement = """SELECT * FROM MyTable
 WHERE date > ?
   AND (item1 IN (%s) OR item2 IN (%s))""" % (params, params)
bindings = [my_date] + my_list
cursor.execute(statement, bindings)

rawDescription: SQL either of two values in a list

description: SQL either of two values in a list


code:
import itertools

l1 = [1, 2, 3, 4]

l2 = [5, 6, 7, 8]

for i in itertools.chain(l1, l2):
    print(i, end = " ")

rawDescription: Iterating over two lists one after one

description: Iterating over two lists one after one


rawDescription: find element in list 1 that is in list 2

description: Find element in list 1 that is in list 2


rawDescription: Python:Can lambda works with *args as it's parameter?


code:
idx = df.groupby(['Date'])['Volume'].transform(min) == df['Volume']
df[idx]

rawDescription: How to subset a Pandas dataframe applying a function by date?

description: Subset a Pandas dataframe applying a function by date


code:
#!/usr/bin/env python
from scipy.stats import bernoulli,poisson,norm,expon

rawDescription: How can I generate random numbers in Python?

description: Generate random numbers in Python


code: map(assignId, lst)

rawDescription: Spark: Using iterator lambda function in RDD map()


code:
import numpy as np

a = np.arange(12).reshape(4,3)
a_with_index = np.array([idx+(val,) for idx, val in np.ndenumerate(a)])
np.savetxt('/tmp/out', a_with_index, fmt='%d')

rawDescription: how to write a matrix to a file in python with this format?

description: Write a matrix to a file in python with this format


code: [(i + 40) * i for i in xrange(60)]

rawDescription: What is correct python syntax for this kind of list comprehension?


code:
import matplotlib.pyplot as plt

g_title = "Big fat redacted title (Income Distribution)"
g_data_list = [['FIN.RES 47% - $41,888.08', 47],
               ['VSC 40% - $36,019.00', 40],
               ['AFTERMARKET 6% - $5,570.00', 6],
               ['GAP 7% - $6,528.00', 7]]

labels = []
sizes = []
for entry in g_data_list:
    labels.append(entry[0])
    sizes.append(entry[1])

patches, texts = plt.pie(sizes, startangle=90)
plt.legend(patches, labels, loc="best", fontsize=6)
plt.axis('equal')
plt.title(g_title, fontsize=14)
plt.savefig('test.png', dpi=300)

rawDescription: Move plot and legend in matplotlib

description: Move plot and legend in matplotlib


code:
def add_vote(self,choice):
    attname = 'votes_{0}'.format(choice) # get the attribute name
    value = getattr(self, attname) # get the value
    setattr(self, attname, value+1) # set the value

rawDescription: Django: How to get/set model field value if it is put into any data structure?


code: elem = etree.fromstring(xml_str, parser=parser)

rawDescription: remove everything between 2 tags that span branches of an xml tree

description: Remove everything between 2 tags that span branches of an xml tree


code:
valid_descriptions = [m.polymorphic_identity for m in
                      Campaign.__mapper__.polymorphic_iterator()]
rows =  session.query(Campaign)\
                .filter(Campaign.description.in_(valid_descriptions))\
                .all()

rawDescription: Can SQLAlchemy handle unknown polymorphic identities?


code: print(df[(mask)])

rawDescription: Filter DataFrame rows that are lists

description: Filter DataFrame rows that are lists


rawDescription: Trying to make a list of dates into date.year, date.month, date.day for comparrison?


code:
oldList = [1, 2, 3, 4]
newList = [x for x in oldList for _ in range(2)]
newList

rawDescription: Python: duplicating each element in a list


code: [{'fruit': f, 'colour': c} for f, c in zip(fruits, colour)]

rawDescription: Convert list to list of dictionaries in python


code:
cur.execute('select * from foo; insert into foo values (123);')
cur.nextset()
conn.commit()
cur.execute('select * from foo')
cur.fetchall()

rawDescription: executing django query in same statement

description: Executing django query in same statement


rawDescription: Numpy drawing from urn

description: Numpy drawing from urn


code: "they're bill's friends from the UK".title()

rawDescription: CamelCase every string, any standard library?


code:
for d in os.listdir(os.getcwd()):
    if not os.path.isdir(d) or not d.startswith(minus_seven):
        continue
    # Do what you need to with 'd' here.

rawDescription: How to move into multiple directories Python

description: Move into multiple directories Python


code: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]

rawDescription: Sum lists with different lengths

description: Sum lists with different lengths


code:
def complete_subset(real_list, expected_list):
    real_set_list = [set(d.items()) for d in real_list]
    expected_set_list = [set(d.items()) for d in expected_list]

    while len(real_set_list):
        real_len = len(real_set_list)
        i = 0
        for real_set in real_set_list:
            for expected_set in expected_set_list:
                if not len(expected_set - real_set):
                    real_set_list.remove(real_set)
                    expected_set_list.remove(expected_set)
            i = i + 1
        if i == real_len:
            break

    return (not len(real_set_list)) and (not len(expected_set_list))

rawDescription: comparing dicts with additional values

description: Comparing dicts with additional values


code:
print(A.array)
# [1]

print(B.array)
# [1, 2, 3]

print(C.array)
# [1, 2, 3, 4]

rawDescription: Joining fields values

description: Joining fields values


code: csv_x = csv.reader(x)

rawDescription: python nested for loop only executes once

description: Python nested for loop only executes once


rawDescription: Merge Columns and Remove Duplication

description: Merge Columns and Remove Duplication


rawDescription: pandas.rolling_sum weird inaccuracy

description: Pandas.rolling_sum weird inaccuracy


rawDescription: Distinguishing 2 lines in a file read

description: Distinguishing 2 lines in a file read


code:
class Dicer():
    def __init__(self, name, role, statTuple):
        self.name = name
        self.level = 1
        self.xp = 0
        self.health = statTuple[0]
        self.attack = statTuple[1]
        self.defense = statTuple[2]

    def print_stats(self):
        print("Name", self.name)
        print("Level", self.level)
        print("XP", self.xp)
        print("Health", self.health)
        print("Attack", self.attack)
        print("Defense", self.defense)

roles = {
    #health, attack defense
    "mage" : (100, 40, 10),
    "warrior" : (100, 30, 20),
    "gunner" : (100, 20, 30),
    "archer" : (100, 10, 40)
}
name = input("What is your name ")
dicer_role_choice = None
while dicer_role_choice not in roles.keys():
    print("Please select a dicer:")

    #prints each role on a new line, showing all the possible choices
    print("\n".join(roles.keys()))
    dicer_role_choice = input()

mainDicer = Dicer(name, dicer_role_choice, roles[dicer_role_choice])
mainDicer.print_stats()

rawDescription: How Do I Fix My Code So It Can print() Out The Results I Want?


rawDescription: Can't plot value counts for pie chart

description: Can't plot value counts for pie chart


rawDescription: how to create a list of identical tuples in python

description: Create a list of identical tuples in python


code:
class Group(BaseModel):
    __tablename__ = 'group'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    paths = db.Column(MutableList.as_mutable(types.PickleType))

rawDescription: PickleType with Mutable Tracking in SqlAlchemy


code:
indices = range(len(pop))
random.shuffle(indices)

rawDescription: Random division of list to two complementary sublists


rawDescription: Python list looping to output averages - too many records returned


code:
class Player():
    def print_cards(self):
        print('I am in Player\'s class.')

class Dealer(Player):
    def print_cards(self):
        print('I am in Dealer\'s class.')
    def print_player(self):
        super().print_cards()

p = Player()
d = Dealer()

p.print_cards()
d.print_cards()
d.print_player()

rawDescription: Use class A method in class B, where B overwrites this method


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = Axes3D(fig)

rad = np.linspace(0, 5, 100)
azm = np.linspace(0, 2 * np.pi, 100)
r, th = np.meshgrid(rad, azm)
z = (r ** 2.0) / 4.0

plt.subplot(projection="polar")

plt.pcolormesh(th, r, z)
#plt.pcolormesh(th, z, r)

plt.plot(azm, r, color='k', ls='none')
plt.grid()

plt.show()

rawDescription: Polar heatmaps in python

description: Polar heatmaps in python


code: rows = [row for row in filereader if any([word in row[1] for word in filterSubstrings])]

rawDescription: Python: simple csv substring filter

description: Python: simple csv substring filter


code:
import sys

def application(environ, start_response):
    status = '200 OK'

    try:
        hr = sys.flags.hash_randomization
        if hr == 0:
            output = 'Hash randomization disabled'
        elif hr == 1:
            output = 'Hash randomization enabled'
        else:
            output = 'Unknown hash randomization: ' + str(hr)
    except AttributeError:
        output = 'Hash randomization not supported'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

rawDescription: Django with mod_wsgi how to set PYTHONHASHSEED env variable?


code:
def f(dfg):
    #dfg is DataFrame
    print (dfg)
    #name of group
    print (dfg.name)
    #select value from select_number
    print (select_number.loc[dfg.name, 'number_to_select'])
    #return top rows per groups
    print (dfg.nlargest(select_number.loc[dfg.name, 'number_to_select'], 'price'))
    return (dfg.nlargest(select_number.loc[dfg.name, 'number_to_select'], 'price'))

print (data.groupby('currency').apply(f))

rawDescription: Selecting top n elements from each group in pandas groupby


code:
df['time2'] = df.apply(lambda row: (row['time']
                                 + datetime.timedelta(0, 1) # 1s
                                     * row['rep']
                                     / row['count']),
                 axis=1)

rawDescription: Timeseries Resampling

description: Timeseries Resampling


code:
arg1.help
arg1.type
arg1.dest
vars(arg1)

rawDescription: Extract values from parse.add_argument in Argparse - python


code:
import matplotlib
childrenLS=ax.get_children()
barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)

rawDescription: Setting Different Bar color in matplotlib Python


code: python -i /path/to/script.py

rawDescription: How do you return to the prompt with access to all objects after a script is finished?

description: Return to the prompt with access to all objects after a script is finished


code:
def fun_fun(some_int): # function that takes hopefully an int/float
    try: # not sure if we got the correct value
        return_value = some_int + 4 % 4 # mathz
        return return_value # return mathz
    except TypeError: # if we didn't get an int/float we'd get this
        return None # So you can return None or do what you like

rawDescription: Checking if function was called with right arguments


code:
from collections import defaultdict
def load(anIterable):
    data = defaultdict(Chrom)
    for line in anIterable:
        f = line.rstrip().split(',')
        if len(f)<4:
            continue
        aGene = Gene(f)
        data[aGene.chr].add(aGene)
    return data

rawDescription: cython: reducing the size of a class, reduce memory use, improve speed

description: Cython: reducing the size of a class, reduce memory use, improve speed


code:
class SubmitField(BooleanField):
    """
    Represents an ``<input type="submit">``.  This allows checking if a given
    submit button has been pressed.
    """
    widget = widgets.SubmitInput()

rawDescription: Does SubmitField need a validator?

description: Does SubmitField need a validator


code:
found = False
for x in some_list:
    if x.value == value:
        print('Found')
        found = True

if not found:
    print("Not Found.")

rawDescription: How can you execute a command at the end of a for loop?

description: Execute a command at the end of a for loop


code: P = C/(1 - PM - MktPct/100 - PayPct/100)

rawDescription: Calculate product price based on multiple percentage factors


rawDescription: JavaScript function similar to Python range()


code:
l = list("abcdefghijklmnopqrstuvwxyz")
l

rawDescription: How do I interpret this Python Code?

description: Interpret this Python Code


code: (itr.repeat(1,5) for _ in range(3))

rawDescription: Generating iterables of iterables with python itertools. (using the repeat function)


code:
c = 'ع'
id = unicodedata.name(c).lower()
if 'arabic letter' in id:
    print("{}: {}".format(c, id[14:].lower()))

rawDescription: How to map a arabic character to english string using python

description: Map a arabic character to english string using python


code: environ = flask.request.environ.copy()

rawDescription: Is it possible to clone a request to use it later?


code:
from subprocess import Popen, PIPE

p1 = Popen(["sudo", "-S", "convert", "imgIn.jpg", "-posterize", "2", "imgOut.jp"], stdin=PIPE, stdout=PIPE)

p1.stdin.write("password\n")
out, err = p1.communicate()

rawDescription: ImageMagick code in Python script

description: ImageMagick code in Python script


code: sorted([True,False,False])

rawDescription: Python list sorting dependant on if items are in another list


code:
import itertools as it
import operator as op
result = reduce(op.add, it.imap(SomeClass.calculate_something, it.product(element_list, xrange(10000))))

rawDescription: Container list in Python: standard list vs numpy array


code: data = zip(*[iter(df['amount'])]*24)

rawDescription: How to generate daily lists from pandas time series

description: Generate daily lists from pandas time series


code: self.respond("\n".join("Ref:{} Amount:{}".format(ref, amt) for ref, amt in result))

rawDescription: Python: Formatting lists of lists

description: Python: Formatting lists of lists


rawDescription: join two pandas dataframe using a specific column

description: Join two pandas dataframe using a specific column


rawDescription: Importing a text file and manipulating it to create and new file


code:
class Color:
    ...

rawDescription: python list all imported modules imported via *, the pythonic way

description: Python list all imported modules imported via *, the pythonic way


rawDescription: Pandas groubpy index count nonblanks

description: Pandas groubpy index count nonblanks


code:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
from .cms_menus import GalleryMenu

class GalleryApp(CMSApp):
    name = _('Gallery')
    urls = ['app.apps.gallery.urls', ]
    app_name = 'gallery'
    menus = [GalleryMenu]

apphook_pool.register(GalleryApp)

rawDescription: Django-CMS apphooks menu and reverse

description: Django-CMS apphooks menu and reverse


code:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

# Find the max length of the word in each row
lens = [max(len(col) for col in row) for row in tableData]

# build a format string with an entry for each column
rowfmt = '{:>{}} ' * len(tableData)

# zip(*list) transposes a list...rows become columns
for row in zip(*tableData):
    # Pass the values and column widths dynamically.
    # The zip pairs up each datum with its column width, but in tuples.
    # For example, [data1,data2],[width1,width2] -> [(data1,width1),(data2,width2)]
    # itertools.chain flattens the list of tuples.
    # For example, above becomes [data1,width1,data2,width2]
    print(rowfmt.format(*itertools.chain(*zip(row,lens))))

rawDescription: nested list displayed in a column

description: Nested list displayed in a column


code:
def custom_join(row, *joins):
    return [''.join(row[i] for i in indices) for indices in joins]

rawDescription: Merge Items in List from different areas Python


code:
import os

os.chdir(path) # will change your cwd to path if you have a specific one in mind

rawDescription: Creating an HTML page from python

description: Creating an HTML page from python


code:
import numpy as np
x = np.arange(10)
x2 = x[x<5]

rawDescription: getting all rows where complex condition holds in scipy/numpy

description: Getting all rows where complex condition holds in scipy/numpy


code:
from scrapy.spiders import CrawlSpider
from scrapy.linkextractors import LinkExtractor
from scrapy import Item, Field
from scrapy.spiders import Rule

class LsbuItem(Item):
    title = Field()
    url = Field()

class LsbuSpider(CrawlSpider):
    name = "lsbu6"
    allowed_domains = ["lsbu.ac.uk"]

    start_urls = [
        "http://www.lsbu.ac.uk"
    ]

    rules = [
        Rule(LinkExtractor(allow=['lsbu.ac.uk/business-and-partners/.+']), callback='parse_item', follow=True),
    ]

    def parse_item(self, response):
        scraped_bit = LsbuItem()
        scraped_bit['url'] = response.url
        yield scraped_bit

rawDescription: Stop Scrapy crawling the same URLs

description: Stop Scrapy crawling the same URLs


rawDescription: Class (not instance) constructor

description: Class (not instance) constructor


code:
d1 = dict(a=1, b=2, c=3, d=4)
d2 = dict(a=1, b=2)
set(d2.items()).issubset( set(d1.items()) )

rawDescription: How to assert a dict contains another dict without assertDictContainsSubset in python?

description: Assert a dict contains another dict without assertDictContainsSubset in python


code:
np.searchsorted(a, b, side='right') - 1
a[np.searchsorted(a, b, side='right') - 1]

rawDescription: Using np.searchsorted to find the most recent timestamp


code: numpy.histogram(a, bins=10, range=None, normed=False, weights=None, new=None)

rawDescription: assigning points to bins

description: Assigning points to bins


code:
import os
import subprocess

for top, dirs, files in os.walk('/my/pdf/folder'):
    for filename in files:
        if filename.endswith('.pdf'):
            abspath = os.path.join(top, filename)
            subprocess.call('lowriter --invisible --convert-to doc "{}"'
                            .format(abspath), shell=True)

rawDescription: Convert PDF to DOC (Python/Bash)

description: Convert PDF to DOC (Python/Bash)


code:
with db:
    cursor.execute(sql, (userid,))

db.close()

rawDescription: Getting value from MySQL and loop over it with if


code:
from pyramid.view import view_config

from example_app.settings.redis import SOME_SETTING_STORED_IN_REDIS

def includeme(config):
    config.add_route('home', '/')

@view_config(
    route_name='home',
    renderer='home.html',
    permission='authenticated'
)
def home_view(request):

    return {
        "some_setting": SOME_SETTING_STORED_IN_REDIS,
    }

rawDescription: Sharing objects between view and application with Pyramid


code:
def run ( self ):
    print ( "Register Timer-Thread: " + self.sThreadName )
    while True:
        hTimer = threading.Timer ( self.iThreadInterval, print_time( self.sThreadName ) )
        hTimer . start ( )

rawDescription: Why I should use threading.Timer instead of a Loop + Sleep?


code:
def is_solvable(index, board):
    if index == len(board) - 1:
        return True
    elif board[index] is None:
        return False
    elif index < 0 or index >= len(board):
        # out of bounds
        return False
    else:
        value = board[index]
        board[index] = None

        left = is_solvable(index - value, board, visited)
        right = is_solvable(index + value, board, visited)
        return left or right

rawDescription: python recursion jumping to last cell

description: Python recursion jumping to last cell


rawDescription: In python, how can you retrieve a key from a dictionary?


code:
class A:
   class_property = 10

   def __init__(self):
      self.object_property = 20

rawDescription: difference between an object property and type property

description: Difference between an object property and type property


code:
f = logger(func)
f(2)
f(3)
f(4)

rawDescription: Using decorators at functions call instead of function definitions


code:
# -*- mode: python -*-
a = Analysis(['myscript.py'],
             pathex=['C:\\SourceCode'],
             hiddenimports=['scipy.special._ufuncs_cxx',
                            'scipy.linalg.cython_blas',
                            'scipy.linalg.cython_lapack',
                            'scipy.integrate',
                            'scipy.integrate.quadrature',
                            'scipy.integrate.odepack',
                            'scipy.integrate._odepack',
                            'scipy.integrate.quadpack',
                            'scipy.integrate._quadpack',
                            'scipy.integrate._ode',
                            'scipy.integrate.vode',
                            'scipy.integrate._dop',
                            'scipy.integrate.lsoda'],
             hookspath=None,
             runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='myscript.exe',
          debug=False,
          strip=None,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=None,
               upx=True,
               name='myscript')

rawDescription: How to use pyinstaller with hidden imports for scipy.optimize leastsq

description: Use pyinstaller with hidden imports for scipy.optimize leastsq


code:
@api.model
def get_age_comp(self):
    for student in self.search([('gender','=','m'), ('birth_date', '<=', date.today() - relativedelta(years=20)), ('status', '=', 'underage')]):
        student.status = 'getCard'
        # do other things here

rawDescription: Automated Action Birthday =19

description: Automated Action Birthday =19


code:
def is_numeric(s):

    for char in s:
        if not char.isdigit() and char not in [" ", ".", ","]:
            return False

    return True

rawDescription: Creating a list from a string that contains numbers separated by commas; Python 3


rawDescription: Import single csv file with one data field going to separate table


code:
import numpy as np

np.savez('myMD.dat',
         xpos1=xpos1, ypos1=ypos1, zpos1=zpos1,
         xvel1=xvel1, yvel1=yvel1, zvel1=zvel1,
         xacc1=xacc1, yacc1=yacc1, zacc1=zacc1,
         xforc=xforc, yforc=yforc, zforc=zforc,
         potn=potn)

rawDescription: save simulation data in python

description: Save simulation data in python


code:
engine = sqlalchemy.create_engine('mysql://scott:tiger@localhost/foo')
df.to_sql('testdata', engine, if_exists='replace')

rawDescription: pandas to_sql truncates my data

description: Pandas to_sql truncates my data


code:
def window_to_bitmap(window):
    width, height = window.GetClientSize()
    bitmap = wx.EmptyBitmap(width, height)
    wdc = wx.ClientDC(window)
    mdc = wx.MemoryDC(bitmap)
    mdc.Blit(0, 0, width, height, wdc, 0, 0)
    return bitmap

rawDescription: get a widgets dc in wxpython

description: Get a widgets dc in wxpython


code:
return render(request, 'contact.html', {
    'form': form,
})

rawDescription: Django - A bit lost with forms

description: Django - A bit lost with forms


code:
class AdvForm(ModelForm):
 class Meta:
  model = Adv
  fields = ['title','description']

class ImageFileForm(ModelForm):
 class Meta:
  model = ImageFile
  fields = ['file','adv']

rawDescription: Django. Inline formset with existing instances of model in template


code:
class AlbumForm(forms.Form):
     artist = forms.CharField(max_length=150)
     name = forms.CharField(max_length=150)

class TrackForm(forms.Form):
     track_no = forms.IntegerField()
     name = forms.CharField(max_length=150)

# In view

from django.forms.formsets import formset_factory

TrackFormSet = formset_factory(TrackForm)
if request.method == 'POST':
    track_formset = TrackFormSet(request.POST)
    album_form = AlbumForm(request.POST)
    if track_formset.is_valid() and album_form.is_valid():
        save_album(album_form, track_formset)
else:
    track_formset = TrackFormSet()
    album_form = AlbumForm()

rawDescription: Validate Django forms for user specified dynamically generated fields


code:
ax = textranges_freq.plot(x='buckets',y='smstext',kind='bar',title='Avg text Frequency by range', width=0.5, legend=False)
ax.set_xlabel('buckets')
ax.set_ylabel('Avg text messages')
plt.show()

rawDescription: How to write a function for barchart in python?

description: Write a function for barchart in python


code:
def __rmul__(self, other):
    return self.__mul__(other)

rawDescription: Duplicating Python int * numpy.array behavior


rawDescription: External python application is not running


rawDescription: Python: Initialize a datetime object with seconds since epoch


code: l.sort(key=lambda d: 'age' in d)

rawDescription: How to reorder a list in Python based on its content

description: Reorder a list in Python based on its content


code:
ymax = np.zeros(13)
month=1
day=0
ymax[month] = 0
for j in range(0, len(xmax)):
    if xmax[j]>ymax[month]:
        ymax[month] += xmax[j]
    day = day+1
    if (day>30):
        month = month+1
        day = 0
        ymax[month] = 0
# then divide it by number of days
ymax = ymax / 30.0

rawDescription: Monthly mean from daily maxima data text file


code:
class Data(LogFile):
    def __init__(self,log_file):
        super().__init__(log_file)
        self._data = ''

class DataNET(Data):
    def __init__(self, logfile):
        super().__init__(logfile)
        self._data = {}

rawDescription: Inheritance in Python, init method overrriding


code:
import itertools

result = []
for pair in itertools.combinations(a, 2):
    result.append(xor(pair[0], pair[1]))

rawDescription: Nested for loop in python

description: Nested for loop in python


code:
longest_substr(['slide', 'glidb', 'flidt', 'cridz', 'bidr'])
longest_substr(['slide', 'glidb', 'flidt', 'cridz', 'bidr', 'balh', 'tejka', 'djakljskdl', 'blah', 'blah', 'blah'])

rawDescription: Longest repeated substring

description: Longest repeated substring


code: inner_list = a.pop(1)

rawDescription: Python - Remove list(s) from list of lists (Similar functionality to .pop() )


code:
import pandas as pd
import numpy as np

df = pd.DataFrame([['A','B','C','D'],[1,2,'C']])

ndf = df[pd.notnull(df[3])][[0,1,3]]
ndf.columns = [0,1,2]
df = df.append(ndf, ignore_index=True)

rawDescription: Create new row if column value exists

description: Create new row if column value exists


code:
data = dict()
data[dict_key] = value

rawDescription: python dictionary keys

description: Python dictionary keys


rawDescription: How to find collocations in text, python

description: Find collocations in text, python


code:
choice = input()
if choice in ('yes', 'Yes'):
    dev_debug = 1
    break

rawDescription: Text Game - Convert input text to lowercase - Python 3.0


code:
def gps(a):
    d = defaultdict(lambda: {"mn":float("inf"),"mx":float("-inf")})
    for sub in a:
        key = sub[-1]
        if d[key]["mn"] > sub[0]:
            d[key]["mn"] = sub[0]
        elif d[key]["mx"] < sub[1]:
            d[key]["mx"]  = sub[1]
    return d

for k,v in gps(a).items():
    print([v["mn"], v["mx"], k])

rawDescription: Mapping diagonal elements recursively and check for condition, Python


code:
cells = ['O'] * NUM_ROWS * NUM_COLS
cells[:NUM_MINES] = ['X'] * NUM_MINES
random.shuffle(cells)
BOARD = [cells[i::NUM_ROWS] for i in range(NUM_ROWS)]

rawDescription: Python: changing element of a list at a random index


code:
import re

def parse_line(line, note):
    fret_pattern = re.compile(r'\d+')
    for match in fret_pattern.finditer(line):
        yield (match.start(), ''.join((note, match.group(0))))

rawDescription: guitar tab to uke tab program help

description: Guitar tab to uke tab program help


code:
if name[0] in "SH":
    print(name)

rawDescription: Trying to read all lines in a file and pick out the ones that begin with 'H' or 'S'


rawDescription: How to call a system command with specified time limit in Python?

description: Call a system command with specified time limit in Python


rawDescription: removing pairs of elements from numpy arrays that are NaN (or another value) in Python

description: Removing pairs of elements from numpy arrays that are NaN (or another value) in Python


code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

pi = np.pi

def square_function(N, square_width):
    """Generate a square signal.

    Args:
        N (int): Total number of points in the signal.
        square_width (int): Number of "high" points.

    Returns (ndarray):
        A square signal which looks like this:

              |____________________
              |<-- square_width -->
              |                    ______________
              |
              |^                   ^            ^
        index |0             square_width      N-1

        In other words, the output has [0:N]=1 and [N:]=0.
    """
    signal = np.zeros(N)
    signal[0:square_width] = 1
    return signal

def check_num_coefficients_ok(N, num_coefficients):
    """Make sure we're not trying to add more coefficients than we have."""
    limit = None
    if N % 2 == 0 and num_coefficients > N // 2:
        limit = N/2
    elif N % 2 == 1 and num_coefficients > (N - 1)/2:
        limit = (N - 1)/2
    if limit is not None:
        raise ValueError(
            "num_coefficients is {} but should not be larger than {}".format(
                num_coefficients, limit))

def test(N, square_width, num_coefficients):
    """Test partial (i.e. filtered) Fourier reconstruction of a square signal.

    Args:
        N (int): Number of time (and frequency) points. We support both even
            and odd N.
        square_width (int): Number of "high" points in the time domain signal.
            This number must be less than or equal to N.
        num_coefficients (int): Number of frequencies, in addition to the dc
            term, to use in Fourier reconstruction. This is the number of
            positive frequencies _and_ the number of negative frequencies.
            Therefore, if N is odd, this number cannot be larger than
            (N - 1)/2, and if N is even this number cannot be larger than
            N/2.
    """
    if square_width > N:
        raise ValueError("square_width cannot be larger than N")
    check_num_coefficients_ok(N, num_coefficients)

    time_axis = np.linspace(0, N-1, N)

    signal = square_function(N, square_width)
    ft = np.fft.fft(signal)

    reconstructed_signal = np.zeros(N)
    reconstructed_signal += ft[0] * np.ones(N)
    # Adding the dc term explicitly makes the looping easier in the next step.

    for k in range(num_coefficients):
        k += 1  # Bump by one since we already took care of the dc term.
        if k == N-k:
            reconstructed_signal += ft[k] * np.exp(
                1.0j*2 * pi * (k) * time_axis / N)
        # This catches the case where N is even and ensures we don't double-
        # count the frequency k=N/2.

        else:
            reconstructed_signal += ft[k] * np.exp(
                1.0j*2 * pi * (k) * time_axis / N)
            reconstructed_signal += ft[N-k] * np.exp(
                1.0j*2 * pi * (N-k) * time_axis / N)
        # In this case we're just adding a frequency component and it's
        # "partner" at minus the frequency

    reconstructed_signal = reconstructed_signal / N
    # Normalize by the number of points in the signal. numpy's discete Fourier
    # transform convention puts the (1/N) normalization factor in the inverse
    # transform, so we have to do it here.

    plt.plot(time_axis, signal,
             'b.', markersize=20,
             label='original')
    plt.plot(time_axis, reconstructed_signal.real,
             'r-', linewidth=3,
             label='reconstructed')
    # The imaginary part is zero anyway. We take the real part to
    # avoid matplotlib warnings.

    plt.grid()
    plt.legend(loc='upper right')

rawDescription: Manually inverting FFT using Numpy

description: Manually inverting FFT using Numpy


code:
value = ws.cell_value(6, cnum)
if value:
    wsHeaders[str(value)] = (cnum, ws.ncols)

rawDescription: Why is win32com so much slower than xlrd?


code:
lis = range(10)
lis[::-1]
reversed(lis)

rawDescription: Why is reversing a list with slicing slower than reverse iterator


code:
import pylab as plt
import numpy as np

Z = np.random.random((500,500))   # Test data
plt.imshow(Z, cmap='gray', interpolation='nearest')
plt.show()

rawDescription: 100x100 image with random pixel colour

description: 100x100 image with random pixel colour


code:
input = raw_input("Please enter your words separated by commas: ")
inputList = input.split(',')              # creates a list from comma delimeters
uniqueList = set(inputList)               # removes duplicates
sortedList = sorted(uniqueList)           # converts to ints and sorts

rawDescription: How do I sort, get rid of numbers and organize?

description: Sort, get rid of numbers and organize


code:
for row in db_session.query(Data).yield_per(10):
    do_something_with_data(row)

rawDescription: Geting results from database one by one

description: Geting results from database one by one


code: map(float, s.split())

rawDescription: how can I have commas instead of space in a given set of number

description: Have commas instead of space in a given set of number


code:
def unmask(num, width, offset):
     return (num >> offset) & (2**width - 1)

unmask(time, 6, 0)
Out[77]: 31

unmask(time, 6, 6)
Out[78]: 42

#etc

rawDescription: Converting binary timestamp to string

description: Converting binary timestamp to string


code:
query = models.Post.select().where(
    (models.Post.language ** language) |  # note the "pipe" instead of "&"
    (models.Post.category ** category))

rawDescription: Routes filtering by Language and/or category


code: new_filter.fields += filters['fields']

rawDescription: python method variables and Objects created in method

description: Python method variables and Objects created in method


code:
obj = myobject()
i = 7
date7 = getattr(obj, 'date%d' % i) # same as obj.date7

rawDescription: How to dynamically compose and access class attributes in Python?

description: Dynamically compose and access class attributes in Python


code:
from scrapy.exceptions import DropItem

class DropIfEmptyFieldPipeline(object):

    def process_item(self, item, spider):

        # to test if only "job_id" is empty,
        # change to:
        # if not(item["job_id"]):
        if not(all(item.values())):
            raise DropItem()
        else:
            return item

rawDescription: remove scraped data with an empty value

description: Remove scraped data with an empty value


code:
df = pd.DataFrame(np.random.random((5,4)), index=pd.Series(range(1,6), name="week"), columns=["City{}".format(i) for i in range(1,5)])
df
df.max() - df.min()
(df.max() - df.min()).idxmax()
df[(df.max() - df.min()).idxmax()]

rawDescription: Pandas: Find the maximum range in all the columns of dataframe


code:
def fx(z, y=999):
    width = len('%0d' % y)
    return ["0%*d" % (width, x) for x in range(y) if str(z) in str(x)]

rawDescription: How to pad leading zero (in a function) dynamically?

description: Pad leading zero (in a function) dynamically


rawDescription: python split strings of a text file

description: Python split strings of a text file


code: overlapped = sorted(overlapped) #this gives a list

rawDescription: Checking two time intervals are overlapping or not


code: zip(*np.where(M == N.max()))

rawDescription: Python find list of surrounding neighbours of a node in 2D array


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

rawDescription: Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?


code:
def collapse_nodes(tree, thresh=3):
    for n in tree:
        if n.dodelete:
            continue
        sub_tree = tree.get_by_path (n.id)
        sub_tree_stack = []
        for child in sub_tree.children:
           if child.val is not None and thresh > child.val:
               sub_tree_stack.append(child)
               tree.get_by_path(child.id).dodelete = True
           if sub_tree_stack:
              sub_tree.add_child(Node(",".join([subnode.name for subnode in sub_tree_stack]),
                                 val = sum([subnode.val for subnode in sub_tree_stack]),
                                 id= sorted([subnode.id for subnode in sub_tree_stack])[0]))
    return tree

rawDescription: clustering based on thresholds

description: Clustering based on thresholds


code:
a.shape
#(2,3,4)

np.all(a.sum(2) == a.sum(-1))
#True
np.all(a.sum(0) == a.sum(-3))
#True

rawDescription: Naming dimensions in python?

description: Naming dimensions in python


rawDescription: Numpy argwhere inequality conditions

description: Numpy argwhere inequality conditions


code:
def merge_dicts(a, *dict_args):
    d = {}
    for dictionary in reversed(dict_args):
        d.update(dictionary)
    d.update(a)
    return d

rawDescription: Pythonic way to get the union of dictionaries


code:
def make_counter(n):
    nw = [n]
    def inc():
       nw[0] = nw[0] + 1
       return nw[0]
    return inc

rawDescription: lambda in python

description: Lambda in python


code:
read
vote
like

rawDescription: Stemming of words using python

description: Stemming of words using python


code:
df1
df2

rawDescription: Determine if one range is within another


rawDescription: Fill zero values of 1d numpy array with last non-zero values


rawDescription: Modify a member variable outside the class object and have changes in the class object


code:
second_set = set(second_list)
third_list = [value for value in first_list if value[:8] in second_set]

rawDescription: Efficient way to loop on comparing string list element to a string list sub-element


code:
{
    'macros': [
        {
            'args':
            {
                'bar': None,
                'x': 'y'
            },
             'function': 'foo_func',
             'iterations': 3,
             'name': 'foo'
        },
        {
            'args':
            {
                'bar': None,
                'x': 'y'
            },
             'function': 'bar_func',
             'iterations': 1,
             'name': 'bar'
        }
    ]
}

rawDescription: Python - how to avoid exec for batching?

description: Python - how to avoid exec for batching


rawDescription: Python: modify global var from a function argument


rawDescription: python button does not work when image is added

description: Python button does not work when image is added


code:
def add_nested(d, keys, value):
    for k in keys[:-1]:
        d = d.setdefault(k, {})
    d[keys[-1]] = value

rawDescription: Python list to nested keys

description: Python list to nested keys


rawDescription: generating random values based on condition in structured array python

description: Generating random values based on condition in structured array python


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

rawDescription: Can't get pygame font to render on image


code: map(lambda d: abs(d - date), dates)

rawDescription: Get the closest datetime from a list

description: Get the closest datetime from a list


code:
def parse_bin(s):
    t = s.split('.')
    return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])

rawDescription: How to convert a string representing a binary fraction to a number in Python

description: Convert a string representing a binary fraction to a number in Python


rawDescription: Python- My for loop only converts half the list from str to int


code:
def is_part(some_string, target):
    if target:
        target_len = len(target)
        for i in range(len(some_string)):
            if some_string[i:i+target_len] == target:
                return True
    return False

rawDescription: See if string contains substring

description: See if string contains substring


code:
import numpy as np
import pandas as pd
df = pd.read_csv('data', parse_dates=[0], sep=',\s*')
start_dates = df['Date'] - pd.Timedelta(minutes=5)
df['start_index'] = df['Date'].values.searchsorted(start_dates, side='right')
df['end_index'] = np.arange(len(df))

def sum_window(row):
    return df['A'].iloc[row['start_index']:row['end_index']+1].sum()
df['rolling_sum'] = df.apply(sum_window, axis=1)

print(df[['Date', 'A', 'rolling_sum']])

rawDescription: pandas rolling sum of last five minutes

description: Pandas rolling sum of last five minutes


code:
def add_stats(xs, ys):
    return Stats(*[(x+y) for (x,y) in zip(xs,ys)])

rawDescription: What is an elegant way to solve this max and min problem in Ruby or Python?


code:
# (note the last ``1`` at the end to limit the substitution only to the first occurrence)
output = re.sub(r"(?s)<Location>.*?</Location>", r"%s" % locUpdate, xml, 1)

rawDescription: Replace xml tag contents using python

description: Replace xml tag contents using python


code:
import numpy as np

pred = [0.99,  0.23,  0.11,  0.64,  0.45,  0.55, 0.76,  0.72,  0.97]
users = ['User2', 'User3', 'User2', 'User3', 'User0', 'User1', 'User4',
         'User4', 'User4']

# assign integer indices to each unique user name, and get the total
# number of occurrences for each name
unames, idx, counts = np.unique(users, return_inverse=True, return_counts=True)

# now sum the values of pred corresponding to each index value
sum_pred = np.bincount(idx, weights=pred)

# finally, divide by the number of occurrences for each user name
mean_pred = sum_pred / counts

print(unames)
# ['User0' 'User1' 'User2' 'User3' 'User4']

print(mean_pred)
# [ 0.45        0.55        0.55        0.435       0.81666667]

rawDescription: Average using grouping value in another vector (numpy / Python)


code: project = Project('My Project', date(2015, 4, 23))

rawDescription: One to many SQL relationship

description: One to many SQL relationship


code:
json_string = '{"id":13,"code":"cflw`2B2[h1s`lNzF@sPC1FtaCiK0VF@","label":"Anonymous lifestyle App cflw`2B2[h1s`lNzF@sPC1FtaCiK0VF@"}'
json_string.replace(chr(1), '')

rawDescription: Python: remove ^A in a string

description: Python: remove ^A in a string


rawDescription: Numpy: Adding radius of circle to form diameter


rawDescription: How to get the index and occurance of each item using itertools.groupby()

description: Get the index and occurance of each item using itertools.groupby()


rawDescription: Add an offset to part of a list in Python?


code:
class Foo(object):
    def produce_nested_scope():
        class Bar(object):
            pass
        class Baz(object):
            class InnerBar(Bar):
                pass
        return Bar, Baz
    Bar, Baz = produce_nested_scope()
    del produce_nested_scope

Foo.Bar
Foo.Baz

rawDescription: Possible to achieve inheritance from nested class definitions?


code:
def all_flattened_sublists(l):
    l_flattened, l_sublists_flattened = flattened_list_and_sublists(l)
    return l_sublists_flattened

rawDescription: Python extract all sublists from a nested list


rawDescription: Copy and Write XML Node in Python

description: Copy and Write XML Node in Python


code: {'something', 'something else', 'another thing', '...'}

rawDescription: Python - Check if word matches list of words with IF statement


code: label = tk.Label(text=label_text_list[i], width=6, bg='red')

rawDescription: Basic Python methods & GUI assistance

description: Basic Python methods & GUI assistance


code:
def set_properties(cls):
    for name, propcls in vars(AttrContainer).iteritems():
        if name in cls.properties:
            setattr(cls, name, vars(propcls)[name])
    return cls

@set_properties
class Item01Object(object):
    properties = ["a","c"]
    ATTR = None

@set_properties
class Item02Object(object):
    properties = ["b","c"]
    ATTR = None

item01 = Item01Object()
item01.c = 20
item01.c
item02 = Item02Object()
item02.b = 42
item02.b

rawDescription: Python: Copy properties with it's functions (fget, fset, fdel) from one class to another


code:
myList[:] = [(dic.get(x[0],x[0]),) + x[1:] for x in myList]
myList

rawDescription: Possible to modify every first tuple element in a list of tuples?


code:
class ClassificationMain(QDialog, Ui_Dialog):

    def __init__(self, parent = None):

        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.chooseWidget=choosePatient.ChoosePatient()
        self.stackedWidget.addWidget(self.chooseWidget)
        self.stackedWidget.setCurrentWidget(self.chooseWidget)

    def reloadPatients(self):
        # whatever your operation should be on the ChoosePatient
        self.chooseWidget.reload()

# MAIN WINDOW
def __init__(self, parent = None):
    ...
    self.classification=classificationMain.ClassificationMain()
    self.stackedWidget.addWidget(self.classification)
    ...
    #connections
    menu.pushButton.clicked.connect(self.showClassification)

def showClassification(self ):
    self.stackedWidget.setCurrentIndex(3)
    self.classification.reloadPatients()

rawDescription: How to connect to parent SIGNAL in PyQt?

description: Connect to parent SIGNAL in PyQt


code: operators = pickle.load(open("operators", "r"))

rawDescription: How to properly pass text file to search the data there?

description: Properly pass text file to search the data there


code:
import theano
import theano.tensor as T

# Input variables
x = T.vector("x")
slice_size = T.iscalar("slice_size")

def step(idx, vect, length):

    # From the idx of the start of the slice, the vector and the length of
    # the slice, obtain the desired slice.
    my_slice = vect[idx:idx + length]

    # Do something with the slice here. I don't know what you want to do
    # to I'll just return the slice itself.
    output = my_slice

    return output

# Make a vector containing the start idx of every slice
slice_start_indices = T.arange(x.shape[0] - slice_size + 1)

out, updates = theano.scan(fn=step,
                        sequences=[slice_start_indices],
                        non_sequences=[x, slice_size])

fct = theano.function([x, slice_size], out)

rawDescription: Overlapping iteration over theano tensor


code:
def abc(cls, *args, **kwargs):
    pass

def abcd(cls, fn=abc):
    pass

class Foo:
    abc = classmethod(abc)
    abcd = classmethod(abcd)

rawDescription: How to surely refer to global objects in a class during definition?

description: Surely refer to global objects in a class during definition


code: [ [inner_list] for i in range(colNum)]

rawDescription: Cannot understand a python code

description: Cannot understand a python code


rawDescription: How to get IP address of hostname inside jinja template

description: Get IP address of hostname inside jinja template