code:
import os
import shutil
from knownfolders import *

all_users = True

filename = 'userid.py'
module_path = os.path.abspath(os.path.dirname(__file__))

if all_users:
    startup_path = get_known_folder_path(FOLDERID.CommonStartup)
else:
    startup_path = get_known_folder_path(FOLDERID.Startup)

src = os.path.join(module_path, filename)
dst = os.path.join(startup_path, filename)

shutil.copyfile(src, dst)

rawDescription: Python: Finding user id and moving directories (Windows)


code:
from collections import OrderedDict
dict = OrderedDict(zip(photos, range(1, len(photos) + 1)))

rawDescription: Sorting a list and dict keys

description: Sorting a list and dict keys


code:
lists = (A, B)
[''.join(x) for x in zip(*lists)]

rawDescription: How to merge Lists in Python?Merging python lists (0,1,2) & (A,B,C) to get (0A, 1B, 2C)

description: Merge Lists in Python?Merging python lists (0,1,2) & (A,B,C) to get (0A, 1B, 2C)


code:
newargs = (a, b, c)
myfunc2(*newargs)

rawDescription: Passing n arguments to a function in Python


code:
details = tree.xpath('.//div[contains(@id, "post_message_33583236")]')[0]
print(details.text_content())

rawDescription: Parsing forum posts using lxml/python

description: Parsing forum posts using lxml/python


code:
def find_all_paths(start, end, graph, visited=None):
    if visited is None:
        visited = set()

    visited |= {start}
    for node in graph[start]:
        if node in visited:
            continue
        if node == end:
            yield [start,end]
        else:
            for path in find_all_paths(node, end, graph, visited):
                yield [start] + path

rawDescription: Python: How to find more than one pathway in a recursive loop when multiple child nodes refers back to the parent?


code:
stream = Your_Streamer()
if stream.ready():
    stream.start()
    logger.debug("pid %i created" % stream.pid)
    while not your_stop_condition:
        import time
        time.sleep(1000) #some sleep
    stream.terminate()

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

description: Disconnect the streaming on the exact date & time


code:
sums = (0, 0, 0)
for j in some_list:
    result = method(j)
    sums = (a + b for a, b in zip(sums, result))

rawDescription: Most pythonic way to 'or' tuples?

description: Most pythonic way to 'or' tuples


code: m = __import__(modname, {}, globals(), [attr])

rawDescription: Dynamically import a callable given the full module path?


code: s.replace("%length", "args[length]")

rawDescription: Replace % followed by a number in a string


code:
# buildings that are within x>5 and y>3
session.query(Building).filter((Building.x > 5) & (Building.y > 3))
# Residential buildings that have only 1 resident
session.query(Residential).filter(Residential.num_residents == 1)

rawDescription: SQLAlchemy Inheritance

description: SQLAlchemy Inheritance


code:
import json
with open("file", "r") as f:
    settings = json.load(f)

rawDescription: Safe conversion String of nested Lists to List - eval() and literal_eval()


code:
from collections import Counter

a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2], "foo", 123, 123]

def counts(x):
    for ele in x:
        if isinstance(ele, Hashable):
            yield ele
        else:
            yield tuple(ele)

def unique_dupes(x):
    cnts = Counter(counts(x))
    for ele in x:
        t = ele
        if not isinstance(ele, Hashable):
            t = tuple(ele)
        if cnts[t] > 1:
            yield ele
            del cnts[t]

print(list(unique_dupes(a)))

rawDescription: How should I get a list of duplicate sublists in a list?


code:
import subprocess
import threading
import signal

def kill_this(procs, hard=False):
    """kill the process pids in the list"""

    for proc in procs:
        if hard:
            os.kill(pid, signal.SIGKILL)
        else:
            proc.terminate(pid, signal.SIGTERM)

rawDescription: How to kill a process within a thread in python?

description: Kill a process within a thread in python


code: ITEM_PIPELINES = {'myproject.pipelines.CSVPipeline': 300 }

rawDescription: How can I use the fields_to_export attribute in BaseItemExporter to order my Scrapy CSV data?

description: Use the fields_to_export attribute in BaseItemExporter to order my Scrapy CSV data


code:
def extract(s, start, end):
  return s[s.index(start) + len(start):s.index(end)]

rawDescription: Is that pythonic?

description: Is that pythonic


code:
condition = conditions[0]
for cond, op in zip(conditions[1:], operators):
    condition = my_eval(condition, op, cond)

rawDescription: Constructing an if statement from the client data in python


code:
from subprocess import Popen

class MyPopen(Popen):

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if self.stdout:
            self.stdout.close()
        if self.stderr:
            self.stderr.close()
        if self.stdin:
            self.stdin.close()
        # Wait for the process to terminate, to avoid zombies.
        self.wait()

if __name__ == '__main__':
    with MyPopen(['ls']) as p:
        print(p)

rawDescription: Exception handling when using Python's subprocess.Popen


rawDescription: How do I do this type of 2D "fancy" indexing without python loops?

description: Do this type of 2D "fancy" indexing without python loops


code:
rowPosition = self.table.rowCount()
table.insertRow(rowPosition)

rawDescription: How to add a row in a tableWidget PyQT?

description: Add a row in a tableWidget PyQT


code:
m = re.search('^!.*vserver\s+(\w+).*^!', text, re.MULTILINE | re.DOTALL)
m.group(0)
m.group(1)

rawDescription: Matching between two ! in a file in python


code:
import argparse
parser=argparse.ArgumentParser(
    usage="""python myscript.py {toolname} filename [-option]""",
    description='''Description.''',
    epilog="""Epilog.""")
parser.add_argument('toolname', choices=['counter', 'fasta2bed'], help='the name of the tool to be used')
parser.add_argument('filename', help='the input file name')
parser.add_argument('-l', '--long', action='store_true',     help='retrive a long summary file (default)')
parser.add_argument('-s', '--short', action='store_true', help='retrive a short summary file')
args=parser.parse_args()

rawDescription: How to skip a positional argument in Python Argparse

description: Skip a positional argument in Python Argparse


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

data = pd.DataFrame({ "A":np.random.normal(0.8,0.2,20),
                      "B":np.random.normal(0.8,0.1,20),
                      "C":np.random.normal(0.9,0.1,20)} )

data.boxplot()

for i,d in enumerate(data):
    y = data[d]
    x = np.random.normal(i+1, 0.04, len(y))
    plt.plot(x, y, mfc = ["orange","blue","yellow"][i], mec='k', ms=7, marker="o", linestyle="None")

plt.hlines(1,0,4,linestyle="--")

rawDescription: Dot-boxplots from DataFrames

description: Dot-boxplots from DataFrames


code:
for line in self.reversed_lines(fh):
    do_something_with_the_line(line)

rawDescription: Read file line by line, but in reverse (last line first, then next to last, etc.)


code:
song = Song(artist='Bob Dylan', title='Blowing in the wind')
lyr = song.lyricwikia()
print(lyr)

rawDescription: Crawling this website to grab lyrics?

description: Crawling this website to grab lyrics


code:
clips = [
ImageClip(os.path.join(folder,pic))
         .resize(width=w*9.3/16)
         .set_start(index*2+1)
         .set_end(index*2+3)
         .set_pos(lambda t:(max((402), (int(w-3*w*t))), "center"))

    for index, pic in enumerate(picfiles)
]

rawDescription: Placing variables inside a python list comprehension


code:
def transform(x, y):
    return x_pt_in_device + x, y_pt_in_device + y

rawDescription: Matplotlib artist to stay same size when zoomed in but ALSO move with panning?


rawDescription: Match bullet numbers with regex using python


code:
def _sort_fn(key_value_pair):
    key, value = key_value_pair
    # negative len -- Longer keys will show up first.
    # also add `key` to the tuple as keys with same length get sorted lexicographically.
    return -len(key), key

def sort_dict(d):
    new_dict = collections.OrderedDict()
    for k, v in sorted(d.items(), key=_sort_fn):
        if isinstance(v, dict):
            new_dict[k] = sort_dict(v)
        else:
            new_dict[k] = v
    return new_dict

rawDescription: how to sort all levels of a Python OrderedDict

description: Sort all levels of a Python OrderedDict


rawDescription: In Python, is there a way to call a method on every item of an iterable?


code:
import numpy as np
class A:
    def __init__(self, values):
        self.partposit = values

PARTS = dict((index, A(np.zeros((50000, 12)))) for index in xrange(163))
p1 = np.dstack((PARTS[k].partposit for k in sorted(PARTS.keys())))
p1.shape

rawDescription: efficiently dstack arrays from dictionary python

description: Efficiently dstack arrays from dictionary python


code: balance = 4711

rawDescription: How do I import and change a value from one script to another in python?

description: Import and change a value from one script to another in python


rawDescription: Pandas - Conditional Probability of a given specific b


code: AC,BD; AC,BE; AD,BE; BC,AD; BC,AE; BD,AE

rawDescription: Contracting elements from two different lists


rawDescription: Python: Extract JSON keys

description: Python: Extract JSON keys


code:
type(obj1) is Item
type(obj2) is Sub
type(obj3) is SubSub

rawDescription: Test an object is a subclass of the type of another instance


code:
from operator import add
map(add,*dict1.values())
map(add,*dict2.values())

rawDescription: Adding to List on For Loop (What do I set the List to initially?)


code:
import fnmatch
import os

start_urls = []
for root, dirnames, filenames in os.walk('/start/dir/'):
  for filename in fnmatch.filter(filenames, '*.html'):
      start_urls.append(os.path.join(root, filename))

rawDescription: Change directory in python and extract .html filenames through scrapy spider


code:
r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))

rawDescription: Implementing binary search tree in python


code:
def main(): #This is the self.osc.main() function
    doSomething() #notice I removed the loop. It only runs once. This is because the looping is handled by the other main() function (the one you call self.main())

def main(): #This is the self.main() function
    while True: #also run forever
        self.osc.main() #since we have now changed the self.osc.main() loop to run only once
        doSomethingElse()

rawDescription: How can I start a graphical widget without control flow getting stuck in its main loop in python?

description: Start a graphical widget without control flow getting stuck in its main loop in python


rawDescription: Pandas: Rename single DataFrame column without knowing column name


code:
with open(fname) as f:
    lines = f.readlines()
    line_count = len(lines)
    for line in lines:
        line_processed += 1

rawDescription: python with statement and 2 for loops

description: Python with statement and 2 for loops


code:
def get_pid(*params):
    return [os.getpid(param) for param in params]

rawDescription: Dynamic method in python

description: Dynamic method in python


rawDescription: Inner print statement not working

description: Inner print statement not working


rawDescription: how to do linear interpolation on a 2D numpy array having sparse data?

description: Do linear interpolation on a 2D numpy array having sparse data


rawDescription: Python Challenge Lvl 3 Explaination (warning spoilers!)


code:
if type(x) == type(y):
    fight()

rawDescription: Python: asking if two objects are the same class


code:
df_grouped['merged'] = df_grouped['recipe'].apply(lambda x: list(join(x)))
df_grouped['merged']

rawDescription: Flattening shallow list with pandas

description: Flattening shallow list with pandas


code:
import urllib2
response = urllib2.urlopen('http://python.org/')
response.headers.type

rawDescription: How to get urllib2 response in json

description: Get urllib2 response in json


code: score = sum(weight[k] * Counter(v)["red"] * Counter(v)["blue"] for k,v in dict1.iteritems())

rawDescription: efficiently do weighted count the elements in the list

description: Efficiently do weighted count the elements in the list


code: colors = pl.cm.Spectral(np.linspace(0, 1, 10))

rawDescription: pyplot equivalent for pl.cm.Spectral in matplotlib

description: Pyplot equivalent for pl.cm.Spectral in matplotlib


code:
list_test = ["adam", "ronny", "dave", "adam", "lisa", "lisa"]
list_test_for = ["adam", "lisa"]

results = []

for name in list_test_for:
    try:
        results.append(next(match for match in list_test if name==match))
    except StopIteration:
        continue

rawDescription: test list for membership and store only first true item + python

description: Test list for membership and store only first true item + python


rawDescription: Get to a dictionary format (by just saving non-zero values and indices) from a sparse matrixin in python


code:
class Person(models.Model):
    first_name = models.CharField(...)
    last_name = models.CharField(...)
    birth_date = models.DateField(...)

rawDescription: Is it possible to use raw SQL with python's django web framework?


code:
a=Foo(1)
b=Foo(1)
c=Foo(-1)
d=Foo(2)
e=a

rawDescription: Three tiers of equality comparison in Python


code:
while True:
    if self.stone < 1 and self.wood < 1:
        self.CraftPickaxe.config(state=DISABLED)
    elif self.stone > 0 and self.wood > 0:
        self.CraftPickaxe.config(state=NORMAL)

rawDescription: Disable a Tkinter button when variables are at 0


code:
import sys

class VerboseSysPath(list):
    def croak(self, action, args):
        frame = sys._getframe(2)
        print('sys.path.{}{} from {}:{}'.format(
            action, args, frame.f_code.co_filename, frame.f_lineno))

    def insert(self, *args):
        self.croak('insert', args)
        return super(VerboseSysPath, self).insert(*args)

    def append(self, *args):
        self.croak('append', args)
        return super(VerboseSysPath, self).append(*args)

    def extend(self, *args):
        self.croak('extend', args)
        return super(VerboseSysPath, self).extend(*args)

    def pop(self, *args):
        self.croak('pop', args)
        return super(VerboseSysPath, self).pop(*args)

    def remove(self, *args):
        self.croak('remove', args)
        return super(VerboseSysPath, self).pop(*args)

    def __delitem__(self, *args):
        self.croak('__delitem__', args)
        return super(VerboseSysPath, self).__delitem__(*args)

    def __setitem__(self, *args):
        self.croak('__setitem__', args)
        return super(VerboseSysPath, self).__setitem__(*args)

    def __setslice__(self, *args):
        self.croak('__setslice__', args)
        return super(VerboseSysPath, self).__setslice__(*args)

sys.path = VerboseSysPath(sys.path)

rawDescription: Debugging modifications of sys.path

description: Debugging modifications of sys.path


code:
for key in set(sourceDict).intersection(targetDict):
    # Now we have only keys that occur in both dicts
    if sourceDict[key] != targetDict[key]:
        diffList.append(key)

rawDescription: Compare values from two different dictionaries in Python?


code:
instance = MyModel.objects.create(some_field=some_value)  # post save signal triggered here
instance.my_m2mfield = my_set_of_m2m_models

rawDescription: ManyToManyField is empty in post_save() function


code:
new_array = old_string.split(' ')

for index, mention in enumerate(new_array):
    for user in users:
        if mention == user and len(mention) == len(user):
            #We won't replace this in old_string, we'll replace the current entry
            #old_string = old_string.replace(a, '<' + user + '>')
            new_array[index] = '<%s>'%user

new_string = ' '.join(new_array)

rawDescription: Python String Replace Behaving Weirdly

description: Python String Replace Behaving Weirdly


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

gs = gridspec.GridSpec(4, 4)

ax1 = plt.subplot(gs[:2, :2])
ax1.plot(range(0,10), range(0,10))

ax2 = plt.subplot(gs[:2, 2:])
ax2.plot(range(0,10), range(0,10))

ax3 = plt.subplot(gs[2:4, 1:3])
ax3.plot(range(0,10), range(0,10))

plt.show()

rawDescription: How to manually position one subplot graph in matplotlib.pyplot

description: Manually position one subplot graph in matplotlib.pyplot


code: string.punctuation + string.digits

rawDescription: pass two arguments into translate()

description: Pass two arguments into translate()


code:
class MyClass:
  def GET(self, args):
     return self.perform(args[1], args[2])
  ...

x = MyClass()
x.GET(sys.argv)

rawDescription: How to call a class's method in python?

description: Call a class's method in python


rawDescription: How to share a list between two files

description: Share a list between two files


rawDescription: Scraping data table from Chinese stock website using Python


code: np.histogram2d(x, y, bins=2, normed=True)

rawDescription: Obtain frequencies in each bin for histogram2d


code:
import csv
from datetime import datetime
from itertools import groupby

LOOKUP_SEASON = {
    11: 'Winter',
    12: 'Winter',
    1: 'Winter',
    2: 'Spring',
    3: 'Spring',
    4: 'Spring',
    5: 'Summer',
    6: 'Summer',
    7: 'Summer',
    8: 'Autumn',
    9: 'Autumn',
    10: 'Autumn'
}

def get_season(row):
    date = datetime.strptime(row[0], '%d/%m/%Y')
    season = LOOKUP_SEASON[date.month]
    if season == 'Winter':
        if date.month == 1:
            last_year, next_year = date.year - 1, date.year
        else:
            last_year, next_year = date.year, date.year + 1
        return '{} {}/{}'.format(season, last_year, next_year)
    else:
        return '{} {}'.format(season, date.year)

def get_year(row):
    date = datetime.strptime(row[0], '%d/%m/%Y')
    if date.month < 8:
        return date.year - 1
    else:
        return date.year

with open('NJDATA.csv') as data_file, open('outfile.csv', 'wb') as out_file:
    headers = next(data_file)
    reader = csv.reader(data_file)
    writer = csv.writer(out_file)

    # Loop over groups distinguished by the "year" from Autumn->Summer,
    # defined by the `get_year` function
    for year, seasons in groupby(reader, get_year):
        mean_data = []
        # Loop over the data in the current year, grouped by season, defined
        # by the get_season method. Since the required "season string"
        # (e.g Autumn 1952) can be used as an identifier for the seasons,
        # the `get_season` method returns the specific string which is used
        # in the output, so you don't have to compile that one more time
        # inside the for loops
        for season_str, iter_data in groupby(seasons, get_season):
            data = list(iter_data)
            mean = sum([float(row[1]) for row in data]) / len(data)
            # Use the next line instead if you want to control the precision
            #mean = '{:.3f}'.format(sum([float(row[1]) for row in data]) / len(data))
            mean_data.extend([season_str, mean])
        writer.writerow(mean_data)

rawDescription: Group data in csv by season and year using python and pandas


code:
def get_slice(my_array, dimension, index):
    items = [slice(None, None, None)] * my_array.ndim
    items[dimension] = index
    array_slice = my_array[tuple(items)]
    return np.squeeze(array_slice)

rawDescription: Python use array axis to select slice

description: Python use array axis to select slice


code:
a = 'Φ'
a
binascii.b2a_qp(a)
magic_text = yaml.load("""
magic_string: '=CE=A6'
""")
magic_text
binascii.a2b_qp(magic_text['magic_string'])

rawDescription: What config file format to use for user-friendly strings of arbitrary bytes?


code:
def match(a, b):
    from collections import Counter
    M = Counter()
    for i in range(len(a)):
        for j in range(len(b)):
            if a[i] == b[j]:
                M[i, j] = M[i-1, j-1] + 1
    unique = set()
    for i in range(len(a)):
        for j in range(len(b)):
            if M[i, j] and not M[i+1, j+1]:
                length = M[i, j]
                unique.add(" ".join(a[i+1-length: i+1]))
    return unique

rawDescription: Find maximum length of all n-word-length substrings shared by two strings


rawDescription: Python code for calculating number of an alphabet


code: sum(a*b for _,a,b in d.values())/sum(a for _,a,b in d.values())

rawDescription: Using dictionary values to calculate sum of weighted values without explicitly defined weights


code: yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)

rawDescription: sorting list of nested dictionaries in python

description: Sorting list of nested dictionaries in python


code:
x = np.arange(1,5,0.5)
plt.figure(1)
plt.plot(x,x,label='Curve 1')
plt.plot(x,2*x,label='Curve 2')
leg = plt.legend(loc = 0, fontsize = 'small')

t1, t2 = leg.get_texts()
# here we create the distinct instance
t1._fontproperties = t2._fontproperties.copy()
t1.set_size('medium')

plt.show()

rawDescription: How to change fontsize of individual legend entries in pyplot?

description: Change fontsize of individual legend entries in pyplot


code:
import httplib, urllib

params = urllib.urlencode({
    'v': 1,
    'tid': 'UA-XXXXXX-Y',
    'cid': '666',
    't': 'event',
    'ec': 'game',
    'ea': 'start',
    'ev': 0
})

connection = httplib.HTTPConnection('www.google-analytics.com')
connection.request('POST', '/collect', params)

rawDescription: How to post to Google Measurement protocol using Python?

description: Post to Google Measurement protocol using Python


code: star1 = next((x for x in starlist if x.id==starid1), None)

rawDescription: value assignment in python

description: Value assignment in python


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')

for _ in range(4):

    worksheet = workbook.add_worksheet()

    worksheet.write('A1', 'Hello')

workbook.close()

rawDescription: python xlsxwriter worksheet object reuse

description: Python xlsxwriter worksheet object reuse


code:
def capitalizeNested(L):
    for i,item in enumerate(L):
        if isinstance(item, list):
            L[i] = [it.title() for it in item]
        elif isinstance(item, str):
            L[i] = item.title()

rawDescription: python capitalize nested list with strings and integers

description: Python capitalize nested list with strings and integers


code:
stations = ["Station A", "Station B", "Station C", "Station D"]
begin = input("What is your begin station?")
end = input("What is your end station?")

ind = stations.index(begin) + 1

for i in range(ind, len(stations)):
    for j in range(i,len(stations)):
        print(stations[j])
    print()

rawDescription: For-Loop: How to 'take one off' every time you pass over?


code:
loss_matrix = tf.maximum(0., 1. - scores_pos + scores_neg)  # we could also use tf.nn.relu here
loss = tf.reduce_sum(loss_matrix)

rawDescription: Max margin loss in TensorFlow

description: Max margin loss in TensorFlow


code:
import csv
import re

fnamein = 'data.csv'
fnameout = 'output.csv'
rex = re.compile(r"'(\d*\.?\d*)%")  # an int/float element with percent sign

with open(fnamein, 'r') as fin, open(fnameout, 'w', newline='') as fout:
    writer = csv.writer(fout)
    for line in fin:
        row = rex.findall(line)         # all elements with percent sign
        row2 = [float(e) for e in row]  # converted explicitly if needed
        writer.writerow(row2)           # write to the output CSV

rawDescription: How do I retain row-and-column arrangement while performing regular expression manipulations in Python

description: Retain row-and-column arrangement while performing regular expression manipulations in Python


code:
nrows=3; ncols=4; np.array([[[23] * ncols]*nrows])
nrows=3; ncols=4; np.array([[[23] * ncols]*nrows]).reshape(nrows, ncols)

rawDescription: Reshaping Arrays in Numpy with variables


code:
from itertools import groupby
from operator import itemgetter

[[k] + [sum(col) for col in zip(*g)[1:]] for k, g in groupby(lst, itemgetter(0))]

rawDescription: Python: Add lists together

description: Python: Add lists together


rawDescription: Read console output of another program in Python


code:
if not incremental:
    self.label_binarizer_.fit(y)

else:
    self.label_binarizer_.fit(self.classes_)

rawDescription: partial_fit Sklearn's MLPClassifier

description: Partial_fit Sklearn's MLPClassifier


code:
class Cryptsy:

    def __init__(self, APIKey, Secret):
        self.APIKey = APIKey
        self.Secret = Secret
        self.privateBaseURL = 'https://api.cryptsy.com/api'
        self.session = requests.Session()

    def private_api_query(self, method, payload={}):
        url = self.privateBaseURL
        payload['method'] = method
        response = self.session.post(url, data=payload, auth=CryptsyAuth(self.APIKey, self.Secret))
        js = response.json()
        return js

    def getMarkets(self):
        return self.private_api_query('getmarkets')

rawDescription: Authenticating API calls using requests and requests-oauthlib in Python 3.3


rawDescription: How to split string on '/' delimiter but prevent splitting when '/ '  occurs just after ' \ '

description: Split string on '/' delimiter but prevent splitting when '/ '  occurs just after ' \ '


code:
sample = df[['catA','catB','catC']]
sample = df.apply(lambda col: col.str.strip())

rawDescription: How to vectorize a data frame with several text columns in scikit learn without losing track of the origin columns

description: Vectorize a data frame with several text columns in scikit learn without losing track of the origin columns


code:
from django.http import HttpResponse
from netadmin.plugins.templatetags.widgets import render_widget

def ajax_render_data(request, object_id):
    return HttpResponse(render_widget(object_id))

rawDescription: How to use Django views and template tag simultanosly?

description: Use Django views and template tag simultanosly


code:
if set(x).issubset({'m', 'u', 'i'}):
    print("true")
else:
    print("false")

rawDescription: Input issue Python

description: Input issue Python


code:
with open('file') as f:
  file_date = f.read()
updated_file_data = "sometext\n".join(map("'{0}'".format, file_date.split('\n')))

rawDescription: Appending Quotations in Text File to Each line


code:
def inAllPolygons(x,y,polygons):
  for p in polygons:
    if not point_in_poly(x,y,p):
      return False
  return True

rawDescription: Removing points inside several polygons

description: Removing points inside several polygons


code:
bapad = plt.rcParams['legend.borderaxespad']
fontsize = plt.rcParams['font.size']
axline = plt.rcParams['axes.linewidth']  #need this, otherwise the result will be off by a few pixels
pad_points = bapad*fontsize + axline  #padding is defined in relative to font size
pad_inches = pad_points/72.0  #convert from points to inches
pad_pixels = pad_inches*fig.dpi  #convert from inches to pixels using the figure's dpi

rawDescription: Matplotlib: Adjust legend location/position


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


code:
import concurrent.futures as CF
import itertools as IT
import logging

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')

def worker(line):
    line = line.strip()
    logger.info(line)

chunksize = 1024
with CF.ThreadPoolExecutor(max_workers=4) as executor, open("big_file") as f:
    for chunk in zip(*[f]*chunksize):
        futures = [executor.submit(worker, line) for line in chunk]
        # wait for these futures to complete before processing another chunk
        CF.wait(futures)

rawDescription: How to spawn future only if free worker is available

description: Spawn future only if free worker is available


rawDescription: Find clusters of bacteria

description: Find clusters of bacteria


code:
{1: [{'comment': "Where's this?", 'comment_id': 1, 'photo_id': 1},
     {'comment': 'Yosemite, CA', 'comment_id': 2, 'photo_id': 1}],
 2: [{'comment': 'Nice photo!', 'comment_id': 3, 'photo_id': 2}]}

rawDescription: Pythonic ways to re-group / pivot database output


code:
Function
def nastava(department, data):
    code = data['odjeli'][department]

    professors = data['profesori']
    filtered_professors = filter(lambda z: z['odjel']==code, professors)

    predmeti = data['predmeti']
    filtered_predmeti = filter(lambda z: z['odjel'] == code, predmeti)

    maped_professors = map(lambda z: {'professor': z['ime'] +" "+ z['prezime']}, filtered_professors)
    maped_predmeti = map(lambda z: {'predmeti': z['popis']}, filtered_predmeti)

    return code, maped_professors, maped_predmeti

rawDescription: Merge two dictionary values to one and add it to another dictionary in Python


code:
for i in range(4): #add numbers that are equal
    for j in range(3,-1,-1):
        if grid[i][j] == grid[i][j-1]:
            grid[i][j-1] = (grid[i][j])+(grid[i][j])
            grid[i][j] = 0
        else:
            pass

rawDescription: Outcome of Function - Python

description: Outcome of Function - Python


rawDescription: Dataframe use grouped row values as a row name


rawDescription: How to insert duplicated values in dictionary?

description: Insert duplicated values in dictionary


code:
wtr = csv.DictWriter(open(filename, 'w'), keys)
wtr.writerows(data)

rawDescription: How do I make one python dictionary to csv with headers?

description: Make one python dictionary to csv with headers


code:
lfunctions = {}

def DeserialiseFunction(aSerialisedFunction):
    lmarshalledFunc, lmarshalledClosureValues, lmoduleName = pickle.loads(aSerialisedFunction)

    lglobals = sys.modules[lmoduleName].__dict__
    lglobals["lfunctions"] = lfunctions

    def make_proxy(f_hash):
        def f_proxy(*args, **kwargs):
            global lfunctions
            f = lfunctions[f_hash]
            f(*args, **kwargs)

        return f_proxy

    def make_cell(value):
        return (lambda x: lambda: x)(value).func_closure[0]

    def UnmarshalClosureValues(aMarshalledClosureValues):
        global lfunctions

        lclosure = None
        if aMarshalledClosureValues:
            lclosureValues = []
            for item in aMarshalledClosureValues:
                ltype = len(item)
                if ltype == 1:
                    lclosureValues.append(pickle.loads(item[0]))
                elif ltype == 2:
                    lfunction = make_proxy(item[0])
                    lclosureValues.append(lfunction)
                elif ltype == 4:
                    lfuncglobals = sys.modules[item[3]].__dict__
                    lfuncglobals["lfunctions"] = lfunctions
                    lfunction = types.FunctionType(marshal.loads(item[1]), lfuncglobals, closure=UnmarshalClosureValues(item[2]))
                    lfunctions[item[0]] = lfunction
                    lclosureValues.append(lfunction)
            lclosure = tuple([make_cell(lvalue) for lvalue in lclosureValues])
        return lclosure

    lfunctionCode = marshal.loads(lmarshalledFunc)
    lclosure = UnmarshalClosureValues(lmarshalledClosureValues)
    lfunction = types.FunctionType(lfunctionCode, lglobals, closure=lclosure)
    return lfunction

def SerialiseFunction(aFunction):
    if not aFunction or not hasattr(aFunction, "func_code"):
        raise Exception ("First argument required, must be a function")

    lfunctionHashes = set()

    def MarshalClosureValues(aClosure, aParentIndices = []):
        lmarshalledClosureValues = []
        if aClosure:
            lclosureValues = [lcell.cell_contents for lcell in aClosure]

            lmarshalledClosureValues = []
            for index, litem in enumerate(lclosureValues):
                lfullIndex = list(aParentIndices)
                lfullIndex.append(index)

                if isinstance(litem, types.FunctionType):
                    lhash = hash(litem)
                    if lhash in lfunctionHashes:
                        lmarshalledClosureValues.append([lhash, None])
                    else:
                        lfunctionHashes.add(lhash)
                        lmarshalledClosureValues.append([lhash, marshal.dumps(litem.func_code), MarshalClosureValues(litem.func_closure, lfullIndex), litem.__module__])
                else:
                    lmarshalledClosureValues.append([pickle.dumps(litem)])

    lmarshalledFunc = marshal.dumps(aFunction.func_code)
    lmarshalledClosureValues = MarshalClosureValues(aFunction.func_closure)
    lmoduleName = aFunction.__module__

    lcombined = (lmarshalledFunc, lmarshalledClosureValues, lmoduleName)

    retval = pickle.dumps(lcombined)

    return retval

rawDescription: Can I restore a function whose closure contains cycles in Python?

description: Restore a function whose closure contains cycles in Python


code: return links

rawDescription: Get list of all paginated URL's from links in txt file in python requests


code:
from itertools import chain
list(chain.from_iterable(myList[0]))

rawDescription: How to print list of list into one single list in python without using any for or while loop?

description: Print list of list into one single list in python without using any for or while loop


code:
req = urllib2.Request(url='http://python.org')
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0)')
req.headers

rawDescription: Get Request Headers for Urllib2.Request?

description: Get Request Headers for Urllib2.Request


code:
def hours(day):
    ...

rawDescription: How can I reference a list element in this function?

description: Reference a list element in this function


rawDescription: date in Flask URL

description: Date in Flask URL


code:
res = soup.find('span')
res

rawDescription: Obtain span title using beautifulsoup

description: Obtain span title using beautifulsoup


code:
b = x.read(1)
lastfivebits = b & 0b11111

rawDescription: How I can read a bit in Python?

description: How I can read a bit in Python


code:
new_user = User.objects.create_user(username, email, password)
new_user.is_active = False
new_user.first_name = first_name
new_user.last_name = last_name
new_user.save()

rawDescription: How to add first name and last name to Django-registeration-redux registeration form?

description: Add first name and last name to Django-registeration-redux registeration form


rawDescription: Python: argparse optional arguments without dashes


rawDescription: How to launch a couple of python scripts from a first python script and then terminate them all at once?

description: Launch a couple of python scripts from a first python script and then terminate them all at once


code:
import numpy as np
from scipy.stats import pearsonr, betai

def corrcoef(matrix):
    r = np.corrcoef(matrix)
    rf = r[np.triu_indices(r.shape[0], 1)]
    df = matrix.shape[1] - 2
    ts = rf * rf * (df / (1 - rf * rf))
    pf = betai(0.5 * df, 0.5, df / (df + ts))
    p = np.zeros(shape=r.shape)
    p[np.triu_indices(p.shape[0], 1)] = pf
    p[np.tril_indices(p.shape[0], -1)] = pf
    p[np.diag_indices(p.shape[0])] = np.ones(p.shape[0])
    return r, p

def corrcoef_loop(matrix):
    rows, cols = matrix.shape[0], matrix.shape[1]
    r = np.ones(shape=(rows, rows))
    p = np.ones(shape=(rows, rows))
    for i in range(rows):
        for j in range(i+1, rows):
            r_, p_ = pearsonr(matrix[i], matrix[j])
            r[i, j] = r[j, i] = r_
            p[i, j] = p[j, i] = p_
    return r, p

rawDescription: Correlation coefficients and p values for all pairs of rows of a matrix


code:
with open(sys.argv[1], 'r') as fo:
    L = fo.readlines()

rawDescription: Scanning a list

description: Scanning a list


code:
return ''.join(
    self._morse_char_map.get(piece, piece[0])
    for piece in (
        code[i: i + 5]
        for i in range(0, len(code), 5)
    )
)

rawDescription: How can I analyze or improve my niece's simple compression algorithm that is based on Morse code?

description: Analyze or improve my niece's simple compression algorithm that is based on Morse code


code:
def count(mylist):
    return len(set(mylist))

rawDescription: Count different numbers in list python

description: Count different numbers in list python


code: foo(some_list, *inputs)

rawDescription: Default empty lists vs. *args in Python

description: Default empty lists vs. *args in Python


code:
def countspace(x):
    return x.count(' ')

rawDescription: Finding how many of a certain character in each element in a list


code:
import pandas as pd
df = pd.DataFrame(a)
df.values[zip(*ix)]

rawDescription: advanced numpy/pandas indexing

description: Advanced numpy/pandas indexing


code:
a[:, ind:ind + nbcols] = np.genfromtxt('file_1000x10.csv',
                                       usecols = range(nbcols)).reshape(-1, nbcols)

rawDescription: forcing genfromtxt output to no-vector

description: Forcing genfromtxt output to no-vector


code:
up = '/tmp/database.txt'
open(up, 'w').write('''\
P61981  1433G_HUMAN
P61982  1433G_MOUSE
Q5RC20  1433G_PONAB
P61983  1433G_RAT
P68253  1433G_SHEEP
''')
def mplist(somelist):
    someset = set(somelist)
    with open(up) as U:
        return [line for line in U if line.split(None, 1)[0] in someset]

mplist(['P61981', 'Q5RC20'])

rawDescription: Python: Looping over 2mln lines

description: Python: Looping over 2mln lines


code: import commands

rawDescription: Can't get output from Tesseract command run through os.system


code:
import json

@app.route('/_array2python')
def array2python():
    wordlist = json.loads(request.args.get('wordlist'))
    # do some stuff
    return jsonify(result=wordlist)

rawDescription: How to pass a javascript array to a python script using flask [using flask example]

description: Pass a javascript array to a python script using flask [using flask example]


code:
with open('to_output.tmp') as ids_file:
    ids_to_keep = set(ids_file.read().split(','))

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


code:
fname = "feed.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += 1
        num_words += len(words)
        num_chars += len(line)

rawDescription: Counting lines, words, and characters within a text file using Python


code: df[df['Slice']=='Slice 4']

rawDescription: Combining MultiIndex and Index in a PANDAS DataFrame


rawDescription: Django attribute is not up to date

description: Django attribute is not up to date


code:
df
df.date_time
df.date_time.map(lambda x: x.strftime('%Y-%m-%d'))

rawDescription: Extracting just Month and Year from Pandas Datetime column (Python)


code:
import requests
r = requests.get("http://minewind.com/forums")
r.status_code

rawDescription: Why am I not able to grab from the url?

description: Why am I not able to grab from the url


code:
get_next_item_ind(values, 0)
get_next_item_ind(values, 1)
get_next_item_ind(values, 2)
get_next_item_ind(values, 3)
get_next_item_ind(values, 4)
get_next_item_ind(values, 5)
get_next_item_ind(values, 6)
get_next_item_ind(values, 7)
get_next_item_ind(values, 8)

rawDescription: Optimize search to find next matching value in a list


code:
plt.plot(*np.transpose(lattice), marker = 'o', ls = '')
axes().set_aspect('equal')

rawDescription: How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay?

description: Find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay


code:
number = int(input("Enter a number: "))
mult = int(input("How many multiples: "))
for i in range(mult+1):
    print("%d times %d is %d" %(number, i, number*i))

rawDescription: Loopin' multiplication in Python?

description: Loopin' multiplication in Python


description: Some Description for the build

rawDescription: Set Hudson Build Description via Web API


code:
lines = ax.plot(arr)
ax.legend(lines, labels)

rawDescription: Assign label names for line plot from numpy 2D array


code:
self.lwalk = [ret_bitmap('lwalk1.bmp'), ret_bitmap('lwalk2.bmp')]
self.rwalk = [ret_bitmap('rwalk1.bmp'), ret_bitmap('rwalk2.bmp')]

self.animation_frame = 0

rawDescription: I can't get my class to work in pygame

description: I can't get my class to work in pygame


code:
import copy
stocklist = {'a': 0, 'b': 0, 'c': 0}
stockmap = [[copy.deepcopy(stocklist) for w in range(WIDTH)] for h in range(HEIGHT)]

rawDescription: Using list comprehension to setup a list of unique dictionaries in Python


code: ('/products/(.*)', ProductsHandler)

rawDescription: app-engine: Request Data

description: App-engine: Request Data


rawDescription: Python-Unable to convert a list to string


code:
s = 1000 * string
timeit.timeit('f(s)', 'from __main__ import s, strip_spaces as f', number=100)
timeit.timeit('f(s)', 'from __main__ import s, strip_spaces_join as f', number=100)
s = 10000 * string
timeit.timeit('f(s)', 'from __main__ import s, strip_spaces as f', number=100)
timeit.timeit('f(s)', 'from __main__ import s, strip_spaces_join as f', number=100)

rawDescription: python list comprehension vs +=

description: Python list comprehension vs +=


code: [(x,y,x*y) for x in range(1,5) for y in range(1,5) if x*y > 8]

rawDescription: Comprehensions in Python and Javascript are only very basic?


code: df1.sort(axis=1) == df2.sort(axis=1)

rawDescription: Equality in Pandas DataFrames - Column Order Matters?


code:
({'drama': True, 'mystery': True, 'horror': True, 'psychological': True}, 'relevant')
({'drama': True, 'fantasy': True, 'romance': True, 'adventure': True, 'science fiction': True}, 'unrelevant')

rawDescription: trouble with nltk python NaiveBayesClassifier, I keep getting same probabilities inputs correct?

description: Trouble with nltk python NaiveBayesClassifier, I keep getting same probabilities inputs correct


code:
d = {}
count = 1
for team, goal in zip(teams, goals):
    for i in range(goal):
        d[count] = team
        count += 1

rawDescription: making dictionary from some logic

description: Making dictionary from some logic


code:
import time

print(time.strftime("%w"))

rawDescription: How to get current day of the week in vimscript?

description: Get current day of the week in vimscript


code: globals()["foo"]

rawDescription: javascript locals()?

description: Javascript locals()


rawDescription: Drop Duplicate in market data

description: Drop Duplicate in market data


code:
lm = lambda x, sample: sample['Intercept'] + sample['x'] * x ## linear model
samples=50 ## Choose to be the same as in plot call
trace_det = np.empty([samples, len(x)]) ## initialise
for i, rand_loc in enumerate(np.random.randint(0, len(trace), samples)):
    rand_sample = trace[rand_loc]
    trace_det[i] = lm(x, rand_sample)
y = trace_det.T
y[0]

rawDescription: Estimating the Posterior Predictive in Regression


code:
from _servers import get_server_type
exec("from %s import *" % get_server_type())

rawDescription: Managing multiple settings.py files

description: Managing multiple settings.py files


code:
for key, value in names.items():
    posX, posY, posZ = value

rawDescription: Multiple values for key in dictionary in Python


code:
import argparse
import sys as _sys

class MyFileType(argparse.FileType):

    def __call__(self, string):
        # the special argument "-" means sys.std{in,out}
        if string == '-':
            if 'r' in self._mode:
                return _sys.stdin
            elif any(m in self._mode for m in 'wa'):
                return _sys.stdout
            else:
                msg = _('argument "-" with mode %r') % self._mode
                raise ValueError(msg)

        # all other arguments are used as file names
        try:
            return open(string, self._mode, self._bufsize)
        except IOError as e:
            message = _("can't open '%s': %s")
            raise ArgumentTypeError(message % (string, e))

def parse_options():
    parser = argparse.ArgumentParser(description='A foo that bars')

    parser.add_argument("-f",
                      "--file", dest="filename", required=True,
                      type=MyFileType('a+'),
                      help="The output file (append mode, see --overwrite).")

    parser.add_argument("-o",
                      "--overwrite", dest="overwrite",
                      action='store_true',
                      help="Will overwrite the filename if it exists")

    args = parser.parse_args()

    if args.overwrite:
        args.filename.truncate(0)
    return args

args = parse_options()
print >> args.filename, 'Hello, World!'

rawDescription: What mode must I specify to argparse.FileType to append, keeping - as a default


code:
A3B4C1D10E2D4
AAABBBBCDDDDDDDDDDEEDDDD

rawDescription: python encoder and decoder

description: Python encoder and decoder


code:
import exte
def f4(x=x,y=y,n=n,z=z):
    rows = [[0]*y for i in range(x)]
    rr = random.randrange

    for i in range(n):
        inputX, inputY = rr(x), rr(y)
        exte.dopoint(x, y, z, inputX, inputY, rows)

rawDescription: Python performance: iteration and operations on nested lists


code: dict(list(enumerate(values)))

rawDescription: populating a dictionary using for loops (python)

description: Populating a dictionary using for loops (python)


code:
def pytest_namespace():
    return {"param": None}

rawDescription: Skip test depending on parameter in py.test


code:
import csv
import fileinput

myDict = {}
csvreader = csv.reader(fileinput.input(mode='rb'), delimiter=',')

rawDescription: Read inputfile as csv in python

description: Read inputfile as csv in python


rawDescription: How to modify specific field in ndarray matrix

description: Modify specific field in ndarray matrix


code: reduce(lambda x, y: np.intersect1d(x, y, assume_unique=True), (a, b, c))

rawDescription: how to get items that belongs to all numpy arrays?

description: Get items that belongs to all numpy arrays


code:
def nextyear(dt):
   try:
       return dt.replace(year=dt.year+1)
   except ValueError:
       # February 29th in a leap year
       # Add 365 days instead to arrive at March 1st
       return dt + timedelta(days=365)

rawDescription: How to Print next year from current year in Python


code: df

rawDescription: Python Pandas: Lookup table by searching for substring


code:
print(res)
# [<TimeitResult : 10000000 loops, best of 3: 61.2 ns per loop>,
#  <TimeitResult : 10000000 loops, best of 3: 61.3 ns per loop>,
#  <TimeitResult : 10000000 loops, best of 3: 61.5 ns per loop>]

rawDescription: %timeit equivalent in code

description: %timeit equivalent in code


code:
def function1(a, b, c):
    return sum((a, b, c)) - min(a, b, c)

rawDescription: Getting two largest numbers from three numbers without using conditional statement or loop in python 3.5


rawDescription: numpy arbitrary precision linear algebra

description: Numpy arbitrary precision linear algebra


code:
C = [[a, b] if a < b else [b, a] for a, b in zip(A, B)]
for sublist in C:
    for i in sublist:
        yield i

rawDescription: Make one list from two list applying constraint


code:
import re

CITY_REG = re.compile(r"([^[]+)\[([0-9.]+),([0-9.]+)\](\d+)")
CITY_TYPES = (str, float, float, int)

def get_city(line):
    match = CITY_REG.match(line)
    if match:
        return [type(dat) for dat,type in zip(match.groups(), CITY_TYPES)]
    else:
        raise ValueError("Failed to parse {} as a city".format(line))

def get_distances(line):
    return [int(i) for i in line.split()]

rawDescription: Regular Expressions in data parsing Python


code: time.sleep(5) ; k.type_string('ΣΣ')

rawDescription: Save text cursor position in the currently focused application/control, then restore it and paste text


code: coalesce(column1, '') + coalesce(column2, '')

rawDescription: Performing concatenate columns in SQLAlchemy


code:
p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char))
p[0]
p[1]
p[3]

rawDescription: Python: how to increment a ctypes POINTER instance


rawDescription: numpy array row major and column major

description: Numpy array row major and column major


code:
import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}

columns = ['a', 'b', 'c', 'd', 'e', 'f']

# combine d1 and d2 into data.. there are other ways but this is easy to understand
data = dict(d1)
data.update(d2)

with open('my_data.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(columns)
    # make a list of values in the order of columns and write them
    w.writerow([data.get(col, None) for col in columns])

rawDescription: Python dictionary keys to csv file with column match


rawDescription: Parsing integers from an alphanumeric string in Python


rawDescription: Numpy indexing multidimensional arrays with array and slice


code:
import os
os.system(r'C:\test\sample.exe -color')

rawDescription: Pass arguments to executable in Python

description: Pass arguments to executable in Python


code: import main

rawDescription: Getting all hard-coded paths out of the code, how to handle the config file?


rawDescription: How do I just extract the second component of a Python array?

description: Just extract the second component of a Python array


code:
import numpy as np
from scipy import ndimage
from numpy.lib import stride_tricks

# pass in `as_strided` as a default arg to save a global lookup
def rotation_matrix2(section, _as_strided=stride_tricks.as_strided):
    section = section.reshape(5, 5)  # sqrt(section.size), sqrt(section.size)
    windows_shape = (3, 3, 3, 3)     # 5 - 3 + 1, 5 - 3 + 1, 3, 3
    windows_strides = section.strides + section.strides
    windows = _as_strided(section, windows_shape, windows_strides)
    rot_filters = windows.reshape(9, 9)
    return rot_filters[rot_filters.std(1).argmin(),:].mean()

def get_rotation_smooth(im, _rm=rotation_matrix2, **kwargs):
    return ndimage.filters.generic_filter(im, _rm, size=5, **kwargs)

if __name__ == '__main__':
    import matplotlib.pyplot as plt
    from scipy.misc import lena
    im = lena()
    im2 = get_rotation_smooth(im)
    #plt.gray()      # Uncomment these lines for
    #plt.imshow(im2) # demo purposes.
    #plt.show()

rawDescription: Optimizing implementation of a rotating mask in numpy/scipy


code: a, b, c = [lambda n=n: n*n for n in l]

rawDescription: Confused by lexical closure in list comprehension


code:
class BlogPostSerializer(serializer.ModelSerializer):
    # ....
    is_liked = serializers.BooleanField(source='is_liked')
    # ...

rawDescription: Django (django-rest-framework) looking for a best practice to find out wether request.user exists in blog.likes


code:
def browse():
    webbrowser.open("http://127.0.0.1:8080")
cherrypy.engine.subscribe('start', browse, priority=90)

rawDescription: Launching browser within CherryPy

description: Launching browser within CherryPy


code:
regex = re.compile(r'^([A-Z])(?!.?\1)([A-Z])(?!\2)([A-Z])[a-z]\1\1\3$')
regex.match('ABAaAAA')  # fails: first three are not different
regex.match('ABCaABC')  # fails: first two of second three are not first char
regex.match('ABCaAAB')  # fails: last char is not last of first three
regex.match('ABCaAAC')  # matches!

rawDescription: Multiple occurences of same character in a string regexp - Python


code:
print(bar is foo) # prints True
print(baz is foo) # prints True

rawDescription: How do I get the string representation of a variable in python?

description: Get the string representation of a variable in python


code:
# parent process is using select to wait for data on the pipes it set
# up to communicate with the child
readable_fds = select([child.stdout, child.stderr])

rawDescription: Python subprocess arbitrarily split output between files


code:
def purchase_possibilities(amounts, goal, current=None, highest=0, curr_sum=0, index=0, flag=None):
    # See if we are done.
    if flag is None:
        flag = [False]
    if  current is None:
        current = []

rawDescription: Determining if a recursion call has no solution


rawDescription: How to submit a javascript variable to the server side

description: Submit a javascript variable to the server side


code:
def writeFile(number):
    print(str(number))

for i in range(10):
    if not i:
        print('number')
    writeFile(i)

rawDescription: How to tell when a method is called for first time of many

description: Tell when a method is called for first time of many


code:
import sqlite3
from xlsxwriter.workbook import Workbook
workbook = Workbook('output2.xlsx')
worksheet = workbook.add_worksheet()

conn=sqlite3.connect('test.sqlite')
c=conn.cursor()
c.execute("select * from abc")
mysel=c.execute("select * from abc ")
for i, row in enumerate(mysel):
    for j, value in enumerate(row):
        worksheet.write(i, j, item)
workbook.close()

rawDescription: how to import data from SQLITE to excel using xlsxwriter in python

description: Import data from SQLITE to excel using xlsxwriter in python


code:
def calculate (i): pass #math goes here
#nested:
aggregateList = [[calculate(i) for i in range(iterates)] for _ in range(trials)]
#flat:
aggregateList = [x for trial in ([calculate(i) for i in range(iterates)] for _ in range(trials)) for x in trial]

rawDescription: Python Overwriting List Element

description: Python Overwriting List Element


code:
from ast import literal_eval
from pprint import pprint
import re

import requests

url = 'http://www.forecasts.org/data/data/PAYEMS.htm'
with requests.Session() as session:
    response = session.get(url)

    pattern = re.compile(r"data = google\.visualization\.arrayToDataTable\((.*?)\);", re.MULTILINE | re.DOTALL)
    data = pattern.search(response.content).group(1)

    data = literal_eval(data)
    pprint(data)

rawDescription: Scrape arraytodatatable with python

description: Scrape arraytodatatable with python


code:
ax = sns.tsplot(sines);                      # capture axis
n = len(ax.xaxis.get_ticklabels())           # count labels
ax.set_xticklabels(np.linspace(-15, 15, n))  # set new tick labels

rawDescription: Seaborn tsplot change labels on x-axis

description: Seaborn tsplot change labels on x-axis


code:
class w(v):
  def visit_Load(self, node): pass

rawDescription: Simple example of how to use ast.NodeVisitor?


code:
from urlparse import urlparse
from functools import wraps
from flask import (
    Flask,
    redirect,
    request,
    render_template_string,
    url_for)
app = Flask(__name__)

def confirm_referrer(paths, redirect_func):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            ref = urlparse(request.referrer or '')
            if any((request.host, path) == (ref.netloc, ref.path)
                   for path in paths):
                return f(*args, **kw)
            return redirect(url_for(redirect_func))
        return wrapper
    return decorator

@app.route('/map')
def map():
    return render_template_string('''

Demonstrate

        ''')

@app.route('/map_ru')
def map_ru():
    return render_template_string(u'''

\u0434\u0435\u043c\u043e\u043d\u0441\u0442\u0440\u0438\u0440\u043e\u0432\u0430\u0442\u044c

        ''')

@app.route('/demo')
@confirm_referrer(['/map', '/map_ru'], 'map')
def demo():
    return '''
This is a demonstration
'''

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

rawDescription: User Must Take Action for Page Redirection to Work in Flask


code:
import fileinput
import sys
import re

def convert(paths):
    for line in fileinput.input(paths, inplace=True, backup='~'):
        line=re.sub(r'#\s*print\s*(.*)',r'logging.debug(\1)',line)
        sys.stdout.write(line)

if __name__=='__main__':
    convert(sys.argv[1:])

rawDescription: Convert commented out print statements to logging calls - Python


rawDescription: Adding Values to an Array and getting distinct values using Python


code:
a = "this"
a = a + "that"

rawDescription: Why is there no insert() method for strings in Python?


code: l = [(e[0]+xk, e[1]+yk) for e in l]

rawDescription: Adding a constant tuple value to a list of tuples


code:
prompt = u"Want to post in %s?(Y/N) " % i['name']
check = raw_input(prompt.encode(sys.stdout.encoding))

rawDescription: Print non-ascii text in Python

description: Print non-ascii text in Python


code:
kolkata_datetime = localized_datetime.astimezone(kolkata)
print(kolkata_datetime)
# 1970-01-01 05:30:00+05:30

rawDescription: How to add two offset in python?

description: Add two offset in python


code: days = getAnswer()

rawDescription: Python <function functionName at 0x00000000>


code:
from tkinter import *
gui = Tk()
Label = "hello"
Label1 = Label(gui, text=Label)

# Traceback (most recent call last):
#   File "stackoverflow.py", line 98, in <module>
#     Label1 = Label(gui, text=Label)
# TypeError: 'str' object is not callable

rawDescription: Tkinter importing without *?

description: Tkinter importing without *


code: pool = mp.Pool(processes=1)

rawDescription: Write data to disk in Python as a background process


code:
import binascii
binascii.hexlify(myhash.digest())
binascii.hexlify(myhash.digest()).decode('ascii')

rawDescription: Checking SHA1 on a String

description: Checking SHA1 on a String


rawDescription: How to test membership of sequence in python list?

description: Test membership of sequence in python list


code:
df['hour'] = df.interval // 100
df['mins'] = df.interval.apply(lambda interval: interval % 100)

rawDescription: Pandas: Convert time interval integers to times


code: {column_index: function_to_apply}

rawDescription: categorical variables with pandas

description: Categorical variables with pandas


code:
with open(my_file) as f:
    for line in f:
        if 'beer' in line:
            print("found beer")

rawDescription: Searching for substrings in file.readlines() in python


rawDescription: Split encrypted string and xor it with a shorter string at every point


code:
from scrapy import Spider

class Foo(Spider):
    # start urls executed at the beginning
    # with default callback "parse"
    start_urls = ["https://en.wikipedia.org/wiki/Main_Page"]
    name = "basic_spider"

    def parse(self, response):
        # use css or xpath selectors to extract text
        print(response.css("::text").extract())

rawDescription: Extraxt & save all text() with Scrapy

description: Extraxt & save all text() with Scrapy


rawDescription: Mask zero values from pandas plot

description: Mask zero values from pandas plot


code:
holidays = [...]  # dates
rng = [d for d in rng if d not in holidays]

rawDescription: Pandas create an intraday DateTimeIndex between 2 times each day excluding weekends and holidays


code: return a, b

rawDescription: Is there any way to map on arrays, and return an array in Python?


code:
import requests

auth = ('someusername', 'somepassword')
response = requests.get(yoururl, auth=auth)
response.raise_for_status()

rawDescription: Check if a https webpage exists in python


code:
class BasePlayer(object):
    def __init__(self, nm, am, wp, ht, tp, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.type = tp
        self.id = ide

    def __str__(self):
        values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "I am a: " + self.type + "\n" + "ID #: " + str(self.id)
        return values

rawDescription: Creating methods with the same attributes


rawDescription: numpy genfromtxt issues in Python3

description: Numpy genfromtxt issues in Python3


code:
region_point = np.argsort(vor.point_region)
points = region_point[regions-1]

rawDescription: voronoi and lloyd relaxation using python/scipy

description: Voronoi and lloyd relaxation using python/scipy


code:
def setup(n1=10000, n2=1000, n3=20, seed=None):

    gen = np.random.RandomState(seed)
    kpt_list = gen.randn(n1, n3).astype(np.float)
    rpt_list = gen.randn(n2, n3).astype(np.float)
    h_r = (gen.randn(n3, n3,n2) + 1j*gen.randn(n3, n3,n2)).astype(np.complex)
    r_ndegen = gen.randn(1000).astype(np.float)

    return kpt_list, rpt_list, h_r, r_ndegen

def original_vec(*args, **kwargs):

    kpt_list, rpt_list, h_r, r_ndegen = setup(*args, **kwargs)

    r_ndegen_tile = np.tile(r_ndegen.reshape(1000, 1), 10000)
    phase = np.exp(1j * np.dot(rpt_list, kpt_list.T)) / r_ndegen_tile
    kpt_data = h_r.dot(phase)

    return kpt_data

def original_loop(*args, **kwargs):

    kpt_list, rpt_list, h_r, r_ndegen = setup(*args, **kwargs)

    kpt_data = np.zeros((20, 20, 10000), dtype='complex')
    for i in range(10000):
        kpt = kpt_list[i, :]
        phase = np.exp(1j * np.dot(kpt, rpt_list.T)) / r_ndegen
        kpt_data[:, :, i] = h_r.dot(phase)

    return kpt_data

rawDescription: performance loss after vectorization in numpy

description: Performance loss after vectorization in numpy


code:
from flask import render_template

@app.route('/')
def hello():
    return render_template('hello.html')

rawDescription: Form Handling Using Flask

description: Form Handling Using Flask


code:
def __lt__(self, other):
    return cmp(self.number, other.number) < 0

rawDescription: sorting list of objects python

description: Sorting list of objects python


code: q = [ [ None for i in range(5) ] for j in range(4) ]

rawDescription: Assign value to an individual cell in a two dimensional python array


rawDescription: Split one level of an multi index into columns


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

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


code:
df['newcol'] = (df[cols] == 'r').any(axis=1)
df

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

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


code: result = df[['Sex', 'Survived', 'Age']]

rawDescription: Write to_csv with Python Pandas: Choose which column index to insert new data


rawDescription: python: Replace/substitute all whole-word match in a string

description: Python: Replace/substitute all whole-word match in a string


code:
from operator import itemgetter

sorted(data, key=itemgetter(3))

rawDescription: Built-in sorted() function in Python

description: Built-in sorted() function in Python


rawDescription: Sending ICQ messages from outside event handlers in Twisted, Oscar


code:
import time

class A(object):
    def __init__(self):
        self.n_f = self.n_g = 0

    @cached_property(0.1)
    def f(self):
        self.n_f += 1
        print('calling f', self.n_f)
        return self.n_f

    @cached_property(0.5)
    def g(self):
        self.n_g += 1
        print('calling g', self.n_g)
        return self.n_g

a = A()
print('f', a.f)
print('g', a.g)
print('f', a.f)
print('g', a.g)
print('sleep 0.2')
time.sleep(0.2)
print('f', a.f)
print('g', a.g)
print('sleep 0.4')
time.sleep(0.4)
print('f', a.f)
print('g', a.g)

rawDescription: How can I cache API data in a class attribute?

description: Cache API data in a class attribute


code:
if actNum == act_num and pinNum == pin_num:
    ...
    self.controller.show_frame(WelcomePage)
    ...

rawDescription: Python Tkinter GUI Frame: How to call a class method from inside a function of another class?


code: ship_to = relation('Address', ...)

rawDescription: sqlalchemy - multiple files - relationships

description: Sqlalchemy - multiple files - relationships


code:
if request.method == 'POST':
    formset = HourFormSet(request.POST)

    if formset.is_valid():
        instances = formset.save(commit=False)  # This will return unsaved Hour objects
        for instance in instances:
            instance.user = request.user        # Add the logged in user
            instance.save()
        return index(request)

formset = HourFormSet(queryset=Hour.objects.none())
context_dict = {'formset': formset}
return render_to_response('add_hours.html', context_dict, context)

rawDescription: Django Formset: Passing a parameter in each form instance


code:
X=hdfpivot.columns.levels[1].values
Y=hdfpivot.index.values
Z=hdfpivot.values
Xi,Yi = np.meshgrid(X, Y)
plt.contourf(Yi, Xi, Z, alpha=0.7, cmap=plt.cm.jet);

rawDescription: Create Contour Plot from Pandas Groupby Dataframe


code:
df['id'] = df['Store'].astype(str) +'_' +df['Dept'].astype(str) +'_'+df['Date']
df

rawDescription: Python Pandas operate on row

description: Python Pandas operate on row


code:
def del_for(mylist):
    for i in reversed(mylist):
        if not i:
            del mylist[-1]
        else:
            break

rawDescription: Remove all trailing zeroes in Python list


code:
b = soup.new_tag('b')
b.append('SEPARATOR')
soup.original_1.body.append(b)
for element in soup_original_2.body:
    soup_original_1.body.append(element)

rawDescription: How to concatenate two html file bodies with BeautifulSoup?

description: Concatenate two html file bodies with BeautifulSoup


rawDescription: How should I share a variable across different classes?


code: print(testOne, testTwo, testThree, finalExam) #will replace with values

rawDescription: Calculate final letter grade in Python given 4 test scores


code: pyplot.title("Spam and Ham")

rawDescription: Matplotlib Xticklabels not working

description: Matplotlib Xticklabels not working


rawDescription: Best way to aggregate a simple dict in Python

description: Aggregate a simple dict in Python


code:
data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]
j = dumps(data, cls=PythonObjectEncoder)
loads(j, object_hook=as_python_object)

rawDescription: Python sets are not json serializable

description: Python sets are not json serializable


code:
from django.forms import TextInput, Textarea
from django.db import models

rawDescription: Resize fields in Django Admin

description: Resize fields in Django Admin


code:
for i in range(len(l)):
    print(list(itertools.product(*l[:i+1])))

rawDescription: How to pull all the unique combinations from a list of lists

description: Pull all the unique combinations from a list of lists


code:
mask = (df.time-df.time.shift()) == np.timedelta64(0,'s')
mask

rawDescription: Python pandas change duplicate timestamp to unique


code:
samples=['aba', 'xyz','aa', 'x', 'bbb']
for elem in samples:
    if (len(elem) >=2 and elem.endswith(elem[0])):
        print(elem)

rawDescription: python list elements start with and end with same character

description: Python list elements start with and end with same character


code:
def concat_copy(a, b):
        new = a.copy()

        # find the end of the copy
        last = new
        while last.next is not None:
            last = last.next
        # append a copy of the other list
        last.next = b.copy()

rawDescription: Python copy and concatenate linked lists, preserve order


code:
@decorator_expression
def function_definition():
    pass

rawDescription: How would one decorate an inherited method in the child class?


rawDescription: Adding another column to a CSV file w/ python


code:
from scipy.interpolate import Akima1DInterpolator

x1, y1 = np.arange(13), np.random.randint(-10, 10, 13)
x2, y2 = [0,2,3,6,12], [100,50,30,18,14]
x3, y3 = [4, 6, 8], [60, 80, 40]

akima1 = Akima1DInterpolator(x1, y1)
akima2 = Akima1DInterpolator(x2, y2)
akima3 = Akima1DInterpolator(x3, y3)

x1_new = np.linspace(min(x1), max(x1), 1000)
x2_new = np.linspace(min(x2), max(x2), 1000)
x3_new = np.linspace(min(x3), max(x3), 1000)

plt.plot(x1, y1, 'bo')
plt.plot(x2, y2, 'go')
plt.plot(x3, y3, 'ro')
plt.plot(x1_new, akima1(x1_new), 'b', label='random points')
plt.plot(x2_new, akima2(x2_new), 'g', label='exponential')
plt.plot(x3_new, akima3(x3_new), 'r', label='3 points')
plt.xlim(-1, 15)
plt.ylim(-10, 110)
plt.legend(loc='best')

rawDescription: Emulating Excel's "scatter with smooth curve" spline function in Matplotlib for 3 points


rawDescription: Getting method parameter names in python


code:
class molecule_iterator(object):
    def __init__(self, obj):
        self.pointer = 0
        self.obj = obj

    def __next__(self):
        self.pointer += 1  # Are you sure to do this here?
        if self.pointer < self.obj.natoms:
            return self.obj[self.pointer]
        raise StopIteration()

class molecule(object):
    ...

    def __iter__(self):
        return molecule_iterator(self)

    ...

rawDescription: Define a iterable class supporting two or more simultaneous iterating


code:
class MyStr(str):
    def change(self):
        result=""
        for index,item in enumerate(self):
            if(index%2 !=0): result=result+item
        return(result)
x = MyStr("hallo world")
x
x.change()
'change' in dir(x)

rawDescription: How to add my own method to the built-in str type?

description: Add my own method to the built-in str type


code: s

rawDescription: extract a str contained between 2 str

description: Extract a str contained between 2 str


code:
def ints_to_ranges(l):
    if not l: return ""

    l = sorted(set(int(n) for n in l))
    ranges = [[l[0], l[0]]]

    for n in l[1:]:
       if n - 1 == ranges[-1][1]:
           ranges[-1][1] += 1
       else:
           ranges.append([n, n])

    return ",".join(r[0] == r[1] and str(r[0]) or "{}-{}".format(*r) for r in ranges)

rawDescription: merge number by using "-" (python)

description: Merge number by using "-" (python)


code:
Module(
    body=[
        Expr(
            value=Call(
                func=Name(id='evaluate', ctx=Load()), args=[
                    Lambda(
                        args=arguments(
                            args=[
                                Name(id='x', ctx=Param())
                            ],
                            vararg=None,
                            kwarg=None,
                            defaults=[]
                        ),
                        body=BoolOp(
                            op=And(),
                            values=[
                                Compare(
                                    left=Name(id='x', ctx=Load()),
                                    ops=[Lt()],
                                    comparators=[Num(n=5)]
                                ),
                                Compare(
                                    left=Name(id='x', ctx=Load()),
                                    ops=[Gt()],
                                    comparators=[Num(n=-5)]
                                )
                            ]
                        )
                    )
                ],
                keywords=[],
                starargs=None,
                kwargs=None
            )
        )
    ]
)

rawDescription: Defining new semantics for expressions in Python


code:
import os
import cv
with open('textFileOfImages.txt','rb') as f:
    img = ['%s/%s'%(os.getcwd(),line.strip()) for line in f]

rawDescription: Loading multiple images from a text file


code:
from itertools import product
list(product(range(1, 10), repeat=2))

rawDescription: Iterate list of numbers

description: Iterate list of numbers


code:
def create_graph(G,nodes,Sets):
    G.add_edges_from(nodes)

    #value assigned to each world
    custom_labels={}
    custom_node_sizes={}
    node_colours=['y']

    for i in range(0, len(Sets)):
        custom_labels[i+1] = Sets[i]
        custom_node_sizes[i+1] = 5000
        if i < len(Sets):
            node_colours.append('b')
    nx.draw(G,node_list = nodes,node_color=node_colours, node_size=1000, with_labels = True)
    plt.savefig("original_graph.png")
    plt.show()
    G_comp = nx.weakly_connected_component_subgraphs(G)
    i =  1
    for comp in G_comp:
        nx.draw(comp,node_color=node_colours,  node_size=1000, with_labels=True)
        #show with custom labels
        fig_name = "graph" + str(i) + ".png"
        plt.savefig(fig_name)
        plt.show()
        i += 1

Edges2 = [(1, 2), (1, 3), (1, 4), (4, 5), (6, 7), (6,8)]
G = nx.DiGraph()
create_graph(G,Edges2,Edges2)

rawDescription: python networkx- save disconnected graphs from single figure into separate files

description: Python networkx- save disconnected graphs from single figure into separate files


code:
my_name = 'Alexander'

for l in my_name:
    if l.lower() in ["a", "e", "i", "o", "u"]: #str.lower() is to check regardless of capitalization
        print("give me an " + l + " !")
    else:
        print('give me a '+l +" !")

rawDescription: Code not working properly

description: Code not working properly


rawDescription: Reconstruct dictionary in python

description: Reconstruct dictionary in python


rawDescription: Convert XML to string to find length

description: Convert XML to string to find length


code: from numpy import NA as NA

rawDescription: Improving performance of operations on a NumPy array


code:
import re
re.my_compile = re.compile
re.compile = lambda pattern, flags: re.my_compile(pattern, flags | re.DOTALL)

rawDescription: Using a global flag for python RegExp compile


code:
df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
df.fillna(method='ffill')

rawDescription: How to replace NaNs by preceding values in pandas DataFrame?

description: Replace NaNs by preceding values in pandas DataFrame


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


code:
import re

m = re.match("^testing", "ptesting_kip-win332")
if m != None:
     print ("Uninstalling" + product.Name + "...")
     result = product.Uninstall()

rawDescription: How to specify python regular expression that starts with "testing" without declaring the content variable?

description: Specify python regular expression that starts with "testing" without declaring the content variable


code:
import copy

class Foo(object):
    def __init__(self, val):
         self.val = val

    def __repr__(self):
        return str(self.val)

foo = Foo(1)

a = ['foo', foo]
b = a[:]
c = list(a)
d = copy.copy(a)
e = copy.deepcopy(a)

# edit orignal list and instance
a.append('baz')
foo.val = 5

print('original: %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r'
      % (a, b, c, d, e))

rawDescription: How to clone or copy a list in Python?

description: Clone or copy a list in Python


code:
from tornado.ioloop import IOLoop
import sys

def on_stdin(fd, events):
    line = fd.readline()
    print("received: %s" % repr(line))
    if line == '':
        print('stdin ctr+d')
        sys.exit()

if __name__ == "__main__":
    IOLoop.instance().add_handler(sys.stdin, on_stdin, IOLoop.READ)
    IOLoop.instance().start()

rawDescription: How to listen for event of closed stdin in a tornado loop?

description: Listen for event of closed stdin in a tornado loop


rawDescription: How can I implement a function that reduces a list to the minimum set of elements that are repeated in the list?

description: Implement a function that reduces a list to the minimum set of elements that are repeated in the list


code:
def convert(items, id):
    new_dict = items.copy()
    for key, value in items.items():
        if key in id:
            new_key = id[key]
            new_dict[new_key] = items[key] # Copy the value
            del new_dict[key]
    return new_dict

rawDescription: Python looping over dictionary to substitute keys with the values from another dictionary


code:
from weakref import WeakKeyDictionary

def cached_resource(method_to_cache):
    cache = WeakKeyDictionary()
    def decorator(self, *args, **kwargs):
        try:
            return cache[self]
        except KeyError:
            result = cache[self] = method_to_cache(self, *args, **kwargs)
        return result
    return decorator

class Profile(BeautifulSoup):
    def __init__(self, page_source):
        super().__init__(page_source)
        self._cache = {}

    @cached_resource
    def username(self):
        return self.title.split(':')[0]

rawDescription: Is it okay for decorators to access private members of a class?


code: item = relationship(ITEM, backref='attribute', uselist=False)

rawDescription: How to store and search list in SQLAlchemy?

description: Store and search list in SQLAlchemy


rawDescription: Can API hooking in python be OS agnostic?


rawDescription: Call GUID function more than once in print formatting in python


rawDescription: Collecting like term of an expression in Sympy


code:
def SetHP(self, hpPercentage, curHP, maxHP):
    if not self.hpGauge.IsShow():
        self.SetSize(200 + 7*self.nameLength, 70)
        self.hpGauge.Show()
        self.UpdatePosition()
    self.hpGauge.SetPercentage(hpPercentage, 100)

    strCurHP = str(curHP)
    strMaxHP = str(maxHP)

    newCurHP = strCurHP[0] + ',' + strCurHP [1] + 'K'
    newMaxHP = strMaxHP[0] + strMaxHP[1] + ',' + strMaxHP[2]  + 'K'

    self.broadCastHP.SetText(newCurHP + " / " + newMaxHP)

rawDescription: Python comma and divide an integer

description: Python comma and divide an integer


code:
import string

def caesar_cipher(msg, shift):
    # create a character-translation table
    trans = dict(zip(string.lowercase, string.lowercase[shift:] + string.lowercase[:shift]))
    trans.update(zip(string.uppercase, string.uppercase[shift:] + string.uppercase[:shift]))

    # apply it to the message string
    return ''.join(trans.get(ch, ch) for ch in msg)

rawDescription: How do I make python encrypt both uppercase and lowercase?

description: Make python encrypt both uppercase and lowercase


code:
def bin_to_float(b):
    return struct.unpack('<d', struct.pack('<Q', int(b, 2)))[0]

def float_to_bin(f):
    return '{:b}'.format(struct.unpack('<Q', struct.pack('<d', f))[0])

rawDescription: python struct "unpack requires a bytes object of length 8" while converting binay to float

description: Python struct "unpack requires a bytes object of length 8" while converting binay to float


rawDescription: Extract two dates, result in seconds (pandas)


rawDescription: Selecting Subset of Pandas DataFrame

description: Selecting Subset of Pandas DataFrame


code:
s="aaabbbbccdaeeee"
from collections import Counter
Counter(s)

rawDescription: Splitting a string into consecutive counts?


code:
from pyquery import PyQuery as pq

html = '''

 Tormented Soul 2 2 Common M13 111/249 9 Tormented Soul can't block and is unblockable.

 Veilborn Ghoul 2 2 Uncommon M13 114/249 09 Veilborn Ghoul can't b|ock.Whenever a Swamp enters the battlefield under your control, you may return Veilborn GI

'''
d = pq(html)

rawDescription: Find words in a file then grab the x,y coordinates next to the text


code:
class Replacer(object):
    def __call__(self, match):
        group = match.group(0)

        if group[1:].lower().endswith('_nm'):
            return '(?:' + Matcher(group).regex[1:]
        else:
            return '(?P<' + group[1:] + '>' + Matcher(group).regex[1:]

rawDescription: Processing malformed text data with machine learning or NLP


code: p_script, p_user_name, p_id = argv

rawDescription: python - parameters declaration ordering

description: Python - parameters declaration ordering


code:
from lxml import etree
import re

# Parse the XML and find the root
with open('input.xml') as input_file:
    tree = etree.parse(input_file)
root = tree.getroot()

# Find the list to sort and sort it
some_arbitrary_expression_to_find_the_list = '.'
element_list = tree.xpath(some_arbitrary_expression_to_find_the_list)[0]

predefined_order = [
    'Protocol',
    'StudyEventDef',
    'FormDef',
    'ItemGroupDef',
    'ItemGroupData',
    'ItemDef',
    'CodeList',
    'ClinicalData']
filter = re.compile(r'Element(.*)at0x.*')

element_list[:] = sorted(
    element_list[:],
    key = lambda x: predefined_order.index(filter.match(x.tag).group(1)))

# Write the XML to the output file
with open('output.xml', 'w') as output_file:
    output_file.write(etree.tostring(tree, pretty_print = True))

rawDescription: python lxml write to file in predefined order

description: Python lxml write to file in predefined order


code:
import example
assert(example.func(type("test")) == -1)
assert(example.func(example.A) == 0)
assert(example.func(example.B) == 1)
assert(example.isSubclassA(example.A))
assert(example.isSubclassA(example.B))
assert(not example.isSubclassA(example.C))
assert(example.func("test") == -1)
assert(example.func(example.A()) == 0)
assert(example.func(example.B()) == 1)
assert(example.isSubclassA(example.A()))
assert(example.isSubclassA(example.B()))
assert(not example.isSubclassA(example.C()))

rawDescription: Pass a type object (class, not an instance) from python to c++


code:
import csv

reader = csv.reader(open("file.csv", "r"), delimiter=',')
print([line for line in reader if 'DEFAULT' not in line])

rawDescription: How do I put lines into a list from CSV using python

description: Put lines into a list from CSV using python


code:
def f(foo):
    print(foo)
    foo += 1
    return foo

foo = f(23)
print(foo)

rawDescription: Use a Variable in a Function Without Passing as an Argument


code:
class Base(object):
    @classmethod
    def new(cls):
        print("Base.new(%r)" % (cls,))
        return cls()

class UseSuper(Base):
    @classmethod
    def new(cls):
        print("UseSuper.new(%r)" % (cls,))
        return super(UseSuper, cls).new() # passes cls as the first arg

class NoSuper(Base):
    @classmethod
    def new(cls):
        print("NoSuper.new(%r)" % (cls,))
        return Base.new()  # passes Base as the first arg

class UseFunc(Base):
    @classmethod
    def new(cls):
        print("UseFunc.new(%r)" % (cls,))
        return Base.new.im_func(cls)  # or `.__func__(cls)`. # passes cls as the first arg

print(UseSuper.new())
print('-'*60)
print(NoSuper.new())
print('-'*60)
print(UseFunc.new())

rawDescription: Why isn't __new__ in Python new-style classes a class method?


code:
import subprocess

cmd = []
cmd.append(r'C:\Program Files\7-Zip\7z.exe')
cmd.append('x')
cmd.append(archive)
cmd.append('-aoa')
cmd.append('-o{}'.format(dst_part))
cmd.append(file_folder_filter)
subprocess.call(cmd)

rawDescription: Command line for 7z to extract specific files from specific folders inside an archive.


rawDescription: Reusing a list in a new function

description: Reusing a list in a new function


rawDescription: SqlAlchemy - Filtering by field defined as a ForeignKey


code:
pattern2 = '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.com'

re.findall(pattern2, "My email is abc@hotmail.com and your email is abcdef_23@gmail.com")

rawDescription: pulling from file in a certain format python

description: Pulling from file in a certain format python


code:
from __future__ import print_function
import timeit
import random
import collections

def f1():
    d={}
    for x in tgt:
        if x in d:
            d[x]+=1
        else:
            d[x]=1
    return d

def f2():
    d = {}
    for x in tgt:
        try:
            d[x]+=1
        except KeyError:
            d[x] = 1
    return d

def f3():
    d={}.fromkeys(tgt, 0)
    for x in tgt:
        d[x]+=1
    return d

def f4():
    d=collections.defaultdict(int)
    for x in tgt:
        d[x]+=1
    return d

def f5():
    return collections.Counter(tgt)

def f6():
    d={}
    for x in tgt:
        d[x]=d.setdefault(x, 0)+1
    return d

def f7():
    d={}
    for x in tgt:
        d[x]=d.get(x,0)+1
    return d

def cmpthese(funcs, c=10000, rate=True, micro=False):
    """Generate a Perl style function benchmark"""
    def pprint_table(table):
        """Perl style table output"""
        def format_field(field, fmt='{:,.0f}'):
            if type(field) is str: return field
            if type(field) is tuple: return field[1].format(field[0])
            return fmt.format(field)

        def get_max_col_w(table, index):
            return max([len(format_field(row[index])) for row in table])

        col_paddings=[get_max_col_w(table, i) for i in range(len(table[0]))]
        for i,row in enumerate(table):
            # left col
            row_tab=[row[0].ljust(col_paddings[0])]
            # rest of the cols
            row_tab+=[format_field(row[j]).rjust(col_paddings[j]) for j in range(1,len(row))]
            print(' '.join(row_tab))

    results={k.__name__:timeit.Timer(k).timeit(c) for k in funcs}
    fastest=sorted(results,key=results.get, reverse=True)
    table=[['']]
    if rate: table[0].append('rate/sec')
    if micro: table[0].append('usec/pass')
    table[0].extend(fastest)
    for e in fastest:
        tmp=[e]
        if rate:
            tmp.append('{:,}'.format(int(round(float(c)/results[e]))))

        if micro:
            tmp.append('{:.3f}'.format(1000000*results[e]/float(c)))

        for x in fastest:
            if x==e: tmp.append('--')
            else: tmp.append('{:.1%}'.format((results[x]-results[e])/results[e]))
        table.append(tmp)

    pprint_table(table)

if __name__=='__main__':
    import sys
    print(sys.version)
    for j in [100,1000]:
        for t in [(0,5), (0,50), (0,500)]:
            tgt=[random.randint(*t) for i in range(j)]
            print('{} rand ints between {}:'.format(j,t))
            print('=====')
            cmpthese([f1,f2,f3,f4,f5,f6,f7])
            print()

rawDescription: Python: is "Except keyerror" faster than "if key in dict"?


rawDescription: Rotating images using PHP and jQuery the fast way


code:
import random
random.choice([p for p in itertools.product(x, repeat=2)])
(6, 3)

rawDescription: generating permutations with repetitions in python

description: Generating permutations with repetitions in python


code:
from datetime import tzinfo, timedelta

class FixedOffset(tzinfo):
    """Fixed offset in minutes east from UTC."""

    def __init__(self, offset, name):
        self.__offset = timedelta(minutes = offset)
        self.__name = name

    def utcoffset(self, dt):
        return self.__offset

    def tzname(self, dt):
        return self.__name

    def dst(self, dt):
        return timedelta(0)

rawDescription: Get tz offset from sting

description: Get tz offset from sting


code:
kwargs = {'predicted_value':F('actual_value')}
Model.objects.filter(**kwargs)

rawDescription: How to compare 2 columns of a table through dynamic querying

description: Compare 2 columns of a table through dynamic querying


code:
product = Product.objects.get(name='Cactus')
price = product.pricing_set.get(currency__name='USD')

rawDescription: How to associate some value in model with ForeignKey?

description: Associate some value in model with ForeignKey


code:
p.stdin.write('104\n')
time.sleep(5)
p.stdin.write('q\n')
p.wait()

rawDescription: Running .exe files with user arguments in python


code:
def foo(request):

    # If I want to do something with the search query, I can access it with
    # request.GET['search_query']

    return HttpResponse()

rawDescription: Pass <input> value to Django view

description: Pass <input> value to Django view


code:
values = [item.slug]
values += str(item.title).ljust(25).split(" ", 1)
values.append(item.date.ljust(10))
content += '%s %s  %s' % values

rawDescription: Python Not Web Linking Entire variable in str.ljust


rawDescription: How to decode a 'url-encoded' string in python

description: Decode a 'url-encoded' string in python


code:
size_of_group = 5
all_states = State.objects.order_by('-population')
grouped_states = [all_states[i:i + size_of_group] for i in xrange(0, len(all_states), size_of_group)]

rawDescription: Grouping Django Model Instances

description: Grouping Django Model Instances


code:
import xml.etree.ElementTree as ET
npdoc_uri = 'http://www.example.com/npdoc/2.1'
nsmap = {
    'npexchange': 'http://www.example.com/npexchange/3.5',
    'npdoc': npdoc_uri
    }
ET.register_namespace("", npdoc_uri)
tree = ET.parse(r'/home/gord/Desktop/nasty.xml')
npexchange = tree.getroot()
for article in npexchange.findall('npexchange:article', nsmap):
    for articleparts in article.findall('npexchange:articleparts', nsmap):
        for articlepart in articleparts.findall('npexchange:articlepart', nsmap):
            id = articlepart.attrib['id']
            print("ArticlePart - id: {0}".format(id))
            for data in articlepart.findall('npexchange:data', nsmap):
                for npdoc in data.findall('npdoc:npdoc', nsmap):
                    for child in npdoc.getchildren():
                        tag = child.tag[child.tag.find('}')+1:]
                        print("    {0}:".format(tag))  ## e.g., "body:"
                        contents = ET.tostring(child).decode('utf-8')
                        # remove HTML block tags, e.g. <body ...> and </body>
                        contents = contents.replace('<' + tag + ' xmlns="' + npdoc_uri + '">\n', '')
                        contents = contents.replace('</' + tag + '>', '')
                        contents = contents.strip()
                        print("        {0}".format(contents))

rawDescription: Parsing a complicated XML file with Python


rawDescription: Running Java Application using Popen

description: Running Java Application using Popen


code:
from itertools import count
from collections import defaultdict, Counter

counters = defaultdict(lambda: count(1))
tally = Counter(inputlist)

result = [(n, next(counters[n])) if tally[n] > 1 else n for n in inputlist]

rawDescription: Find same elements in a list, and then change these elemens to tuple (f.e. 2 to (2,1))


code:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))

rawDescription: How to write LaTeX in IPython Notebook?

description: Write LaTeX in IPython Notebook


code:
import numpy as np

def orig(Kx, Ky, u, v, pk):
    M, N = Kx.shape
    X = u.size
    Y = v.size
    P = np.empty((X, Y), dtype=pk.dtype)
    for m in range(0, M):
        for n in range(0, N):
            for i in range(0,X):
                for j in range(0,Y):
                   Arg = Kx[m,n]*u[i] + Ky[m,n]*v[j]
                   P[i,j] += pk[m,n]*np.cos(Arg)
    return P

def alt(Kx, Ky, u, v, pk):
    Kxu = Kx[:,:,np.newaxis]*u
    Kyv = Ky[:,:,np.newaxis]*v
    Arg = Kxu[:,:,:,np.newaxis] + Kyv[:,:,np.newaxis,:]
    P = (pk[:,:,np.newaxis,np.newaxis]*np.cos(Arg)).sum(axis=0).sum(axis=0)
    return P

M, N = 10, 20
X, Y = 5, 15
Kx = np.random.random((M, N))
Ky = np.random.random((M, N))
u = np.random.random(X)
v = np.random.random(Y)
pk = np.random.random((M, N))

rawDescription: Numpy multiplication of vectors of different size avoiding for loops


code: return [YahooQuote._make(x) for x in csv.reader(csvfile)]

rawDescription: How do I add an ID attribute to each named tuple create from a CSV file?

description: Add an ID attribute to each named tuple create from a CSV file


code:
def read_pbm(fname):
    with open(fname) as f:
        data = [x for x in f if not x.startswith('#')] #remove comments
    p_whatever = data.pop(0)  #P4 ... don't know if that's important...
    dimensions = map(int,data.pop(0).split())
    arr = []
    col_number = 0
    for c in data.pop(0):
        integer = struct.unpack('B',c)[0]
        col_number += 8
        bits = map(int,bin(integer)[2:])
        arr.extend(bits[:min(8,dimensions[0]-col_number)])
        if(col_number > dimensions[0]):
            col_number = 0

    return (dimensions, arr)

rawDescription: Create binary PBM/PGM/PPM

description: Create binary PBM/PGM/PPM


rawDescription: How can I rotate this list of lists with python

description: Rotate this list of lists with python


code:
class MyClass(object):
    def __init__(self, val):
        self._returnVal = val
    def __repr__(self):
        return self._returnVal

rawDescription: Mimicking functionality of built-in types


rawDescription: Change Marker Style/Color in Python Probplot


code:
for k,v  in model_dict.items():
       if server_dict.get(k,object()) != v:
            print(k,v)

rawDescription: Python: Compare two identical dictionaries by key, value


code:
import numpy as np
a = np.arange(2, 3, 0.1)
a
np.ceil(a)

rawDescription: Applying math.ceil to an array in python


code: s = '"this is", "a test", "of the csv", "parser"'

rawDescription: Parse a single CSV string?

description: Parse a single CSV string


code: url(r'^baslik/(?P<title>.*)/$', views.baslik_handle, name = "tek_baslik")

rawDescription: Django create an object when enter its link


rawDescription: Replace the content in between using python regex


code:
content_item = re.compile('\d+\.?\d*? [^\n]*')
appendix_item = re.compile('Appendix[^\n]*|[ABC]\.[^\n]*')

# Indices to limit the contents search
content_start = re.search('\f\fContents', s).span()[1]
content_end = re.search('\f\fPreface', s).span()[0]

content_items = content_item.findall(s, content_start, content_end)
appendices = appendix_item.findall(s, content_start, content_end)

rawDescription: Extract section names and starting pages from a text file


rawDescription: How to offset random sine angles as a whole?

description: Offset random sine angles as a whole


code:
from __future__ import division  # If for some reason you use Python 2.x
import re
from collections import Counter

def count_words(doc, pattern=re.compile("\w+")):
    """Given a tuple (doc_id, text)
    return a tuple (doc_id, tokens_count

    >>> count_words((1, "Foo bar bar."))
    (1, Counter({'Foo': 1, 'bar': 2}))
    """
    (doc_id, text) = doc
    return (doc_id, Counter(pattern.findall(text)))

def compute_tf(cnt):
    """Convert term counter to term frequency

    >>> compute_tf(Counter({'Foo': 1, 'bar': 2}))
    {'Foo': 0.3333333333333333, 'bar': 0.6666666666666666}
    """
    n = sum(cnt.values())
    return {k: v / n for (k, v) in cnt.items()}

rawDescription: spark, small issue about reduceByKey

description: Spark, small issue about reduceByKey


code:
pcolor(D1)
contour(D2)

rawDescription: Combine multiple heatmaps in matplotlib

description: Combine multiple heatmaps in matplotlib


code:
def if_(expr, then, else_):
    return case([
        (expr, then)
    ], else_=else_)

rawDescription: How can I write conditional clauses using SQLAlchemy's expression language?

description: Write conditional clauses using SQLAlchemy's expression language


code: set(s) & d.keys()

rawDescription: How can I check if the characters in a string are in a dictionary of values?

description: Check if the characters in a string are in a dictionary of values


code:
learnkanji.py
class LayoutFunctioning(BoxLayout):
    keyb_height = NumericProperty(260)

rawDescription: Kivy class in .py and .kv interaction 2

description: Kivy class in .py and .kv interaction 2


code: duplicates = [files for files in file_dict.values() if len(files) > 1]

rawDescription: Finding duplicate files via hashlib?

description: Finding duplicate files via hashlib


code: sorted_list[pos - 1] > sorted_list[pos]

rawDescription: Sort a list using selection sort

description: Sort a list using selection sort


code:
func({
    API.arg1: 'foo',
    API.arg2: 'bar',
    DATA.arg1: 'foo1',
})

rawDescription: Magic assign for custom parameters

description: Magic assign for custom parameters


code:
wlist=[]
ftable=nltk.FreqDist (filtered_text)
wlist.append(ftable.keys () )

rawDescription: Fdist and top 10 function words

description: Fdist and top 10 function words


code: df_greater_10 = df.ix[df.ints >= 1997, ['commonName', 'ints']]

rawDescription: How do I create a DataFrame containing a column where rows are greater than a number?

description: Create a DataFrame containing a column where rows are greater than a number


code:
def square_of_average(x1, x2, x3):
    z = (x1 + x2 + x3) / 3
    return z ** 2 # This returns the square of the average

rawDescription: Random function with break command in Python


code:
class StatusDaemonRunner(runner.DaemonRunner):
    def __init__(self, app):
        self.action_funcs = runner.DaemonRunner.action_funcs.copy()
        self.action_funcs['status'] = StatusDaemonRunner._status
        super(StatusDaemonRunner, self).__init__(app)
    def _status(self):
        pass  # do your stuff

rawDescription: Override static member in DaemonRunner

description: Override static member in DaemonRunner


code:
from wand.image import Image
from wand.color import Color

with Image(filename="pic.png") as img:
  with Image(width=img.width, height=img.height, background=Color("white")) as bg:
    bg.composite(img,0,0)
    # -resize 300%
    scaler = 3
    bg.resize(img.width * scaler, img.height * scaler)
    bg.save(filename="pic2.png")

rawDescription: How to convert this command to a python code using Wand & ImageMagick

description: Convert this command to a python code using Wand & ImageMagick


code:
import regex
bigString = "AGAHKGHKHASNHADKRGHFKXXX_I_AM_THERE_XXXXXMHHGRFSAHGSKHASGKHGKHSKGHAK"
regex.search('(?:I_AM_HERE){e<=1}',bigString).group(0)

rawDescription: How to find a substring using partial matching

description: Find a substring using partial matching


code:
class MyModelForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['is_anonymous'].widget = forms.Select(choices=[
            (True, "Anonymous"),
            (False, user.username)
        ])

    class Meta:
        model = MyModel
        fields = ['is_anonymous']

rawDescription: request.user as a choice in select widget in Django

description: Request.user as a choice in select widget in Django


code:
b = [numpy.vstack((a.real.T[i], a.imag.T[i])) for i in range(a.shape[2])]
s = ' '.join(str(d) for x in b for d in x.flat)

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


rawDescription: Remove Outliers from dataset

description: Remove Outliers from dataset


code:
titlebar_label.bindtags(('.titlebar_label','Label', 'clickthru','.','all'))
titlebar.bind_class('clickthru', '<Button-1>', drag_window)

rawDescription: Click event through another widget?

description: Click event through another widget


code:
class UserDataModelForm(forms.ModelForm):
    class Meta:
      model = models.UserData
      exclude = ('owner',)

    def __init__(self, *args, **kwargs):
      self.request = kwargs.pop('request', None)
      super(ActionModelForm, self).__init__(*args, **kwargs)

    def save(self, force_insert=False, force_update=False, commit=True):
      obj = super(UserDataModelForm, self).save(commit=False)
      if obj:
          obj.owner = self.request.user
          obj.save()
      return obj

rawDescription: Object level permissions in Django admin


rawDescription: Python Xpath to find text() that contains @domain


code:
s = pd.Series(t2.index.get_level_values(1), t2.index.get_level_values(0))
s

rawDescription: Retrieve indices of NaN values in a pandas dataframe


code:
mission = missions.objects.order_by('?')[0]
crew = mission.crewmembers.all()

rawDescription: Reference multiple foreign keys in Django Model


code:
re.match(r'^cat\ndog',s).group(0)
re.match(r'^cat$\ndog',s).group(0)  #doesn't match
re.match(r'^cat$\ndog',s,re.M).group(0) #matches.

rawDescription: How to match a new line character in Python raw string

description: Match a new line character in Python raw string