code:
verbs = ["get",
         "put",
         "drop",
         "use",
         "enter",
         "leave",
         "walk",
         "search",
         "attack",
         "defend"]

nouns = ["journal",
         "magnifier",
         "glasses",
         "knife",
         "kite",
         "table",
         "chair",
         "key"]

inventory = ""

user_input = input("What would you like to do?\n")

#checking if there are a set of two instructions
action, obj = user_input.split()

if(action not in verbs):
    print("I did not understand the verb entered.")
    print("Please use:", ", ".join(verbs))
else:
    print("Recognized verb entered.")

    if(obj not in nouns):
        print("I did not understand the noun entered.")
        print("Please use:", ", ".join(nouns))
    else:
        print("Recognized noun entered.")

rawDescription: Why does my code not find a certain string that is present in an array?


code:
from twisted.web import server, resource
from twisted.internet import reactor
import os

# multi part encoding example: http://marianoiglesias.com.ar/python/file-uploading-with-multi-part-encoding-using-twisted/
class Simple(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        return "{0}".format(request.args.keys())
    def render_POST(self, request):
        with open(request.args['filename'][0], 'wb') as fd:
            fd.write(request.content.read())
        request.setHeader('Content-Length', os.stat(request.args['filename'][0]).st_size)
        with open(request.args['filename'][0], 'rb') as fd:
            request.write(fd.read())
        request.finish()
        return server.NOT_DONE_YET

site = server.Site(Simple())
reactor.listenTCP(8080, site)
reactor.run()

rawDescription: twisted get body of POST request

description: Twisted get body of POST request


code:
if __name__ == "__main__":

    doc = MyDocTemplate(
        'filename.pdf',
        pagesize=A4,
        rightMargin=.3*inch,
        leftMargin=.3*inch,
        topMargin=.3*inch,
        bottomMargin=.3*inch
    )

    elements = [
        # Put your actual elements/flowables here, however you're generating them.
    ]

    doc.addPageTemplates([
        # Add your PageTemplates here if you have any, which you should!
    ])

    # Build your doc with your elements and go grab a beer
    doc.build(elements)

rawDescription: Conditional page break in reportlab

description: Conditional page break in reportlab


code:
i = c_int(4)
ci = CDataObject.from_address(id(i))
ci
addressof(i)
id(i) + CDataObject.b_value.offset

rawDescription: What is the difference between id(obj) and ctypes.addressof(obj) in CPython


code: sum(rate[g] * amount[g] for g in range(len(rate))) / sum(amount)

rawDescription: Python - Weighted averaging a list

description: Python - Weighted averaging a list


rawDescription: Referring to the first element of all tuples in a list of tuples


code:
address.find("br").replaceWith(",")
addressComponents = address.text.split(",")

rawDescription: Python - read BeautifulSoup snippet by row? (or other ways of scraping the data I want)


code:
from collections import defaultdict
d = defaultdict(list)
for line in open('filename.txt'):
    tokens = line.split()
    d[tuple(tokens[:3])].extend(tokens[3:])

for k in sorted(d.keys()):
    v = d[k]
    print('{}\t{}\t{}\t{}'.format(k[0],k[1],k[2],','.join(v)))

rawDescription: python: merge lines with common fields

description: Python: merge lines with common fields


code:
import math
import itertools
import multiprocessing
import functools

def smart_calc(valD1, valD2, valD3, valD4, valD5, valD6, valD7, slices):
    # Build an iterator over the entire data set
    prod = itertools.product(([x[1],x[2]] for x in valD1),
                             ([x[1],x[2]] for x in valD2),
                             ([x[1],x[2]] for x in valD3),
                             ([x[1],x[2]] for x in valD4),
                             ([x[1],x[2]] for x in valD5),
                             ([x[1],x[2]] for x in valD6),
                             ([x[1],x[2]] for x in valD7))

    # But only iterate over our unique slice
    for subD1, subD2, subD3, subD4, subD5, subD6, subD7 in itertools.islice(prod, slices[0], slices[1]):
        sol1=float(subD1[0]+subD2[0]+subD3[0]+subD4[0]+subD5[0]+subD6[0]+subD7[0])
        sol2=float(subD1[1]+subD2[1]+subD3[1]+subD4[1]+subD5[1]+subD6[1]+subD7[1])
    return None

def smart_process():
    CHUNKS = multiprocessing.cpu_count()  # Number of pieces to break the list into.
    total_len = len(D1) ** 7  # The total length of itertools.product()
    # Figure out how big each chunk should be. Got this from
    # multiprocessing.map()
    chunksize, extra = divmod(total_len, CHUNKS)
    if extra:
        chunksize += 1

    # Build a list that has the low index and high index for each
    # slice of the list. Each process will iterate over a unique
    # slice
    low = 0
    high = chunksize
    chunk_list = []
    for _ in range(CHUNKS):
        chunk_list.append((low, high))
        low += chunksize
        high += chunksize

    pool = multiprocessing.Pool(processes=CHUNKS)
    # Use partial so we can pass all the lists to each worker
    # while using map (which only allows one arg to be passed)
    func = functools.partial(smart_calc, D1, D2, D3, D4, D5, D6, D7)
    result = pool.map(func, chunk_list)
    pool.close()
    pool.join()
    return result

rawDescription: Single process code performs faster than Multiprocessing - MCVE


code:
lines = [line.strip() for line in open('fileRadiance.txt', 'r')]

Reg = []
Items = []
for line in lines:
    if "Item1" in line or '-----' in line:
        continue
    words = line.split()
    if words[0] == "Region:":
        Reg.append(words[1])
        Items.append([])
    else:
        Items[-1].append([int(i) for i in words])

rawDescription: Read from a file and save integers to a list Python


rawDescription: Moving files to corresponding subdirectory in Python


code:
import math
n = int(input())
for i in range(n):
  memoize = set()
  count = 0
  n = int(input())
  queue = []
  queue.append((n, count))
  while len(queue):
    data, count = queue.pop(0)
    if data <= 1:
      if data==1:
        count += 1
      break
    if data-1 not in memoize:
        memoize.add(data-1)
        queue.append((data-1, count+1))
    sqr = int(math.sqrt(data))
    for i in range(sqr, 1, -1):
      if data%i == 0:
        div = max(int(data/i), i)
        if div not in memoize:
          memoize.add(div)
          queue.append((div, count+1))
  print(count)

rawDescription: down to zero hackerrank getting time exceeded

description: Down to zero hackerrank getting time exceeded


code:
for line in x:
    if line.startswith("?"):
        continue
    DO_STUFF

rawDescription: What is the easiest way to get all strings that do not start with a character?


code:
with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:
        f1.writelines(lines)

rawDescription: Copying from one text file to another using Python


rawDescription: Use repeating iterator in python to insert item into list


code:
from sklearn import base

class Foo(base.BaseEstimator):
    def __init__(self, parameter_a, parameter_b, parameter_c):
        # Correct naming of internal fields
        self.parameter_a = parameter_a
        self.parameter_b = parameter_b
        # Incorrect naming of internal fields
        self.parameter_c_incorrect = parameter_c
p = Foo(1, 2, 3)
print(p.get_params())
# prints {'parameter_c': None, 'parameter_a': 1, 'parameter_b': 2}

rawDescription: Some advice and guidance on rolling your own scikit-learn estimator?


code: True and False

rawDescription: javascript comparison operators

description: Javascript comparison operators


code:
C2 = np.einsum('i,i...->i...', A, B)
np.allclose(C0, C2)

rawDescription: numpy array multiplication with arrays of arbitrary dimensions

description: Numpy array multiplication with arrays of arbitrary dimensions


code:
from django.conf import settings
...
if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
    )

rawDescription: Django: how do you serve media / stylesheets and link to them within templates


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

rawDescription: python matching list items

description: Python matching list items


code:
import requests
from bs4 import BeautifulSoup

r = requests.get('http://goodnewshackney.com')
soup = BeautifulSoup(r.text)

for img in soup.find_all('img'):
    print(img.get('src'))

rawDescription: Any Python modules to extract/suggest images for an URL?


code:
def printPattern(n):
    if n <= 0:
        return ''
    return '*' + printPattern(n-1) + '!'

rawDescription: python beginner recursion

description: Python beginner recursion


code: next(w for w in words if 'I=' in w)

rawDescription: Searching a string and returning only things I specify


code:
from collections import defaultdict

something = 'something'
options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})

for i in xrange(1000000):
    the_thing = options[something]

rawDescription: Most efficient way of making an if-elif-elif-else statement when the else is done the most?


rawDescription: Perform a logical exclusive OR on a Django Q object


rawDescription: Does Django send the signal pre_init/post_init when instances are loaded by a QuerySet?


code:
if op == '+':
    int(left_operand) + int(right_operand)
elif op == '-':
    int(left_operand) - int(right_operand)
# etc.

rawDescription: Python- How to convert stringed operator back to its special meaning?


rawDescription: Populating a sparse list with random 1's


code:
h = hex(address)[2:].zfill(12)
":".join(i + j for i, j in zip(h[::2], h[1::2]))

rawDescription: Python - Get mac address

description: Python - Get mac address


rawDescription: How to extract name/value pairs with BeautifulSoup?

description: Extract name/value pairs with BeautifulSoup


code: exclusion_emails = s_old_emails - s_new_emails

rawDescription: Improving python performance in comparing two lists


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--file', help='file path') #add --file to the args
args = parser.parse_args()

if not(args.file): #if they didn't specify a --file, prompt them
    file = input("Please enter file path?")
else:
    file = args.file #if they did specify file, make file what they specified in the cmd

print(file)

rawDescription: How do I make my program so that the user can specify a file name?

description: Make my program so that the user can specify a file name


code: buyer = models.ForeignKey(User)

rawDescription: Use logged in username as field value in django


code:
row = table[1]  # get row 1 (2nd item of the outer list)
item = row[3]  # from row 1, get column 3 (4th item of the inner list)

rawDescription: why does order of loop nesting matter python?

description: Why does order of loop nesting matter python


code:
per_line = int(input("How many numbers per line would you like: "))

for line in zip(*[iter(range(1, 1001))] * per_line):
    print(" ".join([str(x) for x in line]))

rawDescription: Python 3.4.3 - printing multiple ints per line


code:
np.result_type(np.array([252],np.uint8), np.array(10))
np.result_type(np.array(252,np.uint8), np.array(10))

rawDescription: numpy type conversions for arrays vs. scalars

description: Numpy type conversions for arrays vs. scalars


code:
import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")
root = tree.getroot()

for name in root.findall(".//team/members/*/style"):
    print(name.text)

rawDescription: Read subelement of node values of an xml in python


rawDescription: Arranging nested lists in python

description: Arranging nested lists in python


code: df.loc[df.DATE.shift() != df.DATE]

rawDescription: pandas DataFrame delete contiguous duplicates

description: Pandas DataFrame delete contiguous duplicates


code:
from wsgiref.simple_server import make_server

def my_app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    yield 'Hello world!\n'

make_server('', 8000, my_app).serve_forever()

rawDescription: Differences between BaseHttpServer and wsgiref.simple_server


code:
from cStringIO import StringIO
import sys

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        sys.stdout = self._stdout

rawDescription: How to capture stdout output from a Python function call?

description: Capture stdout output from a Python function call


code:
def subsets_with_sum(lst, target, with_replacement=False):
    x = 0 if with_replacement else 1
    def _a(idx, l, r, t):
        if t == sum(l): r.append(l)
        elif t < sum(l): return
        for u in range(idx, len(lst)):
            _a(u + x, l + [lst[u]], r, t)
        return r
    return _a(0, [], [], target)

rawDescription: Finding Combinations to the provided Sum value


code:
timeit.timeit('s[:-len(s.lstrip())]', 's=" "*200000', number=10000)
timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"\s*");s=" "*200000', number=10000)
timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s=" "*200000', number=100)*100

rawDescription: Grab a line's whitespace/indention with Python


rawDescription: Find x-digit number in a text using Python


code: getNumeric('Python 3: ')

rawDescription: Getting safe user input in python

description: Getting safe user input in python


rawDescription: Iterating over expanding list / nested for loops


code:
def oldcalc_D(Iiajb,nOcc,nVir,Ew):
    D = np.zeros((nOcc,nOcc,nVir,nVir))
    for i in range(nOcc):
       for j in range(i+1):
          tmp = Ew[i] + Ew[j]
          for a in range(nVir):
             tmp2 = tmp - Ew[a+nOcc]
             for b in range(a+1):
                tmp3 = 1.0/(tmp2 - Ew[b+nOcc])
                D[i,j,a,b] = Iiajb[i,a,j,b]*tmp3
                D[i,j,b,a] = Iiajb[i,b,j,a]*tmp3
                D[j,i,a,b] = D[i,j,b,a]
                D[j,i,b,a] = D[i,j,a,b]
    return D

rawDescription: Are there function calls that can replace the for loops in this code?


rawDescription: Sort a python list of strings with a numeric number


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

def my_dist(x):
    return np.exp(-x ** 2)

x = np.arange(-100, 100)
p = my_dist(x)
plt.plot(x, p)
plt.show()

rawDescription: Plotting probability density function by sample with matplotlib


code:
hist,xbinedges,ybinedges = np.histogram2d(x,y,bins=bins,range=range)
BinlowEdgex, BinlowEdgey = np.meshgrid(xbinedges[:-1], ybinedges[:-1])
xbinwidth = ((range[0][1]-range[0][0])/(bins[0]))
ybinwidth = ((range[1][1]-range[1][0])/(bins[1]))
ax.bar3d(BinlowEdgex.flatten(), BinlowEdgey.flatten(), np.zeros(bins[0]*bins[1]), xbinwidth*np.ones(bins[0]*bins[1]), ybinwidth*np.ones(bins[0]*bins[1]), zvalues.flatten())

rawDescription: How to set bin content in a hist2d (matplotlib)

description: Set bin content in a hist2d (matplotlib)


code:
import os
os.path.join('build', distutils_dir_name('lib'))

rawDescription: Testing Python C libraries - get build path


code:
def combine_dicts(*d, **kw):
    """Combine dictionaries into one.

    Keys in later dictionaries override those in earlier dictionaries, with
    keyword arguments being applied last.

    """
    return reduce(lambda d1, d2: dict(d1, **d2), d + (kw,))

rawDescription: Defined dict entries Python

description: Defined dict entries Python


code:
def get_nested_index(list_, element):
    for index, container in enumerate(list_):
        if element in container:
             return index

    # If we made it here, it wasn't in any of the containers
    raise ValueError("{element} not in any element in list".format(element=element))

rawDescription: list's index() method for nested structures OR how to match against particular value of composed element stored in list and get it's index

description: List's index() method for nested structures OR how to match against particular value of composed element stored in list and get it's index


code:
def chunk(l,n):
 result=[]
 for i in range(n):
   result.append(l[i::n])
 return result
A,B,C=chunk(X,3)
A,B,C
A,B,C,D=chunk(X,4)
A,B,C,D

rawDescription: Append new list every iteration of the for loop


code:
df = pd.DataFrame({'A':[0], 'B':[1]})
df
s = pd.Series([2], index=[83])
s
df['new_column'] = s
df
df['new_column'] = s.values
df

rawDescription: Adding a Pandas Dataframe-column to a new dataframe


rawDescription: How does the @property decorator work?

description: How does the @property decorator work


code:
import re

pattern = re.compile(r'/in/(\d+)')
categories = {'15': 'tree', '20': 'flower', '3': 'bird'}

def getcategory(url):
    category = pattern.search(url).group(1)
    return categories[category]

rawDescription: Url parsing with regex

description: Url parsing with regex


code:
from string import ascii_uppercase as alphabet
"".join([str(i) for i, c in enumerate("aAaEaaUA") if c in alphabet])

rawDescription: Persistent index in python string

description: Persistent index in python string


rawDescription: Can you translate this debugging macro from C++ to python?

description: Translate this debugging macro from C++ to python


code:
def sum_digits2(n):
    s = 0
    while n:
        n, remainder = divmod(n, 10)
        s += remainder
    return s

rawDescription: Sum the digits of a number - python

description: Sum the digits of a number - python


rawDescription: Randomly sample rows (first dimension) of an array with unknown dimension


rawDescription: Find index where elements change value numpy


code: class HaltException(Exception): pass

rawDescription: Stop python script without killing the python process


code:
from itertools import izip_longest

d = { 'a': ['s','b'], 'b': ['x1','y1','z1'] }

print([i for t in izip_longest(*[d[k] for k in sorted(d)])
                  for i in t if i is not None])

rawDescription: iterating through dictionary with list as values in python

description: Iterating through dictionary with list as values in python


code:
previous = None
for name, num in group:
    if name != previous:
        counter += 1
    ...
    previous = name

rawDescription: Dictionary value sorting

description: Dictionary value sorting


code:
df2['range'] = range(len(df2))
df2

rawDescription: How to select columns from frame in HDFStore

description: Select columns from frame in HDFStore


code: full_list = test.split(', ')

rawDescription: Add characters (',') every time a certain character ( , )is encountered ? Python 2.7.3


code:
with open("test.csv") as f, open("file_out.csv","w") as out:
    from collections import Counter
    header = next(f) # get header
    next(f) # skip blank line
    counts = Counter(tuple(map(str.lower,line.split(",", 2)[:2])) for line in f)
    f.seek(0) # back to start of file
    next(f), next(f) # skip again
    out.write(header) # write original header ?
    out.writelines(line for line in  f
                   if counts[map(str.lower,line.split(",", 2)[:2])] == 1)

rawDescription: Remove duplicate rows in CSV comparing data in only two columns with Python


code:
template_values = {
    'title': 'GalaStore',
    'values': kw,
    'games_list': self.rendered_games_list()
}
template = JINJA_ENVIRONMENT.get_template(template)
self.response.out.write(template.render(self.templateValues))

rawDescription: Update Jinja2 template variables

description: Update Jinja2 template variables


code:
zpairs = namepairs.groupby(['Name1', 'Name2']).apply(merge_zpairs)
zpairs_dict = zpairs.to_dict(orient='index')

rawDescription: How to Process Row Pairs Preserving an ID Column without Dictionaries using Pandas?


rawDescription: python logistic regression (beginner)

description: Python logistic regression (beginner)


rawDescription: Get HTML Source of WebElement in Selenium WebDriver using Python


rawDescription: Counting non zeros in only 1 column of a numpy array


code: open('./testing.json','w').write("[%s]" % ",\n ".join(json.dumps(e) for e in d))

rawDescription: Python JSON dump a list of object.

description: Python JSON dump a list of object.


code:
from itertools import combinations
weights = get_weights()
aux1, aux2 = min(combinations(_list, 2),
                 key=lambda pair: sum(weights[key] * (pair[0][key] - pair[1][key]) ** 2
                                      for key in self.__fields))

rawDescription: Compress dict sum statement with Python

description: Compress dict sum statement with Python


rawDescription: How can I extract this obvious event from this image?

description: Extract this obvious event from this image


code:
def func():
    return 1,2,3

a,b,c = func()

rawDescription: Is there a way in Python to return value via output parameter?


code: df

rawDescription: Pandas multiIndex DataFrame sort

description: Pandas multiIndex DataFrame sort


code:
rng = pd.date_range('1/1/2000', periods=100, freq='D')
r = [timedelta(hours=i) for i in np.random.random(len(rng))]
ts = pd.Series(r, index=rng)
ts

rawDescription: Trouble resampling Pandas timeseries data on Python timedelta objects


rawDescription: How to get pyparser to work in a particular form

description: Get pyparser to work in a particular form


code: print("walrus", end=" ", file=sys.stderr)

rawDescription: Python waits to print incomplete lines?

description: Python waits to print incomplete lines


code: [int(value) for value in your_list]

rawDescription: Remove single quotes from python list item


rawDescription: Using .join() in Python

description: Using .join() in Python


code:
def f(x, y):
    return x * y

A = {1:1, 2:3}
B = {7:3, 2:2}
merge(A, B, f)
merge(A, B, lambda a, b: '{} merged with {}'.format(a, b))

rawDescription: Python merge dictionaries with custom merge function


code:
q = Queue.Queue()
for item in enumerate(my_generator):
    q.put(item)

rawDescription: Idiomatic list of all natural numbers

description: Idiomatic list of all natural numbers


code: len([x for x in product(range(100),range(100),range(100)) if sum(x)==100])

rawDescription: Python: Generate matrix of Nx4 integers who sum is a constant


rawDescription: PIG: Compute max distance between pairs of latitudes and longitudes


code:
Z = np.zeros((m, n))
for i in range(d):
    Z += f(x[:, :, i], y[:, :, i])

rawDescription: Function application and reduction on large arrays


code:
import collections
def flatten(foo):
    for x in foo:
        if isinstance(x, collections.Iterable) and not isinstance(x, str):
            for y in flatten(x):
                yield y
        else:
            yield x

my_sentence = " ".join(flatten(array))

rawDescription: Join on nested lists of strings

description: Join on nested lists of strings


code:
def lookahead(iterable):
    """Pass through all values from the given iterable, augmented by the
    information if there are more values to come after the current one
    (True), or if it is the last value (False).
    """
    # Get an iterator and pull the first value.
    it = iter(iterable)
    last = next(it)
    # Run the iterator to exhaustion (starting from the second value).
    for val in it:
        # Report the *previous* value (more to come).
        yield last, True
        last = val
    # Report the last value.
    yield last, False

rawDescription: What is the pythonic way to detect the last element in a python 'for' loop?


code:
"12"*10             # This is what your code is doing
int("12")*10        # Expected output

rawDescription: python accessing the value of the raw_input as parameter

description: Python accessing the value of the raw_input as parameter


code:
def list(self):
    """List the names of all files stored in this instance of
    :class:`GridFS`.
    .. versionchanged:: 3.1
       ``list`` no longer ensures indexes.
    """
    # With an index, distinct includes documents with no filename
    # as None.
    return [
        name for name in self.__files.distinct("filename")
        if name is not None]

rawDescription: The gridfs "list" method returns empty list with non empty collection


code:
orig = np.zeros((3,2), dtype=np.object)
a, b, c = orig
orig
a
a[0] = 9
a
orig

rawDescription: assigning an object to multiple variables - python

description: Assigning an object to multiple variables - python


code: np.sqrt(np.sum(f**2, axis=1))

rawDescription: Parallel array manipulations in numpy

description: Parallel array manipulations in numpy


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

table={'time':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5],
       'data':[1,1,2,2,2,1,2,3,4,5,1,2,2,2,3],
       'type':['a','a','a','a','a','b','b','b','b','b','c','c','c','c','c']}
df=pd.DataFrame(table, columns=['time','data','type'])

df.index = df['time']
groups = df[['data', 'type']].groupby('type')

fig, ax = plt.subplots()
groups.plot(ax=ax, legend=False)
names = [item[0] for item in groups]
ax.legend(ax.lines, names, loc='best')

plt.show()

rawDescription: Python Pandas Matplotlib Plot Colored by type value defined in single column


rawDescription: Merge multiple list with intersection and add the items


code:
import timeit
timeit.timeit("arr+='1234567890'", setup="arr = ''", number=10000)

rawDescription: subclass str, and make new method with same effect as +=

description: Subclass str, and make new method with same effect as +=


code: countries =  [(key, value) for (key, value) in counted.items() if key[0] == "Country"]

rawDescription: Search in a python list

description: Search in a python list


code:
import os, sys, subprocess, shutil, re, string, glob, tvdb_api, itertools, multiprocessing, ftplib

#No longer an instance method -- just a regular function.
#accepts an iterable and then splits it as [host,filename]
def upload_files(inpt):
    host=inpt[0]
    f=inpt[1]
    #host,f=inpt  #This might be a little cleaner, depending on your programming style.
    host.storbinary(('STOR /'+f.split('/')[-1]), open(f, 'rb'))

files = [os.path.join(r, f) for r, d, fs in os.walk(os.getcwd()) for f in fs if not f[0]=='.']
class FTP_Upload:
    def __init__(self, p=os.getcwd()):
        self.files_to_upload = sorted([f for f in files if os.path.split(f)[0] == p])
        self.target = raw_input("Enter the host you want to upload to: ")
        self.host = FTP('ftp.host1.com', 'user_name1', 'super_secret_password1') if self.target == 'host' else FTP('ftp.host2.com', 'user_name2', 'secret_password2') if self.target == 'host2' else None
    def multiupload(self):
        p = multiprocessing.Pool(processes=5)
        upload_this=[(self.host,f) for f in self.files_to_upload]
        p.map(upload_files,upload_this)
FTP_Upload().multiupload()

rawDescription: Python FTP Upload Multiple Files at Once


rawDescription: Annoying white space in bar chart (matplotlib, Python)


code:
import unittest
import os
def run(verbosity=2):
    suite = unittest.TestLoader().discover(os.path.dirname(__file__))
    unittest.TextTestRunner(verbosity=verbosity).run(suite)
run()

rawDescription: Unittests not run with python -m unittest command


rawDescription: Finding gradient of a Caffe conv-filter with regards to input


code:
class LinkedKeyProperty(ndb.KeyProperty):
    def _fix_up(self, cls, code_name):
        super(LinkedKeyProperty, self)._fix_up(cls, code_name)
        modelclass = ndb.Model._kind_map[self._kind]
        collection_name = '%s_ref_%s_to_%s' % (cls.__name__,
                                               code_name,
                                               modelclass.__name__)
        setattr(modelclass, collection_name, (cls, self))

rawDescription: Following backreferences of unknown kinds in NDB


rawDescription: Find all combinations of N items in N groups without duplicates of item combos (python)?


code:
def __eq__(self, other):
    return all(getattr(self, a, Ellipsis) == getattr(other, a, Ellipsis)
               for a in self.metainfo)

rawDescription: Python: Can you make this __eq__ easy to understand?


code:
import numpy as np
matrix = np.random.randint(100, size=(4000, 5000))
rows, cols = np.indices(matrix.shape)

rawDescription: Sorting cells of big numpy matrices

description: Sorting cells of big numpy matrices


code:
contents = input_file.readlines()
input_file.close()

rawDescription: Python: How do you read a chunk of text from a file without knowing how long the file actually is?


code:
import hello
import pickle

c1 = hello.MyClass()
c1.set_values()
print('c1', c1)
print('fifth item', c1.get(5))

d = pickle.dumps(c1)
del(c1)  # delete the original object

c2 = pickle.loads(d)
print('c2', c2)
print('fifth item', c2.get(5))

rawDescription: Pickle Cython Class with C pointers

description: Pickle Cython Class with C pointers


rawDescription: Classes in python, get attribute

description: Classes in python, get attribute


code:
with open(input,"r") as infile:
    for line in infile:
        line = doSomething(line, next(infile))

rawDescription: Getting next line in a file

description: Getting next line in a file


code: fruit = [f[-3:] for f in fruit]

rawDescription: How do I check how many entries there are within a nested list and then remove all other values other than the last 3 for each item?

description: Check how many entries there are within a nested list and then remove all other values other than the last 3 for each item


code:
cmds.createDisplayLayer (name='Torso_Control_Shapes', empty=True)
cmds.setAttr ('Head_Control_Shapes.color', 4)

rawDescription: Place object within a layer in Python - Maya


rawDescription: how to divide integer and take some part

description: Divide integer and take some part


code:
def sales(infile, infilelist):
    #set initial
    t_sales=0

    n_sales=int(input("Number of sales"))

    while t_sales<n_sales:

        #increasement
        t_sales+=1

        #for loop
        for s in range(1,n_sales+1):
            totalsale_each=0 #set the acc for total sales by each sales person

            # EDIT: this seems useless, so remove it
            #sales_no=s*1
            sales_person=input("sales person name:")
            print("sales for sales no."+str(s)+"by"+sales_person+":")
            infilelist.append(sales_person)

            for count in range (5): #assuming one sales person can sell only 5item per cust
                sales=float(input('sales#' +str(count)+ ':'))

                if sales<=300:
                    t_sales=t_sales+sales
                    totalsale_each=totalsale_each+sales

                if sales>300: #if sales>300, need to change the sales person
                    t_sales=t_sales+sales
                    # write the last sales_person's total, and ask for another one
                    infilelist.append(str(totalsale_each))
                    sales_person=input("another sales pesron")
                    # add it to the list, after that, everything counts for him
                    infilelist.append(sales_person)
                    totalsale_each=sales
            # EDIT: decrease indentation so that the total is written once, after the loop
            infilelist.append(str(totalsale_each)) #to write total sales for each person
    return totalsale_each,sales_person

rawDescription: How to continue writing the loop to the file and how to reset the initial value to 0 after each condition met?

description: Continue writing the loop to the file and how to reset the initial value to 0 after each condition met


code: [a for a in list if ...]

rawDescription: Removing elements from a List in Python

description: Removing elements from a List in Python


code:
from django.conf import settings

def save(self, *args, **kwargs):

   if not settings.SKIP_TASKS:

       celery_app.send_task('test.apps.action')
   else:
       pass

rawDescription: How to stop Tasks firing during Django Nose tests?

description: Stop Tasks firing during Django Nose tests


code:
from __future__ import division #import py3x's division in py2x
4200/820

rawDescription: Rounding of variables

description: Rounding of variables


code:
from operator import add
rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
sorted(rdd.reduceByKey(add).collect())

rawDescription: (PySpark) Nested lists after reduceByKey


code:
class CustomStatusBar(wx.StatusBar):
    """A custom status bar for displaying the application version in the bottom
    right corner."""
    def __init__(self, parent):
        wx.StatusBar.__init__(self, parent, -1)

        self.SetFieldsCount(2)
        self.SetStatusWidths([-1, -1])

        # Set up the version label.
        self.version_label = wx.StaticText(self, -1, 'Version: ' + VERSION)
        self.reposition_version_label()

        # Listen to the resize event.
        self.Bind(wx.EVT_SIZE, self.on_resize)

    def on_resize(self, event):
        self.reposition_version_label()

    def reposition_version_label(self):
        # Get the rect of the second field.
        field_rect = self.GetFieldRect(1)
        label_rect = self.version_label.GetRect()

        # Reduce the width of the field rect to the width of the label rect and
        # increase it's x value by the same about. This will result in it being
        # right aligned.
        width_diff = field_rect.width - label_rect.width

        field_rect.width = label_rect.width
        field_rect.x += width_diff

        # On windows, the text is a little too high up, so increase the Y value
        # a little.
        if sys.platform == 'win32':
            field_rect.y += 3

        # Set the resulting rect to the label.
        self.version_label.SetRect(field_rect)

rawDescription: How can I align the text in a StatusBar to the right in wxPython?

description: Align the text in a StatusBar to the right in wxPython


code:
timeit.timeit('match("0-0016ub5j2oi06u30tj30g6790v3nug[hoyj39867i6gy9thvb05y4b896y3n098vty98thn98qg5y4n8ygnqp", "0-0016ub5j2oi06u30tj30g6790v3gug[hoyj39867i6gy9thvb05y4b896y3n098vty98thn98qg5y4n8ygnqp")', setup="""
def match(s1, s2):
    combo = zip(s1, s2)
    return any(c1 != c2 for c1, c2 in combo) and all(c1 == c2 for c1, c2 in combo)
""")

rawDescription: Compare strings, allowing one character difference


code:
dict = {
        'cat' : {10: [value1, value2, value3, ..., value10]},
        'dog' : {15: [value1, value2, value3, ..., value15]},
        'zen' : {15: [value1, value2, value3, ..., value15]}
       }

rawDescription: Constructing a dictionary with multi part keys


code:
bb = bytearray(int(b, 16) for b in x.split())
bb

rawDescription: convert a hexadecimal file and extract / display characters that belongs to a language

description: Convert a hexadecimal file and extract / display characters that belongs to a language


rawDescription: Parsing html data into python list for manipulation


code:
from config import * # has settings
from commands import *

from logsys import log
import filesys

class myprogram(object):
    def __init__(self):
        log(_class=self.__name__, _func='__init__', _level=0)
        log(_class=self.__name__, _func='__init__',  text="DEBUG LEVEL %s" % settings["debug"], _level=0)
        self.settings = settings
        self.cmds = commands
    def prepare(self):
        log(_class=self.__name__, _func='prepare', _level=1)
        self.dirs = {}
        for key in settings["dir"].keys():
            self.dirs[key] = settings["dir"][key]
            filesys.checkDir(self.dirs[key])

    def initCommands(self):
        log(_class=self.__name__, _func='initCommands', _level=1)
        options = sys.argv
        for option in options:
            for cmd in self.cmds.keys():
                if option.find(cmd) != -1:
                    return self.cmds[cmd]()

if __name__ == '__main__':
    p = myprogram()
    p.prepare()
    p.initCommands()

rawDescription: How are Python command line arguments related to methods?


code:
class DownloadItem(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    downloadItem = models.ImageField(upload_to='./images/downloadItems', blank=True)

    def __unicode__(self):
        return self.name

    def get_sample_by_order(self):
        if self.downloaditemsample_set.count():
            return self.downloaditemsample_set.order_by('order')[0]

rawDescription: Django model with many to one relationship in template


rawDescription: In python, is 'foo == (8 or 9)' or 'foo == 8 or foo == 9' more correct?


code: type(n) is int

rawDescription: How can I type-check variables in Python?

description: Type-check variables in Python


code:
### Decorate all the above functions
import types
for k,v in globals().items():
    if isinstance(v, types.FunctionType):
        globals()[k] = my_decorator(v)

rawDescription: Defining Python decorators for a complete module


rawDescription: Right clicking on QHeaderView inside of QTreeView


rawDescription: Namespace, argparse, and usage

description: Namespace, argparse, and usage


code:
def update(self,event):
    self.main_label.text = "Changed to change"

rawDescription: Update label's text when pressing a button in Kivy for Python


rawDescription: Python - Intersection of two lists of lists


code:
class Vuln(models.Model):
  pub_date = models.DateTimeField("Publication Date")
  short_description = models.CharField("Description", max_length=70)
  vendor = models.ForeignKey(Vendor, verbose_name="Vendor")

class Url(models.Model):
  url = models.URLField("URL", max_length=200)
  vulnerability = models.ForeignKey(Vuln)

rawDescription: Django One-To-Many Models

description: Django One-To-Many Models


rawDescription: Watching for multiprocessing to finish

description: Watching for multiprocessing to finish


code:
df2[(result.A.isin(isin) | result.A.isin(isin))].info()
df2[(result.A.isin(isin) | result.A.isin(isin))].head()

rawDescription: Cythonizing string array comparison function to be applied to pandas DataFrame


code: imdata

rawDescription: pcolormesh with masked invalid values

description: Pcolormesh with masked invalid values


code:
def HomeView(request):
  dict = func(request)
  ... # rest of code that is not common with other views

rawDescription: Django: How do I extend the same functionality to many views?


rawDescription: Python slice how to distinguish slice arguments and default arguments (e.g., x[i:] vs. x[i:None])?


code:
from itertools import combinations

x = ['a','b','c','d','e']
n = 2
c = [comb for i in range(n) for comb in combinations(x, i + 1)]
print(c)

rawDescription: Listing all combinations of a list up to length n (Python)


code:
a = []
for i in range(10):
  a.append(i)

rawDescription: Why isn't my solution to Project Euler 9 working?


code:
class A:
  def a(self): pass
A.a
type(A.a)
A().a
type(A().a)

rawDescription: Difference between methods and functions


code: val = hex(reduce(lambda total, wall: total << 1 | wall, walls, 0))

rawDescription: Elegant way to convert list to hex string


rawDescription: Validate a filename in python

description: Validate a filename in python


code: id_map = {k: v for v, k in enumerate(df.phone_no.unique(), 1)}

rawDescription: how to rename a column value in pandas dataframe on some condition

description: Rename a column value in pandas dataframe on some condition


code:
delta_Array = np.array([0.01,0.02,0.03, 0.04, 0.05, 0.06,0.07, 0.08, 0.09, 0.10])
theta_Matrix = np.zeros((N, 8))

for i in range(N):
     t = Ridge(Xtrain, ytrain, .3)
     theta_Matrix[i] = t

rawDescription: creating a numpy array of arrays while looping (Python)

description: Creating a numpy array of arrays while looping (Python)


code:
for index, row in last_movement.iterrows():
    print('Serial Number {} has a movement type {} and was last updated {}'
          .format(index, row['Movement type'], row['Posting date']))

rawDescription: Python CSV data analysis based on date time


code:
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    transaction_id = Column(Integer, ForeignKey('transaction.id'))
    transaction = relationship(
        "Transaction", uselist=False, backref=backref("user", uselist=False))

class Transaction(Base):
    __tablename__ = 'transaction'
    id = Column(Integer, primary_key=True)
    amount = Column(Integer)
    date = Column(DateTime, default=datetime.datetime.now)

rawDescription: What kind of database schema would I use to store users' transaction histories?


code: data = data.replace('EV', 'even').replace('OD', 'odd')

rawDescription: Automatic in python

description: Automatic in python


code:
import logging
LOG = logging.getLogger(__name__)

rawDescription: Naming Python loggers

description: Naming Python loggers


rawDescription: Slicing pandas dataframe as per expression value


code:
with open('data.pickle', 'w') as pickle_file:
    pickle.dump(data, pickle_file)

rawDescription: Python: How to get a object database

description: Python: How to get a object database


code: sorted([1, 2, 3], key=(lambda x:(-x)))

rawDescription: Sorting a list with a dictionary at items


rawDescription: getting GtkTressStore parent from child in python

description: Getting GtkTressStore parent from child in python


rawDescription: Add 0 to number with 5 characters (pandas)


code:
class myIterator:
    def __init__(self, n):
        self.last = n
        self.next = self.myGenerator().next  # Use the generator `.next`

    def __iter__(self):
        return self

    def myGenerator(self):
        prev = 0
        fib = 1
        while fib < self.last:
            res = fib
            yield res
            fib += prev
            prev = res

rawDescription: What is the best way to write a python iterator based on a generator


rawDescription: read HDF5 file to pandas DataFrame with conditions

description: Read HDF5 file to pandas DataFrame with conditions


code:
from pyquery import PyQuery as pq
d = pq(html)
selector = '#cmeProductSlatePaginiationTop ul'
n_pages = len(d(selector))-2

rawDescription: Accessing JSON feeds

description: Accessing JSON feeds


code:
n = 3
I, T, A = np.identity(n), np.ones(n), np.zeros([n * n, n * n])
for i in range(n):
    a, b, c = i * n, (i + 1) * n, (i + 2) * n
    A[a:b, a:b] = T
    if i < n - 1: A[b:c, a:b] = A[a:b, b:c] = I

rawDescription: Tridiagonal Matrix with Matrix Blocks

description: Tridiagonal Matrix with Matrix Blocks


code:
item = {}
item['foo'] = ["blah"]
item['foo'].append("garble")
print(item)

rawDescription: Python add to a list that is a value of a key


code: c = store.select_as_coordinates('df', ['index<3'])

rawDescription: Selecting rows from an HDFStore by index using where


rawDescription: Python/numpy issue with array/vector with empty second dimension


code:
(df.pivot_table(index='Name', columns='hour', values='var',
                aggfunc='sum', fill_value=0)
   .plot.bar(stacked=True)
)

rawDescription: Pandas plot on 3 variables

description: Pandas plot on 3 variables


code:
import os
class EvaluatingName(object):
    def __init__(self, callable):
        self._callable = callable
    def __call__(self):
        return self._callable()
    def __repr__(self):
        return repr(self())
ls = EvaluatingName(os.getcwd)
os.chdir('/')
ls
os.chdir('/tmp')
ls

rawDescription: call function through variable or without parentheses in python

description: Call function through variable or without parentheses in python


code:
import re
keywords = open('fileOne.txt', 'r').readlines()
sentences = open('fileTwo.txt', 'r').readlines()
for sentence in sentences:
    for keyword in keywords:
        if re.search(r'\b%s\b' % keyword.strip(), sentence):
            print("Found '%s' in '%s'" % (keyword.strip(), sentence.strip()))

rawDescription: specific words matching in file python

description: Specific words matching in file python


code: delimiter = "\u00A0"

rawDescription: Python 3.3. Concatenating strings from input. How?


code:
#!/usr/bin/python

import pydoc
import re

t = re.sub('\n([^\n])', ' \g<1>', pydoc.__doc__)
pydoc.__doc__ = t
help(pydoc)

rawDescription: Set the wrap width for python docs in a terminal


code:
def conv(s):
  if isinstance(s, unicode):
    s = s.encode('iso-8859-1')
  return s.decode('string-escape').decode('utf-8')

map(conv, [u'D\\xc3\\xa9cor', u'D\xc3\xa9cor', 'D\\xc3\\xa9cor', 'D\xc3\xa9cor'])

rawDescription: Dealing with wacky encodings in Python

description: Dealing with wacky encodings in Python


rawDescription: Python dictionary to equivalent pymongo statement


code: sorted(people, key=lambda dct: dct['name'])

rawDescription: Sorting associative arrays in Python

description: Sorting associative arrays in Python


code:
pipeline = Pipeline([
    ('vect', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('clf', SGDClassifier()),
])
predicted = pipeline.fit(Xtrain).predict(Xtrain)
# Now evaluate all steps on test set
predicted = pipeline.predict(Xtest)

rawDescription: Python - What is exactly sklearn.pipeline.Pipeline?


code:
i = dictionary['Name'].index('Thomas')
y = dictionary['Age'][i]

rawDescription: Find a strings location in a list - Python


code:
from collections import Counter

def counter(fobj):
    scores = Counter()
    fobj.seek(0)
    for line in fobj:
        key, score = line.split()
        scores.update({key: int(score)})
    return scores.most_common()

from collections import defaultdict
from operator import itemgetter

def default(fobj):
    scores = defaultdict(int)
    fobj.seek(0)
    for line in fobj:
        name, score = line.split()
        scores[name] += int(score)
    return sorted(scores.items(), key=itemgetter(1), reverse=True)

rawDescription: Efficiently processing data in text file


code: n.phone = "%s%s%s-%s%s%s-%s%s%s%s" % tuple(n.phone)

rawDescription: Format an un-decorated phone number in django?


code: pd.Series(proxy.date, index=df.index)

rawDescription: Custom time series resampling in Pandas

description: Custom time series resampling in Pandas


code:
import ast

string_version = str(S)
list_version = ast.literal_eval(string_version)

rawDescription: Clean conversion from int list to character and then back to int list, in Python


code:
def name_sort(contact):
    if contact.lastName:
        return contact.lastName, contact.firstName
    return contact.firstName, ''

addressBook.contactsList.sort(key=name_sort)

rawDescription: Python - sort method parameter takes same precedence


code:
class PersonForm(forms.ModelForm):
    abstract = forms.CharField(
        widget=TinyMCE(attrs={'cols': 80, 'rows': 30})
    )

    class Meta:
        model = Person

class PersonAdmin(reversion.VersionAdmin):
    form = PersonForm
    # The Form Fieldsets
    fieldsets = [
        (
            None,
            {
                'fields'    : [('first_name', 'last_name', 'post_nominal', ), 'slug', 'title', 'headshot', 'large_photo', ('email', 'phone', ), 'abstract']
            },
        )
    ]

    # Prepopulated fields
    prepopulated_fields = {'slug': ('first_name', 'last_name', 'post_nominal', )}

    # Fields that are readonly
    #readonly_fields = ('slug', )

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'headshot':
            request = kwargs.pop("request", None)
            kwargs['widget'] = AdminImageWidget
            return db_field.formfield(**kwargs)
        return super(PersonAdmin, self).formfield_for_dbfield(db_field, **kwargs)

rawDescription: Define an order for ManyToManyField with django


code: c = a * np.sum(lattice) + b * np.sum(lattice * neigh_sum)

rawDescription: Numpy vectorization for nearest neighbor calculation in semi-sparse arrays


code: filter(lambda x: 19 in x[1], mydict.items())

rawDescription: Get dictionary key by value if value is list


rawDescription: Creating a dictionary from a list

description: Creating a dictionary from a list


code: C = np.linalg.solve(Z[rnk:], -x1[rnk:])

rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
def quicksort(A):
    global count
    count = 0
    return _quicksort(A)

def _quicksort(A, left=None, right=None):
    global count
    ...
    _quicksort(A,left,i-1)
    ...

rawDescription: Counting comparisons quicksort without global Python


code:
class Player(object):
    def __init__(self, name):
        self.name = name
        self.lifecondition = True
        self.hitpoints = 100
    def death(self):
        self.lifecondition = False

rawDescription: Function adding objects to a class through a list - calling objects


code:
for v in orig.values(): del v['key']
orig

rawDescription: Python defaultdict get original dictionary


code:
ip = '127.0.0.1'

ip = ip.split('.')

ip.reverse()

print('.'.join(ip))

rawDescription: read an ip address conversely using python

description: Read an ip address conversely using python


rawDescription: how to pass list values through url

description: Pass list values through url


code:
def as_attrdict(val):
    if not isinstance(val, AttrDict):
        raise TypeError('not AttrDict')
    return AttrDictForJson(val)

class AttrDictForJson(dict):

    def __init__(self, attrdict):
        super().__init__()
        self.items = attrdict.items
        self._len = attrdict.__len__
        # key creation necessary for json.dump to work with CPython
        # This is because optimised json bypasses __len__ on CPython
        if self._len() != 0:
            self[None] = None

    def __len__(self):
        return self._len()

rawDescription: How do you enable python's json package to encode attrdict.AttrDict objects?

description: Enable python's json package to encode attrdict.AttrDict objects


code: re.search(regex, "home/ abc")

rawDescription: Django URL matching any 140 characters

description: Django URL matching any 140 characters


code:
for i in range(0, 10):
      QApplication.processEvents()

self.resize(minimumSizeHint())

rawDescription: Resize QMainWindow to minimal size after content of layout changes


code:
# initialize your skeleton array using 'empty' for lowest-memory footprint
M = NP.empty(shape=(10, 5), dtype=float)
# create a small function to mimic step-wise populating this empty 2D array:
fnx = lambda v : NP.random.randint(0, 10, v)

rawDescription: Growing matrices columnwise in NumPy

description: Growing matrices columnwise in NumPy


code:
def main():
    x, y, z = generate_data()
    plot(*reorient(x, y, z))
    plt.show()

rawDescription: Finding the opening of a 3D surface

description: Finding the opening of a 3D surface


rawDescription: Why does hough transform for lines returning sinusoids divided halfway?


code:
def count_modify(string):
        d = {}
        for i in string:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
        n_str = ''
        for i in d:
            n_str += str(i)+str(d[i])
        return n_str

rawDescription: Print custom string with character and character count without using python built-in methods


rawDescription: Is there a difference between putting .lower() in one place or another?


code:
from itertools import chain

chain.from_iterable((f(month), g(month)) for month in months)

rawDescription: Python: How to pass functions to another function as arguments?


code:
import urllib2
response = urllib2.urlopen(link)
content = resonse.read()

rawDescription: pandas.read_html returns only one table

description: Pandas.read_html returns only one table


code:
from string import ascii_letters
import re
s = 'this is 123 some text! that has someñ \n other stuff.'
re.findall('[{}]+'.format(ascii_letters), s)

rawDescription: Regex only searching for words

description: Regex only searching for words


code:
# Replacing the for loop from before...
plot_percentiles = range(0, 110, 10)
for ax, data, color, marker in zip(axes, values, colors, markers):
    x = np.percentile(data, plot_percentiles)
    ax.plot(x, plot_percentiles, color=color, marker=marker,
            markersize=10, linestyle='none')

rawDescription: Python: Matplotlib - probability plot for several data set


rawDescription: Python Tkinter: Tree selection

description: Python Tkinter: Tree selection


code:
def rotate(coords, angle, center=(0, 0,)):
    rotated = np.array([np.cos(np.radians(angle)) * (coords[:,0] - center[0]) - np.sin(np.radians(angle)) * (coords[:,1] - center[1]) + center[0],
                np.sin(np.radians(angle)) * (coords[:,0] - center[0]) + np.cos(np.radians(angle)) * (coords[:,1] - center[1]) + center[1]])
    return rotated.T #<-- Modification here

rawDescription: numpy - issue with creating a 2D matrix

description: Numpy - issue with creating a 2D matrix


code:
from app import db
from geoalchemy2.types import Geometry

class Point(db.Model):

    """represents an x/y coordinate location."""

    __tablename__ = 'point'

    id = db.Column(db.Integer, primary_key=True)
    geom = db.Column(Geometry(geometry_type='POINT', srid=4326))

rawDescription: Flask with GeoAlchemy sample code

description: Flask with GeoAlchemy sample code


rawDescription: order all row according to contents of a row

description: Order all row according to contents of a row


rawDescription: How to iterate an array in Python pointer-likely and efficiently?

description: Iterate an array in Python pointer-likely and efficiently


code:
import numpy
numpy.nextafter(0,1)
numpy.nextafter(.1, 1)
numpy.nextafter(1e6, -1)
numpy.nextafter(-.1, 1)

rawDescription: Increment a python floating point value by the smallest possible amount


code:
curve = plotItem.plot(data)
plotItem.setXRange(x1, x2)  # Move the view

rawDescription: Live Data Monitor: PyQtGraph

description: Live Data Monitor: PyQtGraph


code:
text = """In the third category he included those Brothers (the majority) who saw nothing in Freemasonry but the external forms and ceremonies, and prized the strict performance of these forms without troubling about their purport or significance. Such were Willarski and even the Grand Master of the principal lodge. Finally, to the fourth category also a great many Brothers belonged, particularly those who had lately joined. These according to Pierre's observations were men who had no belief in anything, nor desire for anything, but joined the Freemasons merely to associate with the wealthy young Brothers who were influential through their connections or rank, and of whom there were very many in the lodge.Pierre began to feel dissatisfied with what he was doing. Freemasonry, at any rate as he saw it here, sometimes seemed to him based merely on externals. He did not think of doubting Freemasonry itself, but suspected that Russian Masonry had taken a wrong path and deviated from its original principles. And so toward the end of the year he went abroad to be initiated into the higher secrets of the order.What is to be done in these circumstances? To favor revolutions, overthrow everything, repel force by force?No! We are very far from that. Every violent reform deserves censure, for it quite fails to remedy evil while men remain what they are, and also because wisdom needs no violence. "But what is there in running across it like that?" said Ilagin's groom. "Once she had missed it and turned it away, any mongrel could take it," Ilagin was saying at the same time, breathless from his gallop and his excitement. """
answer = """In the third category he included those Brothers (the majority) who saw nothing in Freemasonry but the external forms and ceremonies, and prized the strict performance of these forms without troubling about their purport or significance.
Such were Willarski and even the Grand Master of the principal lodge.
Finally, to the fourth category also a great many Brothers belonged, particularly those who had lately joined.
These according to Pierre's observations were men who had no belief in anything, nor desire for anything, but joined the Freemasons merely to associate with the wealthy young Brothers who were influential through their connections or rank, and of whom there were very many in the lodge.
Pierre began to feel dissatisfied with what he was doing.
Freemasonry, at any rate as he saw it here, sometimes seemed to him based merely on externals.
He did not think of doubting Freemasonry itself, but suspected that Russian Masonry had taken a wrong path and deviated from its original principles.
And so toward the end of the year he went abroad to be initiated into the higher secrets of the order.
What is to be done in these circumstances?
To favor revolutions, overthrow everything, repel force by force?
No!
We are very far from that.
Every violent reform deserves censure, for it quite fails to remedy evil while men remain what they are, and also because wisdom needs no violence.
"But what is there in running across it like that?" said Ilagin's groom.
"Once she had missed it and turned it away, any mongrel could take it," Ilagin was saying at the same time, breathless from his gallop and his excitement."""

output = text.split('\n')
sum(1 for sent in text.split('\n') if sent in answer)

rawDescription: Python re.split() vs nltk word_tokenize and sent_tokenize


code:
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import XmlXPathSelector

class MySpider(BaseSpider):
    name = 'myspider'

    def parse(self, response):
        xxs = XmlXPathSelector(response)
        links = xxs.select("//link/text()").extract()
        return [Request(x, callback=self.parse_link) for x in links]

rawDescription: Scrapy - Follow RSS links

description: Scrapy - Follow RSS links


code:
import sys
new_list = sys.argv[1:-1]
step3 = sys.argv[-1]

rawDescription: Transfering arguments in Automator's workflow . Python Shells


code:
import itertools
from timeit import timeit

string = 'abcdef'

def string_splosion_loop():
    i, result = 0, ''
    while i < len(string):
        i += 1
        result += string[:i]
    return result

def string_splosion_join_gen():
    return ''.join(string[:i] for i in range(1, len(string) + 1))

def string_splosion_join_lc():
    # str.join performs faster when the argument is a list
    return ''.join([string[:i] for i in range(1, len(string) + 1)])

def string_splosion_itertools():
    return ''.join(itertools.accumulate(string))

funcs = (string_splosion_loop, string_splosion_join_gen,
         string_splosion_join_lc, string_splosion_itertools)

for f in funcs:
    print('{.__name__}({}): {}'.format(f, string, timeit(f)))

rawDescription: python3 string "abcd" print: aababcabcd?

description: Python3 string "abcd" print: aababcabcd


code:
input1 = input('Please provide the string:\n')
re.search(r'(\d+)\D*' + input1, s).group(1)

rawDescription: Python: split a string using ONLY multiple spaces or single newline


code:
def is_connection_up(connection):
    if connection.ping() == 0:
        return True
    else:
        return False

rawDescription: Keeping a connection open for the purposes of testing


code:
from django.conf.urls import patterns, url
from yourapp import views

urlpatterns = patterns(
    '',
    url(r'^email/$',
        views.email,
        name='email'
        ),
    url(r'^thanks/$',
        views.thanks,
        name='thanks'
        ),
)

rawDescription: Python Django e-mail form example

description: Python Django e-mail form example


code: loader = SecondaryWindow(Toplevel())

rawDescription: TKinter checkbox behaves different in different contexsts


rawDescription: Python - Get Multiple Characters From String


code:
import random
def RandomDoorCreator(level):
    locationsfordoor = []
    xpos = ypos = 0
    for element in level:
        ypos=0
        for letter in element:
            if letter == 'R':
                locationsfordoor.append([xpos,ypos]) #If it's a possible door location, add it to the list of possibilities
            ypos+=1
        xpos+=1
    doorlocation = random.choice(locationsfordoor) #Pick a random location from our list of locations
    newrow = list(level[doorlocation[0]]) #Create a list of strings for the row that we want to replace
    newrow[doorlocation[1]] = ' ' #Replace the correct value in the row with ' '
    del(level[doorlocation[0]]) #Delete the old row from the level
    level.insert(doorlocation[0],''.join(newrow)) #Add the new row to the level

rawDescription: Create a random door in pygame

description: Create a random door in pygame


code:
def commands (command):
    command_dict = {'/help' : help, '/clear' : clear, '/commands' : commands}
    func = command_dict.get(command)

    if func is not None:
        func()
    else:
        print("I don't have such a command: %s" % command)

rawDescription: Can I call a function by inputting a string?

description: Call a function by inputting a string


code:
counts = {}
for dirpath, dirnames, fnames in os.walk("./corpus", topdown=False):
    counts[dirpath] = len(fnames)
    for d in dirnames:
        key = os.path.join(dirpath, d)
        counts[dirpath] += counts[key]

rawDescription: Counting number of documents

description: Counting number of documents


rawDescription: Fine-Uploader in depth information on the use of Azure Blob Storage through python flask


rawDescription: Pygame not displaying text

description: Pygame not displaying text


code:
import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

rawDescription: scatter plot in matplotlib

description: Scatter plot in matplotlib


rawDescription: how to convert the datatype of a varible while reading in python?

description: Convert the datatype of a varible while reading in python


code:
def __init__(self):
    self.findMe = "Here I am!"

rawDescription: How can one locate where an inherited variable comes from in Python?


code: query = reduce(operator.or_, [si.Q(word) for word in words])

rawDescription: Creating a dynamic sized OR query using Sunburnt+Solr


code:
from functools import wraps

def _log_method(val):
    @wraps(val)
    def wrapper(*a, **ka):
        print('calling', val.__name__)
        val(*a, **ka)
    return wrapper

class LogMethodCalls(type):
    def __new__(cls, cls_name, bases, attrs):
        for name, attr in attrs.items():
            if callable(attr):
                attrs[name] = _log_method(attr)
            elif isinstance(attr, (classmethod, staticmethod)):
                attrs[name] = type(attr)(_log_method(attr.__func__))
        return type.__new__(cls, cls_name, bases, attrs)

class Foo(metaclass=LogMethodCalls):

    def my_instance_method(self):
        pass

    @classmethod
    def my_class_method(cls):
        pass

    @staticmethod
    def my_static_method():
        pass

Foo().my_instance_method() # calling my_instance_method
Foo.my_class_method() # calling my_class_method
Foo.my_static_method() # calling my_static_method

rawDescription: Python - Print method name whenever the methods of a class is called


code: path2 = r'"C:\Users\bgbesase\Documents\Brent\Code\Visual Studio'

rawDescription: Adding a simple value to a string

description: Adding a simple value to a string


code:
with open('data.csv', 'rb') as csv_file:
    int_cities_data = [line for line in csv.DictReader(csv_file) if line['City'] in int_cities]

rawDescription: More efficent way to loop through list then using a double loop in python


code:
history = []
while url not in history and len(history) < 42:
    history.append(url)
    r = requests.get(url, allow_redirects=False)
    if 'location' in r.headers:
        url = r.headers['location']

rawDescription: How to handle catch and handle redirect loops through requests.get or selenium?

description: Handle catch and handle redirect loops through requests.get or selenium


code:
chocolate_ingredients = chocolate_cupcake()
lemon_drizzle_ingredients = lemon_drizzle()

rawDescription: How can I add together two local variables from different functions?

description: Add together two local variables from different functions


code: newinteger = int(gsBinary, 2) & int(binaryCode, 2)

rawDescription: Bitwise & outputting numbers other than 1 and 0


code: people_dict = dict((p.get_name(), p) for p in people_list)

rawDescription: List of classes to dict

description: List of classes to dict


code:
tuple_list = [(u'17',u'1', u'2', u'2'), (u'17',u'2', u'1', u'4')]
a = ["("+", ".join(a)+")" for a in tuple_list]
sql = "insert into 'Predictions' (userid, fixture_no, home_score, away_score) VALUES %s" % (",".join(a))
print(sql)

# Insert into database (code from memory)
args_str = ','.join(cursor.mogrify("%s", (x, )) for x in tuple_list)
cursor.execute("INSERT INTO 'Predictions' (userid, fixture_no, home_score, away_score) VALUES "+args_str)

rawDescription: Importing tuple list into Postgres via Python


code: _1s_loss_freq = grouped.apply(lambda x: x['fill'][x['1000'] < 0].sum())

rawDescription: Performing multiple calculations on a Python Pandas group from CSV data


code:
from django.contrib.auth.models import User
user = User.objects.get(username='ea87')
user
user.password
user.set_password('666monkeysAndDogs777')
user.password

rawDescription: How to use Bcrypt to encrypt passwords in Django

description: Use Bcrypt to encrypt passwords in Django


rawDescription: I need to update a specific column when writing to a text file using python


code:
import numpy

w = numpy.array([0.3, float("nan"), 0.2, 0.7, 1., -0.6]) # weights
x = numpy.array([0, 1, 1, 2, 2, 2])
numpy.bincount(x,  weights=w)
#>>> array([ 0.3,  nan,  1.1])

rawDescription: Ignore NaN in numpy bincount in python

description: Ignore NaN in numpy bincount in python


code:
# in my_app/context_processors.py
from my_app.models import MyTable

def is_empty(request):
    """Returns a bool depending on whether MyTable is empty"""
    return {'is_empty': not MyTable.objects.exists()}

rawDescription: Where is the Django Administration's view?


code:
def a(x, y, z):
   return x + y - z
b = lambda m, n: a(m, 1, n)
b(2, 5)

rawDescription: Map list by partial function vs lambda

description: Map list by partial function vs lambda


code:
PLAYSOUNDEVENT = USEREVENT + 1
...
pygame.time.set_timer(PLAYSOUNDEVENT, 6500)

rawDescription: pygame.time.set_timer confusion?

description: Pygame.time.set_timer confusion


code:
from nltk import Tree
t = Tree.fromstring("(S A/DT (VP red/VBN (NP cat/NN)) with/IN a/DT hat/JJ)")
print(t[1])
print(t[1][0])   # Element 0 of the subtree at index 1

rawDescription: NLTK Convert Tree to Array?

description: NLTK Convert Tree to Array


code:
Result
{'Country': 'USA',
 'HeadQuarters': {'LA': 'LA', 'NY': 'NY'},
 'cities': {'LA': 'Los Angeles', 'NY': 'New York'},
 'desgination': 'yyyy',
 'name': 'xxxx'}

rawDescription: Converting string into dictionary - pythonic Way


code:
def f(x): print(x)
data = list(range(53))  # list from 0 (included) to 52 (included)
# here is the top part

rawDescription: Adding 'n' values in list using for-loop and step-loop for that 'n' values in python


code:
class Rectangle:
    # Init function
    def __init__(self):
        # The only members are length and width
        self.length = 1
        self.width = 1

    # Setters
    def set_width(self, width):
        self.width = width

    def set_length(self, length):
        self.length = length

    # Getters
    def get_width(self):
        return self.width

    def get_length(self):
        return self.length

    def get_area(self):
        return self.length * self.width

    # String representation
    def __str__(self):
        return 'length = {}, width = {}'.format(self.length, self.width)

rawDescription: Creating a Rectangle class

description: Creating a Rectangle class


code:
import sys
import unittest
import logging

logger = logging.getLogger()
logger.level = logging.DEBUG

class TestCase(unittest.TestCase):
    def testSimpleMsg(self):
        stream_handler = logging.StreamHandler(sys.stdout)
        logger.addHandler(stream_handler)
        try:
            print("AA")
            logging.getLogger().info("BB")
        finally:
            logger.removeHandler(stream_handler)

rawDescription: PyDev unittesting: How to capture text logged to a logging.Logger in "Captured Output"


code:
st='''9605,Ace Ventura: Pet Detective,5
9606,Ace Ventura: Pet Detective,1
9607,Ace Ventura: Pet Detective,4
9608,Ace Ventura: Pet Detective,3
9609,Ace Ventura: Pet Detective,2
9610,Ace Ventura: Pet Detective,4
9611,Ace Ventura: Pet Detective,3
9612,Ace Ventura: Pet Detective,4
9613,Ace Ventura: Pet Detective,5
9614,Ace Ventura: Pet Detective,5
9615,Ace Ventura: Pet Detective,4
9616,Ace Ventura: Pet Detective,1
9617,Ace Ventura: Pet Detective,3
9618,Ace Ventura: Pet Detective,4
9619,Ace Ventura: Pet Detective,3
9620,Ace Ventura: Pet Detective,1
9621,Ace Ventura: Pet Detective,2
9622,Ace Ventura: Pet Detective,3
9623,Ace Ventura: Pet Detective,5
9624,Ace Ventura: Pet Detective,2
9625,Ace Ventura: Pet Detective,2
9626,Ace Ventura: Pet Detective,4
9627,Ace Ventura: Pet Detective,3
9628,Ace Ventura: Pet Detective,1'''

rawDescription: Python regular expression issues

description: Python regular expression issues


rawDescription: Dynamic Django Mail Configuration

description: Dynamic Django Mail Configuration


code:
def find_all_paths(graph, start, end, path=[], max_length=10):
    if len(path) >= max_length:
        return []
    path = path + [start]
    if start == end:
        return [path]
    if start not in graph:
        return []
    paths = []
    for node in graph[start]:
        paths += find_all_paths(graph, node, end, path, max_length=max_length)
    return paths

rawDescription: Depth First Search in Python (including cycles)


rawDescription: Parsing XML file with lxml in Python

description: Parsing XML file with lxml in Python


code:
att = {
    "roll": 34,
    "hit": False,
    "dmg": 1
}

rawDescription: python list of variables, retrieve value of variable by variable name

description: Python list of variables, retrieve value of variable by variable name


code:
a,1,file1.csv
b,2,file1.csv
aa,11,file2,csv
bb,22,file2.csv

rawDescription: 3 Dimensional Data in Python

description: 3 Dimensional Data in Python


rawDescription: Create 3D Object out of 3 views

description: Create 3D Object out of 3 views


code:
def inAll(xs, *lsts):
    return all(all(x in l for x in xs) for l in lsts)

rawDescription: How to check if an element is also in another list

description: Check if an element is also in another list


code:
class attrdict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, dict(*args))
        self.__dict__ = self

rawDescription: class __dict__ from output **kwargs, *args

description: Class __dict__ from output **kwargs, *args


code:
handle = interact('ls -lah')
while handle.poll() is None:
    pass
result = handle.done()

rawDescription: run a shell script in a python function and get data from the script

description: Run a shell script in a python function and get data from the script


code:
for class_name in class_names:
    class_name.list_name = map(lambda x: x+5 , class_name.list_name)

rawDescription: add number to all elements of a list within a class?

description: Add number to all elements of a list within a class


code:
class Bar(Base):
    __tablename__ = 'bar'
    __acl__ = [
            (Allow, 'admin', ALL_PERMISSIONS),
            (Allow, 'bar_manager', ('view', 'new', 'edit', 'delete')),
        ]
    id = Column(Integer, primary_key=True)
    foo = Column(Unicode(255))

rawDescription: Pyramid and FormAlchemy admin interface

description: Pyramid and FormAlchemy admin interface


code:
cmds = {'check': do_check, 'diff': do_diff, 'install': do_install}
fn = cmds[args.command]

rawDescription: Creating a Python command line application


code:
import json, urllib2

url = 'https://ip-ranges.amazonaws.com/ip-ranges.json'
req = urllib2.Request(url)
res = urllib2.urlopen(req)
j = json.load(res)
#print j['prefixes'][0]['ip_prefix']

prefixes = j['prefixes']
destfile = 'destfile.txt'
with open('destfile.txt', 'w') as f:
    for i in prefixes:
        #print i['ip_prefix']
        f.write(i['ip_prefix'])
        f.write('\n')
        f.close

rawDescription: Python: How to add content of file to list from position


code:
import urllib2, re

def get_data_text(month, year):
    """given a month and a year, this method returns the raw data file (as a list of rows)"""
    url_pattern = 'http://www.treasurydirect.gov/govt/reports/pd/mspd/{year:4d}/opds{month:02d}{year:4d}.prn'
    url = url_pattern.format(month=month, year=year)
    source = urllib2.urlopen(url)
    data = source.readlines()
    source.close()
    return data

def keep_only_interesting_rows(data, interesting_rows):
    """filter data rows in order to keep only the ones that start with strings in interesting_rows list"""
    return [line for line in data if any([line.strip().startswith(ir) for ir in interesting_rows])]

def convert_data_to_dict(data):
    """converts every row in data to a dictionary element """
    return {re.sub('\.*\s*$', '', el[0:46]).strip():(int(el[47:63].replace(',','')), int(el[69:90].replace(',','')), int(el[95:115].replace(',',''))) for el in data}

rawDescription: Formatting data from Text (.prn) file

description: Formatting data from Text (.prn) file


code:
x = range(0, 4)
y = range(4, 8)
ov = range(8, 12)
aa = range(12, 16)
numpy.array([x, y, ov, aa])

rawDescription: combining numpy arrays and masking

description: Combining numpy arrays and masking


code:
def f(a):
    # take left middle element for even-length lists
    mid = len(a)//2 if len(a)%2 else len(a)//2-1
    # take len(a)//2 as a middle element
    #mid = len(a)//2
    if len(a) <= 2:
        return a
    elif(len(a) == 3):
        return a[[0,-1,mid]]
    else:
        return np.append(a[[0,-1,mid]], f(np.delete(a, [0,len(a)-1,mid])))

rawDescription: Median sort a list in unordered fashion

description: Median sort a list in unordered fashion


code:
def precalc(jmat):
  JM1 = np.zeros((N,N,N))
  JM2 = np.zeros((N,N,N))
  for i in range(N):
    for j in range(N):
      for k in range(N):
        #JJ[i,j,k]=jmat[k,i]+jmat[k,j]
        if k!=i and k!=j:
          JM1[i,j,k]=jmat[k,i]+jmat[k,j]
          JM2[i,j,k]=jmat[k,i]-jmat[k,j]
  return JM1, JM2

def corr_time1(t, JM1, JM2):
    return np.prod(np.cos(2*JM1*t),axis=-1)+np.prod(np.cos(2*JM2*t),axis=-1)

JM1, JM2 = precalc(jmat)
result = np.array([np.sum(corr_time1(t,JM1,JM2)) for t in t_output])

rawDescription: Implementing intereaved products and sums in Python without loop overhead


code:
from collections import deque

d = deque(list1)
d.rotate(1)
print(d)
d.rotate(1)
print(d)

rawDescription: How to move values in a list one by one?

description: Move values in a list one by one


code: cheapest_rooms = []

rawDescription: remove all values from multiple lists at same index position with some logic

description: Remove all values from multiple lists at same index position with some logic


code: sum(x for counter in numbers.values() for x in counter.values())

rawDescription: Sum of values across all nested dictionaries in python


rawDescription: Compute fast log base 2 ceiling in python


code:
# open a file to save the data to ("wb" means write binary mode)
outfile = open(savepath+"/"+fname, "wb");
# download the data from the url specified above
infile = urllib2.urlopen(url);
# read the downloaded data and write it to our output file
outfile.write(infile.read());
# close the output file once we're done
outfile.close();

rawDescription: How to download and rewrite a file in Python?

description: Download and rewrite a file in Python


code:
alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphabet[32:1]

rawDescription: slicing dynamically in python

description: Slicing dynamically in python


code:
class MyModel(models.Model):
    title = Models.CharField()
    description = Models.TextField()

    def aux_info(self):
        return "I'm not in the database!"

rawDescription: Using __init__ in django to annotate a model with extra information


code:
{'action_type__count': 11, 'action_type': u'created'},
{'action_type__count': 11, 'action_type': u'deleted'},
{'action_type__count': 10, 'action_type': u'updated'}

rawDescription: What is an efficient way to get a count of objects grouped by a field in Django?


rawDescription: Python 3 String Method?

description: Python 3 String Method


code:
import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

rawDescription: Results in CSV should be in lists rather than strings


code:
max_vals = {}
for item, value in mylist:
    max_vals[item] = max(max_vals.get(item, value), value)

rawDescription: Improving efficiency in iterating over list sets in python


rawDescription: Efficiently re-indexing one level with "forward-fill" in a multi-index dataframe


code:
with open('test.txt', 'w') as f:
    f.write(myString.encode('latin-1'))

rawDescription: Getting the correct encoding for strings and csv-files in Python


code:
# df1 = pd.read_csv('foo.csv', sep=',', header=None, parse_dates=[0], index_col=0)

In [11]: df1.index.minute
Out[11]: array([3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4], dtype=int32)

rawDescription: Slicing Pandas Dataframe by minutes

description: Slicing Pandas Dataframe by minutes


code:
class QueueList(VirtualList):
  def __init__(self, parent, colref = 'queue_columns'):
    VirtualList.__init__(self, parent, colref)

    self.SetDropTarget(ListDrop(self.onJobDrop, 'JobIdList', True))

  def onJobDrop(self, x, y, data):
    idx, flags = self.HitTest((x, y)) #@UnusedVariable

    if idx == -1: # Not dropped on a list item in the target list.
      return

    # Code here to handle incoming data.

rawDescription: Python Simple GUI Windows Drag&Drop

description: Python Simple GUI Windows Drag&Drop


code:
coeff = [0]*len(data)
def RecursivelyListAllThatWork(k, sum): # Using last k variables, make sum
    # /* Base case: If we've assigned all the variables correctly, list this
    # * solution.
    # */
    if k == 0:
        # print what we have so far
        print(' + '.join("%2s*%s" % t for t in zip(coeff, data)))
        return
    x_k = data[k-1]
    # /* Recursive step: Try all coefficients, but only if they work. */
    for c in range(sum // x_k + 1):
       if T[sum - c * x_k, k - 1]:
           # mark the coefficient of x_k to be c
           coeff[k-1] = c
           RecursivelyListAllThatWork(k - 1, sum - c * x_k)
           # unmark the coefficient of x_k
           coeff[k-1] = 0

RecursivelyListAllThatWork(len(data), target_sum)

rawDescription: Unable to implement a dynamic programming table algorithm in python


code:
import os
import sys
import contextlib
import numpy as np
import scipy.integrate as integrate
from numpy import pi

def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd

@contextlib.contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    """
    http://stackoverflow.com/a/22434262/190597 (J.F. Sebastian)
    """
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied:
        stdout.flush()  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush()
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

#Constants and parameters
alpha=1/137.
k=1.e-9
T=40.
V= 6.e-6
r = 6.9673e12
u = 1.51856e7

#defining dy/dt's
def f(y, t):
       A, B, C, D, E = y
       # the model equations
       f0 = 1.519e21*(-2*k/T*(k - (alpha/pi)*(B+V))*A)
       f1 = ((3*B**2 + 3*C**2 + 6*B*C + 2*pi**2*B*T + pi**2*T**2)**-1
             *(-f0*alpha/(3*pi**3) - 2*r*(B**3 + 3*B*C**2 + pi**2*T**2*B)
               - u*(D**3 - E**3)))
       f2 = u*(D**3 - E**3)/(3*C**2)
       f3 = -u*(D**3 - E**3)/(3*D**2)
       f4 = u*(D**3 - E**3)/(3*E**2) + r*(B**3 + 3*B*C**2 + pi**2*T**2*B)/(3*E**2)
       return [f0, f1, f2, f3, f4]

t  = np.linspace(1e-15, 1e-10, 1000000)   # time grid
y2 = [2e13, 0, 50, 50, 25]
t2  = np.linspace(1.e-10, 1.e-5, 1000000)

with stdout_redirected():
    soln2 = integrate.odeint(f, y2, t2, mxstep = 5000)

rawDescription: Disable warnings originating from scipy

description: Disable warnings originating from scipy


code: import a

rawDescription: module holding variables, mutable vs immutable

description: Module holding variables, mutable vs immutable


code:
old_string = ' to eat breakfast at http://bobsburgers.com'
new_string = 'Bob likes to eat breakfast at http://bobsburgers.com'
old_chars = collections.Counter(old_string)
new_chars = []
for ch in new_string:
    if old_chars[ch]:
        old_chars[ch] -= 1
    else:
        new_chars.append(ch)
new_string = ''.join(new_chars)

rawDescription: Compare two sets of strings and then return whole strings that are different in Python 3.4


code:
thefile.write("%s " % name)
for item in thelist:
  thefile.write("%s,"% item)

rawDescription: How to write variable and array on the same line for a text file?

description: Write variable and array on the same line for a text file


code:
for link in links[:]:
    if {"source":link["target"], "target":link["source"]} not in links:
        links.remove(link)

rawDescription: does the for each loop in python based index?

description: Does the for each loop in python based index


code:
class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __iter__(self):
        return vars(self).iteritems()

rawDescription: Casting a custom class to a dict in python


code: args=(item,) # <- add a , to make a tuple

rawDescription: Python Threading, Arg turns itself into list


code:
results['datetime'] = datelist
results['ix'] = ixlist
results['sat_id'] = satlist
results['altitude'] = altitude

final=pd.merge(df,results,on='ix')

rawDescription: Pandas calculate new column from two other column variables within dataframe


code:
df['sums'] =  df.groupby('from')['amt'].transform('sum')
df['frac'] = df['amt'] / df['sums']
df.pivot(index='from', columns='to', values='frac')

rawDescription: matrix representation of pandas data-frame in python

description: Matrix representation of pandas data-frame in python


code:
class Image(db.Model):
    primary_image = blobstore.BlobReferenceProperty()

rawDescription: How to upload images and storing it in db google app engine

description: Upload images and storing it in db google app engine


code:
# a helper function to compute distance of two items
dist = lambda xs, ys: sum( DistMatrix[ x ][ y ] for ( x, y ) in zip( xs, ys ) )

# a second helper function to compute distances from a given item
xdist = lambda x: { idx: dist( x, y ) for (idx, y) in sample.iterrows( ) }

# the pairwise distance matrix
pd.DataFrame( { idx: xdist( x ) for ( idx, x ) in sample.iterrows( ) } )

rawDescription: Distance calculation between rows in Pandas Dataframe using a distance matrix


rawDescription: Force print statement to a single line in python


code:
def maxrow(x, col):
    return x.loc[x[col].argmax()].to_frame().T

result = df.groupby('c1').apply(maxrow, 'c3')
result = result.reset_index(level=0, drop=True)
print(result)

rawDescription: How to get rows in pandas data frame, with maximal values in a column and keep the original index?

description: Get rows in pandas data frame, with maximal values in a column and keep the original index


rawDescription: Is my eval implementation completely safe?


code:
import requests
from  lxml import html
import js2xml

post = "http://www.asambleamadrid.es/ES/QueEsLaAsamblea/ComposiciondelaAsamblea/LosDiputados/Paginas/RelacionAlfabeticaDiputados.aspx"

def validate(xml):
    # these fields are the minimum required as cannot be hardcoded
    data = {"__VIEWSTATEGENERATOR": xml.xpath("//*[@id='__VIEWSTATEGENERATOR']/@value")[0],
            "__EVENTVALIDATION": xml.xpath("//*[@id='__EVENTVALIDATION']/@value")[0],
            "__VIEWSTATE": xml.xpath("//*[@id='__VIEWSTATE']/@value")[0],
            " __REQUESTDIGEST": xml.xpath("//*[@id='__REQUESTDIGEST']/@value")[0]}
    return data

with requests.Session() as s:
    # make initial requests to get the links/hrefs and the from fields
    r = s.get(
        "http://www.asambleamadrid.es/ES/QueEsLaAsamblea/ComposiciondelaAsamblea/LosDiputados/Paginas/RelacionAlfabeticaDiputados.aspx")
    xml = html.fromstring(r.content)
    hrefs = xml.xpath("//*[@id='moduloBusqueda']//div[@class='sangria']/ul/li/a/@href")
    form_data = validate(xml)
    for h in hrefs:
        js_xml = js2xml.parse(h)
        _id = js_xml.xpath(
            "//identifier[@name='WebForm_PostBackOptions']/following-sibling::arguments/string[starts-with(.,'ctl')]")[
            0]
        form_data["__EVENTTARGET"] = _id.text
        r = s.post(post, data=form_data)
        xml = html.fromstring(r.content)
        print(xml.xpath("//ul[@class='listadoVert02']/ul/li/a/text()"))

rawDescription: Scrapy crawling not working on ASPX website


code:
s = get_support(df)
s[s.Support >= 3]

rawDescription: best way to implement Apriori in python pandas

description: Implement Apriori in python pandas


code:
file = pd.read_table('table.txt', index_col=False)
file

rawDescription: Pandas DataFrame Cannot Read Data

description: Pandas DataFrame Cannot Read Data


code:
import sys
import os
import time

def mainLoop(size):
    myBuffer = [0]*size
    count = 0

    while True:
        for i in range(size):
            myBuffer[i] = sys.stdin.readline()

        f = open('/home/development/textFilter/' + repr(count) + '.dat', 'w')
        f.write(''.join(myBuffer))
        f.close()

        f = open('/home/development/textFilter/count.dat~', 'w')
        f.write(repr(count))
        f.flush()
        os.fsync(f.fileno())
        f.close()
        time.sleep(0.01)
        os.rename('/home/development/textFilter/count.dat~','/home/development/textFilter/count.dat')

        count += 1
        count = count % 16

if __name__ == "__main__":
    try:
        mainLoop(int(sys.argv[1]))
    except Exception:
        mainLoop(100)

rawDescription: Python: clear stdin Buffer

description: Python: clear stdin Buffer


code:
class FooWrapper(object):
    def __init__(self, value):
         self.value = value
    def __repr__(self):
         return 'FooWrapper(' + repr(self.value) + ')'
    def __str__(self):
        return str(self.value)
    def __call__(self,value):
        self.value = value

rawDescription: List element Pointer in Python

description: List element Pointer in Python


code:
missingint(0,1) == 2
missingint(1,0) == 2
missingint(0,2) == 1
missingint(2,0) == 1
missingint(1,2) == 0
missingint(2,1) == 0

rawDescription: Given two of three items, return the missing item


code:
import re
inputtext = '''\
- launchers
   - say hello
      - command: echo "hello" | festival --tts
      - icon: sayHello.png
   - say world
      - command: echo "world" | festival --tts
      - icon: sayWorld.png
   - wait
      - command: for ((x = 0; x < 10; ++x)); do :; done
      - icon: wait.png
'''
line = re.compile(r'( *)- ([^:\n]+)(?:: ([^\n]*))?\n?')
depth = 0
stack = [{}]
for indent, name, value in line.findall(inputtext):
    indent = len(indent)
    if indent > depth:
        assert not stack[-1], 'unexpected indent'
    elif indent < depth:
        stack.pop()
    stack[-1][name] = value or {}
    if not value:
        # new branch
        stack.append(stack[-1][name])
    depth = indent

result = stack[0]
from pprint import pprint
pprint(result)

rawDescription: How can a Markdown list be parsed to a dictionary in Python?


code:
from collections import defaultdict
from datetime import datetime, timedelta
from itertools import chain, groupby

def aggregate(data, resolution='daily'):
    assert resolution in ['hourly', 'daily']
    if resolution == 'hourly':
        round_dt = lambda dt: dt.replace(minute=0, second=0, microsecond=0)
    else:
        round_dt = lambda dt: dt.date()

    flat = sorted((round_dt(datetime.strptime(d, '%m-%d-%Y-%H-%M')), f, c)
                  for (d, f, c) in chain(*A))
    counts = [(d, f, sum(e[2] for e in l))
              for (d, f), l
              in groupby(flat, key=lambda t: (t[0], t[1]))]
    result = {}
    for day, data in groupby(counts, key=lambda d: d[0]):
        d = result[day] = defaultdict(int)
        d.update((f, c) for d, f, c in data)
    return result

def xaggregate(data, resolution='daily'):
    aggregated = aggregate(data, resolution)
    curr = min(aggregated.keys())
    end = max(aggregated.keys())
    interval = timedelta(days=1) if resolution == 'daily' else timedelta(seconds=3600)
    while curr <= end:
        # None is sensible value in case of missing data I think
        yield curr, aggregated.get(curr)
        curr += interval

rawDescription: Aggregate and fill data for missing dates (days and hours)


code:
import random
def randreplace(str,c,c_replace,maxnum=0):
    if maxnum >= str.count(c) or maxnum<1:
        return str.replace(c,c_replace)
    indices = [i for i,x in enumerate(str) if x==c]
    replacements = random.sample(indices,maxnum)
    st_pieces = (x if not i in replacements else c_replace for i,x in enumerate(str))
    return "".join(st_pieces)

rawDescription: Conditionally format a string - Python

description: Conditionally format a string - Python


code:
import urllib2

alan2 = urllib2.urlopen("http://ifarchive.plover.net/if-archive/games/competition2001/alan/chasing/chasing.acd").read(4)
alan3 = urllib2.urlopen("http://mirror.ifarchive.org/if-archive/games/competition2006/alan/enterthedark/EnterTheDark.a3c").read(4)

alan2
alan3

rawDescription: Translating a C binary data read function to Python


rawDescription: Every possible combination of a multi-list


code: subprocess.call(['bash', '-c', 'rm grep.tmp'])

rawDescription: strange output when using flags in python

description: Strange output when using flags in python


code: list(g)  # happens to be the same as the above...

rawDescription: Sorting the grouped data as per group size in Pandas


code: by_id = weakref.WeakValueDictionary()

rawDescription: Can I iterate over a class in Python?

description: Iterate over a class in Python


code:
from operators import itemgetter
sorted(results, key=itemgetter(0))

rawDescription: Can I manipulate how sorted() organizes things?

description: Manipulate how sorted() organizes things


code:
somevariable = 1.1
time.sleep(somevariable)

rawDescription: How can I use a variable instead of a floating value for time.sleep()

description: Use a variable instead of a floating value for time.sleep()


rawDescription: How to find the max number in this type of data structure in Python

description: Find the max number in this type of data structure in Python


rawDescription: Function that prints all the strings in A that start with '-1' or with '1'


code:
from tifffile import imsave, imread
a
imsave("a.tif", a)
b = imread("a.tif")
b

rawDescription: Why do values in my 3D numpy array change when I write it to file?


code:
import numpy as np
ndcg, rmse, mae = [], [], []
for i in xrange(11):
    rand = np.random.sample(3)
    ndcg.append(rand[0])
    rmse.append(rand[1])
    mae.append(rand[2])

rawDescription: Convert from matplotlib to ggplot2 within python


code: r'^admin/', include(admin.site.urls)

rawDescription: Django mixes my templates

description: Django mixes my templates


rawDescription: Is it possible to use .tk_setPalette() on the content of only one Frame?


code:
def linkify(raw_message):
    message = raw_message
    for url in url_regex.findall(raw_message):
        if url.endswith('.'):
            url = url[:-1]
        if 'http://' not in url:
            href = 'http://' + url
        else:
            href = url
        message = message.replace(url, '%s' % (href, url))

    return message

rawDescription: Making links clickable in retrieved tweets


code:
from Crypto.Cipher import AES
from Crypto import Random
key = b'Sixteen byte key'
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')
msg.encode("hex")

rawDescription: Python: Two-way Alphanumeric Encryption

description: Python: Two-way Alphanumeric Encryption


code: means = df.groupby(group, axis=1).transform('mean')

rawDescription: DataFrame subtract group-wise means

description: DataFrame subtract group-wise means


rawDescription: Get a value from a dictionary without linking to the memory location


rawDescription: Is there a python method to set the specified elements to be some value in a list?


rawDescription: Apply a comparison between two numpy.arrays to only one column but retrieve whole rows


rawDescription: Appending '0x' before the hex numbers in a string


code: x = re.compile("(%s|%s|%s)" % (re.escape(userstring), re.escape(userStrHEX), re.escape(userStrASCII)), re.IGNORECASE)

rawDescription: I'm trying to implement a valid Regex pattern


code:
class StudentList(generics.ListCreateAPIView):
    serializer_class = PersonSerializer

    def get_queryset(self):
        city = City.objects.get(pk=self.kwargs.get('pk', None))
        students = Student.objects.filter(city=city)
        return students

rawDescription: Consuming api from django rest framework


code:
def test_list(l):
    return (len(l)==2 and {t[1] for t in l}==set('AB'))

rawDescription: Python: Compare Filenames in Folder

description: Python: Compare Filenames in Folder


code:
while True:
    response = input("for demonstration purpose: did the payment succeed, yes or no?").lower()
    if response in ('y', 'yes', 'n', 'no'):
        payment_succeeded = response in ('y', 'yes')
        break
    print('Sorry, I did not understand that input, please try again.')

rawDescription: if statement somehow always true

description: If statement somehow always true


code:
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.dialects.postgresql import ARRAY

modmethods = ['add', 'clear', 'difference_update', 'discard',
              'intersection_update', 'pop', 'remove',
              'symmetric_difference_update', 'update',
              '__ior__', '__iand__', '__isub__', '__ixor__']

class MutableSet(Mutable, set):
    @classmethod
    def coerce(cls, key, value):
        if not isinstance(value, cls):
            return cls(value)
        else:
            return value

def _make_mm(mmname):
    def mm(self, *args, **kwargs):
        try:
            retval = getattr(set, mmname)(self, *args, **kwargs)
        finally:
            self.changed()
        return retval
    return mm

for m in modmethods:
    setattr(MutableSet, m, _make_mm(m))

del modmethods, _make_mm

def ArraySet(_type, dimensions=1):
    return MutableSet.as_mutable(ARRAY(_type, dimensions=dimensions))

rawDescription: SQLAlchemy/PostgreSQL mutable, deduplicated array


rawDescription: Python Convert Int List to Decimal string then back to Int List


code:
my_l = [1,2,3]
ref_my_l = my_l
ref_my_l
my_l.append(4)
my_l
ref_my_l

rawDescription: List getting replaced

description: List getting replaced


code:
from tkinter import *
from functools import partial

ENTER = '7'
LEAVE = '8'

# extra argument - unique tag
def change_color_on_enter_or_leave(event, tag):

    canvas = event.widget

    # find by tag
    item_ids = canvas.find_withtag(tag)

    for item_id in item_ids:
        if event.type == ENTER:
            canvas.itemconfig(item_id, fill="orange")
        elif event.type == LEAVE:
            canvas.itemconfig(item_id, fill="red")

root = Tk()
canvas = Canvas(root, background="white")
label = Label(root)

for x in range(0, 200, 50):
    for y in range(0, 200, 50):

        # create unique tag
        tag = 'rectangle_%s_%s' % (x,y)
        canvas.create_rectangle((x, y), (x + 40, y + 40), fill='red', tag=tag)

        # use unique tag in function
        canvas.tag_bind(tag, '<Enter>', lambda event,t=tag:change_color_on_enter_or_leave(event,t))
        canvas.tag_bind(tag, '<Leave>', lambda event,t=tag:change_color_on_enter_or_leave(event,t))

canvas.grid()
label.grid()

root.mainloop()

rawDescription: Tkinter canvas leave event isn't trigged


rawDescription: Sum values in a Python dict?

description: Sum values in a Python dict


code:
import matplotlib.pyplot as plt
plt.bar(bins,fracs)
plt.show()

rawDescription: plotting bounded CDF of discrete count data in matplotlib python

description: Plotting bounded CDF of discrete count data in matplotlib python


code:
a = [[0 for _ in range(rows)] for _ in range(cols)]
a[2][1] = a[2][1] + 5
a

rawDescription: Python two dimensional list add value to element


code:
import wx

class ForgotPass(wx.Dialog):

    def __init__(self, *args, **kwargs):
        super(ForgotPass, self).__init__(*args, **kwargs)

        self.InitUI()

    def InitUI(self):
        self.panel = wx.Panel(self)
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.title = wx.StaticText(self.panel, label='Forgotten Your Password?', style=wx.ALIGN_CENTER)
        self.title.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, underline=True))  # Underlined & Bold
        self.sizer.Add(self.title)

        self.text = wx.StaticText(self.panel, label="Contact 'TheHiguty' via ingame PM to have your password reset!", style=wx.ALIGN_CENTER)
        self.sizer.Add(self.text)

        self.SetSizer(self.sizer)
        self.sizer.Fit(self.panel)
        self.SetSize((400, 150))
        self.SetTitle('Forgotten Your Password')
        self.Center()
        self.Show(True)

def main():
    app = wx.App(False)
    ForgotPass(None)
    app.MainLoop()

if __name__ == "__main__":
    main()

rawDescription: wxPython Custom Dialog loading incorrectly

description: WxPython Custom Dialog loading incorrectly


code:
s = 'GigabitEthernet0/0/0/0 '
s[:2]+''.join([i for i in s if i.isdigit()])

rawDescription: Complex regex in Python

description: Complex regex in Python