code:
create_query(who_id=123, subject="Boss", description="he's bossy",
             will_be_ignored="really?")

rawDescription: Auto format arguments to string

description: Auto format arguments to string


code:
(np.array([np.array(h)[...,:] == c for h in classes]).all(axis = -1) *
         (2 + np.arange(len(classes)))[:, None, None]).max(axis=0) - 1

rawDescription: Numpy.select from 3D array

description: Numpy.select from 3D array


code:
for c in itertools.combinations(zip(foo, bar, baz), 2):
    for u in zip(*c):
        print(u)

rawDescription: How to do simultaneous combinations in python? (itertools)

description: Do simultaneous combinations in python? (itertools)


code:
cubed = (x ** 3 for x in range(1, 11))
cube4 = [c for c in cubed if c % 4 == 0]

rawDescription: Is this list comprehension pythonic enough?


code:
class PKMovie(db.Model):
    # ...
    future_show_times = db.relationship(
        lambda: ShowTime,
        primaryjoin=lambda: db.and_(
            PKMovie.id == ShowTime.pk_movie_id,
            ShowTime.date >= db.func.current_timestamp()
        ),
        viewonly=True
    )

rawDescription: Can the contents of a relationship be filtered when querying parent model?


code:
{key: [{k: v} for sublist in value for k, v in sublist] for key, value in dic1.items()}
from pprint import pprint
pprint(_)

rawDescription: Converting a nested tuples into nested dictionaries


code:
import random
keys, values = [[1,2,3,4], ['a','b','c','d']]
random.shuffle(values)
result =  [{k:v} for k, v in zip(keys, values)]

rawDescription: create a list of dictionaries with randomised elements from two lists - python

description: Create a list of dictionaries with randomised elements from two lists - python


code:
import json
d = {'apple': 1, 'bear': 2}
print(d)
print(json.dumps(d))

rawDescription: Import a exported dict into python

description: Import a exported dict into python


code: full_links = [ x.replace(pattern,pattern+str(number)) for x in full_links]

rawDescription: Insert a character into a url

description: Insert a character into a url


From: David

To: Carl

From: George

From: Bob

To: Dave

To: Alice

rawDescription: MongoDB: Remove duplicate records from Projection


code:
from sqlalchemy.orm import Query

class MyQuery(Query):

  def all_active(self):
    return self.filter(User.is_active == True)

rawDescription: SQLAlchemy - can you add custom methods to the query object?


code:
import pycuda.autoinit
import pycuda.driver as cuda

(free,total)=cuda.mem_get_info()
print("Global memory occupancy:%f%% free"%(free*100/total))

for devicenum in range(cuda.Device.count()):
    device=cuda.Device(devicenum)
    attrs=device.get_attributes()

    #Beyond this point is just pretty printing
    print("\n===Attributes for device %d"%devicenum)
    for (key,value) in attrs.iteritems():
        print("%s:%s"%(str(key),str(value)))

rawDescription: PyCUDA: Querying Device Status (Memory specifically)


code: scatter(x, np.sqrt(x), y_axis_type="log", y_range=[0.1, 10**2], line_width=2, line_color="yellow", legend="y=sqrt(x)")

rawDescription: Log scale using Bokeh's scatter function


rawDescription: group by values across two columns and filter in Pandas

description: Group by values across two columns and filter in Pandas


code:
class UserLikes(db.Model):
    food = db.StringListProperty()

rawDescription: modelling the google datastore/python

description: Modelling the google datastore/python


code:
f = open('/dev/null', 'w')
sys.stdout = f

rawDescription: Redirecting stdout to "nothing" in python


code:
def morris_generator(maxlen, start=1):
    num = str(start)
    while len(num) < maxlen:
        yield int(num)
        num = next_morris(num)

rawDescription: Can anyone provide a more pythonic way of generating the morris sequence?


code: df = read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])

rawDescription: Having trouble with lists and matrix using xlrd and python


code:
# noinspection PyUnusedLocal
def foo():
    unused_thing = something()

rawDescription: Explicitly declaring variable as unused in Python/PyCharm


rawDescription: Print different results in Python a dictionary


code:
for k,v in sorted(((max(d[k]), k) for k in d), reverse=True):
    print('{} : {}'.format(v,k))

rawDescription: Sorting a dictionary by highest value of nested list


code:
import sys

with suppress_output(sys.stderr):
    import pynotify

rawDescription: GTK errors when importing pynotify

description: GTK errors when importing pynotify


code:
iter0, iter1, iter2 = itertools.tee(input_iter, 3)

len_gen = itertools.accumulate(map(lambda x: 1, iter0))
sum_gen = itertools.accumulate(iter1)
sum_sq_gen = itertools.accumulate(map(lambda x: x*x, iter2))

parallel_gen = zip(len_gen, sum_gen, sum_sq_gen)  # zip is a generator in Python 3

for ilen, sum_x, sum_x_sq in parallel_gen:
    pass    # the generators do all the work, so there's nothing for us to do here

# ilen_x, sum_x, sum_x_sq have the right values here!

rawDescription: iterating over a single list in parallel in python

description: Iterating over a single list in parallel in python


rawDescription: Finding a pattern inside a string in Python


rawDescription: Regular expression matching [^a-z] or $

description: Regular expression matching [^a-z] or $


code:
@models.signals.m2m_changed(sender=MyModel.second_m2m.through)
def duplicate_other_on_this_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
    # just before adding a possibly empty set in "second_m2m", check and populate.
    if action == 'pre_add' and not pk_set:
        instance.__was_empty = True
        pk_set.update(instance.first_m2m.values_list('pk', flat=True))

@models.signals.m2m_changed(sender=MyModel.first_m2m.through)
def duplicate_this_on_other_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
    # Just in case the "first_m2m" signals are sent after the other
    # so the actual "population" of the "second_m2m" is wrong:
    if action == 'post_add' and not pk_set and getattr(instance, '__was_empty'):
        instance.second_m2m = list(pk_set)
        delattr(instance, '__was_empty')

rawDescription: Django many-to-many field copy

description: Django many-to-many field copy


rawDescription: How to rewrite static url about flask?

description: Rewrite static url about flask


rawDescription: How to efficiently modify all elements of a list of lists and add them to the existing list of lists

description: Efficiently modify all elements of a list of lists and add them to the existing list of lists


rawDescription: Reading request parameters in Python

description: Reading request parameters in Python


code:
x=[1,2,3]
k= x.pop(0)
x.append(k)
return k

rawDescription: How to make a function that will return items in a list one at a time?

description: Make a function that will return items in a list one at a time


code:
scene = QGraphicsScene()
ellipseItem = MyGraphicsEllipseItem(centerx, centery, rad, rad)
scene.addItem(ellipseItem)

view = QGraphicsView(scene)
view.show()

scene.setBackgroundBrush(Qt.black)

rawDescription: How to detect mouse click on ellipse drawn in pyside?

description: Detect mouse click on ellipse drawn in pyside


code:
def sort_tuple(t):
    result = () # start with an empty result
    for val in t:
        result = insert_tup(val, result) # insert each value into its place
    return result

rawDescription: how to define sort_tuple that returns a tuple in ascending order

description: Define sort_tuple that returns a tuple in ascending order


rawDescription: Keep only sentences with a single word in Pandas DatFrame


code:
import SimpleHTTPServer
import BaseHTTPServer

def main():
    request_handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    request_handler.server_version = "Server: Apache123"
    request_handler.sys_version = ""
    BaseHTTPServer.test(HandlerClass = request_handler, ServerClass = BaseHTTPServer.HTTPServer)

if __name__ == "__main__":
    main()

rawDescription: Python SimpleHTTPServer: change response header


code: url.replace('github', access_token() + '@github')

rawDescription: Cleaner way to use re.sub

description: Cleaner way to use re.sub


code:
import re
import pickle

inputfile = open("input.txt").read()
inputfile = inputfile.decode('utf-8')

pat = re.compile(r"(@.*\*)")

mylist = pat.findall(inputfile)

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

pickle.dump(mylist, outputfile)

outputfile.close()

rawDescription: Python: Problems with latin characters in output


code: stream = [' '.join(x.replace('\t',' ').split()) for x in stream]

rawDescription: Delete tab character from config files

description: Delete tab character from config files


rawDescription: Selenium: do javascript actions reflect in driver.page_source?


code:
from django.db import models

class CanceledTask(models.Model):
    task_id = models.CharField(max_length=200)

def cancel_task(request_id):
    CanceledTask.objects.create(task_id=request_id)

def task_canceled(request_id):
    return CanceledTask.objects.filter(task_id=request_id).exists()

rawDescription: Celery revoke task before execute using django database


code:
def rnd(l):
    return random.choice(l)

rawDescription: Trying to output to file as well as printing to screen inside a for loop


rawDescription: How can I reduce lines in a DataFrame, aggregating identical values in a given column?

description: Reduce lines in a DataFrame, aggregating identical values in a given column


code:
class TrieSearch(object):
    def __init__(self, trie, starting_index):
        self.trie = trie
        self.starting_index = starting_index
        self.ending_index = starting_index + 1

    def update(self, letter):
        """ This returns a boolean indicating
            if the search can accept the letter """
        self.trie = self.trie.traverse(letter)
        if self.trie is not None:
            self.ending_index = self.ending_index + 1
            return True
        return False

    def get_match(self, letters):
        return letters[self.starting_index:self.ending_index]

def find_matches(root, letters):
    completed_matches = []
    current_matches = []

    for index, letter in enumerate(letters):
        new_current = []

        for current in current_matches:
            if current.update(letter):
                new_current.append(current)
            else:
                completed_matches.append(current)

        new_search_trie = root.traverse(letter)
        if new_search_trie is not None:
            new_current.append(TrieSearch(new_search_trie, index))

        current_matches = new_current

    all_matches = completed_matches + current_matches
    return [match.get_match(letters) for match in all_matches]

rawDescription: find and remove common substring with python

description: Find and remove common substring with python


rawDescription: How can I add an element at the top of an OrderedDict in python?

description: Add an element at the top of an OrderedDict in python


rawDescription: Dump a Python dictionary with array value inside to CSV


code: newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]

rawDescription: deleting multiple elements without updating till the end

description: Deleting multiple elements without updating till the end


code:
for word in words_in_string(my_word_list, a_string):
    print(word)

rawDescription: Python: how to determine if a list of words exist in a string


code:
import itertools
import operator

def split_series(points, interval):
    start = points[0][0]

    return [[v for k, v in grouper] for group, grouper in
            itertools.groupby((((n - start) // interval, val)
                               for n, val in points), operator.itemgetter(0))]

rawDescription: Grouping data points into series

description: Grouping data points into series


rawDescription: Can someone explain how to use the repr function to format the output?


code:
foo_proc = subprocess.Popen(['foo'], stderr=subprocess.PIPE)

thread = threading.Thread(target=stream_reader, args=(foo_proc.stderr,))
thread.setDaemon(True) # optional
thread.start()

# do other stuff

thread.join() # await thread termination (optional for daemons)

rawDescription: subprocess stdout/stderr to finite size logfile

description: Subprocess stdout/stderr to finite size logfile


rawDescription: Sort N-D numpy array by column with a smaller N-D array


rawDescription: csv parsing and manipulation using python

description: Csv parsing and manipulation using python


code:
from struct import Struct

class StructIBM32(object):
    """
    see example in:
    http://en.wikipedia.org/wiki/IBM_Floating_Point_Architecture#An_Example

    >>> import struct
    >>> c = StructIBM32(1)
    >>> bit = '11000010011101101010000000000000'
    >>> c.unpack(struct.pack('>L', int(bit, 2)))
    [-118.625]
    """
    def __init__(self, size):
        self.p24 = float(pow(2, 24))
        self.unpack32int = Struct(">%sL" % size).unpack
    def unpack(self, data):
        int32 = self.unpack32int(data)
        return [self.ibm2ieee(i) for i in int32]
    def ibm2ieee(self, int32):
        if int32 == 0:
            return 0.0
        sign = int32 >> 31 & 0x01
        exponent = int32 >> 24 & 0x7f
        mantissa = (int32 & 0x00ffffff) / self.p24
        return (1 - 2 * sign) * mantissa * pow(16, exponent - 64)

if __name__ == "__main__":
    import doctest
    doctest.testmod()

rawDescription: python: unpack IBM 32-bit float point

description: Python: unpack IBM 32-bit float point


code: player, blocklist = load() or (None, [])

rawDescription: Save a list of objects on exit of pygame game


code:
class MaskInputDelegate(QItemDelegate):

    def __init__(self, mask, parent=None):
        QItemDelegate.__init__(self, parent)
        self._mask = mask

    def createEditor(self, parent, option, index):
        editor = QLineEdit(parent)
        editor.setInputMask(self._mask)
        return editor

rawDescription: PyQt4 QStandardItem need setInputMask

description: PyQt4 QStandardItem need setInputMask


code:
member = NodeID.EIGENVECTOR
member.value

rawDescription: Django API passing class/field names, not values associated with them


code:
from flask import Markup

def linkify(text):
    return Markup(re.sub(r'@([a-zA-Z0-9_]+)', r'@\1', text))

rawDescription: How to make a filter to check if someone has tagged a user with @?

description: Make a filter to check if someone has tagged a user with @


rawDescription: numpy and pandas timedelta error

description: Numpy and pandas timedelta error


code:
aGrid = np.arange(0, 10, dtype=float)
mGrid = np.arange(100, 110, dtype=float)
eGrid = np.arange(1000, 1200, dtype=float)
A,M,E = np.meshgrid(aGrid, mGrid, eGrid, indexing='ij')
Z = A.copy()
Z[Z > 3] = np.NaN

grids = [A,M,E]
grid_bc = np.broadcast_arrays(*grids)
Z2 = np.column_stack([g.ravel() for g in grid_bc])
Z2[np.isnan(Z.ravel())] = np.nan
Z3 = Z2[~np.isnan(Z2)]

rawDescription: Correspondence between a "ij" meshgrid and a long meshgrid


code: grants = sel.xpath('.//html//body')

rawDescription: Added iterating over page id in Scrapy, responses in parse method no longer run


code:
[wnl.lemmatize(i) for i in word_tokenize("the woman's going home")]
[wnl.lemmatize(i) for i in word_tokenize("the women's home is in London")]

rawDescription: What should be the outcome of stemming a word with apostrophe?


code:
def print_file(x):
    return open('/home/me/data/db/test.blast', 'r').read()

rawDescription: Retain formatting

description: Retain formatting


code:
def sum_digits(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s

rawDescription: Sum the digits of a number - python

description: Sum the digits of a number - python


code:
from forms.py import SearchForm

def cdr(request, form_class=SearchForm):
  queryset = CdrView.objects.all()
  search_form = SearchForm(request.REQUEST)
  if search_form.is_valid():
      search_src = search_form.cleaned_data.get('search_src',None)
      search_dest = search_form.cleaned_data.get('search_dest',None)
      if search_src:
          queryset = queryset.filter(src__icontains=search_src)
      if search_dest:
          queryset = queryset.filter(dest__icontains=search_dest)
  return object_list(request,
                     queryset = queryset,
                     template_name = "reports/cdrview_list.html",
                     extra_context = {'search_form': search_form },
                     paginate_by = 200,
                     page = request.GET.get('page', 1)
                     )

rawDescription: How to filter objects of an object_list of a generic view in Django

description: Filter objects of an object_list of a generic view in Django


code:
def yield_sentences(node):
    if node.is_leaf():
        yield node.word
    else:
        for child in node.children:
            for sentence in yield_sentences(child):
                yield '{} {}'.format(node.word, sentence)

rawDescription: Retrieving branches from a nested dictionary


code:
import couchdb.design
from couchview.version import CurrentVersion

db = get_couch_db() # omitted for brevity
couchdb.design.ViewDefinition.sync_many(db, [CurrentVersion()], remove_missing=True)

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


rawDescription: Numpy Lookup (Map, or Point)

description: Numpy Lookup (Map, or Point)


rawDescription: DFT gives different results if iterated

description: DFT gives different results if iterated


code: l = np.array([list(method().values()) for _ in range(1, 11)])

rawDescription: How to get values from a map and set them into a numpy matrix row?

description: Get values from a map and set them into a numpy matrix row


code:
from StringIO import StringIO
import sys

stringio = StringIO()
previous_stdout = sys.stdout
sys.stdout = TeeOut(stringio, previous_stdout)

# do stuff

sys.stdout = previous_stdout

myString = stringio.getvalue()

rawDescription: Read python stdout as string

description: Read python stdout as string


code: m2 = [i for i, (csum, counter) in enumerate(zip(countersum, gmcounter)) if csum == 2 and 2 in counter]

rawDescription: return list indices if two conditions met in python

description: Return list indices if two conditions met in python


code:
@register.filter
def in_list(value,arg):
    return value in arg

rawDescription: Django multiselect checkboxes

description: Django multiselect checkboxes


code:
doc = Document()
v = doc.appendChild(doc.createElement('v'))
v.toxml()
v.childNodes
v.appendChild(doc.createTextNode(''))
v.childNodes
v.toxml()

rawDescription: Empty XML element handling in Python

description: Empty XML element handling in Python


code:
x, y = sorted((x, y))
range(x, y)

rawDescription: python for loop increasing or decreasing

description: Python for loop increasing or decreasing


code: str(var)

rawDescription: How to add multiple variables on the same line with string in between?

description: Add multiple variables on the same line with string in between


rawDescription: Webscraping with Xpath in Python

description: Webscraping with Xpath in Python


rawDescription: Python urlparse -- extract domain name without subdomain


code: X[:] = instances

rawDescription: storing record arrays in object arrays

description: Storing record arrays in object arrays


code:
type(1)
type('X')

rawDescription: Does the list have any numbers?

description: Does the list have any numbers


code:
q
q.reshape(4,2,3,order='F')

rawDescription: numpy create 3D array from indexed list

description: Numpy create 3D array from indexed list


code:
from collections import defaultdict
d2_dict = defaultdict(dict)
d2_dict[('canned_food', 'food')]['spam'] = 'delicious'
d2_dict

rawDescription: 2d dictionary with multiple keys per value


code:
import json
from collections import Counter

with open(path) as file:
    c = Counter(json.loads(line).get('tz') for line in file)
print(c['America/New_York']) # -> 1251

rawDescription: Example from "Python for Data Analysis", Chapter 2


code: from django.core.urlresolvers import reverse

rawDescription: Django, redirected url is not proper

description: Django, redirected url is not proper


code:
from itertools import groupby

groups = groupby(sorted(tuples), key=lambda kv: kv[0])

rawDescription: flip keys and values in dictionary python

description: Flip keys and values in dictionary python


code:
from heapq import nlargest
lst = [9,1,6,4,2,8,3,7,5]
nlargest(3, lst) # Gives [9,8,7]

rawDescription: how to efficiently get the k bigger elements of a list in python

description: Efficiently get the k bigger elements of a list in python


code: data = session.query(T1).join(T2, and_(T1.some_int == T2.id, T1.some_string == T2.name)).all()

rawDescription: SQLAlchemy: filtering multiple column values in a subquery


code:
#convert dataframe to data array and removes date column not to be processed,
sliced = df.iloc[0:, 1:8].dropna()
hpc = sliced.values

k_means = KMeans()
k_means.fit(hpc)

# array of indexes corresponding to classes around centroids, in the order of your dataset
classified_data = k_means.labels_

#copy dataframe (may be memory intensive but just for illustration)
df_processed = df.copy()
df_processed['Cluster Class'] = pd.Series(classified_data, index=df_processed.index)

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


code:
import pylab as pl
pl.figure(figsize=(18, 4))
pl.vlines(pd.Series(t1), 0, 1, colors="g", lw=1)
pl.vlines(df.t1, 0.3, 0.7, colors="r", lw=2)
pl.vlines(df.t2, 0.3, 0.7, colors="b", lw=2)
pl.margins(0.02)

rawDescription: pandas.merge: match the nearest time stamp >= the series of timestamps

description: Pandas.merge: match the nearest time stamp >= the series of timestamps


code:
s = '❄'
s.encode() # "utf8" by default

rawDescription: How can I print the decimal representation of a unicode string?

description: Print the decimal representation of a unicode string


rawDescription: Numpy: Generate 2 sequences of n random numbers with no overlaps


code:
def someFunc(args):
    return expr

rawDescription: What does this lambda function do?

description: What does this lambda function do


code:
class dd_dict(dict):    # the dd is for "deferred delete"
    _deletes = None
    def __delitem__(self, key):
        if key not in self:
            raise KeyError(str(key))
        dict.__delitem__(self, key) if self._deletes is None else self._deletes.add(key)
    def __enter__(self):
        self._deletes = set()
    def __exit__(self, type, value, tb):
        for key in self._deletes:
            try:
                dict.__delitem__(self, key)
            except KeyError:
                pass
        self._deletes = None

rawDescription: custom dict that allows delete during iteration

description: Custom dict that allows delete during iteration


code:
def maps(list):
    list_integer = []
    for i in list:
        list_integer.append(len(i))
    return list_integer

rawDescription: Assigning return value of a function to a variable in Python


rawDescription: Django Rest Framework 3.1 breaks pagination.PaginationSerializer


rawDescription: accessing values from a list in python

description: Accessing values from a list in python


code:
import collections
sentence = """As far as the laws of mathematics refer to reality they are not certain as far as they are certain they do not refer to reality"""
words = sentence.split()
word_counts = collections.Counter(words)
for word, count in sorted(word_counts.items()):
    print('"%s" is repeated %d time%s.' % (word, count, "s" if count > 1 else ""))

rawDescription: Python Duplicate words

description: Python Duplicate words


code: contains_all = two.viewkeys() <= one.viewkeys()

rawDescription: Python dictionnary items() method cost inside iterable


code: days = min//1440

rawDescription: Zero out a value

description: Zero out a value


code: hex(result)

rawDescription: Single Byte Multiplication in Python?

description: Single Byte Multiplication in Python


code:
str_MemoryID = "Object {0:10} memory location is: {1}"
str_Contents = "Object {0:10} contents are: {1}"

test = {"one":1, "two":2}
new = test
new_copy = test.copy()

# printing the memory ID of the objects
print(str_MemoryID.format("test", id(test)))
print(str_MemoryID.format("new", id(new)))
print(str_MemoryID.format("new_copy", id(new_copy)))

print("\n")

# print the contents of the dictionaries

print(str_Contents.format("test", test))
print(str_Contents.format("new", new))
print(str_Contents.format("new_copy", new_copy))

print("\n")

# make a change to the "new" dictionary and let's see what happens
new['new_item'] = 3

print(str_Contents.format("test", test))
print(str_Contents.format("new", new))
print(str_Contents.format("new_copy", new_copy))

print("\n")

# make a change to the "new_copy" dictionary and let's see what happens
new_copy.popitem()

print(str_Contents.format("test", test))
print(str_Contents.format("new", new))
print(str_Contents.format("new_copy", new_copy))

rawDescription: Why can't I modify one dictionary while iterating over another dictionary (get changed size error)?


code:
def checkstocklevel(code):
    with open('stockcontrol.csv',newline='') as f:
        for line in f:
            if code in line:
                data = line.split(",")
                stocklevel = int(data[1])
                if stocklevel < 1:
                    print("Sorry, this product is out of stock")
                    f = open("receipts","a")
                    f.write(code)
                    f.write(" Product Out Of Stock\n")
                    f.close()
                    return False,stocklevel
                elif stocklevel <= 5:
                    print("New Order Required - Remaining Stock:",data[1],)
                elif stocklevel <= 10:
                    print("Low Stock - Remaining Stock:",data[1],)
                else:
                    print("Normal Stock -",data[1],)
                return True,stocklevel

rawDescription: How To Skip Functions?

description: How To Skip Functions


rawDescription: Count choices in django

description: Count choices in django


code:
import multiprocessing as mp
import tables as pt

num_arrays = 100
num_processes = mp.cpu_count()
num_simulations = 1000
sentinel = None

def Simulation(inqueue, output):
    for ii in iter(inqueue.get, sentinel):
        output.put(('createGroup', ('/', 'A%s' % ii)))
        for i in range(num_arrays):
            output.put(('createArray', ('/A%s' % ii, 'B%s' % i, [ii, i])))

def handle_output(output):
    hdf = pt.openFile('simulation.h5', mode='w')
    while True:
        args = output.get()
        if args:
            method, args = args
            getattr(hdf, method)(*args)
        else:
            break
    hdf.close()

if __name__ == '__main__':
    output = mp.Queue()
    inqueue = mp.Queue()
    jobs = []
    proc = mp.Process(target=handle_output, args=(output, ))
    proc.start()
    for i in range(num_processes):
        p = mp.Process(target=Simulation, args=(inqueue, output))
        jobs.append(p)
        p.start()
    for i in range(num_simulations):
        inqueue.put(i)
    for i in range(num_processes):
        # Send the sentinal to tell Simulation to end
        inqueue.put(sentinel)
    for p in jobs:
        p.join()
    output.put(None)
    proc.join()

rawDescription: Write data to hdf file using multiprocessing


code:
import operator
result = np.vectorize(operator.le)(lhs, rhs)

rawDescription: numpy elementwise comparison with overloaded operator

description: Numpy elementwise comparison with overloaded operator


code:
d = {}
for api_name, runtime in whatever:
    if api_name in d:  # we've seen it before
        d[api_name].append(runtime)
    else:  # first time
        d[api_name] = [runtime]  # list with one entry

rawDescription: Generate set of API timings from CSV

description: Generate set of API timings from CSV


code:
dt.append( [] ) # add to list
dt[tablenum] = [] # or add to dictionary

rawDescription: How do I create a table in Python? [rewritten, was a bit unclear]

description: Create a table in Python? [rewritten, was a bit unclear]


code:
with urllib.request.urlopen(url) as link:
    s = link.read()
    result = json.loads(s.decode('utf-8'))

rawDescription: Geocoding Strategies - Python 2.x to Python 3.x


rawDescription: splitting an array into two smaller arrays in python

description: Splitting an array into two smaller arrays in python


code:
@app.route('/database')
def database():
    # generate some file name
    # save the file in the `database_reports` folder used below
    return render_template('database.html', filename=stored_file_name)

@app.route('/database_download/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename)

rawDescription: Return a download and rendered page in one Flask response


code:
import re
sequence = 'AAATGAAATAAGGATGGGGTAGTATGATGTGTTT'
codons = re.findall(r'ATG(?:...)*?(?:TAA|TAG|TGT)', sequence)
codon_list = [[s[i:i+3] for i in range(0, len(s), 3)] for s in codons]

rawDescription: Create a list for values between certain occurences within a sequence . . . Python


code: cmap = plt.get_cmap('cool', 5)

rawDescription: How would one add a colorbar to this example?


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

rawDescription: universal method for working with currency with no rounding, two decimal places, and thousands separators

description: Universal method for working with currency with no rounding, two decimal places, and thousands separators


code:
for chunk in gridout:
    do_something_with(chunk)

rawDescription: How to retrieve file's with grid fs

description: Retrieve file's with grid fs


code:
class A(object):
    foo = 20
    bar = 30
    def build_b(self):
        class B(object):
            foo = self.foo
            bar = self.bar
        return B()

rawDescription: Is it possible to access parent class's members from a nested class in an aggregation


code:
def update(self, request, *args, **kwargs):
    data = request.DATA
    qs = Student_academic_program.objects.filter(student=2773951)
    serializer = StudentAcademicProgramSerializer(qs, data=data, many=True)

    if serializer.is_valid():
        serializer.save()

        return Response(serializer.data)

    ...

rawDescription: Django rest framework update method in API view to changing values in db json


code:
if any(item in 'cat' for item in ['a', 'd']):  # Will evaluate to True
    win()

rawDescription: How to check if *either* character is in a string in Python?

description: Check if *either* character is in a string in Python


code:
def to_timezone(aware_dt, zonename):
    tz = pytz.timezone(zonename)
    return tz.normalize(aware_dt.astimezone(tz))

rawDescription: Creating a function with PYTZ's timezones


code:
from itertools import groupby
from operator import itemgetter

with open(os.path.join(path, "student_rosters.csv"), "rb") as rosters:
    reader = csv.DictReader(rosters)
    for course, rows in groupby(reader, itemgetter('COURSES_COLUMN_HEADER')):
        with open(os.path.join(path, course + ".csv"), "wb") as outfile:
            writer = csv.DictWriter(outfile, reader.fieldnames)
            writer.writerows(rows)

rawDescription: How do I make the filename of the output csv file equal to the the content of a column

description: Make the filename of the output csv file equal to the the content of a column


code:
psimaps_simp = np.zeros((len(features)-1, size, size))
for k in range(len(features)-1):
    psimaps_simp[k] = np.sum(featureParams*features[k], axis=1, keepdims=True) + transitiveParams
psimaps_simp[-1] += np.sum(featureParams*features[-1], axis=1)

rawDescription: How to eliminate for-loop and use list comprehension when using numpy array?

description: Eliminate for-loop and use list comprehension when using numpy array


code:
fig, axes = pyplot.subplots(ncols=4, figsize=(12, 5), sharey=True)
df.query("E in [1, 2]").boxplot(by='E', return_type='axes', ax=axes)

rawDescription: Python Side-by-side box plots on same figure


code:
# urls.py
url(r'^accounts/profile/$',
    UserProfileView.as_view(),
    name='user_profile_view'
),

# views
class UserProfileView(View):
    @method_decorator(login_required)
    def get(self, request):
        profile = get_object_or_404(UserProfile, user=request.user)
        return render(request, 'accounts/profile.html', {'profile': profile})

rawDescription: Username in URL for Django User Profile

description: Username in URL for Django User Profile


code:
def non_commutative_sympify(expr_string):
    parsed_expr = sympy.parsing.sympy_parser.parse_expr(
        expr_string,
        evaluate=False
    )

    new_locals = {sym.name:sympy.Symbol(sym.name, commutative=False)
                  for sym in parsed_expr.atoms(sympy.Symbol)}

    return sympy.sympify(expr_string, locals=new_locals)

rawDescription: Non-commutative sympify (or simplify)

description: Non-commutative sympify (or simplify)


code:
from timeit import timeit

s1="""
def printCommon(list1,list2):
    for i in list1:
        found = False
        for j in list2:
            if i == j:
                #print i
                break

list1 = [1,2,3,4,5]
list2 = [9,8,7,6,5]
printCommon(list1,list2)
"""
s2="""
list1 = [1,2,3,4,5]
list2 = [9,8,7,6,5]
set(list1).intersection(set(list2))
    """

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

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


code: assignId("lonely line")

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


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


code: zooklogger.info("steps:: Actual Steps :: %s, Workflow Path :: %s, Host Path :: %s" % (steps, wf_path, status_path))

rawDescription: How to log in a specifc format in Python using logger?

description: Log in a specifc format in Python using logger


code:
import dateutil.parser as dparser
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import time
import datetime
import re
import pprint
pdt_parser = pdt.Calendar(pdc.Constants())
record_time_pat=re.compile(r'^(.+)\s+:')
sex_pat=re.compile(r'\b(he|she)\b',re.IGNORECASE)
death_time_pat=re.compile(r'died\s+(.+hours later).*$',re.IGNORECASE)
symptom_pat=re.compile(r'[,-]')

def parse_record(astr):
    match=record_time_pat.match(astr)
    if match:
        record_time=dparser.parse(match.group(1))
        astr,_=record_time_pat.subn('',astr,1)
    else: sys.exit('Can not find record time')
    match=sex_pat.search(astr)
    if match:
        sex=match.group(1)
        sex='Female' if sex.lower().startswith('s') else 'Male'
        astr,_=sex_pat.subn('',astr,1)
    else: sys.exit('Can not find sex')
    match=death_time_pat.search(astr)
    if match:
        death_time,date_type=pdt_parser.parse(match.group(1),record_time)
        if date_type==2:
            death_time=datetime.datetime.fromtimestamp(
                time.mktime(death_time))
        astr,_=death_time_pat.subn('',astr,1)
        is_dead=True
    else:
        death_time=None
        is_dead=False
    astr=astr.replace('and','')
    symptoms=[s.strip() for s in symptom_pat.split(astr)]
    return {'Record Time': record_time,
            'Sex': sex,
            'Death Time':death_time,
            'Symptoms': symptoms,
            'Death':is_dead}

if __name__=='__main__':
    tests=[('11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later',
            {'Sex':'Male',
             'Symptoms':['got nausea', 'vomiting'],
             'Death':True,
             'Death Time':datetime.datetime(2010, 11, 11, 13, 0),
             'Record Time':datetime.datetime(2010, 11, 11, 9, 0)}),
           ('11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room',
           {'Sex':'Female',
             'Symptoms':['got heart burn', 'vomiting of blood'],
             'Death':True,
             'Death Time':datetime.datetime(2010, 11, 11, 10, 0),
             'Record Time':datetime.datetime(2010, 11, 11, 9, 0)})
           ]

    for record,answer in tests:
        result=parse_record(record)
        pprint.pprint(result)
        assert result==answer
        print

rawDescription: Medical information extraction using Python


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

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


code:
foo1 = iter(open('foo1', 'r'))
foo2 = iter(open('foo2', 'r'))

outArr = [ [0 if p==q else 1 for p,q in zip(i.split(), j.split()) ] for i,j in zip(foo1,foo2) ]

totalSum = sum([ sum(row) for row in outArr ])

with open('outFile', 'w') as out:
   for row in outArr:
      out.write(' '.join(map(str,row))+'\n')

rawDescription: Comparing the individual values in two separate files such that if same, assign value 0 else 1 in python


code:
def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect # l = left,  t = top
    _, _, w, h = camera      # w = width, h = height
    return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

rawDescription: Add scrolling to a platformer in pygame

description: Add scrolling to a platformer in pygame


code: centrality.append((i, degree[i], between[i], close[i], eigen[i]))

rawDescription: csv.writer and every value seperated by a comma, column seperated by "," - what am I missing?

description: Csv.writer and every value seperated by a comma, column seperated by "," - what am I missing


code:
df = pd.read_csv('test_data.csv', skip_blank_lines=False)
len(df)
10

rawDescription: difference in csv.reader and pandas - python

description: Difference in csv.reader and pandas - python


code:
foo = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
next((i for i,d in enumerate(foo) if 'key1' in d), None)
next((i for i,d in enumerate(foo) if 'key2' in d), None)
next((i for i,d in enumerate(foo) if 'key3' in d), None)
next((i for i,d in enumerate(foo) if 'key4' in d), None)

rawDescription: Find index in a list of dictionaries

description: Find index in a list of dictionaries


code:
import ast
import pandas as pd

restaurant_categories_list=['Soup','Sandwiches','Salad', 'Restaurants','Burgers', 'Breakfast & Brunch']

df_orig = pd.read_csv('yelp_academic_dataset_business.csv', low_memory=False)

df = df_orig[(pd.notnull(df_orig['categories']))]

mask = df['categories'].apply(ast.literal_eval).apply(pd.Series).isin(restaurant_categories_list).sum(axis=1) > 0

print(df.ix[mask, ['categories']])
df[mask].to_csv('result.csv', index=False)

rawDescription: Filter DataFrame rows that are lists

description: Filter DataFrame rows that are lists


rawDescription: What is Python 's default setting for width on String Operations and how is it different that "0"?


code:
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys

from pylab import rcParams
rcParams['figure.figsize'] = 8, 2

def parsexydata(fdata):
    keys=[]
    xy=[]
    with open(fdata,'r') as f:
        pre=''
        for idx, i in enumerate(f.read().replace('\n','').split(',')[2:]):
            if idx%2==0:
                pre=i
                continue
            tmp = pre.split('.')
            if len(tmp)!=3: continue
            [before,key,after] = pre.split('.')
            pre = before+'.'+after
            if key not in keys: keys.append(key)
            xy.append([pre,i,key])
    return [xy,keys]

[xydata, keys] = parsexydata(sys.argv[1])

for idx, k in enumerate(keys):
    px=py=''
    for [x,y,key] in xydata:
        if key!=k: continue
        x=float(x)+float(k)
        if key=='01': print(x)
        plt.scatter(x,y,s=1)
        if px!='':
            plt.plot([px,x],[py,y],'-o',markersize=1)
        px,py=x,y

plt.axis('equal')
plt.tight_layout()
plt.savefig('result.png', dpi=200)

rawDescription: matplotlib: Don't compress plot in the horizontal direction

description: Matplotlib: Don't compress plot in the horizontal direction


code:
import re
location = re.search(r"licensed in ([^.]*)", my_text).group(1)

rawDescription: Extract a string after some string

description: Extract a string after some string


rawDescription: Missing information in nested dictionary python


rawDescription: Strange Python memory usage with Scapy

description: Strange Python memory usage with Scapy


code: a = [c[::2] for c in a]

rawDescription: transfer every second item in list (python)

description: Transfer every second item in list (python)


rawDescription: Counting qualitative values based on the date range in Pandas


rawDescription: Python lists and their splitting

description: Python lists and their splitting


code:
tipo = request.GET.get('tipo')
residuo_id = request.GET.get('residuo_id')

rawDescription: Django Urls regex to suport old php pages


code:
import requests
r = requests.get('https://example.com/big-file', stream=True)
r.raw

rawDescription: Protection against downloading too big files


code: [foo() for _ in range(10)]

rawDescription: Omit iterator in list comprehension?

description: Omit iterator in list comprehension


code:
barrel = pygame.transform.scale(barrel, (init(barrely/4),init(barrely/4)))
screen.blit(barrel, (barrelx, barrely))
barrel = pygame.image.load("images\Barrel.gif")

rawDescription: Scaling Problem with Pygame

description: Scaling Problem with Pygame


code:
output
starting
joining
host #2 Jun 27 16:28:25 palabras kernel: [158950.369443] ideapad_laptop: Unknown event: 1
host #2 Jun 27 16:29:12 palabras kernel: [158997.098833] ideapad_laptop: Unknown event: 1
host #1 Jun 27 16:28:25 palabras kernel: [158950.369443] ideapad_laptop: Unknown event: 1
host #1 Jun 27 16:29:12 palabras kernel: [158997.098833] ideapad_laptop: Unknown event: 1
host #1 Jun 27 16:29:36 palabras kernel: [159020.809748] ideapad_laptop: Unknown event: 1

rawDescription: Python process hanging due to open Paramiko ssh connections


code:
vals = []
for node in p.body:
    if isinstance(node, FunctionDef) and node.name == "my_method":
        for node in walk(node):
            if isinstance(node, Call) and node.func.id == "foobar":
                kws = node.keywords
                if kws:
                    print("Found keywords",[(kw.arg, literal_eval(kw.value)) for kw in kws])
                else:
                    print([literal_eval(val) for val in node.args])

rawDescription: Getting method calls and their arguments from method object


code:
t1, t2, t3 = Team(name='uno'), Team(name='due'), Team(name='tre')
m1 = Match(first_opponent=t1, second_opponent=t2)
m2 = Match(first_opponent=t1, second_opponent=t3)
m3 = Match(first_opponent=t2, second_opponent=t3)
assert 2 == len(t1.matches)
assert 2 == len(t2.matches)
assert 2 == len(t3.matches)
session.add_all([t1, t2, t3])
session.commit()

assert 2 == len(t1.matches)

rawDescription: Backreferencing twice to the same name in sqlalchemy


code: reader = csv.DictReader(open("so.csv",'rU'), ["Year", "Make", "Model", "Description", "Price"], dialect=csv.excel_tab, delimiter=',')

rawDescription: How can I put a CSV file in an array?

description: Put a CSV file in an array


code:
class A(object):
    name = ''                      # these are class
    children = []                  # attributes

rawDescription: What's the best way of appending in a recursive method in Python?


code:
z = [0, 0, 0, 0, 0]

for i, elem in enumerate(a):
    if elem > 2200:
         z[i] += 1

rawDescription: Python matching one list to dict values in another list


code:
return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
    if (child.nodeType === Node.TEXT_NODE)
        ret += child.textContent;
    child = child.nextSibling;
}
return ret;
""", element)

rawDescription: How to get text of an element in Selenium WebDriver (via the Python api) without including child element text?

description: Get text of an element in Selenium WebDriver (via the Python api) without including child element text


code:
def _get_id(self):
   return self._id

def _set_id(self, newid):
   self._id = newid

rawDescription: Are accessors in Python ever justified?

description: Are accessors in Python ever justified


code: myChain = myChain(a,b) if a & b else myChain

rawDescription: Python using function with if

description: Python using function with if


code:
def string_to_dict(string):
    # Split the string on commas
    list_of_entries = string.split(',')
    # Each of these entries needs to be split on '='
    # We'll use a list comprehension
    list_of_split_entries = map(lambda e: e.split('='), list_of_entries)
    # Now we have a list of (key, value) pairs.  We can pass this
    # to the dict() function to get a dictionary out of this, and
    # that's what we want to return
    return dict(list_of_split_entries)

rawDescription: Update dictionary in xml from csv file in python


code:
def repeats(lst):
    i_0 = None
    n = -1 # will still work if lst starts with None
    for i in lst:
        if i == i_0:
            n += 1
        else:
            n = 0
        yield n
        i_0 = i
# list(repeats([1,1,1,2,2,3])) == [0,1,2,0,1,0]

rawDescription: Timeseries Resampling

description: Timeseries Resampling


rawDescription: Python/Pandas: Pivot table

description: Python/Pandas: Pivot table


code:
import numpy as np

# Generate a random points
pts = np.random.normal(size=(10**6,))

# Compute a PDF
PDF,bins = np.histogram(pts, bins=50)

# Normalize (could have used normed=True in hist)
PDF = PDF / np.trapz(PDF, bins[1:])

# Create the inverse distribution
delta = .1
inverse_PDF = 1/(PDF + delta)

# Normalize
inverse_PDF = inverse_PDF / np.trapz(inverse_PDF, bins[1:])

# Plot the results
import pylab as plt
plt.subplot(211)
plt.plot(bins[1:],PDF,lw=4,alpha=.7)
plt.title("Original Distribution")
plt.subplot(212)
plt.plot(bins[1:],inverse_PDF,lw=4,alpha=.7)
plt.title(r"'Inverse' Distribution with $\delta=%.3f$" % delta)
plt.tight_layout()
plt.show()

rawDescription: Inverse Weighted Distribution

description: Inverse Weighted Distribution


rawDescription: Import 36 columns in python for plotting, first column is date


code:
from email.parser import HeaderParser
from email.utils import parseaddr

hp = HeaderParser()

def get_id(response):
    header_string = response[0][1]
    header = hp.parsestr(header_string)
    return parseaddr(header['message-id'])[1]

response = [('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}',
             'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n'), ')']

print(get_id(response))

rawDescription: Parsing Message-ID header returned by imaplib


rawDescription: NetworkX extensibility for custom storage of nodes/edges


rawDescription: Python regular expression

description: Python regular expression


code:
import unicodedata
unicodedata.name('a')
unicodedata.name('ع')
unicodedata.name('ع').split()[-1]

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

description: Map a arabic character to english string using python


rawDescription: Looping over a tuple in jinja2

description: Looping over a tuple in jinja2


code: set(s.split("_")[0] for s in l if "_L" in s)

rawDescription: match the pattern at the end of a string?

description: Match the pattern at the end of a string


code: map(str.upper, mylis)

rawDescription: Apply function to each element of a list


code:
with open('Bmi.csv', newline='') as f:
    #are you sure the newline ^ should be ''?
    for row in f:
        listbox.insert(END, row)
    #fr.close() #the with statement closes f, not sure what fr is...

rawDescription: Delete Line in Csv file from selected line in Listbox


rawDescription: Python simple number comparison

description: Python simple number comparison


code:
df
df2

rawDescription: Convert three column text file to matrix


code:
with open(file, 'r') as f:
    lines = f.read().split('\n')
# ... or whichever way you obtained your content as an array of lines
lines = [x for x in unuuencode(lines)]

rawDescription: Python - delete uuencoding lines

description: Python - delete uuencoding lines


code: [(lst[i], lst2[i]) for i in xrange(len(lst))]

rawDescription: how to get tuples from lists using list comprehension in python

description: Get tuples from lists using list comprehension in python


code:
class A(object):
    def __new__(cls, obj):
        if isinstance(obj, cls):
            return obj
        rv = object.__new__(cls)
        rv._initialized = False
        return rv

    def __init__(self, obj):
        if self._initialized: return
        self._obj = obj
        self._initialized = True

class B(A):
    def __init__(self, obj):
        if self._initialized: return
        A.__init__(self, obj)
        self._otherthing = "foo"

rawDescription: How to prevent a wrapper object wrapping itself?

description: Prevent a wrapper object wrapping itself


code:
abc
Dave      |        14

rawDescription: python - Conditional list formatting

description: Python - Conditional list formatting


code:
def prime(a):
    if a < 2: return False
    if a % 2 == 0: return False
    if a == 3 or a == 5 or a == 7: return True
    for n in range(3,int(a ** 0.5) + 1):
        if a % n == 0: return False

    return True

rawDescription: Difficulty with python prime number check


code:
rajantserver = subprocess.Popen(["cmd",command],\
        creationflags = subprocess.CREATE_NEW_CONSOLE,\
        cwd = path)

rawDescription: Starting jython program from python using subprocess module?


rawDescription: Python append list in loop

description: Python append list in loop


code:
args.add_argument('width', default=80, type=int,
              help='The width of the menu.', nargs='?')
args.add_argument('length', default=24, type=int,
              help='The length of the menu.', nargs='?')

rawDescription: How to give a python program two optional command-line integer arguments?

description: Give a python program two optional command-line integer arguments


code: filter(lambda d: d['hostName'] == hostName, json.loads(data))

rawDescription: Search a complex data structure in Python


code:
def start():
   print ("hello")
def litroom():
   start()
start()

rawDescription: import a single function

description: Import a single function


code:
scores = [
        {'name': 'Lenard', 'score': 5 },
        {'name': 'Tim', 'score': 10}
        ]

file = 'students.txt'

rawDescription: Write dictionary data to file

description: Write dictionary data to file


code:
from flask import Flask, render_template

app = Flask(__name__)

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

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

rawDescription: Font-awesome doesn't work in Flask?

description: Font-awesome doesn't work in Flask


rawDescription: Difference between multiple elements in list with same string . Python 2.7


code:
def get_nested_attr(vars_dict, attrs):
    inst = vars_dict[attrs[0]]
    return operator.attrgetter('.'.join(attrs[1:]))(inst)

def set_nested_attr(vars_dict, attrs, value):
    setattr(get_nested_attr(vars_dict, attrs[0:-1]), attrs[-1], value)

rawDescription: Use a dict to access nested instances of classes in Python


code:
def main():
    for count in range(ROLLS):
        print()
        print('-----------------------------------------------')
        combined_roll = point()
        print('This program simulates two die being rolled five')
        print('times and calculates their total numbers.')
        print('Here are the combined rolls for the dice!')
        print('The combined roll is:', combined_roll)

def point():
    die_1 = (random.randint(MIN, MAX))
    die_2 = (random.randint(MIN, MAX))
    print(die_1)
    print(die_2)
    roll_1 = die_1 + die_2
    combined_roll = roll_1
    return combined_roll

rawDescription: My program runs great but my client wants


rawDescription: How to use Python 3.4's enums without significant slowdown?

description: Use Python 3.4's enums without significant slowdown


code:
import curses

def main(stdscr):
    curses.start_color()
    curses.use_default_colors()
    for i in range(0, curses.COLORS):
        curses.init_pair(i + 1, i, -1)
    try:
        for i in range(0, 255):
            stdscr.addstr(str(i), curses.color_pair(i))
    except curses.ERR:
        # End of screen reached
        pass
    stdscr.getch()

curses.wrapper(main)

rawDescription: How to use terminal color palette with curses

description: Use terminal color palette with curses


code:
for i, value in enumerate(self.x):
    self.x[i] = value + 1

rawDescription: Updating Class Instance Attributes via SuperClass update() method


code:
text_file = open("OutputFile.txt", "w")
text_file.write("Write blablabla into a file")
text_file.close()

rawDescription: redirecting python output to a log file

description: Redirecting python output to a log file


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


code: df.to_sql(con=con_mysql, name='testdata', if_exists='replace', flavor='mysql')

rawDescription: pandas to_sql truncates my data

description: Pandas to_sql truncates my data


code:
#!/usr/bin/env python
from random import randrange
import datetime

now = datetime.datetime.now()

#generate random temperature
temperature = randrange(50, 100)

#database structure
structure = "{'last_hour': [], 'last_3_hours': [], 'last_12_hours': [], " \
            "'last_24_hours': [], 'last_7_days': []}"

#file for the database
database = 'temperature_database.txt' #use absolute path when running from cron

#check database file exists, if not write the database structure
try:
    with open(database): pass
except IOError:
    with open(database, 'w') as handler:
        handler.write(structure)

#read the contents of the database
with open(database, 'r') as handler:
    db_contents = eval(handler.read())

#first save every minute
db_contents['last_hour'].append(temperature)
if len(db_contents['last_hour']) > 60:
    db_contents['last_hour'] = db_contents['last_hour'][-60:] #get the last 60 elements

if now.minute in [10, 0]: #every ten minutes
    db_contents['last_3_hours'].append(temperature)
    if len(db_contents['last_3_hours']) > 18:
        db_contents['last_3_hours'] = db_contents['last_3_hours'][-18:]

    db_contents['last_12_hours'].append(temperature)
    if len(db_contents['last_12_hours']) > 72:
        db_contents['last_12_hours'] = db_contents['last_12_hours'][-72:]

    db_contents['last_24_hours'].append(temperature)
    if len(db_contents['last_24_hours']) > 144:
        db_contents['last_24_hours'] = db_contents['last_24_hours'][-144:]

if now.minute == 1: #every hour
    db_contents['last_7_days'].append(temperature)
    if len(db_contents['last_7_days']) > 168:
        db_contents['last_7_days'] = db_contents['last_7_days'][-168:]

#save the contents to the database
with open(database, 'w') as handler:
    handler.write(str(db_contents))

rawDescription: Python use last x lines

description: Python use last x lines


code:
dynamicContent = "Foo Bar"
content = "
%s
" % (dynamicContent)

with open('todaysNBAScores.html', 'w') as newHTMLFile:
    newHTMLFile.write(content)
    newHTMLFile.close()

rawDescription: I made a script using python that generates a html file. How can I dynamically change its content using data being retrieved by a web crawler


code:
def df_bar(df, xcol, ycol, xlabel=None, ylabel=None, title=None):
    if xlabel is None:
        xlabel = xcol
    if ylabel is None:
        ylabel = xcol
    ax = textranges_freq.plot(x=xcol,y=ycol,kind='bar',title=title, width=0.5, legend=False)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    plt.show()

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

description: Write a function for barchart in python


rawDescription: Python combinations of overlapping pairs on a list


code:
import random
nums = [random.gauss(10, 1) for _ in range(10)]
nums

rawDescription: How to simulate random normal variate Python

description: Simulate random normal variate Python


code:
Numbers = []
value =  df1.iloc[24,50]
Numbers.append(value)

rawDescription: Selecting a data value from pandas dataframe based on row and column to append to list


code:
l.sort(key=lambda d: d.get('age', float('-inf')))
pprint(l)

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

description: Reorder a list in Python based on its content


rawDescription: How to initialize variable amount of Django model fields at once?

description: Initialize variable amount of Django model fields at once


code:
lines = []
for x in range(0, 2):
    line = [data[x][abst.index(item)] for item in dic if item in abst]
    lines.append(line)

rawDescription: how to print lists separately instead of merging them?

description: Print lists separately instead of merging them


code:
findusername = re.compile("^[a-zA-Z]+\s[0-9]+\s[0-9:]{8}\s<([A-Za-z]+)>", re.MULTILINE)
finduseraction = re.compile("^[a-zA-Z]+\s[0-9]+\s[0-9:]{8}\s\*\s+([A-Za-z]+)\s", re.MULTILINE)
findusername.findall(logs)
finduseraction.findall(logs)

rawDescription: Extracting username in IRC logs with regex?


cmd: python3 -u $file

rawDescription: How to set which version of python sublime text uses

description: Set which version of python sublime text uses


code:
for album in albums:
    album_list.append((album, Photo.objects.filter(album=album).order_by('?')[0]))

rawDescription: How to chain quesrysets in the right order not sorted by date, sorted by foreignKey?

description: Chain quesrysets in the right order not sorted by date, sorted by foreignKey


code:
class Book(models.Model):
  author = models.CharField(max_length = 20)
  title = models.CharField(max_length = 40)
  publication_year = models.IntegerField()

rawDescription: Display from a table using Django

description: Display from a table using Django


code:
"foo".lower() == "foo"
"FOO".lower() == "foo"

rawDescription: Python- how to init random function

description: Python- how to init random function


code: [test.id() for test in testtools.testsuite.iterate_tests(suite)]

rawDescription: Python unittest - get TestCase id's from nested TestSuite


code:
dt = clock.tick() # only call once per iteration
if attack_blocked:
    attack_block_count += dt
    if attack_block_count >= 3000: # dt is in ms
        attack_blocked = False

rawDescription: Pygame - Run event for 3 seconds only once


code:
import csv
with open('data.csv', 'rb') as fh:
    reader = csv.reader(fh, delimiter='\t')

rawDescription: Process CSV in Python

description: Process CSV in Python


code:
from itertools import groupby
from operator import itemgetter

def gps(a):
    for k, v in groupby(a, key=itemgetter(2)):
        v = list(v)
        yield [v[0][0],  v[-1][1], v[0][2]]

print(list(gps(a)))

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


code:
L = list(range(-10,10))
L
filter(lambda x: x >= 0, L)

rawDescription: How to remove negative values from a list using lambda functions by python

description: Remove negative values from a list using lambda functions by python


code:
import os
import fnmatch

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in fnmatch.filter(files, '*.txt')]

rawDescription: How can I search sub-folders using glob.glob module in Python?

description: Search sub-folders using glob.glob module in Python


rawDescription: Selenium get text from a table cell (td) with XPath


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

fig = plt.figure()
ax = fig.gca(projection='3d')

x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.8))

u = 0
v = y**2
w = -2*y*z - y

ax.quiver(x, y, z, u, v, w, length=0.1)

plt.show()

rawDescription: Calculate curl of a vector field in Python and plot it with matplotlib


code:
def list_replace_test(s, chars):
    """Replaces a set of chars to 0"""
    return [a if a not in chars else '0' for a in s]

rawDescription: Why is list element replacement slower than string element replacement in python?


code:
MSWord.Documents.Open(filename)
Selection = MSWord.Selection

rawDescription: Can I use Win32 COM to replace text inside a word document?

description: Use Win32 COM to replace text inside a word document


code:
@app.route("/images/<int:pid>.jpg")
def getImage(pid):
    response = make_response(image_binary)
    response.headers['Content-Type'] = 'image/jpeg'
    response.headers['Content-Disposition'] = 'attachment; filename=img.jpg'
    return response

rawDescription: flask return image created from database

description: Flask return image created from database


code:
def extract_fields(logfile):
    fields = set()
    for line in logfile:
        row = line.strip().split(';')
        for cell in row:
            if cell:
                key, value = cell.split('=')
                fields.add(key)

    logfile.seek(0)
    return sorted(list(fields))

rawDescription: Parse Specific Text File to CSV Format with Headers


code:
import matplotlib.dates as dates
fig1 = plt.figure(1)
# x is a list of datetime objects
plt.title('Portfolio Instruments')
plt.subplot(111)
plt.plot(x, y)

plt.xticks(x,fontsize='small')
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%b %d %Y'))

plt.yticks([i * 5 for i in range(0, 15)])

fig1.autofmt_xdate()
plt.show()

rawDescription: Showing entire X Axis Ticks in Graph

description: Showing entire X Axis Ticks in Graph


rawDescription: Python - converting multiple lines to one


code: data.insert(0, tuple(header))

rawDescription: join new tuple to first list of tuples in Python

description: Join new tuple to first list of tuples in Python


code:
d = {}
for a, b, c in e:
    d.setdefault(a, {})[b] = c

rawDescription: How to convert a tuple to a dict?

description: Convert a tuple to a dict


code:
for e in L.keys():
    dR[e] = {}
    for i in L[e].keys():
        dR[e][i] = {}
        for l, ivalue in L[e][i].iteritems():
            for j in Q[e].keys():
                #dR[e][i][j] = {} # What's up with this?  If you don't want an empty dict,
                                 # just don't create one.
                for q, jvalue in Q[e][j].iteritems():
                    deltaR = DeltaR(ivalue, jvalue) #this is a function that I create previously
                    if (0 < deltaR < 100):
                        dR[e][i][j] = deltaR
                if dR[e][i][j] in (nan, inf):
                    del dR[e][i][j]

rawDescription: remove values from a python dict

description: Remove values from a python dict


code:
with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow(('Correct?', 'Successes', 'Failures'))
    writer.writerows([c.strip() for c in r.strip(', ').split(',')]
                     for r in list_results)

rawDescription: csv: writer.writerows() splitting my string inputs

description: Csv: writer.writerows() splitting my string inputs


code: validate_input("New, or used?", {"new", "used"})

rawDescription: How to redo an input if user enters invalid answer

description: Redo an input if user enters invalid answer


code: formatted_yymm = ['{:>02}{:>02}.mat'.format(yy % 100, mm) for yy, mm in yymm]

rawDescription: Python: Generating YYMM string between two dates


code: reverse('foo', 'path.to.test_urls')

rawDescription: How to make a simple Django URLconf and reverse() on it for a test? (getting TypeError: unhashable type: 'list')

description: Make a simple Django URLconf and reverse() on it for a test? (getting TypeError: unhashable type: 'list')


code: result = text.lower().replace(string.punctuation, ' ').split(' ')

rawDescription: Can you call multiple methods on one line?

description: Call multiple methods on one line


rawDescription: Routes filtering by Language and/or category


code: del ls[:]

rawDescription: Iterating through a list using for loops in Python3


code:
class Video(models.Model):
    components = models.ManyToManyField('VideoComponent')

class VideoComponent(models.Model):
    image = models.ForeignKey('ImageModel')
    video_clip = models.ForeignKey('VideoClipModel ')
    position = models.IntegerField()

    class Meta:
        ordering = ['position']

rawDescription: Django: Store multiple & dynamically ordered model sequence


rawDescription: Best way to add a "+" and "-"?

description: Add a "+" and "-"


code:
#!/usr/bin/env python

import subprocess

svn_with_args = ['svn', 'cat', 'url_to_repo/path/to/tarball']
proc = subprocess.Popen(svn_with_args, stdout=subprocess.PIPE)
content = ''.join(proc.stdout.readlines())

rawDescription: How to fetch a file from tarball resides remotely

description: Fetch a file from tarball resides remotely


code: os.system("cd /directory/path/here; run the commands")

rawDescription: pushd through os.system

description: Pushd through os.system


code:
engine.Runtime.IO.SetOutput(stream, txtWriter);
engine.Runtime.IO.SetErrorOutput(stream, txtWriter);

rawDescription: How can I redirect the stdout of IronPython in C#?

description: Redirect the stdout of IronPython in C#


code:
import gzip
import datetime

from scrapy import signals
from scrapy.mail import MailSender
from scrapy.exceptions import NotConfigured
from scrapy.utils.serialize import ScrapyJSONEncoder

from collections import defaultdict

try:
    from cStringIO import cStringIO as StringIO
except ImportError:
    from StringIO import StringIO

def format_size(size):
    for x in ['bytes', 'KB', 'MB', 'GB']:
        if size < 1024.0:
            return "%3.1f %s" % (size, x)

        size /= 1024.0

class GzipCompressor(gzip.GzipFile):
    extension = '.gz'
    mimetype = 'application/gzip'

    def __init__(self):
        super(GzipCompressor, self).__init__(fileobj=PlainCompressor(), mode='w')
        self.read = self.fileobj.read

class PlainCompressor(StringIO):
    extension = ''
    mimetype = 'text/plain'

    def read(self, *args, **kwargs):
        self.seek(0)

        return StringIO.read(self, *args, **kwargs)

    @property
    def size(self):
        return len(self.getvalue())

class StatusMailer(object):
    def __init__(self, recipients, mail, compressor, crawler):
        self.recipients = recipients
        self.mail = mail
        self.encoder = ScrapyJSONEncoder(crawler=crawler)
        self.files = defaultdict(compressor)

        self.num_items = 0
        self.num_errors = 0

    @classmethod
    def from_crawler(cls, crawler):
        recipients = crawler.settings.getlist('STATUSMAILER_RECIPIENTS')
        compression = crawler.settings.get('STATUSMAILER_COMPRESSION')

        if not compression:
            compressor = PlainCompressor
        elif compression.lower().startswith('gz'):
            compressor = GzipCompressor
        else:
            raise NotConfigured

        if not recipients:
            raise NotConfigured

        mail = MailSender.from_settings(crawler.settings)
        instance = cls(recipients, mail, compressor, crawler)

        crawler.signals.connect(instance.item_scraped, signal=signals.item_scraped)
        crawler.signals.connect(instance.spider_error, signal=signals.spider_error)
        crawler.signals.connect(instance.spider_closed, signal=signals.spider_closed)
        crawler.signals.connect(instance.request_received, signal=signals.request_received)

        return instance

    def item_scraped(self, item, response, spider):
        self.files[spider.name + '-items.json'].write(self.encoder.encode(item))
        self.num_items += 1

    def spider_error(self, failure, response, spider):
        self.files[spider.name + '.log'].write(failure.getTraceback())
        self.num_errors += 1

    def request_received(self, request, spider):
        self.files[spider.name + '.log'].write(str(request) + '\n')

    def spider_closed(self, spider, reason):
        files = []

        for name, compressed in self.files.items():
            files.append((name + compressed.extension, compressed.mimetype, compressed))

        try:
            size = self.files[spider.name + '-items.json'].size
        except KeyError:
            size = 0

        body='''Crawl statistics:

 - Spider name: {0}
 - Spider finished at: {1}
 - Number of items scraped: {2}
 - Number of errors: {3}
 - Size of scraped items: {4}'''.format(
            spider.name,
            datetime.datetime.now(),
            self.num_items,
            self.num_errors,
            format_size(size)
        )

        return self.mail.send(
            to=self.recipients,
            subject='Crawler for %s: %s' % (spider.name, reason),
            body=body,
            attachs=files
        )

rawDescription: Emailing items and logs with Scrapy

description: Emailing items and logs with Scrapy


code:
import numpy as np

def find_rate(present_value, final_sum, periods):
    """
    Given the initial value, sum, and number of periods in
    a geometric series, solve for the rate of growth.
    """
    # The formula for the sum of a geometric series is
    #     final_sum = sum_i[0..periods](present_value * rate**i)
    # which can be reduced to
    #     final_sum = present_value * (1 - rate**(periods+1) / (1 - rate)
    # and then rearranged as
    #     rate**(periods+1) - (final_sum / present_value)*rate + (final_sum / present_value - 1) = 0

    # Build the polynomial
    poly     = [0.] * (periods + 2)
    poly[ 0] =  1.
    poly[-2] = -1. * final_sum / present_value
    poly[-1] =  1. * final_sum / present_value - 1.

    # Find the roots
    roots = np.roots(poly)

    # Discard unusable roots
    roots = [rt for rt in roots if rt.imag == 0. and rt.real != 1.]

    # Should be zero or one roots left
    if len(roots):
        return roots[0].real
    else:
        raise ValueError('no solution found')

def main():
    pv, fs, p = 11., 126., 7
    print('Solution for present_value = {}, final_sum = {}, periods = {}:'.format(pv, fs, p))
    print('rate = {}'.format(find_rate(pv, fs, p)))

if __name__=="__main__":
    main()

rawDescription: solving for a compound interest between PV and "summation" FV?

description: Solving for a compound interest between PV and "summation" FV


rawDescription: Will dict(**kwargs) always give dictionary where Keys are of type string?


code:
class WhitelistRemoteAddrFix(object):
    """This middleware can be applied to add HTTP proxy support to an
    application that was not designed with HTTP proxies in mind.  It
    only sets `REMOTE_ADDR` from `X-Forwarded` headers.

    Tests proxies against a set of trusted proxies.

    The original value of `REMOTE_ADDR` is stored in the WSGI environment
    as `werkzeug.whitelist_remoteaddr_fix.orig_remote_addr`.

    :param app: the WSGI application
    :param trusted_proxies: a set or sequence of proxy ip addresses that can be trusted.
    """

    def __init__(self, app, trusted_proxies=()):
        self.app = app
        self.trusted_proxies = frozenset(trusted_proxies)

    def get_remote_addr(self, remote_addr, forwarded_for):
        """Selects the new remote addr from the given list of ips in
        X-Forwarded-For.  Picks first non-trusted ip address.
        """

        if remote_addr in self.trusted_proxies:
            return next((ip for ip in reversed(forwarded_for)
                         if ip not in self.trusted_proxies),
                        remote_addr)

    def __call__(self, environ, start_response):
        getter = environ.get
        remote_addr = getter('REMOTE_ADDR')
        forwarded_for = getter('HTTP_X_FORWARDED_FOR', '').split(',')
        environ.update({
            'werkzeug.whitelist_remoteaddr_fix.orig_remote_addr': remote_addr,
        })
        forwarded_for = [x for x in [x.strip() for x in forwarded_for] if x]
        remote_addr = self.get_remote_addr(remote_addr, forwarded_for)
        if remote_addr is not None:
            environ['REMOTE_ADDR'] = remote_addr
        return self.app(environ, start_response)

rawDescription: How do I safely get the user's real IP address in Flask (using mod_wsgi)?

description: Safely get the user's real IP address in Flask (using mod_wsgi)


code:
import itertools

combos = {(i1,i2):overlap(int1,int2)
             for (i1,int1),(i2,int2)
                in itertools.product(enumerate(Intervals1),enumerate(Intervals2))}

print(*combos.items(),sep="\n")

rawDescription: Checking two time intervals are overlapping or not


code:
M = np.random.random((5, 5))
M

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


rawDescription: Pandas' equivalent of resample for integer index


rawDescription: Minimize overhead in Python multiprocessing.Pool with numpy/scipy


code: {i:d[i] for i in d if i!='c'}

rawDescription: Remove key from dictionary in Python returning new dictionary


rawDescription: Delete digits in Python (Regex)

description: Delete digits in Python (Regex)


code:
agent_states_index = {}
for index, agent in enumerate(agents):
    agent_states_index.setdefault(agent.state, []).append(index)

agent_index = random.choice(agent_states_index[0])
agent = agents[agent_index]

rawDescription: Selecting random elements in a list conditional on attribute


code: [' '.join([nltk.tag.tuple2str(item) for item in sent]) for sent in tpl]

rawDescription: operating on embedded tuples/strings, python

description: Operating on embedded tuples/strings, python


code:
import pika
import sys

def callback_func(channel, method, properties, body):
    print(body)

if __name__ == "__main__":
    credentials = pika.PlainCredentials("guest", "guest")

    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=sys.argv[1],
                                  credentials=credentials))

    channel = connection.channel()

    result = channel.queue_declare(exclusive=True)

    channel.queue_bind(result.method.queue,
                       exchange="my-exchange",
                       routing_key="*.*.*.*.*")

    channel.basic_consume(callback_func, result.method.queue, no_ack=True)

    channel.start_consuming()

rawDescription: Python and RabbitMQ - Best way to listen to consume events from multiple channels?


code:
a = np.random.permutation(10)
a

rawDescription: Vectorized search of element indeces

description: Vectorized search of element indeces


code:
colprint([(name, version[0].summary or '')
      for (name, version) in sorted(versions.iteritems())])

rawDescription: lisp-style style `let` syntax in Python list-comprehensions

description: Lisp-style style `let` syntax in Python list-comprehensions


code:
found = []
for a,bs in data.items():
    bint = bs.intersection
    for b in bs:
        if a not in data[b]:
            for c in bint(data[b]):
                if a not in data[c] and b not in data[c]:
                    found.append("{} {} {}".format(a, b, c))

rawDescription: Print Feedforward Loops in python

description: Print Feedforward Loops in python


code:
def make_counter(n):
    def inc():
        nonlocal n
        n = n + 1
        return n
    return inc

rawDescription: lambda in python

description: Lambda in python


code:
import io
s = u"a\r\nb\nc\rd"
sio = io.StringIO(s, newline=None)
sio.readlines()

rawDescription: How can I access an uploaded file in universal-newline mode?

description: Access an uploaded file in universal-newline mode


code:
import re
from itertools import product
line = 'a   b  c  d,e,f    g   h  i,j,k,l   m   n'
items = [x[0].split(',') for x in re.findall(r'((\w+,)+\w)',line)]
strs = re.sub(r'((\w+,)+\w+)','{}',line)
for prod in product(*items):
    print (strs.format(*prod))

rawDescription: Python: Split a mixed String

description: Python: Split a mixed String


code: {i[0] : i[1:] for i in stations}

rawDescription: Nested list to nested dictionary in python


code:
if condition:
    return True
else:
    return False

rawDescription: Writing string comparing function in python


code:
valid_word(words, letters)
valid_word(words, 'hideg')

rawDescription: Check which words from a list could be formed with a string of letters


code:
N = 4
np.triu_indices(N,1)

rawDescription: Processing upper triangular elements only with NumPy einsum


code:
for item in thelist:
  print>>thefile, item

rawDescription: Writing a list to a file with Python

description: Writing a list to a file with Python


code:
import json

# Get JSON data from elsewhere and parse it
macros = json.loads(json_data)

# Do something with the macros
for macro in macros:
    run_macro(macro) # For example

rawDescription: Python - how to avoid exec for batching?

description: Python - how to avoid exec for batching


code: li = map(int, li)

rawDescription: how to change the type of items in the list?

description: Change the type of items in the list


code:
character_equally_often = {i: counter1[i] == counter2[i] for i in set(string1).union(set(string2))}
print(character_equally_often)
# {'i': False, 'u': False, 'f': False, 'g': False, 'o': True,
#  's': False, 'v': False, 'n': False, 't': False, 'h': True,
#  'b': False, 'e': False, 'q': False, 'r': False, 'y': False,
#  'a': True, 'd': False}

rawDescription: How to compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists

description: Compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists


code:
H = 80.0
M,N,R = B.shape
B4D = B[:,None,:,:]
out = ((A.reshape(M,-1,N,R)*np.log(H/B4D))/np.log(10./B4D)).reshape(-1,N,R)

rawDescription: Vectorizing triple for loop in Python/Numpy with different array shapes


code:
nchoices = 4
x = ['tree.jpg','house.jpg','car.jpg','door.jpg','train.jpg','moon.jpg']

def redraw():
    choices = random.sample(x, nchoices)
    correct = random.choice(choices)

    display(Image(correct))
    time.sleep(3)

    buttons = [widgets.Button(description = choice) for choice in choices]

    container = widgets.HBox(children=buttons)
    display(container)

    def on_button_clicked(b):
        # [insert code to record choice]
        container.close()
        clear_output()
        redraw()

    for button in buttons:
        button.on_click(on_button_clicked)

redraw()

rawDescription: Using ipywidget for multiple choice test


rawDescription: Removing tuple from list

description: Removing tuple from list


code:
divisor_list = []
for x in range(1, limit + 1):
    if number % x == 0:
        divisor_list+=([x, number / x])

rawDescription: Adding two data items in a list comprehension simultaneously, after a mathematical operation


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

rawDescription: One to many SQL relationship

description: One to many SQL relationship


code: "C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\wish84.exe" "C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\IxiaWish.tcl"

rawDescription: TCL in Python: can't find package

description: TCL in Python: can't find package


rawDescription: Change elements in 2d ndarray into arrays


code:
next(pool)
next(pool)

rawDescription: Circular list iterator in Python

description: Circular list iterator in Python


code:
import sub_animal
getattr(sub_animal, 'Dog')

rawDescription: Dynamically load module with Inheritance


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 4.5))
plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.00)
m = Basemap(resolution='c',projection='robin',lon_0=0)
m.fillcontinents(color='white',lake_color='white',zorder=2)
coasts = m.drawcoastlines(zorder=1,color='white',linewidth=0)
coasts_paths = coasts.get_paths()

ipolygons = range(83) + [84] # want Baikal, but not Tanganyika
# 80 = Superior+Michigan+Huron, 81 = Victoria, 82 = Aral, 83 = Tanganyika,
# 84 = Baikal, 85 = Great Bear, 86 = Great Slave, 87 = Nyasa, 88 = Erie
# 89 = Winnipeg, 90 = Ontario
for ipoly in ipolygons:
    r = coasts_paths[ipoly]
    # Convert into lon/lat vertices
    polygon_vertices = [(vertex[0],vertex[1]) for (vertex,code) in
                        r.iter_segments(simplify=False)]
    px = [polygon_vertices[i][0] for i in xrange(len(polygon_vertices))]
    py = [polygon_vertices[i][2] for i in xrange(len(polygon_vertices))]
    m.plot(px,py,linewidth=0.5,zorder=3,color='black')

plt.savefig('world2.png',dpi=100)

rawDescription: world map without rivers with matplotlib / Basemap?

description: World map without rivers with matplotlib / Basemap


code:
# south is setting logging on import-time; import it before setting our logger
# so it is not overwriting our settings
try:
    import south.logger
except ImportError:
    pass

import logging.config
if LOGGING_CONFIG_FILE:
    logging.config.fileConfig(LOGGING_CONFIG_FILE)

rawDescription: South's syncdb/migrate creates pages of output?


code:
for i in a[:]:
    if i in b:
        a.remove(i)
        b.remove(i)

rawDescription: Removing common elements in two lists

description: Removing common elements in two lists


code:
title = "life is amazing"
body = """
_here my html code_
"""

rawDescription: Post picture to Tumblr using Python

description: Post picture to Tumblr using Python


code: randomValue = phrase[randomPhrase]

rawDescription: Python Key/Value point to same random number


code:
import pylab as pl
import matplotlib.colors as col
import numpy as np

cdict = {'red':   [(0.0,  1.0, 1.0),
                   (1.0,  0.0, 0.0)],
         'green':  [(0.0,  0.0, 0.0),
                   (1.0,  1.0, 1.0)],
         'blue':   [(0.0,  0.0, 0.0),
                    (1.0,  0.0, 0.0)]}

my_cmap = col.LinearSegmentedColormap('my_colormap',cdict,256)

for theta in np.linspace(0, np.pi*2, 30):
    pl.plot([0,np.cos(theta)], [0,np.sin(theta)], color=my_cmap(theta/(2*np.pi)) )

pl.show()

rawDescription: Plotting multiple segments with colors based on some variable with matplotlib


code:
def view_generator(model_class):
    class MyForm(forms.ModelForm):
         class Meta:
              model = model_class

    def my_view(request):
        form = MyForm(request.POST or None)
        if request.method == 'POST':
            if form.is_valid():
                form.save()
                return http.HttpResponse("Thanks for posting!")
        return render(request, "mytemplate.html", {'form': form})
    return my_view

# urls.py
from foo import view_generator

(r'^my_first_feedback_form', view_generator(Model1))
(r'^my_second_feedback_form', view_generator(Model2l))

rawDescription: Multiple Instances of a django app, does django support this


code: a_list[1:1] = b_list

rawDescription: list extend() to index, inserting list elements not only to the end

description: List extend() to index, inserting list elements not only to the end


code: [w for w in words_list if set(sys.argv[1]).intersection(w)]

rawDescription: Find out the words from a python list which contains permutation of another word


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self._offset = 200
        self._closed = False
        self._maxwidth = self.maximumWidth()
        self.widget = QtGui.QWidget(self)
        self.listbox = QtGui.QListWidget(self.widget)
        self.editor = QtGui.QTextEdit(self)
        self.editor.setStyleSheet("QTextEdit {color:red}")
        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(self.widget)
        layout.addWidget(self.editor)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.move(500, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: pyqt - How to change the color of a word from my textedit

description: Pyqt - How to change the color of a word from my textedit


rawDescription: Skipping rows in a csv file using Python Pandas


code:
def build_ribbon_zip():

    """
        build_ribbon_zip handles manipulation of the .ZIP contents and places the
        necessary components within the PPTM ZIP archive structure
        3. converts the PPTM to a .ZIP
        4. Adds the CustomUI XML to the .ZIP directory
        5. converts the .ZIP to a PPTM

    """
    bom = u'\ufeff'
    _path=output_path.replace('.pptm', '.zip')
    copy_path=r'C:\debug\copy.zip'

    # Convert to ZIP archive
    os.rename(output_path, _path)
    z=zipfile.ZipFile(_path, 'a', zipfile.ZIP_DEFLATED)
    copy=zipfile.ZipFile(copy_path, 'w', zipfile.ZIP_DEFLATED)

    guid=str(uuid.uuid4()).replace('-', '')[:16]

    """
        the .rels files are written directly from XML string built in procedure
        the [Content_Types].xml file needs to include additional parameter for the 'jpg' extension
    """
    for itm in [itm for itm in z.infolist() if itm.filename != r'_rels/.rels']:
        buffer = z.read(itm.filename)
        if itm.filename == "[Content_Types].xml":
            # Modify the [Content_Types].xml file to include the jpg reference
            # <Default Extension="jpg" ContentType="image/.jpg" />
            # copy the XML from the original zip archive, this file has not been copied in the above loop
            root = ET.fromstring(buffer)

            ET.SubElement(root, '{http://schemas.openxmlformats.org/package/2006/content-types}Default', {'Extension': 'jpg', 'ContentType': 'image/.jpg'})

            copy.writestr(itm, ET.tostring(root).encode('utf-8'))

            # Append the Logo file to the .zip and create the archive
            copy.write(ribbon_logo_path, r'\customUI\images\jdplogo.jpg')

        else:
            copy.writestr(itm, buffer)

    # append the CustomUI xml part to the .zip and create the archive
    copy.write(ribbon_xml_path, r'\customUI\customUI14.xml')

    # create the string & append the .rels to CustomUI\_rels
    rels_xml = """<?xml version="1.0" encoding="utf-8"?>
        <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
        <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="images/jdplogo.jpg" Id="jdplogo" />
    </Relationships>"""

    copy.writestr(r'customUI\_rels\customUI14.xml.rels', rels_xml.encode('utf-8'))

    # get the existing _rels/.rels XML content and copy to the copied archiveI:

    rels_xml = r'<?xml version="1.0" encoding="utf-8" ?>'
    rels_xml += r'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
    rels_xml += r'<Relationship Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/'
    rels_xml += r'core-properties" '
    rels_xml += r'Target="docProps/core.xml" Id="rId3" />'
    rels_xml += r'<Relationship Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail" '
    rels_xml += r'Target="docProps/thumbnail.jpeg" Id="rId2" />'
    rels_xml += r'<Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" '
    rels_xml += r'Target="ppt/presentation.xml" Id="rId1" />'
    rels_xml += r'<Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" '
    rels_xml += r'Target="docProps/app.xml" Id="rId4" /><Relationship '
    rels_xml += r'Type="http://schemas.microsoft.com/office/2007/relationships/ui/extensibility" '
    rels_xml += r'Target="/customUI/customUI14.xml" Id="R'+guid+'" /></Relationships>'

    copy.writestr(r'_rels\.rels', rels_xml.encode('utf-8'))

    z.close()
    copy.close()

    os.remove(_path)
    os.rename(copy_path, output_path)

rawDescription: Python Build Script for VBA Add-In file

description: Python Build Script for VBA Add-In file


code: con.row_factory = my_row_factory

rawDescription: Mapping result rows to namedtuple in python sqlite


rawDescription: django - using regex to strip and replace a urlfield

description: Django - using regex to strip and replace a urlfield


code:
import numpy as np
from itertools import izip
from scipy.stats import zscore

def zify_scipy(d):
    keys, vals = zip(*d.items())
    return dict(zip(keys, zscore(vals, ddof=1)))

# test cases
test1 = dict(izip(range(1000),   np.random.randn(1000)))
test2 = dict(izip(range(10000),  np.random.randn(10000)))
test3 = dict(izip(range(100000), np.random.randn(100000)))

rawDescription: Python: Calculate all values of dictionary to z-scores


code: rule_defs['and'](r)(d, r1, r2)

rawDescription: Getting a return value from Lambda python


code: results = [[] for _ in range(13)]

rawDescription: Initialise list correctly

description: Initialise list correctly


code:
import subprocess

p = subprocess.Popen("gzip -c > zipped.gz", shell=True, stdin=subprocess.PIPE)
p.communicate("Hello World\n")

rawDescription: Python equivalent of piping file output to gzip in Perl using a pipe


code:
i, j = [2, 1]
return room[i][j]

rawDescription: More pythonic method of indexing with a list of coordinates


code:
for row in csv.reader(open('data.csv')):
    id, val, val2, rsn = row
    # do something...

rawDescription: Python CSV reader print out specific field


code: print(max(x, key=sum))

rawDescription: What is the proper way to print a nested list with the highest value in Python


code:
from suds.sax.element import Element
client = client(url)
ssnns = ('ssn', 'http://namespaces/sessionid')
ssn = Element('SessionID', ns=ssnns).setText('123')
client.set_options(soapheaders=ssn)
result = client.service.addPerson(person)

rawDescription: How to pass SOAP headers into python SUDS that are not defined in WSDL file

description: Pass SOAP headers into python SUDS that are not defined in WSDL file


rawDescription: Merge multiple list with intersection and add the items


code: items = [int(j) for j in contents[i].split(";")]

rawDescription: I can't turn elements of my list into integers


code:
from b import ClassB
obj_b = ClassB()
obj_b.some_func()

rawDescription: How do I import other scripts?

description: Import other scripts


code:
from scipy.stats import chi2
chi2.ppf(.8, df=2) # two degress of freedom

rawDescription: python equivalent of qnorm, qf and qchi2 of R

description: Python equivalent of qnorm, qf and qchi2 of R


rawDescription: reading specific cell in csv using pandas

description: Reading specific cell in csv using pandas


code:
a_sampled = tablesample(A, 2.5)

query = session.query(a_sampled).options(
    subqueryload(a_sampled.rel1),
    subqueryload(a_sampled.rel2)
).filter(a_sampled.id >= min_id, a_sampled.id < max_id, [...])

rawDescription: How to TABLESAMPLE with SQLAlchemy?

description: TABLESAMPLE with SQLAlchemy


code: foo = static_var("counter", 0)(foo)

rawDescription: static variable in a function with Python Decorator

description: Static variable in a function with Python Decorator


code: segments = [final[pos:pos+1] for pos in xrange(len(final) - 1)]

rawDescription: How to make a partition structure

description: Make a partition structure


code:
import igraph
import pandas as pd

node_names = ['A', 'B', 'C']
a = pd.DataFrame([[1,2,3],[3,1,1],[4,0,2]], index=node_names, columns=node_names)

# Get the values as np.array, it's more convenenient.
A = a.values

# Create graph, A.astype(bool).tolist() or (A / A).tolist() can also be used.
g = igraph.Graph.Adjacency((A > 0).tolist())

# Add edge weights and node labels.
g.es['weight'] = A[A.nonzero()]
g.vs['label'] = node_names  # or a.index/a.columns

rawDescription: igraph Graph from numpy or pandas adjacency matrix

description: Igraph Graph from numpy or pandas adjacency matrix


rawDescription: How to find all the indices of all the elements in a 2d matrix using Python?

description: Find all the indices of all the elements in a 2d matrix using Python


rawDescription: How to run multiple scripts from a script in python

description: Run multiple scripts from a script in python


code:
out = A.T + A
mask = np.eye(out.shape[0],dtype=bool)
out[mask] = A[mask]

rawDescription: Convert triangle matrix to square (Python | NumPy)?


code: import numpy as np

rawDescription: Fastest way to grow a numpy numeric array


rawDescription: python matplotlib changing default axis for image

description: Python matplotlib changing default axis for image


rawDescription: use random functions (python)

description: Use random functions (python)


code:
from subprocess import Popen, PIPE
p = Popen(['xsel','-pi'], stdin=PIPE)
p.communicate(input='Hello, World')

rawDescription: Is there a way to directly send a python output to clipboard?


code:
from django.utils import timezone

timezone.activate(tz)

datetime = timezone.now() if checked else None

rawDescription: How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?

description: Get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4


code:
s = (2,2)
np.zeros(s)

rawDescription: More elegant way to initialize list of duplicated items in Python


code:
a=np.arange(4)
a
np.tile(a,(6,1))
b= np.eye(2)
b
np.tile(b,(3,1,1))

rawDescription: Expanding NumPy array over extra dimension


code:
@app.task(bind=True)
def gen_crunched_numbers(self, cache_key):
    res = do_heavy_lifting()
    cache.set(cache_key, res)
    if self.request.called_directly:
        return res
    else:
        return { 'result': res, 'cache': cache_key }

rawDescription: Celery task best practices in Django/Python


code:
def rolling_window(a, size):
    shape = a.shape[:-1] + (a.shape[-1] - size + 1, size)
    strides = a.strides + (a. strides[-1],)
    return numpy.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

rawDescription: Python/NumPy first occurrence of subarray


code:
input_text = input('Enter some text: ')
s = input_text.lower()
seen = set()
for c in s:
     if c not in seen:
         print(c, s.count(c))
         seen.add(c)

rawDescription: How to remove duplicates from a list python

description: Remove duplicates from a list python


code: the_value = the_ball[sys.argv[2]]

rawDescription: python getting a specific attribute from a list of objects

description: Python getting a specific attribute from a list of objects


code:
def apply_async(self, func, args=(), kwds={}, callback=None):
    assert self._state == RUN
    result = ApplyResult(self._cache, callback)
    self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
    return result

class ApplyResult(object):

    def __init__(self, cache, callback):
        self._cond = threading.Condition(threading.Lock())
        self._job = job_counter.next()
        self._cache = cache
        self._ready = False
        self._callback = callback
        cache[self._job] = self

    def _set(self, i, obj):
        self._success, self._value = obj
        if self._callback and self._success:
            self._callback(self._value)
        self._cond.acquire()
        try:
            self._ready = True
            self._cond.notify()
        finally:
            self._cond.release()
        del self._cache[self._job]

rawDescription: Who runs the callback when using apply_async method of a multiprocessing pool?


rawDescription: Splitting longer patterns using regex without losing characters Python 3+


code:
marker = "#pragma Mark - Method\n"
method = "code to add to the file\n"

with open("C:\codefile.cpp", "r+") as codefile:
    # find the line
    line = ""
    while line != marker:
        line = codefile.readline()
    # save our position
    pos = codefile.tell()
    # read the rest of the file
    remainder = codefile.read()
    # return to the line after the #pragma
    codefile.seek(pos)
    # write the new method
    codefile.write(method)
    # write the rest of the file
    codefile.write(remainder)

rawDescription: Get to specific line in file, then start writing after that line


code:
class DirContents(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        files = FileObj.objects.filter(parent=kwargs.get('dir_id'))
        dirs = DirObj.objects.filter(parent=kwargs.get('dir_id'))

        files_list = list(files)
        dirs_list = list(dirs)

        combined = files_list + dirs_list

        serializer = YourCombinedSerializer(combined, many=True)

        return Response(serializer.data)

rawDescription: Serialize multiple models in a single view


code: list(set('aaabcabccd'))

rawDescription: Python: List of all unique characters in a string


code:
category = ['Toy','Cloth','Food','Auto']
inventory = {'A':['Food', 5], 'B':['Food', 6],
          'C':['Auto', 5], 'D':['Cloth', 14],
           'E':['Toy',19], 'F':['Cloth', 13], 'G':['Toy',20], 'H':['Toy',11]}
cat_order = {cat: i for i, cat in enumerate(category)}
sorted(inventory.items(), key=lambda i: (cat_order[i[1][0]], -i[1][1]))
from pprint import pprint
pprint(_)

rawDescription: python dictionary sorted by list

description: Python dictionary sorted by list


code: self.display = Label(master, textvariable=self.displaytext)

rawDescription: tkinter labels, or "updating variables in a loop"

description: Tkinter labels, or "updating variables in a loop"


code:
next_line_time = 0

while True:

    while time.time.get_ticks() >= next_line_time:
        start_points.append(self.get_random_pixel())
        next_line_time += 1000

rawDescription: drawing lines from a list in pygame

description: Drawing lines from a list in pygame


rawDescription: python: check if a hostname is resolved

description: Python: check if a hostname is resolved


code:
class SomeHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('username') # this will get the value from the field named username
        self.response.write(name) # this will write on the document

rawDescription: How are POST and GET variables handled in Python?


code:
l = [1,2,3]
a = ['a','b','c']
all(isinstance(i, int) for i in l)
all(isinstance(i, int) for i in a)

rawDescription: How to make sure if parameter is a list of numbers? (python)

description: Make sure if parameter is a list of numbers? (python)


code:
import re
a = re.compile('^\d+$')
b = re.compile('^\d+\.\d+$')
a.match('10')
a.match('10.94')
b.match('10')
b.match('10.94')
a.match("string")
b.match("string")

rawDescription: Using regex on Charfield in Django

description: Using regex on Charfield in Django


code:
def two(positions,regions):
    d = defaultdict(list)
    for k,v in one(regions):
        d[k].append(v)
    with open(positions,'r') as g:
        for line in g:
            ls = tuple(line.split())
            yield ls + (1 if any(x <= int(ls[1]) <= y for (x,y) in d[ls[0]])
                        else 0,)

rawDescription: Python: How to read in file once but not exhaust iterator in nested for loops


code:
button['command'] = 0 #this disables the callback
button['relief'] = 'sunken' #makes the button fixed

rawDescription: Disabling a button but visually keeping it as if it wasn't disabled


rawDescription: Pandas how to apply multiple functions to dataframe


code: inverted = 1 - binary_image_array

rawDescription: Calculate the area of two separate geometries in Python