code:
class MyApp(App):
    def build(self):
        Factory.register('LoginMain', module='myapp.modules.login.main')
        Factory.register('Other', module='myapp.modules.other.other')
        return Factory.LoginMain()

rawDescription: Looking for a good way to organize big kivy project


code: a = "Hello" if foo() else "Goodbye"

rawDescription: Python putting an if-elif-else statement on one line


code:
for i in hrIn:
    hrOut.write("{}\n".format(i.rstrip().zfill(5)))

rawDescription: How to .write() two items, a zero and an iterator in Python?


code:
def make_socket_factory(srcip):
    def socket_factory():
        s = socket.socket()
        s.bind((srcip, 0))
        return s
    return socket_factory

rawDescription: open a site every 15 seconds with different IP

description: Open a site every 15 seconds with different IP


rawDescription: How to unset EOL option in TCP packet with scapy

description: Unset EOL option in TCP packet with scapy


code:
a = 'a'
b = 'b'

a, b = b, a

print(a) # 'b'
print(b) # 'a'

rawDescription: How does a comma followed by a variable assignment concatenate?


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
import matplotlib.gridspec as gridspec

delta = 0.025

x = y = np.arange(0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 1e6 * (Z1 * Z2)

fig=plt.figure()

#
# define 2 subplots, using gridspec to control the
# width ratios:
#
# note: you have to import matplotlib.gridspec for this
#
gs = gridspec.GridSpec(1, 2,width_ratios=[15,1])

# the 1st subplot
ax1 = plt.subplot(gs[0])

lvls = np.logspace(0,4,20)

CF = ax1.contourf(X,Y,Z,
                  norm = LogNorm(),
                  levels = lvls
                 )
CS = ax1.contour(X,Y,Z,
                 norm = LogNorm(),
                 colors = 'k',
                 levels = lvls
                )

#
# the pseudo-colorbar
#

# the 2nd subplot
ax2 = plt.subplot(gs[1])

#
# new levels!
#
# np.logspace gives you logarithmically spaced levels -
# this, however, is not what you want in your colorbar
#
# you want equally spaced labels for each exponential group:
#
levls = np.linspace(1,10,10)
levls = np.concatenate((levls[:-1],np.linspace(10,100,10)))
levls = np.concatenate((levls[:-1],np.linspace(100,1000,10)))
levls = np.concatenate((levls[:-1],np.linspace(1000,10000,10)))

#
# simple x,y setup for a contourf plot to serve as colorbar
#
XC = [np.zeros(len(levls)), np.ones(len(levls))]
YC = [levls, levls]
CM = ax2.contourf(XC,YC,YC, levels=levls, norm = LogNorm())
# log y-scale
ax2.set_yscale('log')
# y-labels on the right
ax2.yaxis.tick_right()
# no x-ticks
ax2.set_xticks([])

plt.show()

rawDescription: matplotlib contour plot: proportional colorbar levels in logarithmic scale

description: Matplotlib contour plot: proportional colorbar levels in logarithmic scale


code:
import urlparse
path = urlparse.urlparse('http://localhost:8000/dashboard/').path

rawDescription: How to compare Referer URL in Django Request to another URL using reverse()?

description: Compare Referer URL in Django Request to another URL using reverse()


code:
import csv
from itertools import izip

writer = csv.writer(open("output.csv", "wb"))
for name, membership in izip(graph.vs["name"], membership):
    writer.writerow([name, membership])

rawDescription: Using iGraph in python for community detection and writing community number for each node to CSV


code:
4
2
none

rawDescription: Python: giving answer according to given arguments


rawDescription: Writing tab spaced words to a file in Python


code: empty_lists = [ [] for i in range(n) ]

rawDescription: How to create a list of empty lists

description: Create a list of empty lists


code:
val = ast.literal_eval(s)
if not isinstance(val, basestring):
    raise BadUserError("Why are you giving me {} when I wanted a string?".format(s))

rawDescription: How to specify a unicode and other escaped literals to Python 2.x ConfigParser

description: Specify a unicode and other escaped literals to Python 2.x ConfigParser


rawDescription: How to find a specific file in Python

description: Find a specific file in Python


code:
from whoosh.index import open_dir
ix = open_dir('whoosh_index')
ix.schema

rawDescription: Whoosh index viewer

description: Whoosh index viewer


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


code:
#!/usr/bin/env python2.7

import xml.etree.ElementTree as ET
import itertools

tree = ET.parse('gateway.xml')
root = tree.getroot()

MAX_VERSIONS = 5

for component in root:
    counter = itertools.count()
    histories = sorted((history.attrib.get("version", 0), counter, history)
                       for history in component if history.tag == "history")
    if len(histories) <= MAX_VERSIONS:  # Nothing to remove
        continue
    remove_histories = histories[:-MAX_VERSIONS]  # These should be removed
    for v, c, history in remove_histories:
        component.remove(history)

tree.write('output.xml')

rawDescription: Having only 5 elements per XML component python


code:
import lxml.html as LH
import pandas as pd

content = '''

265
 JonesBlue
29

266
 Smith
34

'''

table = LH.fromstring(content)
for df in pd.read_html(content):
    df['refname'] = table.xpath('//tr/td/a/@href')
    df['refname'] = df['refname'].str.extract(r'([^./]+)[.]')
    print(df)

rawDescription: HTML table to pandas table: Info inside html tags


code:
for row in iterable:
    Eg_dict[row[1]] = row[2]

rawDescription: Add new key value pair in a Python Dictionary


code:
import pyglet
from pyglet.gl import *

glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_LINE_SMOOTH)
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE)

pyglet.clock.set_fps_limit(60)

class baseSprite(pyglet.sprite.Sprite):
    def __init__(self, texture, x, y, batch, subgroup):
        self.texture = texture

        super(baseSprite, self).__init__(self.texture, batch=batch, group=subgroup)
        self.x = x
        self.y = y

    def move(self, x, y):
        """ This function is just to show you
            how you could improve your base class
            even further """
        self.x += x
        self.y += y

    def _draw(self):
        """
        Normally we call _draw() instead of .draw() on sprites
        because _draw() will contains so much more than simply
        drawing the object, it might check for interactions or
        update inline data (and most likely positioning objects).
        """
        self.draw()

class main(pyglet.window.Window):
    def __init__ (self):
        super(main, self).__init__(800, 800, fullscreen = False)
        self.x, self.y = 0, 0
        self.sprites = {}
        self.batches = {}
        self.subgroups = {}

        self._handles = {}

        self.batches['main'] = pyglet.graphics.Batch()
        self.subgroups['base'] = pyglet.graphics.OrderedGroup(0)

        monster_image = pyglet.image.load('./roar.png')
        for i in range(100):
            self._handles['monster'+str(i)] = baseSprite(monster_image, randint(0, 50), randint(0, 50), self.batches['main'], self.subgroups['base'])

        # Note: We put the sprites in `_handles` because they will be rendered via
        # the `self.batches['main']` batch, and placing them in `self.sprites` will render
        # them twice. But we need to keep the handle so we can use `.move` and stuff
        # on the items later on in the game making process ;)

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def render(self):
        self.clear()

        for batch_name, batch in self.batches.items():
            batch.draw()

        for sprite_name, sprite in self.sprites.items():
            sprite._draw()

        self.flip() # This updates the screen, very much important.

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze.
            # Basically it flushes the event pool that otherwise
            # fill up and block the buffers and hangs stuff.
            event = self.dispatch_events()

            # Fun fact:
            #   If you want to limit your FPS, this is where you do it
            #   For a good example check out this SO link:
            #   http://stackoverflow.com/questions/16548833/pyglet-not-running-properly-on-amd-hd4250/16548990#16548990

x = main()
x.run()

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
def __new__(cls, *args, **kwargs):
    typ = kwargs.get('type')  # or .pop(...)

    if typ and not kwargs.pop('_my_hack', None):
        # print("Special handling for {}...".format(typ))

        if typ == 'parent':
            # here we can *properly* call the next in line
            return super(Parent, cls).__new__(cls, *args, **kwargs)
        elif typ == 'child':
            # @note: need this to avoid endless recursion
            kwargs["_my_hack"] = True
            # here we need to cheat somewhat
            return Child.__new__(Child, *args, **kwargs)
        else:
            raise Exception("nono")
    else:
        x = super(Parent, cls).__new__(cls, *args, **kwargs)

    return x

rawDescription: Add child classes in SQLAlchemy session using parent constructor


rawDescription: Python: Using a variable inside a function (but the variable should be users input)


rawDescription: How to define a new string formatter

description: Define a new string formatter


rawDescription: Efficient algorithm to solve (m choose x) = n in python


code:
a = {}
a["hello"]={'n': 1,'m': 2,'o': 3}
a["bye"]={'n': 2,'m': 1,'o': 0}
a["goodbye"]={'n': 0,'m': 2,'o': 1}
import collections
result = collections.Counter()
for d in a.values():
    result += collections.Counter(d)
result
dict(result)

rawDescription: Summing dictionaries in a large dictionary


code:
density = .03
points = []
ring = 0
while ring < n_rings:
    angle = 0
    base_points_per_division = density*math.pi*(dr**2)*(2*ring+1)/n_angles
    while angle < n_angles:
        for i in xrange(int(base_points_per_division)):
             ra = angle*da + min(da,da*random.random())
             rr = ring*dr + dr*random.random()
             x = rr*math.cos(ra)
             y = rr*math.sin(ra)
             points.append((x,y))
        angle += 1
    ring += 1

rawDescription: Method to uniformly randomly populate a disk with points in python


code:
from datetime import datetime, timedelta
import math
import pyodbc

def VT_DATE_double_to_datetime(dbl):
    # math.modf() returns (<fractional_part>, <integer_part>)
    day_parts = math.modf(dbl)
    return (
        datetime(1899, 12, 30) +
        timedelta(days=day_parts[1]) +
        timedelta(seconds=abs(day_parts[0]) * 86400)
        )

connStr = (
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:\Users\Public\Database1.accdb;"
    )
cnxn = pyodbc.connect(connStr)
crsr = cnxn.cursor()

sql = """\
SELECT CDbl([Time]) AS ddbl FROM ConditionData WHERE ID=1
"""
crsr.execute(sql)
row = crsr.fetchone()
mydatetime = VT_DATE_double_to_datetime(row[0])

print(repr(mydatetime))
print(mydatetime)

crsr.close()
cnxn.close()

rawDescription: Pyodbc not returning precise datetime data


code:
mylist=[]
with open('x.dat') as f:
   rows = 2
   for _ in xrange(rows):
       line = next(f)
       x, y, k = [float(z) for z in line.split()]
       mylist.append(Point(x, y, k))

rawDescription: PYTHON - reading single row from a file

description: PYTHON - reading single row from a file


code:
p = Pool(6)
pool.map(func, [(vector, 1), (vector, 2), (vector, 1), ...])

rawDescription: When to and when not to use map() with multiprocessing.Pool, in Python? case of big input values


code:
mapping = df2.to_dict()['value']
for col in ['pin', 'pin1', 'pin2', 'pin3']:
    df1['{}_value'.format(col)] = df1[col].map(mapping)

rawDescription: Multiple merge of data frame without replacing the values


code:
['phabaa', 'phabea', 'phabia', 'phaboa', 'phabua', 'phabya', 'phabrca', 'phebaa', 'phebea', 'phebia', 'pheboa', 'phebua', 'phebya', 'phebrca', 'phibaa', 'phibea', 'phibia', 'phiboa', 'phibua', 'phibya', 'phibrca', 'phobaa', 'phobea', 'phobia', 'phoboa', 'phobua', 'phobya', 'phobrca', 'phubaa', 'phubea', 'phubia', 'phuboa', 'phubua', 'phubya', 'phubrca', 'phybaa', 'phybea', 'phybia', 'phyboa', 'phybua', 'phybya', 'phybrca', 'phrcbaa', 'phrcbea', 'phrcbia', 'phrcboa', 'phrcbua', 'phrcbya', 'phrcbrca', 'sdabaa', 'sdabea', 'sdabia', 'sdaboa', 'sdabua', 'sdabya', 'sdabrca', 'sdebaa', 'sdebea', 'sdebia', 'sdeboa', 'sdebua', 'sdebya', 'sdebrca', 'sdibaa', 'sdibea', 'sdibia', 'sdiboa', 'sdibua', 'sdibya', 'sdibrca', 'sdobaa', 'sdobea', 'sdobia', 'sdoboa', 'sdobua', 'sdobya', 'sdobrca', 'sdubaa', 'sdubea', 'sdubia', 'sduboa', 'sdubua', 'sdubya', 'sdubrca', 'sdybaa', 'sdybea', 'sdybia', 'sdyboa', 'sdybua', 'sdybya', 'sdybrca', 'sdrcbaa', 'sdrcbea', 'sdrcbia', 'sdrcboa', 'sdrcbua', 'sdrcbya', 'sdrcbrca', 'nnabaa', 'nnabea', 'nnabia', 'nnaboa', 'nnabua', 'nnabya', 'nnabrca', 'nnebaa', 'nnebea', 'nnebia', 'nneboa', 'nnebua', 'nnebya', 'nnebrca', 'nnibaa', 'nnibea', 'nnibia', 'nniboa', 'nnibua', 'nnibya', 'nnibrca', 'nnobaa', 'nnobea', 'nnobia', 'nnoboa', 'nnobua', 'nnobya', 'nnobrca', 'nnubaa', 'nnubea', 'nnubia', 'nnuboa', 'nnubua', 'nnubya', 'nnubrca', 'nnybaa', 'nnybea', 'nnybia', 'nnyboa', 'nnybua', 'nnybya', 'nnybrca', 'nnrcbaa', 'nnrcbea', 'nnrcbia', 'nnrcboa', 'nnrcbua', 'nnrcbya', 'nnrcbrca', 'mmabaa', 'mmabea', 'mmabia', 'mmaboa', 'mmabua', 'mmabya', 'mmabrca', 'mmebaa', 'mmebea', 'mmebia', 'mmeboa', 'mmebua', 'mmebya', 'mmebrca', 'mmibaa', 'mmibea', 'mmibia', 'mmiboa', 'mmibua', 'mmibya', 'mmibrca', 'mmobaa', 'mmobea', 'mmobia', 'mmoboa', 'mmobua', 'mmobya', 'mmobrca', 'mmubaa', 'mmubea', 'mmubia', 'mmuboa', 'mmubua', 'mmubya', 'mmubrca', 'mmybaa', 'mmybea', 'mmybia', 'mmyboa', 'mmybua', 'mmybya', 'mmybrca', 'mmrcbaa', 'mmrcbea', 'mmrcbia', 'mmrcboa', 'mmrcbua', 'mmrcbya', 'mmrcbrca', 'ghabaa', 'ghabea', 'ghabia', 'ghaboa', 'ghabua', 'ghabya', 'ghabrca', 'ghebaa', 'ghebea', 'ghebia', 'gheboa', 'ghebua', 'ghebya', 'ghebrca', 'ghibaa', 'ghibea', 'ghibia', 'ghiboa', 'ghibua', 'ghibya', 'ghibrca', 'ghobaa', 'ghobea', 'ghobia', 'ghoboa', 'ghobua', 'ghobya', 'ghobrca', 'ghubaa', 'ghubea', 'ghubia', 'ghuboa', 'ghubua', 'ghubya', 'ghubrca', 'ghybaa', 'ghybea', 'ghybia', 'ghyboa', 'ghybua', 'ghybya', 'ghybrca', 'ghrcbaa', 'ghrcbea', 'ghrcbia', 'ghrcboa', 'ghrcbua', 'ghrcbya', 'ghrcbrca']
['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']

rawDescription: Python script to generate words from letters and two letter combination


code:
from threading import Timer

def kill_yourself(delay):
    t = Timer(delay, kill_yourself_now)
    t.daemon = True # no need to kill yourself if we're already dead
    t.start()

rawDescription: Timeout function in Python

description: Timeout function in Python


rawDescription: Assign new values to slice from MultiIndex DataFrame


code: result = re.search(r'Schedule \(1\).*?\(2\)', data, flags=re.DOTALL)

rawDescription: Returning characters after regex has found match in python


code: z = set(key for key in itertools.chain(x, y))

rawDescription: Merging dictionaries using a counter

description: Merging dictionaries using a counter


code:
def QuickSort(dataset, low, high):
    if (low >= high):
        return
    #Set pivot to last element
    pivot = dataset[high - 1]
    #Set wall at first element
    wall = low
    #Loop through list - if current element is less or equal
    #to the pivot, swap current element with element right of wall
    #and move wall on.
    for i in range(low, high):
        if (dataset[i] <= pivot):
            temp = dataset[wall]
            dataset[wall] = dataset[i]
            dataset[i] = temp
            wall = wall + 1
            if wall >= high:
                break
         #recursively call for subsequent part of list
    QuickSort(dataset, low, wall - 1)
    QuickSort(dataset, wall, high)

dataset = [1,6,2,3,6,7,4,2,5]
dataset_length = len(dataset)
QuickSort(dataset, 0, dataset_length)
print(dataset)

rawDescription: Quick Sort is not returning expected results - Python3


code:
I
m

rawDescription: Python program to extract text from a text file?


code:
def parse(self, response):
    # make a selector and search the fields inside it
    sel = response.xpath('//div[@id="siteTable"]')

    item = ExItem()
    item["title"] = sel.xpath('.//p[contains(@class,"title")]/a/text()').extract()
    item["rank"] = sel.xpath('.//span[contains(@class,"rank")]/text()').extract()
    item["votes_dislike"] = sel.xpath('.//div[contains(@class,"score dislikes")]/text()').extract()
    item["votes_unvoted"] = sel.xpath('.//div[contains(@class,"score unvoted")]/text()').extract()
    item["votes_likes"] = sel.xpath('.//div[contains(@class,"score likes")]/text()').extract()
    item["video_reference"] = sel.xpath('.//a[contains(@class,"thumbnail may-blank")]/@href').extract()
    item["image"] = sel.xpath('.//a[contains(@class,"thumbnail may-blank")]/img/@src').extract()
    return item

rawDescription: remove the unicode from the output of JSON using scrapy

description: Remove the unicode from the output of JSON using scrapy


code:
seen = set()
for (value, fmt) in formats:
    l1 = len(seen)
    seen.add(fmt)
    if l1 != len(seen):
         process(value, fmt)

rawDescription: How to process each item in an ordered list with duplicates only once in Python?

description: Process each item in an ordered list with duplicates only once in Python


rawDescription: Required format for month-day-year plot in matplotlib


code:
textRect.centerx = x
textRect.centery = y

rawDescription: How do I change the color of a button once it is clicked in Pygame?

description: Change the color of a button once it is clicked in Pygame


code:
number_1 = random.randrange(10,20+1)
number_2 = random.randrange(1,10+1)
symbol = random.choice(symbols.keys())
operator = symbols[symbol]
result = operator(number_1, number_2)

rawDescription: How to convert '*' to *

description: Convert '*' to *


code:
from fuzzywuzzy import fuzz
fuzz.partial_ratio("my name is joran","my nam is")

rawDescription: Fuzzy Startswith

description: Fuzzy Startswith


code:
for i in range(len(weights)):
    for j in range(max_v + 1):
        if j >= values[i]:
            m[i + 1][j] = min(m[i][j], m[i][j - values[i]] + weights[i])
        else:
            m[i + 1][j] = m[i][j]

rawDescription: 0/1 Knapsack with integer values and irrational weights?


code: from tkinter import *

rawDescription: tkinter wrap text if larger than column width

description: Tkinter wrap text if larger than column width


code: var_name = "value"

rawDescription: python global parameters file

description: Python global parameters file


code:
from lxml.html import fromstring

data = """

Field1:" Value1"

Field2:" Value2"

Field3:" Value3"

Field4:" Value4"

Field5:" Value5"

"""

root = fromstring(data)
for b in root.xpath("//b"):
    label = b.text_content()
    value = b.xpath("following-sibling::text()")[0].strip()

    print(label, value)

rawDescription: Parsing text after bold tag using XPath

description: Parsing text after bold tag using XPath


code:
def find_adjacent(message, pairs, k):
  if k == len(message)-1:
    return("Number of pairs:", pairs)
  elif message[k] == message[k+1]:
    if k == 0:
      return find_adjacent(message, pairs+1, k+1) # first letter of message, all good
    elif message[k] != message[k-1]:
      return find_adjacent(message, pairs+1, k+1) # not first letter, and this pair hasn't been counted before
    else:
      return find_adjacent(message, pairs, k+1) # this sequence has already been counted
  else:
    return find_adjacent(message, pairs, k+1)

rawDescription: Finding adjacent pairs of characters in a string using recursion


code:
class Radio:
    def __init__(self):
        self.stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
        self.station_index = 0

    def seek(self):
        print("Currently tuned to", self.stations[self.station_index])
        print("Seeking...")
        self.station_index = (self.station_index + 1) % len(self.stations)
        print("Now tuned to", self.stations[self.station_index])

rawDescription: I need some help starting of this radio program


rawDescription: Django Haystack Indexing More than one models


code:
type(None)
type(None).mro()
issubclass(type(None), object)
isinstance(None, object)

rawDescription: Does NoneType class inherit object class?


code:
import urllib
import urlparse

def url_fix(s, charset='utf-8'):
    if isinstance(s, unicode):
        s = s.encode(charset, 'ignore')
    scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
    path = urllib.quote(path, '/%')
    qs = urllib.quote_plus(qs, ':&=')
    return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))

rawDescription: How to handle links containing space between them in Python

description: Handle links containing space between them in Python


code:
def my_view(request):

    # Retrieve the author the way you see fit
    author = Author.objects.get(id=request.session['author'])

    articles = author.get_articles()
    context = {"articles": articles}
    return render(request, 'mytemplate.html', context)

rawDescription: Confused regarding ForeignKey relationship in Django


rawDescription: .fillna column if two cells are empty in Pandas


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# Make random number generation consistent between runs
np.random.seed(5)

def main():
    numlines, numpoints = 2, 3
    points = np.random.random((numlines, numpoints, 2))

    # Add "num" additional segments to each line
    segments, color_scalar = zip(*[interp(item, num=20) for item in points])

    segments = np.vstack(segments)
    color_scalar = np.hstack(color_scalar)

    fig, ax = plt.subplots()
    coll = LineCollection(segments)
    coll.set_array(color_scalar)
    ax.add_collection(coll)

    plt.show()

def interp(data, num=20):
    """Add "num" additional points to "data" at evenly spaced intervals and
    separate into individual segments."""
    x, y = data.T
    dist = np.hypot(np.diff(x - x.min()), np.diff(y - y.min())).cumsum()
    t = np.r_[0, dist] / dist.max()

    ti = np.linspace(0, 1, num, endpoint=True)
    xi = np.interp(ti, t, x)
    yi = np.interp(ti, t, y)

    # Insert the original vertices
    indices = np.searchsorted(ti, t)
    xi = np.insert(xi, indices, x)
    yi = np.insert(yi, indices, y)

    return reshuffle(xi, yi), ti

def reshuffle(x, y):
    """Reshape the line represented by "x" and "y" into an array of individual
    segments."""
    points = np.vstack([x, y]).T.reshape(-1,1,2)
    points = np.concatenate([points[:-1], points[1:]], axis=1)
    return points

if __name__ == '__main__':
    main()

rawDescription: Matplotlib: How to colorize a large number of line segments as independent gradients, efficiently


code:
import zmq

def worker(addr):
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.bind(addr)
    while True:
        # get message from boss
        msg = socket.recv()
        # ...do smth
        # send back results
        socket.send(msg)

if __name__ == '__main__':
    # spawn 5 workers
    from multiprocessing import Process
    for i in range(5):
        Process(target=worker, args=('tcp://127.0.0.1:500%d' % i,)).start()

rawDescription: 0mq one-to-many connection

description: 0mq one-to-many connection


code:
queryset = Submission.objects.extra(
    select={'total': 'IFNULL((SELECT SUM(vote_value) ' + \
        'FROM submissions_vote ' + 'WHERE submissions_vote.submission_id = ' + \
        'submissions_submission.id), ' + '0)',
    'has_voted': 'CASE WHEN %d IN (SELECT voter_id FROM submissions_vote WHERE ' + \
        'submissions_vote.submission_id = submissions_submission.id) THEN 1 ELSE 0 END'
    }, select_params=(self.request.user.pk,)).order_by('-total')

rawDescription: Django querysets and foreign keys

description: Django querysets and foreign keys


rawDescription: groupby common values in two columns

description: Groupby common values in two columns


code:
email = ['apples','bananas','cats','dogs','elephants','fish','gee']
start, stop = 'ban', 'ele'
ind_s = next(i for i, j in enumerate(email) if j.startswith(start))
ind_e = next(i for i, j in enumerate(email) if j.startswith(stop) and i > ind_s)
email[ind_s+1:ind_e]

rawDescription: Python: Find X to Y in a list of strings


code:
import xml.etree.ElementTree
e = xml.etree.ElementTree.parse('thefile.xml').getroot()

rawDescription: How do I parse XML in Python?

description: Parse XML in Python


code:
import timeit
timeit.timeit("'one, two'.split(',', 1)[0]")
timeit.timeit("'one, two'.partition(',')[0]")

rawDescription: How to delete some characters from a string by matching certain character in python

description: Delete some characters from a string by matching certain character in python


rawDescription: Parse hours without leading zeroes by strptime in Python


code:
with open(logfilePath) as f:
    contents = f.read()
    if any(needle in contents for needle in needle):
        ...

rawDescription: How to cut short a long 'if' statement with multiple logical AND in Python?

description: Cut short a long 'if' statement with multiple logical AND in Python


rawDescription: How to use NLTK to generate random paragraphs

description: Use NLTK to generate random paragraphs


code:
import scipy.interpolate
f = scipy.interpolate.UnivariateSpline(x, y)
f
f(5.05)

rawDescription: extract value of a numeric array function in numpy

description: Extract value of a numeric array function in numpy


code:
merge(df1.reset_index(),
      df2.reset_index(),
      on=['index1'],
      how='inner'
     ).set_index(['index1','index2'])

rawDescription: Merge on single level of MultiIndex

description: Merge on single level of MultiIndex


rawDescription: Minimum x and y coordinate of 2d array. Python


code:
def __repr__(self):
    return '<Stats: description={0.description!r}, mystat={0.mystat!r}>'.format(self)

rawDescription: Python __repr__ and None

description: Python __repr__ and None


code:
for object in sequence:
   if selector(object):
      result.append(object)

rawDescription: How to pick lines containg numbers in given positions on the line with python

description: Pick lines containg numbers in given positions on the line with python


code:
import os
import email
import email.encoders
import email.mime.text
import smtplib

# message/email details
my_email = 'myemail@gmail.com'
my_passw = 'asecret!'
recipients = ['jack@gmail.com', 'jill@gmail.com']
subject = 'This is an email'
message = 'This is the body of the email.'
file_name = 'C:\\temp\\test.txt'

# build the message
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = my_email
msg['To'] = ', '.join(recipients)
msg['Date'] = email.Utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(email.MIMEText.MIMEText(message))

# build the attachment
att = email.MIMEBase.MIMEBase('application', 'octet-stream')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)

# send the message
srv = smtplib.SMTP('smtp.gmail.com', 587)
srv.ehlo()
srv.starttls()
srv.login(my_email, my_passw)
srv.sendmail(my_email, recipients, msg.as_string())

rawDescription: Cannot send an email with python smtp

description: Cannot send an email with python smtp


code:
from multiprocessing import Pool
pool = Pool()

rawDescription: Parallelize loop over numpy rows

description: Parallelize loop over numpy rows


rawDescription: Add fields and correct indentation for json file (using python or ruby)


code:
import re
from __future__ import division
s = "7 1/2"
re.sub(r'(\d+)/(\d+)', lambda m: str(int(m.group(1))/int(m.group(2))), s)
re.sub(r'(\d+)/(\d+)', lambda m: str(int(m.group(1))/int(m.group(2))), '7 9/2')

rawDescription: Python regex fractions

description: Python regex fractions


code:
for i,v in enumerate(y):
    x.insert(2*i+1,v)

rawDescription: python merge two lists (even/odd elements)

description: Python merge two lists (even/odd elements)


code:
import sys
def robot_print():
   sys.__stdout__.write("this is a testlib log for robot test - Test.robot")

rawDescription: Pybot - redirect test library print statements to the console


code: sum(item == x for item in y)

rawDescription: How to print the number of times an element appears in a list in Python?

description: Print the number of times an element appears in a list in Python


code:
def your_sort(your_list):
    return sorted(your_list, key=lambda e: (-e[1], e[0]))

rawDescription: Python 3 List: How do I sort [('NJ', 81), ('CA', 81), ('DC', 52)] base on number and then letters?


code:
import scipy
row1 = [91,90,51]
row2 = [150,200,155]
row3 = [109,198,172]
data=[row1,row2,row3]
chi2_contingency(data)
scipy.stats.chi2_contingency(data)

rawDescription: Chi Square Test of Independence in Python


code:
class FooSpider(BaseSpider):
    def __init__(self, *args, **kwargs):
        super(FooSpider, self).__init__(*args, **kwargs)
        dispatcher.connect(self.dont_close_me, signals.spider_idle)

    def dont_close_me(self, spider):
        if spider != self:
            return

        self.crawler.engine.crawl(self.create_request(), spider)

        raise DontCloseSpider("..I prefer live spiders.")

rawDescription: Scrapy: How to manually insert a request from a spider_idle event callback?


code:
def foo1():
    data = ((a,b) for a in (i*i for i in xrange(1,101) if i%2) for b in [1,2,3,4,5] if a+b > 40)
    return list(data)

rawDescription: How fast are nested python generators?

description: How fast are nested python generators


code:
def clear_something(modeladmin, request, queryset):
    queryset.update(field=0)
    for a in queryset:
        a.b_set.all().delete()

rawDescription: Custom Django admin action, remove entries related by ForeignKey


code:
open('log','w').writelines([
    (line[:33]+line[42:])
    for line in open(fl) if "Current Track Playing" in line])

rawDescription: Deleting Mix of Numbers and Letters

description: Deleting Mix of Numbers and Letters


code: fn = lambda: None

rawDescription: Argumentless lambdas in Python?

description: Argumentless lambdas in Python


code: [n for n, i in enumerate(a) if i not in b]

rawDescription: Slicing Python lists vs Slicing R vectors


code:
AUTHENTICATION_BACKENDS = (
   # 'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
)

rawDescription: when logging from facebook using django allauth request user is admin

description: When logging from facebook using django allauth request user is admin


code:
import json
json_value = '{"key":null,"key2":"yyy"}'
def remove_nulls(d):
    return {k: v for k, v in d.iteritems() if v is not None}

json.loads(json_value, object_hook=remove_nulls)
json_value = '{"key":null,"key2":"yyy", "key3":{"foo":null}}'
json.loads(json_value, object_hook=remove_nulls)

rawDescription: is there a way to config python json library to ignore fields that has null values when calling json.loads?

description: Is there a way to config python json library to ignore fields that has null values when calling json.loads


code:
# creates a str literal (with utf-8 encoding, if this was
# specified on the beginning of the file):
len('ë́aúlt')
# creates a unicode literal (you should generally use this
# version if you are dealing with special characters):
len(u'ë́aúlt')
# the same str literal (written in an encoded notation):
len('\xc3\xab\xcc\x81a\xc3\xbalt')
# you can convert any str to an unicode object by decoding() it:
len('\xc3\xab\xcc\x81a\xc3\xbalt'.decode('utf-8'))

rawDescription: Python returning the wrong length of string when using special characters


code:
def code_char(char, key):
    ichar = int(char)
    ikey = int(key)
    return str(ichar+ikey)

rawDescription: Python encoding blocks of text using strings


rawDescription: Is there a way to append the name of a function to a list automatically?


code:
with self.mutex:
    return self._statistics.copy()

rawDescription: Correct usage of Python threading.RLock

description: Correct usage of Python threading.RLock


rawDescription: python replace multiple elements in string with str methods

description: Python replace multiple elements in string with str methods


code:
import numpy as np
import matplotlib as mpl
mpl.use('pgf')
import matplotlib.pyplot as plt

x = np.linspace(0., 1., num=100)
y = x**2

plt.plot(x, y, label=r'Data \cite{<key>}')
plt.legend(loc=0)
plt.savefig('fig.pgf')

rawDescription: Latex Citation in matplotlib Legend

description: Latex Citation in matplotlib Legend


code:
import itertools
for year, month, hour, node in itertools.product(
        yearsindex, monthindex, hourindex, nodeindex):
    dosomething(year, month, hour, node)

rawDescription: How to combine multiple for loops into a single generator python

description: Combine multiple for loops into a single generator python


code: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)

rawDescription: Creating a processing queue in python

description: Creating a processing queue in python


code:
import numpy as np
a = np.array([1.,2.,3.,4.])
a
a.dtype
a.dtype = complex
a

rawDescription: Python: unpacking string of floats to complex numbers


code: df.drop(1, axis=0).drop(2, axis=1)

rawDescription: Numpy Construct a new matrix without rowi,columnj keeping row,column indices


code:
hit = random.uniform(0, 10)
if hit <= 2:
    damage = 0.00
else:
    damage = (hit - 2) / 8

rawDescription: Random Python module and creating chances


rawDescription: Two's complement of Hex number in Python


code:
def __init__(self):
    tk.Tk.__init__(self)
    self.drawing_area = tk.Canvas(self, width=600, height=600, background="white")
    self.drawing_area.pack()
    self.drawing_area.bind("<Motion>", self.motion)
    self.drawing_area.bind("<ButtonPress-1>", self.b1down)
    self.drawing_area.bind("<ButtonRelease-1>", self.b1up)

    self.button1 = tk.Button(self, text = "Reset", command = self.blank_canvas, anchor = tk.N)
    self.button1.configure(width = 3, background = "#FFFFFF", relief = tk.FLAT)
    self.button1.pack(side="left")

    self.button2 = tk.Button(self, text = "Undo", command = self.undo, anchor = tk.N)
    self.button2.configure(width = 3, background = "#FFFFFF", relief = tk.FLAT)
    self.button2.pack(side="left")

    self.button3 = tk.Button(self, text = "Redo", command = self.redo, anchor = tk.N)
    self.button3.configure(width = 3, background = "#FFFFFF", relief = tk.FLAT)
    self.button3.pack(side="left")

def blank_canvas(self):
    self.drawing_area.delete("line")

def undo(self):
    self.counter -= 1 #decrements the counter to look at the previous item
    currentlist = [] #creates a list to store the coordinates in
    for item in self.drawing_area.find_withtag("line"+str(self.counter)): #find all sub lines from the previous line
        currentlist.append(self.drawing_area.coords(item)) #get and add the coordinates to the working list
    self.drawing_area.delete("line"+str(self.counter)) #delete all items of the current line
    self.undone.append(currentlist) #add the working list to the stored list

def redo(self):
    try:
        currentlist = self.undone.pop() #fetch and remove last set of coordinates
        for coords in currentlist: #for set of coordinates redraw subline
            self.drawing_area.create_line(coords,smooth=tk.TRUE,fill = self.color, width=self.linesize, tags=["line", "line"+str(self.counter)])
        self.counter += 1 #re increment counter
    except IndexError:
        pass #occurs if list is empty

def b1down(self, event):
    self.b1 = "down"

def b1up(self, event):
    self.b1 = "up"
    self.xold = None
    self.yold = None
    self.counter += 1

def motion(self, event):
    if self.b1 == "down":
        if self.xold is not None and self.yold is not None:
            event.widget.create_line(self.xold,self.yold,event.x,event.y,smooth=tk.TRUE,fill = self.color, width=self.linesize, tags=["line", "line"+str(self.counter)])
        self.xold = event.x
        self.yold = event.y

rawDescription: Python tkinter delete event.widget.create_line


code:
import sys
from django.conf import settings
settings.configure()
from django.contrib.auth import hashers
raw_password = sys.argv[1]
try:
    salt = sys.argv[2]
except IndexError:
    salt = None
hash = hashers.make_password(raw_password, salt=salt)
sys.stdout.write("%s\n" % hash)
sys.stdout.flush()
sys.exit(0)

rawDescription: Using django passwords in php for authentication


rawDescription: Add Integer into existing list

description: Add Integer into existing list


code: list3 = [key + (value,) for key, value in d3.iteritems()]

rawDescription: Check whether an entry present in python list and add the elements


rawDescription: ValueError while trying to convert an array of strings to an array with mixed given dtypes


code: from old import *

rawDescription: Pass class variables onto a class on another script in Python


rawDescription: Python: Script to detect data Hazards

description: Python: Script to detect data Hazards


code:
import sublime, sublime_plugin

class UpArrowInAutoCompleteCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.settings().set('autoCompleteFlag',True)
        self.view.settings().set('initialPoint', self.view.sel()[0].begin())

        """ Move one line up """
        self.view.run_command('move', {"by": "lines", "forward": False});
        """ Auto-complete was opened and up arrow was pressed, so if the cursor changes
        (on_selection_modified will be triggered) we have gone outside the list.
        If we were not in the first element on_selection_modified will not be triggered, so
        we turn of the flag"""
        sublime.set_timeout(lambda: self.view.settings().set('autoCompleteFlag', False),300)

class AutoCompleteSelectionModifiedTriggerCommand(sublime_plugin.EventListener):
    def on_selection_modified(self, view):
        if view.settings().get('autoCompleteFlag'):
            """ If the up arrow was pressed and on_selection_modified
            has been triggered, then we know that we were in the first element
            of the list and we hitted the up arrow"""
            view.settings().set('autoCompleteFlag', False)
            initialPoint = view.settings().get('initialPoint')

            """ We don't know how many words the auto_complete has, so,
            in order to calculate that number, we move down in the list
            till we get outside the list. After that we make the list appear
            again and move down n-1 times to go (and stay) to the last line """
            view.sel().clear()
            view.sel().add(initialPoint)
            view.run_command('auto_complete')

            numLines = 0
            while view.sel()[0].begin() == initialPoint:
                view.run_command('move', {"by": "lines", "forward": True})
                numLines += 1
                if numLines == 401:
                    return

            if numLines == 0:
                return

            view.sel().clear()
            view.sel().add(initialPoint)
            view.run_command('auto_complete')

            numLine = 0
            while numLine < (numLines-1):
                view.run_command('move', {"by": "lines", "forward": True})
                numLine += 1

rawDescription: Sublime Text autocomplete window closes when scrolling off the list


code: infile = None

rawDescription: "Initializing" a constant containing a file in python?


code:
url(r'^recover/(?P<signature>.+)/$', 'password_reset_recover.views.recover_done',
    name='password_reset_sent'),
# next we override our url, assuming your app name is called 'core'
url(r'^recover/$', 'core.views.myrecover', name='password_reset_recover'),
url(r'^/', include('password_reset.urls')),

rawDescription: django-password-reset - how to set attributes

description: Django-password-reset - how to set attributes


rawDescription: How to do linear regression, taking errorbars into account?

description: Do linear regression, taking errorbars into account


code: sentences = re.findall(r'([A-Z].*?)[.!?;]', stripped_value, re.MULTILINE | re.DOTALL | re.UNICODE)

rawDescription: python, regex find a subsentence, exclude bounaries

description: Python, regex find a subsentence, exclude bounaries


code:
text = "foo bar baz quux bla"
X = HashingVectorizer(n_features=8).transform([text])
X.toarray()
scipy.linalg.norm(np.abs(X.toarray()))

rawDescription: Why is my scikit learn HashingVectorizor giving me floats with binary = True set?


code:
class forrange:

    def __init__(self, startOrStop, stop=None, step=1):
        if step == 0:
            raise ValueError('forrange step argument must not be zero')
        if not isinstance(startOrStop, int):
            raise TypeError('forrange startOrStop argument must be an int')
        if stop is not None and not isinstance(stop, int):
            raise TypeError('forrange stop argument must be an int')

        if stop is None:
            self.start = 0
            self.stop = startOrStop
            self.step = step
        else:
            self.start = startOrStop
            self.stop = stop
            self.step = step

    def __iter__(self):
        return self.foriterator(self.start, self.stop, self.step)

    class foriterator:

        def __init__(self, start, stop, step):
            self.currentValue = None
            self.nextValue = start
            self.stop = stop
            self.step = step

        def __iter__(self): return self

        def next(self):
            if self.step > 0 and self.nextValue >= self.stop:
                raise StopIteration
            if self.step < 0 and self.nextValue <= self.stop:
                raise StopIteration
            self.currentValue = forrange.forvalue(self.nextValue, self)
            self.nextValue += self.step
            return self.currentValue

    class forvalue(int):
        def __new__(cls, value, iterator):
            value = super(forrange.forvalue, cls).__new__(cls, value)
            value.iterator = iterator
            return value

        def update(self, value):
            if not isinstance(self, int):
                raise TypeError('forvalue.update value must be an int')
            if self == self.iterator.currentValue:
                self.iterator.nextValue = value + self.iterator.step

rawDescription: How do I use a C-style for loop in Python?

description: Use a C-style for loop in Python


code:
Iteration and counting
while years > 1:
    years = years - 1

rawDescription: Should I do anything to make my code more pythonic?


code:
df1.loc[df1['size'] > 0.3, 'Flower.Type'] = 'Setosa'
print(df1)

rawDescription: Merging two data frames and doing calculation


code:
class MainFrame(gui.MainFrame):
    def __init__(self, parent):
        dom = parse("data.xml")
        data = dom.getElementById("album")
        self.m_textCtrl2.SetValue(data)

rawDescription: python - AttributeError: 'MainFrame' object has no attribute 'm_textCtrl2'

description: Python - AttributeError: 'MainFrame' object has no attribute 'm_textCtrl2'


code:
import glob
import subprocess
filelist=glob.glob('/path/to/file/*.fileending')
for dat in filelist:
    subprocess.call("cachedel "+dat, shell=True)

rawDescription: Disable Caching for Python

description: Disable Caching for Python


code:
from matplotlib import pyplot as plt # import libraries
import pandas as pd # import libraries
import netCDF4 # import libraries
fp='uwstemp.nc' # your file name with the eventual path
nc = netCDF4.Dataset(fp) # reading the nc file and creating Dataset
""" in this dataset each component will be
in the form nt,nz,ny,nx i.e. all the variables will be flipped. """
plt.imshow(nc['Temp'][1,:,0,:])
""" imshow is a 2D plot function
according to what I have said before this will plot the second
iteration of the vertical slize with y = 0, one of the vertical
boundaries of your model. """
plt.show() # this shows the plot

rawDescription: Read .nc (netcdf) files using python

description: Read .nc (netcdf) files using python


code:
DOC = """<clade>
<name>Espresso</name>
<branch_length>2.0</branch_length>
</clade>"""

import lxml.etree
tree = lxml.etree.XML(DOC)
matches = tree.xpath('//name[text()="Espresso"]')

rawDescription: how to add an xml node based on the value of a text node

description: Add an xml node based on the value of a text node


rawDescription: Select row prior as.freq() occurance

description: Select row prior as.freq() occurance


code:
df['bool'] = df.iloc[:, 0] == df.iloc[:, 2]
df

rawDescription: Column to Column match using pandas or numpy in Python


code: ['topic', ['subtopic', ['sub-subtopic'], 'subtopic2'], 'topic2']

rawDescription: Difficulty of this particular job using pyparsing? (beginner)


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

# N = 100
# lat = np.linspace(-90, 90, N)
# temp = 50*(1-np.cos(np.linspace(0, 2*np.pi, N)))
# temp[::5] = np.nan
# np.savetxt(filename, np.column_stack([lat, temp]))

lat, temp = np.genfromtxt('temperatures.txt', usecols = (0,1), unpack=True)
valid = np.isfinite(temp)
lat = lat[valid]
temp = temp[valid]

grid = np.linspace(-90, 90, 40)

count, bin_edges = np.histogram(lat, bins=grid)
temp_sum, bin_edges = np.histogram(lat, bins=grid, weights=temp)
temp_avg = temp_sum / count

plt.plot(bin_edges[1:], temp_avg, 'o')
plt.show()

rawDescription: Recursively select elements in numpy array


rawDescription: Python create list of objects from list of 2 elements lists


rawDescription: Grouping model objects in Django

description: Grouping model objects in Django


code: list(set(frozenset(item) for item in L))

rawDescription: removing duplicates of a list of sets

description: Removing duplicates of a list of sets


code:
for matchingdiv in tree.xpath('.//h3//a/ancestor::*[self::div[contains(@class,"cont")]]'):
    # no need to skip anymore, this is a div.cont with h3 and a contained
    link = matchingdiv.xpath('.//h3//a')

    # grab the `p` text and of course the link

rawDescription: Iterating Over Elements and Sub Elements With lxml


code:
from scipy.interpolate import griddata
x -= shift_x
y -= shift_y
zi = griddata((x,y),z,(xi,yi),method='linear')
xi += shift_x
yi += shift_y

rawDescription: Interpolation resampling large irregular matrix or surface data points to regular grid


code:
bytesread = 0
while True:
  line = fh.readline()
  if line == '':
    break
  bytesread += len(line)

rawDescription: Keep Track of Number of Bytes Read

description: Keep Track of Number of Bytes Read


code:
string = "abc\ndef"
print (repr(string))
'abc\ndef'

rawDescription: In Python, is it possible to escape newline characters when printing a string?


code:
import sys
from PyQt4 import QtGui, QtCore

class Bar(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.initUI()

    def initUI(self):
        self.setGeometry(300,300,200,200)
        self.b1 = QtGui.QPushButton("Button", self)
        self.b1.move(100,100)
        self.setWindowTitle("Example")
        self.statusBar().showMessage("Statusbar")

def main():
    app = QtGui.QApplication(sys.argv)
    bar = Bar()
    bar.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

rawDescription: multiple classes in PyQt4

description: Multiple classes in PyQt4


code: new_lis = [item for item in lis if "(page does not exist)" not in item]

rawDescription: Deleting elements with specific substring in python


code:
def run(self, cmd):
    try:
        if "$file_name" in cmd:
            cur_view = self.window.active_view()
            cmd_string=cmd.replace("$file_name",cur_view.file_name())
            os.system("start "+cmd_string)
        else:
            cmd_string=cmd
            os.system("start "+cmd_string)
    except TypeError:
        sublime.message_dialog("Something went wrong with the command given... \n\n\n"+traceback.format_exc())

rawDescription: In Sublime Text 2 how can I pass the current file path to a command called by a key binding


rawDescription: how to generate unicode strings only with multi-byte characters

description: Generate unicode strings only with multi-byte characters


code:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
val = bits2int([i >= 3 for i in arr])
# Now, val = 63 = 0b00111111

# Handle additional integer
new_int = 9             # Give the additional integer a name, to make it clear
val <<= 1               # Shift up all bits
val |= (new_int >= 3)   # Set lowest bit according to some logic
                        #   (here, if new_int >= 3)
print(val)
print("{:08b}".format(val))

rawDescription: Python dynamic bit manipulation example

description: Python dynamic bit manipulation example


rawDescription: 2to3 range(...) -> list(range(...))

description: 2to3 range(...) -> list(range(...))


code:
def wrapper(fn, *params, **keyword_params):  # Note the asterisks
    return fn(*params, **keyword_params)

def myfunc(a, b, c=1):
    return (a + b)/c

wrapper(myfunc, 2, 5, c=3)  # Nicer function call

rawDescription: How do I call a function with arbitrary parameters from another function?

description: Call a function with arbitrary parameters from another function


rawDescription: xtick max value setup with panda and matplotlib

description: Xtick max value setup with panda and matplotlib


code:
def runInParallel(*fns):
  proc = []
  for fn in fns:
    p = Process(target=fn)
    p.start()
    proc.append(p)
  for p in proc:
    p.join()

rawDescription: Python - Fork Modules

description: Python - Fork Modules


code:
my_dict = {'a':a, 'b':b}
for key, val in my_dict.iteritems():
    pickle.dump(val,open('{0}.p'.format(key),'wb'))

rawDescription: How to assign pickle name dynamically in Python?

description: Assign pickle name dynamically in Python


rawDescription: selecting across multiple columns with python pandas?

description: Selecting across multiple columns with python pandas


code:
from lxml import etree
from StringIO import StringIO

xml = etree.parse(StringIO('''<TextWithNodes>
<Node id="0"/>TEXT1<Node id="19"/>TEXT2 <Node id="20"/>TEXT3<Node id="212"/></TextWithNodes>'''))

xml.xpath("//text()")
Out[43]: ['\n', 'TEXT1', 'TEXT2 ', 'TEXT3']

rawDescription: Extracting text from XML node with minidom


code: k_keys_sorted_by_values = heapq.nlargest(k, dictionary, key=dictionary.get)

rawDescription: finding top k largest keys in a dictionary python

description: Finding top k largest keys in a dictionary python


rawDescription: How to efficiently locate and save pixels with a certain value using OPENCV?

description: Efficiently locate and save pixels with a certain value using OPENCV


code:
def user_replace(match):
    """Pull from replacements dict or prompt"""
    placeholder = match.group(1)
    return (replacements[placeholder][0]
             if placeholder in replacements else
              raw_input('%s? ' % placeholder))

rawDescription: How to extend this search-and-replace python script to accept variables from command line?

description: Extend this search-and-replace python script to accept variables from command line


code: del d[key]

rawDescription: Delete an element from a dictionary

description: Delete an element from a dictionary


code:
import pylung
pylung.deutsch()

import os # I want to preserve object identity with the original os

os.ERREICHE_SETZEN
os.durchlaufe(...)

rawDescription: Replace object with another in the entire process / become in Python


rawDescription: Dictionary from parsed text. Simpler way to create?


code:
extra = len(s) % 16
if extra > 0:
    s = s + (' ' * (16 - extra))

rawDescription: How to make sure the input is a multiple of 16, and if not add padding to it

description: Make sure the input is a multiple of 16, and if not add padding to it


code:
from requests import post

data = "{'email':{'email':'example@email.com'}}"
response = post("http://some/API/endpoint", data=data, headers={'Content-type': 'application/json', 'Accept': 'text/plain'}).text

rawDescription: Passing structs through urllib2

description: Passing structs through urllib2


code: text_area = PyTediTextArea(self)

rawDescription: Tkinter Class method

description: Tkinter Class method


code:
with open('out.dat', 'rb') as pkl_file:
    x,y = pickle.load(pkl_file)

rawDescription: processing a binary file containing an array using python

description: Processing a binary file containing an array using python


code:
create.argtypes = [POINTER(POINTER(List)),]
control = Pointer(List)()
create(byref(control))

rawDescription: Python ctypes pointer to pointer to structure


code:
def removeOutlier(lowerBound, upperBound, colData):
    return colData.clip(lowerBound, upperBound)

rawDescription: Refactoring a bad 'code smell' in multiplication of columns in a dataframe


rawDescription: Use size in Python

description: Use size in Python


rawDescription: How can I call the metaclass's __call__?

description: Call the metaclass's __call__


code:
ItemID, ItemName
2, Apple
4, Orange
5, Pear
6, Banana
15, Kiwi

rawDescription: Input List of Items, Output List of ItemIDs


rawDescription: I have two lists. I would like to make a third from the elements given in one of the lists


code:
class DisjointSet:
    def __init__(self):
        self.parent = {}
        self.rank = {}

    def find(self, element):
        if element not in self.parent: # leader elements are not in `parent` dict
            return element
        leader = self.find(self.parent[element]) # search recursively
        self.parent[element] = leader # compress path by saving leader as parent
        return leader

    def union(self, leader1, leader2):
        rank1 = self.rank.get(leader1,0)
        rank2 = self.rank.get(leader2,0)

        if rank1 > rank2: # union by rank
            self.parent[leader2] = leader1
        elif rank2 > rank1:
            self.parent[leader1] = leader2
        else: # ranks are equal
            self.parent[leader2] = leader1 # favor leader1 arbitrarily
            self.rank[leader1] = rank1+1 # increment rank

rawDescription: In Python, count unique key/value pairs in a dictionary


code:
for root, dirnames, filenames in os.walk(root_path):
    dirnames[:] = natsort.natsorted(dirnames)
    # continue with other directory processing...

rawDescription: How can I use os.walk or any other alternative to traverse folders recursively by the natural name order?

description: Use os.walk or any other alternative to traverse folders recursively by the natural name order


code:
common/models.py
class CommonPostModel(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()

    class Meta:
        abstract = True

rawDescription: Reusing django models

description: Reusing django models


code: CumulativeMonth = (year - 1645) * 12 + month

rawDescription: Manipulating a non-evenly spaced data series in python


code:
import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

rawDescription: python: Change the scripts working directory to the script's own directory

description: Python: Change the scripts working directory to the script's own directory


code:
Data[day1] = {}
Data[day1][e1] = 4

rawDescription: Assign Nested Keys and Values in Dictionaries


code:
amount = 129
times = 100

import re

def addevery(amount):
  global lines
  lresult = []
  for line in lines:
    result = ''

    for item in re.findall(r'.{5}', line):
      result += "%5s" % (int(item.strip()) + amount)

    lresult.append(result)

  lines = list(lresult)
  return lresult

with open('Input.txt', 'r') as fin:
  with open('Output.txt', 'w') as fout:
    lines = fin.read().split('\n')
    for i in range(0,times):
      if i == 0:
        fout.write('\n'.join(['CONECT'+i for i in lines]) + '\n')
      else:
        fout.write('\n'.join(['CONECT'+i for i in addevery(amount)]) + '\n')

rawDescription: Increasing numbers in strings by python or Tcl


code:
GridSize = [3,4]
allG = [np.linspace(-0.5,0.5, G) for G in GridSize]
out[0]
out[1]

rawDescription: numpy linspace and mesh grid for multiple dimensions

description: Numpy linspace and mesh grid for multiple dimensions


code:
textchars = bytearray([0,7,8,9,10,12,13,27]) + bytearray(range(0x20, 0x100))
b'abcdefasdas'.translate(None,textchars)

rawDescription: migrate str.translate from Python 2 to Python 3

description: Migrate str.translate from Python 2 to Python 3


rawDescription: Better algorithm to riffle shuffle (or interleave) multiple lists of varying lengths


code:
for h3 in soup.find_all('h3'):
    ul = h3.find_next_sibling('ul')
    lis = ul.findChildren('li')
    for i in range(3):
        print [h3.text,
               lis[0].text,
               lis[i].text]

rawDescription: How do you use Beautiful Soup to pull out list items that have certain class attributes?

description: Use Beautiful Soup to pull out list items that have certain class attributes


code: return bisection(a, b, fun, tol)

rawDescription: Function not returning value (Python 2.7)


code:
import sys

codes = {}

with open(sys.argv[2], 'r') as f2:
    for line in f2:
        fields = line.split()
        codes[fields[0]] = fields[1]

with open(sys.argv[1], 'r') as  f1:
    for line in f1:
        fields = line.split(None, 1)
        if fields[0] in codes:
            print('{0:4s}{1:s}'.format(codes[fields[0]], line[4:]), end='')
        else:
            print(line, end='')

rawDescription: Python: compare column in two files

description: Python: compare column in two files


code:
sizes = [(path, os.stat(path).st_size) for path in paths]
sizes

rawDescription: How to check size of the files in a directory with python?

description: Check size of the files in a directory with python


code:
from tkinter import *
from random import randint

root = Tk()
root.geometry('600x470')
root.title('Catch The Button - Game')

clicks = 0
time = 20

def change():
    global clicks
    clicks += 1
    clicksLabel['text'] = 'Clicks: ' + str(clicks)
    rand = randint(1,5)

    if rand == 1:
        button.pack(side = LEFT, padx = randint(1, 220), pady = randint(1, 220))
    elif rand == 2:
        button.pack(side = RIGHT, padx = randint(1, 220), pady = randint(1, 220))
    elif rand == 3:
        button.pack(side = TOP, padx = randint(1, 220), pady = randint(1, 220))
    else:
        button.pack(side = BOTTOM, padx = randint(1, 220), pady = randint(1, 220))

def update_time():
    global time
    time = time-0.1
    timeLabel.config(text=str(time))
    if time<0.01: # Account for rounding errors
        timeLabel.config(text='0')
        button.pack_forget()
        Label(root, text='You scored {}'.format(clicks), font=('Helvetica', 20, 'bold')).pack()
    else:
        timeLabel.after(100, update_time)

clicksLabel = Label(root, text = 'Clicks: 0')
clicksLabel.pack(side=LEFT, anchor=N)

timeLabel = Label(root, text=str(time))
timeLabel.pack(side=RIGHT, anchor=N)
timeLabel.after(100, update_time)

button = Button(root, text = 'Catch me  :P', command = change)
button.pack(side = BOTTOM, padx = randint(1, 220), pady = randint(1, 220))

root.mainloop()

rawDescription: Python tkinter - timer

description: Python tkinter - timer


code:
def addseventosix(n):
    if n != 6:
        return
    else:
        return n + 7

rawDescription: What does return do? Nothing is ever returned


rawDescription: python: using nested lists as arguments

description: Python: using nested lists as arguments


code:
class Bar: pass
class Foo(Bar): #Foo is subclass of Bar now
    pass

rawDescription: What parameters would go in the brackets just after the name of a class?


code:
def f():
  return 'python!'
def g():
  return 'python!'
f() is g()

rawDescription: Why and where python interned strings when executing `a = 'python'` while the source code does not show that?


code:
import pandas as pd

def read_data(data, states, columns):
    id = data[0]
    factor = data[1]
    reshaped_data = []
    for i in xrange(len(states)):
        j += 2+2*i
        if not data[j] == data[j+1]:
            reshaped_data.append([data[j], id, factor*states[i]])
            reshaped_data.append([data[j+1], id, -1*factor*states[i]])
    return pd.DataFrame(reshaped_data, columns=columns)

rawDescription: Inexpensive way to add time series intensity in python pandas dataframe


code:
import pandas as pd
from bokeh.charts import Bar, show

all_data={
'nr':  [1,2,3,4,5,
        1,2,3,4,5,
        1,2,3,4,5,
        1,2,3,4,5,
        1,2,3,4,5],
'rank':['First','First','First','First','First',
       'Second','Second','Second','Second','Second',
       'Third','Third','Third','Third','Third',
       'Fourth','Fourth','Fourth','Fourth','Fourth',
       'Fifth','Fifth','Fifth','Fifth','Fifth'],
'data':[27,10,32,8,9,
        22,27,10,6,5,
        33,18,11,14,6,
        20,31,8,16,6,
        9,14,10,15,2]
      }
df=pd.DataFrame(all_data)

p=Bar(df,label='nr',values='data',stack='rank',legend='top_right')
show(p)

rawDescription: Moving a stacked bar that that worked in Bokeh 0.9 to Bokeh 0.11


code: py2output = subprocess.check_output(["python", "py2.py", my_args[0]])

rawDescription: Using Python 3 with Python 2

description: Using Python 3 with Python 2


rawDescription: Python Regex - checking for a capital letter with a lowercase after


code:
df = pd.pivot_table(df.reset_index(),values='value',
                    rows=['time'],cols=['col1', 'col2'])

df.plot(colormap='jet')

rawDescription: Pandas colormap with groupby

description: Pandas colormap with groupby


code:
series_dict ={}
for i in range(3):
    series_dict[i] = df[None]

rawDescription: Rename Pandas column inside Python dictionary


code:
def fixture_a():
    return varA

def fixture_b():
    return varB

def fixture_c():
    return varC

def fixture_mod_A():
    return modified_varA

rawDescription: unittest Vs pytest

description: Unittest Vs pytest


code:
from __future__ import print_function
from dis import dis

def f1(s):
    a = "help"
    print('f1', id(s), id(a))
    return s > a

def f2(s):
    a = "help"
    print('f2', id(s), id(a))
    return s > a

a = "help"
print(id(a))
print(f1("he" + "lp"))
b = "h"
print(f2(b + "elp"))

print("\nf1")
dis(f1)

rawDescription: Does python create an object for string constants in equality comparisons?


code: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

rawDescription: Python 2: insert existing list inside of new explicit list definition


code:
from ctypes import *
from ctypes.wintypes import UINT
from ctypes.wintypes import DWORD

timeproc = WINFUNCTYPE(None, c_uint, c_uint, DWORD, DWORD, DWORD)
timeSetEvent = windll.winmm.timeSetEvent
timeKillEvent = windll.winmm.timeKillEvent

class mmtimer:
    def Tick(self):
        self.tickFunc()

        if not self.periodic:
            self.stop()

    def CallBack(self, uID, uMsg, dwUser, dw1, dw2):
        if self.running:
            self.Tick()

    def __init__(self, interval, tickFunc, stopFunc=None, resolution=0, periodic=True):
        self.interval = UINT(interval)
        self.resolution = UINT(resolution)
        self.tickFunc = tickFunc
        self.stopFunc = stopFunc
        self.periodic = periodic
        self.id = None
        self.running = False
        self.calbckfn = timeproc(self.CallBack)

    def start(self, instant=False):
        if not self.running:
            self.running = True
            if instant:
                self.Tick()

            self.id = timeSetEvent(self.interval, self.resolution,
                                   self.calbckfn, c_ulong(0),
                                   c_uint(self.periodic))

    def stop(self):
        if self.running:
            timeKillEvent(self.id)
            self.running = False

            if self.stopFunc:
                self.stopFunc()

rawDescription: How to implement high speed, consistent sampling?

description: Implement high speed, consistent sampling


rawDescription: python split string based on regular expression

description: Python split string based on regular expression


code:
source.append(5)
source
tpl

rawDescription: Does tuple() copy the elements of the argument?


rawDescription: scrapy with newline characters and nested tags

description: Scrapy with newline characters and nested tags


code:
bydate = []
planNames = set()
for d in data:
    ddict = {'date': d['date']}
    plans = d
    del plans['date']
    planNames = planNames.union(plans.keys())
    ddict['plans']=plans
    bydate.append(ddict)

rawDescription: generate html table with potentially expanding columns and need to reordering columns, using django

description: Generate html table with potentially expanding columns and need to reordering columns, using django


code:
from collections import Counter
...
[item for item, count in Counter(l).items() if count == 1]

rawDescription: python get non repeating items - fastest method

description: Python get non repeating items - fastest method


code:
from multiprocessing.managers import BaseManager
class ClientManager(BaseManager): pass
ClientManager.register('get_client')
manager = ClientManager(address=('localhost', 50000), authkey='abracadabra')
manager.connect()
client = manager.get_client()

@app.task
def function():
    message = "Message to send to the server using the established connection"
    client.send_message(message)

rawDescription: Accessing python class variable defined inside the main module of a script


rawDescription: find maximum length of consecutive repeated numbers in a list (python)

description: Find maximum length of consecutive repeated numbers in a list (python)


code:
Matrix = []
with open('dataset3.txt') as f:
    for line in f:
        data = line.split()
        target = float(data[0]) # target value
        row = []

        for i, (idx, value) in enumerate([item.split(':') for item in data[1:]]):
            n = int(idx) - (i + 1) # num missing
            for _ in range(n):
                row.append(0) # for missing
            row.append(float(value))
        Matrix.append(row)

rawDescription: How to load dataset in libsvm python

description: Load dataset in libsvm python


rawDescription: Merge 2 columns in pandas into one columns that have data in python


code:
for message in listOfMessages:
    time.sleep(message.time)
    change(message)

rawDescription: time.sleep() Equivalent on Tkinter

description: Time.sleep() Equivalent on Tkinter


rawDescription: How to replicate a Python 2.7, Bottle, MongoDB OpenShift application locally in Linux Mint 17?

description: Replicate a Python 2.7, Bottle, MongoDB OpenShift application locally in Linux Mint 17


code: map(sum, zip(*l))

rawDescription: sum each value in a list of tuples

description: Sum each value in a list of tuples


code:
def remspace(my_str):
    if len(my_str) < 2: # returns ' ' unchanged
        return my_str
    if my_str[-1] == '\n':
        if my_str[-2] == ' ':
            return my_str[:-2] + '\n'
    if my_str[-1] == ' ':
        return my_str[:-1]
    return my_str

rawDescription: Remove Space at end of String but keep new line symbol


code:
def main():
    # Get a random number.
    number = random.randint(1, 101)
    guess(number)

rawDescription: Using random library to guess number (Python)


code: ts = ts.unstack(level=0)

rawDescription: Making missing time slots and filling in 0 values in a Pandas series?


code:
for l in big_list:
    l.sort(key=lambda x: s[x[1]])

rawDescription: Sorting a list of list of tuples based on the sum of first field in the tuple in Python


code:
def fileSelection(self):
    selection = listbox.curselection
    print(selection)

rawDescription: Returning the index of an item clicked in a tkinter Listbox


code:
try:
    N = float(N)
except ValueError:
    pass
except TypeError:
    pass

rawDescription: How can I verify if a string is a valid float?

description: Verify if a string is a valid float


code:
if __name__ == "__main__":
    all_results = parallel_predict(subjects,conditions)

rawDescription: Multiprocessing processes in uninterruptible sleep (D) state when run from iPython Notebook


code:
from werkzeug import FileStorage

f = open('example.jpg','r')
fs = FileStorage(f)

payload['media'] = fs

rawDescription: Use put_internal to upload file using python eve


rawDescription: subprocess popen stdout

description: Subprocess popen stdout


code: sorted(['Bear', 'bear', 'Apple', 'apple'], key=lambda x: (x.lower(), x.swapcase()))

rawDescription: How to sort a list in python to make lowercase precede uppercase?

description: Sort a list in python to make lowercase precede uppercase


code:
##
# Histograms and Percentiles
##

# Get the histograms
num_bins = 10
hist, edges = np.histogram(bars.Value, bins=num_bins)

hist
array([20,  7,  0,  2,  0,  0,  0,  0,  0,  1])

# Edges defining the histogram bins
edges
array([  1. ,   3.8,   6.6,   9.4,  12.2,  15. ,  17.8,  20.6,  23.4,
    26.2,  29. ])

# Calculate the percentiles
p_90 = np.percentile(bars_filtered.Value, q=90)
p_95 = np.percentile(bars_filtered.Value, q=95)

p_90
6.0

p_95
6.0

rawDescription: Histogram from Pandas data and specify groupby time


code:
def randomname():
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(30))

db = sqlite3.connect(':memory:')
db.execute('CREATE TABLE mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR)')
db.executemany('INSERT INTO mytable (name) VALUES (?)',
               [[randomname()] for _ in range(10000)])

filename = 'db.csv'

for f in manual, row, rows, rowsall:
    t = timeit.timeit(f, number=1)
    print('{:<10} {}'.format(f.__name__, t))

rawDescription: Fastest way to write database table to file in python


code:
q = {'a':1}
lst = []
lst.append(q)
q['a']=2
lst
lst.append(q)
lst

rawDescription: issue in list of dict

description: Issue in list of dict


code:
tbhdu = pyfits.new_table(cols)
hdu = pyfits.PrimaryHDU(data=M)
thdulist = pyfits.HDUList([hdu,tbhdu])
thdulist.writeto(outfilename)
thdulist.close()

rawDescription: How is it possible in python to convert an ascii table to a fits table?


rawDescription: Python Counter alternative for Java

description: Python Counter alternative for Java


rawDescription: python regular expression replace two situations with one command

description: Python regular expression replace two situations with one command


code: video = assessment_obj.video_id

rawDescription: How to access data via dot-notation

description: Access data via dot-notation


rawDescription: How to convert seconds to hh:mm:ss with the Django's date template tag?

description: Convert seconds to hh:mm:ss with the Django's date template tag


code:
from collections import defaultdict
import csv

per_label = defaultdict(list)

with open(inputfilename, 'rb') as inputfile:
    reader = csv.reader(inputfile)
    next(reader, None)  # skip the header row

    for timestamp, value, label in reader:
        per_label[label.strip()].append([timestamp.strip(), float(value)])

rawDescription: Python - reading a csv and grouping data by a column


code:
import numpy as np

def zero_runs(a):
    # Create an array that is 1 where a is 0, and pad each end with an extra 0.
    iszero = np.concatenate(([0], np.equal(a, 0).view(np.int8), [0]))
    absdiff = np.abs(np.diff(iszero))
    # Runs start and end where absdiff is 1.
    ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
    return ranges

rawDescription: Finding the consecutive zeros in a numpy array


rawDescription: Rapid Class Declaration

description: Rapid Class Declaration


code:
import pandas as pd
df = pd.read_table('data', sep='\s+')

common = ['weather', 'location', 'time', 'date', 'Condition']
grouped = df.groupby(common)
df['idx'] = grouped.cumcount()
df2 = df.set_index(common+['idx'])
df2 = df2.unstack('idx')
df2 = df2.swaplevel(0, 1, axis=1)
df2 = df2.sortlevel(axis=1)
df2.columns = df2.columns.droplevel(0)
df2 = df2.reset_index()
print(df2)

rawDescription: How can I use python pandas to parse CSV into the format I want?

description: Use python pandas to parse CSV into the format I want


code:
with open(outFileName, 'w') as f:
     for city, values in d.items():
        f.write('{} {}\n'.format(city, ' '.join(values)))

rawDescription: Sort os.listdir files Python

description: Sort os.listdir files Python


code:
REGEX = re.compile(r'/b\((\d+)\)/')  # change to match your needs

def path_grouper(path):
    match = REGEX.search(path)
    if match is None:
        return (False, path)
    return (True, int(match.group(1)))

rawDescription: How to cluster similar file paths?

description: Cluster similar file paths


code:
class Test:

    def __init__(self, a, b, c, d, e, f, g, h, i):
        self._vars = [a, b, c, d, e, f, g, h, i]

    def fancy_stuff(self):
        a, b, c, d, e, f, g, h, i = self._vars
        a += d * h - g
        b -= e * f - c
        g = a + b - i
        self._vars[:] = a, b, c, d, e, f, g, h, i

rawDescription: Python importing class attributes into method local namespace


code:
u = []
v = []
w = []

with open(filename, "r") as f:
    for linenum, line in enumerate(f):
        x = int(line.split()[3])
        if x > 2000:
            u.append(x)
        if x > 1000:
            v.append(x)
        if x > 500:
            w.append(x)

rawDescription: python file manipulations (bash script porting)

description: Python file manipulations (bash script porting)


code: PYthon_Script.SetVariable("path", "C:\Program Files (x86)\IronPython 2.7\Lib")

rawDescription: Importing Python Librarys over C#?

description: Importing Python Librarys over C#


code:
import matplotlib.pyplot as plt

def onclick(event):
    print(event.xdata, event.ydata)

fig,ax = plt.subplots()
ax.plot(range(10))
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

rawDescription: Python : Mouse click coordinates as simply as possible


code:
for i in range(len(points)):
   x = points[i][0]
   y = points[i][1]

rawDescription: How do I create matrix in numpy to be called like this?

description: Create matrix in numpy to be called like this


rawDescription: What endianness does Python use to write into files?


code:
from django.core.urlresolvers import reverse_lazy

LOGIN_URL = reverse_lazy('login')

rawDescription: login_required doesn't work when redirecting

description: Login_required doesn't work when redirecting


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

data = np.arange(100).reshape(10, 10).astype(float)

cmap = plt.cm.gray
cmap.set_bad((1, 0, 0, 1))

# Set the diagonal to NaN
data[range(10), range(10)] = np.nan

plt.imshow(data, cmap=cmap, interpolation='nearest')
plt.show()

rawDescription: Changing colours of pixels of plt.imshow() image


code: '_' if char != guess else char

rawDescription: Replace a certain index of a string in python 3.0


code:
import threading

class MyCounter(object):

    def __init__(self):
        self.val = 0
        self.lock = threading.Lock()

    def inc(self):
        with self.lock:
            self.val += 1
        return self.val

sms_counter = MyCounter()

rawDescription: What is the scope of a variable in logging?


rawDescription: Operations on 'N' dimensional numpy arrays


code:
def is_outlier(points, thresh=3.5):
    """
    Returns a boolean array with True if points are outliers and False
    otherwise.

    Parameters:
    -----------
        points : An numobservations by numdimensions array of observations
        thresh : The modified z-score to use as a threshold. Observations with
            a modified z-score (based on the median absolute deviation) greater
            than this value will be classified as outliers.

    Returns:
    --------
        mask : A numobservations-length boolean array.

    References:
    ----------
        Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and
        Handle Outliers", The ASQC Basic References in Quality Control:
        Statistical Techniques, Edward F. Mykytka, Ph.D., Editor.
    """
    if len(points.shape) == 1:
        points = points[:,None]
    median = np.median(points, axis=0)
    diff = np.sum((points - median)**2, axis=-1)
    diff = np.sqrt(diff)
    med_abs_deviation = np.median(diff)

    modified_z_score = 0.6745 * diff / med_abs_deviation

    return modified_z_score > thresh

rawDescription: matplotlib: disregard outliers when plotting

description: Matplotlib: disregard outliers when plotting


code:
with open("text.txt") as f:
    out = []
    for line in f:
        temp = ""
        for ch in line:
            if ch.isalnum():
                temp += ch
            else:
                temp += " {} ".format(ch)
        out.extend(temp.split())

rawDescription: Splitting strings at multiple delimiters in python


rawDescription: How do I lock window resizing in a Python matplotlib window?

description: Lock window resizing in a Python matplotlib window


code: re.sub(r'@.*?(?=\s)', '', 'text before `at`@text-right-arter`at` text after first space')

rawDescription: Python regular syntax remove @ string until space


code:
def validate_file_size(value):
    if value.size > 1048576:  # Larger than 1MB
        raise ValidationError(u'%s file is too big' % value.name)

rawDescription: IntegerField automatically set to size of FileField


code:
import time
for x in range(10):
    match.create_match()
    time.sleep(60)

rawDescription: python: is there anyway to initialize a variable only one time?

description: Python: is there anyway to initialize a variable only one time


code:
import re
text_ = re.sub("[0-9]+", " ", text);

rawDescription: Remove unwanted characters and convert to int in Python


code:
import requests

URL = "http://192.168.94.1/SubSystem/Portal/Index1/Login/Login2.aspx"

# Set up session object so we can store cookies across requests
session = requests.session()
# GET the page to get any initial cookies required for the POST
r = session.get(URL)
# POST to the login form (making sure to add "Command")
r = session.post(URL, data={'Command': 'LOGIN', 'username': 'x', 'password': 'y'})

rawDescription: Why I can't fill this form using Python "requests" library?


code:
ast.parse('5+a')
ast.parse('5+a').body
ast.parse('5+a').body[0]
ast.parse('5+a').body[0]._fields
ast.parse('5+a').body[0].value
ast.parse('5+a').body[0].value._fields
ast.parse('5+a').body[0].value.left

rawDescription: Python AST: How to get the children of a node


code:
cmyk = lut[tuple(rgb)]
cmyk = np.rollaxis(cmyk, -1).copy()

rawDescription: Fancier Fancy Indexing in NumPy?

description: Fancier Fancy Indexing in NumPy


code:
top, left = moveLeft()
bottom, right = addThirty(moveLeft())
can.coords(oval1, top, left, bottom, right)

rawDescription: Passing function returns as method parameters in Python


code: target - coverage

rawDescription: How to check if a number is present in a group of ranges?

description: Check if a number is present in a group of ranges


code:
class Form(BaseForm):
    "A collection of Fields, plus their associated data."
    # This is a separate class from BaseForm in order to abstract the way
    # self.fields is specified. This class (Form) is the one that does the
    # fancy metaclass stuff purely for the semantic sugar -- it allows one
    # to define a form using declarative syntax.
    # BaseForm itself has no way of designating self.fields.
    __metaclass__ = DeclarativeFieldsMetaclass

rawDescription: How to dynamically create a ModelForm based on James Bennett's article "So you want a dynamic form"?

description: Dynamically create a ModelForm based on James Bennett's article "So you want a dynamic form"


code:
from pprint import pprint
pprint(list(pairwise(pleio)))

rawDescription: Pair combinations of elements in dictionary without repetition


code:
import wx

class mainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(650, 1000))

        panel = wx.Panel(self)

        vbox = wx.BoxSizer(wx.VERTICAL)

        topLabel = wx.StaticText(panel, size = (-1, -1), label="Itinerary")

        vbox.Add(topLabel, 0, wx.ALL, 5)

        self.listBox = wx.ListCtrl(panel, style = wx.LC_LIST)
        self.listBox.InsertColumn(0, "Test Column")
        self.listBox.Append(["This is an item"])
        self.listBox.Append(["This is another item"])

        vbox.Add(self.listBox, 1, wx.EXPAND | wx.ALL, 20)

        panel.SetSizer(vbox)

        self.Show(True)

app = wx.App(False)
frame = mainWindow(None, "Itinerary Manager")

app.MainLoop()

rawDescription: wxPython control spacing

description: WxPython control spacing


code:
with Action(1) as a1, Action(2) as a2:
    pass

rawDescription: Maintaining a roll-backable flow of code in python without extreme identation


code:
def confusion_matrix(results, tagset):
    output = np.zeros((len(tagset), len(tagset)), dtype=float)
    for guessed, real in results:
        output[tagset.index(guessed), tagset.index(real)] += 1
    num_guessed = output.sum(axis=1)[:, None]
    num_guessed[num_guessed == 0] = 1
    return output / num_guessed

rawDescription: White lines in confusion matrix?

description: White lines in confusion matrix


code:
def words(f):
    for line in f:
        yield from line.split()

rawDescription: Anyway to input next string from a file in python


code: my_dict = {row[0]: row for row in my_list}

rawDescription: Retrieving an item from a 2D list

description: Retrieving an item from a 2D list


code:
def divisible_by_five_B():
    for n in range(100):
        return n, (n and not n % 5)

divisible_by_five_B()
# O: 0, 0

rawDescription: Depth first search: return values

description: Depth first search: return values


code: [[int(c) for c in line.strip()] for line in f]

rawDescription: Converting file data to nested list

description: Converting file data to nested list


code:
class Test(object):
    def __init__(self, somevalue):
        self.somevalue = somevalue

@memoize
def get_test_from_value(somevalue):
    return Test(somevalue)

rawDescription: How can I memoize a class instantiation in Python?

description: Memoize a class instantiation in Python


code: map(type, a.atoms(sy.Function))

rawDescription: Check if sympy expression contains function


code:
rolled_mask = np.roll(np.roll(mask, -2, axis=0), -2, axis=1)
ones[rolled_mask] = 255
ones

rawDescription: Applying circular mask with periodic boundary conditions in python


code:
from string import ascii_lowercase
from itertools import product

def letterrange(last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            yield result
            if result == last:
                return

rawDescription: What is the python equivalent to perl "a".."azc"


code:
july_first = find_by_date(email_list, '2014-07-01')
next(july_first)
next(july_first)

rawDescription: How to efficiently select entries by date in python?

description: Efficiently select entries by date in python


code:
from objectifiedetree import *

tree = ET.parse('/path/to/file.xml')
# dot notation :-)
el = tree.xpath.to.your.element

# use normal etree attributes
print(el.attrib)

# access name crashes
attrib_el = el.find('./attrib')

rawDescription: Inherit or mock pythons etree.ElementTree.Element possible?


code: c = sorted(a + b)

rawDescription: Union of two lists in Python

description: Union of two lists in Python


code:
#ax.w_xaxis.set_ticklabels(column_names)
#ax.w_yaxis.set_ticklabels(row_names)

ticksx = np.arange(0.5, 5, 1)
plt.xticks(ticksx, column_names)

ticksy = np.arange(0.6, 7, 1)
plt.yticks(ticksy, row_names)

rawDescription: Python matplotlib -> 3D bar plot -> adjusting tick label position, transparent bars


code: output[:] = input[-len(output):]  # last 3 items

rawDescription: Python: Output list = x largest numbers of input list


code: filter(lambda d: d['acronym'] == 'lol', loaded_data)

rawDescription: Get Dictionary value Python

description: Get Dictionary value Python


code: params = CASPER +' '+ saStr + ' ' + SCRIPT

rawDescription: I dont know how to add Proxy to my Phantomjs script


code:
cnxn = {}
xyz = ["x","y","z"]

for combo in xyzdict.keys():
    #print "the combo is %s" % (combo) #xyzdict[two] #actual value
    first_letter = combo[0]

    not_second = [combo[0],combo[1]]
    not_second_letter = list(set(xyz) - set(not_second))

    if len(not_second_letter) > 1:
        multi_cnxn = []
        for each_not_second_letter in not_second_letter:

            fwd = ''.join((first_letter,each_not_second_letter))
            rev = ''.join((each_not_second_letter,first_letter))
            cnxnval = xyzdict[fwd] * xyzdict[rev]

            multi_cnxn.append(cnxnval)

        rowvalue = xyzdict[combo] + sum(multi_cnxn)
        cnxn[combo] =rowvalue
    else:
        fwd = ''.join((first_letter,not_second_letter[0]))
        rev = ''.join((not_second_letter[0],first_letter))
        cnxnval = xyzdict[fwd] * xyzdict[rev]

        rowvalue = xyzdict[combo] + cnxnval
        cnxn[combo] = rowvalue

rawDescription: Conditionally and interatively calculate column based on value of three columns


rawDescription: How to scrape the video src url from video tag which is injected via javascript?

description: Scrape the video src url from video tag which is injected via javascript


code:
geoip = pygeoip.GeoIP("GeoIPCountry.dat", pygeoip.STANDARD)
result = geoip.record_by_addr(ip)

rawDescription: Check users country

description: Check users country


code: data2 = np.ones((4, 5))

rawDescription: Python: mask a numpy.ndarray with another numpy.ndarray with elegant solution


code:
list1 = ['physics', 'chemistry', "dog", "cat","dog"]

string = input()
res = [i for i, el in enumerate(list1) if el == string]

print(res)

rawDescription: Python-check what position it is in a list


code:
df.columns = pd.MultiIndex(levels = [level_0.values,
                                     df.columns.levels[1]],
                           labels = [level_0.index,
                                     df.columns.labels[1]])

rawDescription: How can I read in a csv file as a MultiIndexed DataFrame when the spanning column header isn't repeated?

description: Read in a csv file as a MultiIndexed DataFrame when the spanning column header isn't repeated


code: [[0 for r in range(10)] for c in range(10)]

rawDescription: How to create a very large 2 dimensional matrix in python?

description: Create a very large 2 dimensional matrix in python


code:
def pad_lines_vertically(lines, size):
    ''' List of lines of exactly `size` length.
    Extended with empty lines if needed.
    '''
    orig_lines = list(lines)
    assert size >= len(orig_lines)
    return orig_lines + [''] * (size - len(orig_lines))

def pad_lines_horizontally(lines):
    ''' Pad lines to the lenght of the longest line.
    '''
    line_length = max(len(line) for line in lines)
    return [
        line.ljust(line_length)
        for line in lines
    ]

def text_add(text1, text2, padding=' '):
    lines1 = text1.splitlines()
    lines2 = text2.splitlines()
    line_count = max(len(lines1), len(lines2))

    def pad_lines(lines):
        return pad_lines_horizontally(
            pad_lines_vertically(lines, line_count)
        )

    return '\n'.join(
        ''.join(line1 + padding + line2)
        for line1, line2 in zip(pad_lines(lines1), pad_lines(lines2))
    )

rawDescription: Python PrettyTable printing table on same line


code:
import numpy as np

a = np.array(['john', 'bill', 'greg', 'bill', 'bill', 'greg', 'bill'])
b = np.array(['john', 'bill', 'greg'])

my_dict = dict(zip(b, range(len(b))))

result = np.vectorize(my_dict.get)(a)

rawDescription: Numpy Indexing of 2 Arrays

description: Numpy Indexing of 2 Arrays


code:
import socket, socketserver, select, datetime, time, threading
import sys, struct

from OpenSSL.SSL import SSLv23_METHOD, SSLv3_METHOD, TLSv1_METHOD, OP_NO_SSLv2
from OpenSSL.SSL import VERIFY_NONE, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, Context, Connection
from OpenSSL.SSL import FILETYPE_PEM
from OpenSSL.SSL import WantWriteError, WantReadError, WantX509LookupError, ZeroReturnError, SysCallError
from OpenSSL.crypto import load_certificate
from OpenSSL import SSL

# see note at beginning of answer
import _sni, _cams_db

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    def __init__(self, server_address, HandlerClass, config):
        socketserver.BaseServer.__init__(self, server_address, HandlerClass)
        self.address_family  = socket.AF_INET6
        self.connected       = []
        self.logger          = config['logger']
        self.config          = config

        self.socket = socket.socket(self.address_family, self.socket_type)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sc = Context(TLSv1_METHOD)
        sc.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT, _sni.verify_cb)
        sc.set_tlsext_servername_callback(_sni.pick_certificate)
        self.sc = sc

        self.server_bind()
        self.server_activate()

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        config         = self.server.config
        logger         = self.server.logger
        connected      = self.server.connected
        sc             = self.server.sc

        try:
           self.peer_hostname = socket.gethostbyaddr(socket.gethostbyname(self.request.getpeername()[0]))[0]
        except:
           self.peer_hostname = '!'+self.request.getpeername()[0]

        logger.info('peer: {}'.format(self.peer_hostname))

        ssl_s = Connection(sc, self.request)
        ssl_s.set_accept_state()

        try:
            ssl_s.do_handshake()
        except:
            t,v,tb = sys.exc_info()
            logger.warn('handshake failed {}'.format(v))

        ssl_s.setblocking(True)
        self.ssl_s = ssl_s

        try:
            peercert = ssl_s.get_peer_certificate()
        except:
            peercert = False
            t,v,tb = sys.exc_info()
            logger.warn('SSL get peer cert failed: {}'.format(v))

        if not peercert:
            logger.warn('No peer certificate')

        else:
            acl = config['configp']['main'].get('client cn acl', '').split(' ')
            cert_subject = peercert.get_subject().CN
            logger.info('Looking for {} in acl: {}'.format(cert_subject,acl))

            if cert_subject in acl:
                logger.info('{} is permitted'.format(cert_subject))
            else:
                logger.warn('''client CN not approved''')

        # it's ok to block here, every socket has its own thread
        ssl_s.setblocking(True)

        self.db  = config['db']
        msgcount = 0

        p = select.poll()
        # don't want writable, just readable

        p.register(self.request, select.POLLIN|select.POLLPRI|select.POLLERR|select.POLLHUP|select.POLLNVAL)
        peername = ssl_s.getpeername()

        x = peername[0]
        if x.startswith('::ffff:'):
            x = x[7:]
        peer_ip = x

        try:
            host = socket.gethostbyaddr(x)[0]
        except:
            host = peer_ip

        logger.info('{}/{}:{} connected'.format(host, peer_ip, peername[1]))
        connected.append( [host, peername[1]] )

        if peercert:
            threading.current_thread().setName('{}/port={}/CN={}'.format(host, peername[1], peercert.get_subject().CN))
        else:
            threading.current_thread().setName('{}/port={}'.format(host, peername[1]))

        sockclosed = False
        while not sockclosed:
            keepreading = True

            #logger.debug('starting 30 second timeout for poll')
            pe = p.poll(30.0)
            if not pe:
                # empty list means poll timeout
                # for SSL sockets it means WTF. we get an EAGAIN like return even if the socket is blocking
                continue

            logger.debug('poll indicates: {}'.format(pe))

            #define SSL_NOTHING     1
            #define SSL_WRITING     2
            #define SSL_READING     3
            #define SSL_X509_LOOKUP 4

            while keepreading and not sockclosed:
                data,sockclosed,keepreading = self._read_ssl_data(2, head=True)
                if sockclosed or not keepreading:
                    time.sleep(5)
                    continue

                plen = struct.unpack('H', data)[0]
                data,sockclosed,keepreading = self._read_ssl_data(plen)

                if sockclosed or not keepreading:
                    time.sleep(5)
                    continue

                # send thank you, ignore any errors since we appear to have gotten
                # the message
                try:
                    self.ssl_s.sendall(b'ty')
                except:
                    pass

                # extract the timestamp

                message_ts = data[0:8]
                msgtype    = chr(data[8])
                message    = data[9:].decode()

                message_ts = struct.unpack('d', message_ts)[0]
                message_ts = datetime.datetime.utcfromtimestamp(message_ts).replace(tzinfo=datetime.timezone.utc)

                self.db.enqueue(config['group'], peer_ip, msgtype, message, message_ts)
                self.db.pending.set()

        # we're recommended to use the return socket object for any future operations rather than the original
        try:
            s = ssl_s.unwrap()
            s.close()
        except:
            pass

        connected.remove( [host, peername[1]] )
        t_name = threading.current_thread().getName()
        logger.debug('disconnect: {}'.format(t_name))

    def _read_ssl_data(self, wantsize=16384, head=False):
        _w = ['WANT_NOTHING','WANT_READ','WANT_WRITE','WANT_X509_LOOKUP']

        logger = self.server.logger

        data        = b''
        sockclosed  = False
        keepreading = True

        while len(data) < wantsize and keepreading and not sockclosed:
            rlen = wantsize - len(data)
            try:
                w,wr = self.ssl_s.want(),self.ssl_s.want_read()

                #logger.debug('  want({}) want_read({})'.format(_w[w],wr))
                x = self.ssl_s.recv(rlen)
                #logger.debug('  recv(): {}'.format(x))

                if not ( x or len(x) ):
                    raise ZeroReturnError

                data += x
                if not (len(x) == len(data) == wantsize):
                    logger.info('  read={}, len(data)={}, plen={}'.format(len(x),len(data),wantsize))

            except WantReadError:
                # poll(), when ready, read more
                keepreading = False
                logger.info('  got WantReadError')
                continue

            except WantWriteError:
                # poll(), when ready, write more
                keepreading = False
                logger.info('  got WantWriteError')
                continue

            except ZeroReturnError:
                # socket got closed, a '0' bytes read also means the same thing
                keepreading = False
                sockclosed  = True
                logger.info('  ZRE, socket closed normally')
                continue

            except SysCallError:
                keepreading = False
                sockclosed  = True

                t,v,tb = sys.exc_info()

                if v.args[0] == -1: # normal EOF
                    logger.info('  EOF found, keepreading=False')

                else:
                    logger.info('{} terminated session abruptly while reading plen'.format(self.peer_hostname))
                    logger.info('t: {}'.format(t))
                    logger.info('v: {}'.format(v))

                continue

            except:
                t,v,tb = sys.exc_info()
                logger.warning('  fucked? {}'.format(v))
                raise

        if not head and not len(data) == wantsize:
            logger.warn('  short read {} of {}'.format(len(data), wantsize))

        return data,sockclosed,keepreading

rawDescription: issues with socket programming - python

description: Issues with socket programming - python


code:
def show_files(request):
    objects = MyModel.objects.all()
    return render_to_response('show_files.html', {'objects': objects},
                              context_instance=RequestContext(request))

rawDescription: django - How to insert the content of uploaded file in template?

description: Django - How to insert the content of uploaded file in template


code:
cg = sns.clustermap(df, metric="correlation")
plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)

rawDescription: Labels for clustermap in seaborn?

description: Labels for clustermap in seaborn


rawDescription: 'leet' program - getting all permutations


code:
class AjaxApp(Flask or Blueprint):

    def ajax_route(self, rule, **options):
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return f(*args, **kwargs)
                return render_template("masterPage.html")

            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, wrapper, **options)
            return wrapper
        return decorator

rawDescription: How to redirect from a CatchAll method without being re-catched in Python/Flask

description: Redirect from a CatchAll method without being re-catched in Python/Flask


code:
# db is an exemplary database connection object, which
#   - supports nested (stacked) transactions,
#   - has autocommit on.

db.begin() # START TRANSACTION
try:
  # no-conflict op
  db.update()

  db.begin() # SAVEPOINT sp1
  try:
    # conflict op,
    # e.g. attempt to change exclusively locked rows by another transaction
    db.update()

    db.commit() # RELEASE SAVEPOINT sp1
  except:
    # Everything interesting happens here:
    #   - the change attempt failed with OperationalError: (1213, 'Deadlock...'),
    #   - the transaction is rolled back with all the savepoints,
    #   - next line will attempt to rollback to savepoint which no longer exists,
    #   - so will raise OperationalError: (1305, 'SAVEPOINT sp1 does not exist'),
    #   - which will shadow the original exception.

    db.rollback() # ROLLBACK TO SAVEPOINT sp1
    raise

  db.commit() # COMMIT
except:
  db.rollback() # ROLLBACK
  raise

rawDescription: Django + MySQL: savepoint does not exist?


code:
class MyList(list):
    def ljust(self, n, fillvalue=''):
        return self + [fillvalue] * (n - len(self))

a = MyList(['1'])
b = a.ljust(5, '')

rawDescription: Some built-in to pad a list in python

description: Some built-in to pad a list in python


code:
with open(filename) as f:
    for line in f:
        for c in line:
            pass

rawDescription: Reading a single character from a file in python?