code:
import urllib.request
sock = urllib.request.urlopen (url)
print (sock.read (200))

rawDescription: The method urllib.urlopen python 2.x does not work in python 3.x


code:
import model

...

model.client_module = MyMockModule()

rawDescription: Replace a client library with a mock from a test?


code: repo.git.tag(l=True) # equals git tag -l

rawDescription: GitPython tags sorted

description: GitPython tags sorted


code:
import numpy as np
a=np.random.randint(0,20,size=24)
b=np.arange(24)
b[(8<a)&(a<15)] #rather than 8<a<15

rawDescription: Subset of an ndarray based on another array


code: yhist *= len(y) / len(x)

rawDescription: Normalize a multiple data histogram

description: Normalize a multiple data histogram


code:
a = [np.array([1, 2, 3]), np.array([1, 2, 3])]
b = [np.array([1, 2, 3]), np.array([1, 2, 3])]
all(np.allclose(x, y) for x, y in zip(a, b))#True
b = [np.array([1, 2, 3]), np.array([1, 2, 4])]
all(np.allclose(x, y) for x, y in zip(a, b))#False

rawDescription: How to compare list of arrays in python?

description: Compare list of arrays in python


code:
from sprucepress.models import Tag, Category
from flask_wtf import Form
from wtforms.fields import StringField, DateTimeField
from wtforms.widgets import TextArea
from wtforms.validators import DataRequired
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.ext.sqlalchemy.fields import QuerySelectField

def enabled_categories():
    return Category.query.all()

class PostForm(Form):
    title = StringField(u'title', validators=[DataRequired()])
    body = StringField(u'Text', widget=TextArea())
    pub_date = DateTimeField(u'date create')
    category = QuerySelectField(query_factory=enabled_categories,
                                allow_blank=True)

rawDescription: A Complete Many-to-One Example Using Flask, WTForm, SQLAlchemy, and Jinja2


code:
thing.avg_ratings = ((thing.avg_ratings * thing.num_ratings) + new_rating) / thing.num_ratings + 1
thing.num_ratings += 1
thing.put()

rawDescription: Google app engine How to count SUM from datestore?


rawDescription: Multiplying tensors containing images in numpy


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1977)

# Generate some interesting-looking random data...
num = 200
grid = np.random.normal(0, 1, (20, num)).cumsum(axis=1).cumsum(axis=0)
x = np.linspace(0, 360, num)
y1 = np.random.normal(0, 1, num).cumsum()
y2 = np.random.normal(0, 1, num).cumsum()

# Plot on three seperate axes
fig, axes = plt.subplots(nrows=3, sharex=True)
axes[0].plot(x, y1)
axes[1].plot(x, y2)
im = axes[2].imshow(grid, extent=[0, 360, 0, 20], aspect='auto')
fig.colorbar(im)

plt.show()

rawDescription: Matplotlib mixed subplots with plot and pcolor(mesh) to have the same x axis length when colorbar is on


code: line, = ('foo',)   # same as line = 'foo' in this example

rawDescription: Mystical comma in a Python expression

description: Mystical comma in a Python expression


code: func(**dct)

rawDescription: How do I store identical arguments to be used by multiple functions

description: Store identical arguments to be used by multiple functions


rawDescription: Celery discover tasks in files with other filenames


code:
import random
primes = [i for i in range(p,q) if isPrime(i)]
n = random.choice(primes)

rawDescription: Random prime Number in python

description: Random prime Number in python


rawDescription: Send url seed to EC2 instances using Python


code:
content = """From: Fromname <fromemail>
    To: {toname} <{toemail}>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: {subject}

    This is an e-mail message to be sent in HTML format

    This is HTML message.

This is headline.

    """
mail.sendmail('from', 'to', content.format(toname="Peter", toemail="p@tr", subject="Hi"))

rawDescription: Is there any way to use variables in multiline string in Python?


rawDescription: How to use a map with *args to unpack a tuple in a python function call

description: Use a map with *args to unpack a tuple in a python function call


code:
from __future__ import print_function
from collections import Counter, OrderedDict
from itertools import chain

check_list = [[[('1',), ('2',)]], [[('2',), ('3',)], [('3',), ('4',)]], [[('1',), ('3',)]]]

a_list = [('1',), ('2',), ('3',), ('4',)]

cn = OrderedDict(sorted(Counter(a_list).items()))

print(" ".join([str(t[0]) for t in cn]))
for chk in check_list:
    _cn = Counter(chain(*chk))
    # cn.keys() python 3
    diff = cn.viewkeys() - _cn
    for k  in cn:
        if k not in diff:
            print(_cn[k], end=" ")
        else:
            print(0, end=" ")
    print()

rawDescription: Python 2.7 creating a matrix from lists

description: Python 2.7 creating a matrix from lists


code:
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

rawDescription: Read from a gzip file in python

description: Read from a gzip file in python


code: from flask import request

rawDescription: How to configure a single flask application to handle multiple domains?

description: Configure a single flask application to handle multiple domains


rawDescription: Python: determine length of sequence of equal items in list


rawDescription: variation of a paramentes for numbers smaler than 1

description: Variation of a paramentes for numbers smaler than 1


code: srcs = [ele.get_attribute("src") for ele in list_of_elements]

rawDescription: Selenium/Python2.7 Find elements with similar src?


code:
import flickrapi
from pprint import pprint

api_key = 'your api key'
secret = 'your secret key'
flickr = flickrapi.FlickrAPI(api_key, secret, format='parsed-json')

group_id = '544735@N20'    # caterpillarequipment's group_id
response = flickr.groups.pools.getPhotos(group_id=group_id, per_page=3)
pprint(response)
{u'photos': {u'page': 1,
             u'pages': 1033,
             u'perpage': 3,
             u'photo': [{u'dateadded': u'1428715622',
                         u'farm': 8,
                         u'id': u'16912446348',
                         u'isfamily': 0,
                         u'isfriend': 0,
                         u'ispublic': 1,
                         u'owner': u'71639059@N00',
                         u'ownername': u'ocrr4204',
                         u'secret': u'311b63f966',
                         u'server': u'7685',
                         u'title': u'Dufresne Construction 146 a CAT D7H bulldozer Ottawa, Ontario Canada 04252007 \xa9Ian A. McCord'},
                        {u'dateadded': u'1428713719',
                         u'farm': 8,
                         u'id': u'16896411327',
                         u'isfamily': 0,
                         u'isfriend': 0,
                         u'ispublic': 1,
                         u'owner': u'62532775@N03',
                         u'ownername': u'Jibup',
                         u'secret': u'76dc9110ed',
                         u'server': u'7695',
                         u'title': u'Caterpillar'},
                        {u'dateadded': u'1428554028',
                         u'farm': 8,
                         u'id': u'17058845816',
                         u'isfamily': 0,
                         u'isfriend': 0,
                         u'ispublic': 1,
                         u'owner': u'73369431@N07',
                         u'ownername': u'Stephen Ball Photography',
                         u'secret': u'607f522144',
                         u'server': u'7705',
                         u'title': u'One Up One Down'}],
             u'total': u'3097'},
 u'stat': u'ok'}

rawDescription: python flickr api for group search and get image data set

description: Python flickr api for group search and get image data set


code: a, b, c = [int(_) for _ in raw_input().split()]

rawDescription: Read more numbers in a line in Python

description: Read more numbers in a line in Python


code:
if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
    from .interpolate import interp1d
    points = points.ravel()
    ...
    ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
                  fill_value=fill_value)
    return ip(xi)

rawDescription: why 1D scipy.interpolate.griddata using method=nearest produces nans?

description: Why 1D scipy.interpolate.griddata using method=nearest produces nans


rawDescription: How to remove the last repeating letters of a word

description: Remove the last repeating letters of a word


rawDescription: how do i equate raw input with a variable value in python

description: Equate raw input with a variable value in python


code: on_validate: mytextinput.focus = True

rawDescription: How to set cursor position in TextInput in Kivy

description: Set cursor position in TextInput in Kivy


code:
import networkx as nx
G1=nx.Graph()
G1.add_edges_from([("a","b"),("b","c"),("c","d"),("d","e"),("f","g")])
sorted(nx.connected_components(G1), key = len, reverse=True)

rawDescription: How to aggregate matching pairs into "connected components" in Python

description: Aggregate matching pairs into "connected components" in Python


code: (a.reshape(-1, 1) + b).ravel()

rawDescription: Add two arrays without using for. Python


code:
def no_update(self, **kwargs):
    # probably want a more specific Exception
    raise Exception('NO UPDATING HERE')

from django.db.models.query import QuerySet
QuerySet.update = no_update

rawDescription: UPDATE doesnt use Model save method

description: UPDATE doesnt use Model save method


rawDescription: Python/Numpy subarray selection

description: Python/Numpy subarray selection


code:
import struct
x = struct.pack("@L",1000)
map(ord, x)

rawDescription: Extracting strings from struct.pack

description: Extracting strings from struct.pack


code:
z1 = x.astype('<u2').tostring()
z2 = struct.pack('<'+'H'*x.size,*np.asarray(x).reshape(-1).astype(int))
assert z1 == z2

rawDescription: struct.pack is much slower in python 2.6 when working with numpy arrays

description: Struct.pack is much slower in python 2.6 when working with numpy arrays


code:
s1.ax_marg_y.cla() # clear axis
sns.kdeplot(data.y, ax=s1.ax_marg_y, # choose the ax
            kernel="biw", # choose your kernel
            legend=0, # remove the legend
            vertical=True) # swap axis

rawDescription: is it possible to use a non gaussian kernel for the two lateral distributions in seaborn jointplot

description: Is it possible to use a non gaussian kernel for the two lateral distributions in seaborn jointplot


code:
suits = ["h","c", "d", "s"]
suits.remove("c")

rawDescription: python: a quick way to return list without a specific element

description: Python: a quick way to return list without a specific element


code:
def apply_appstruct(self, appstruct):
    """ Set the product with appstruct from the submitted form. """

    for kw, arg in appstruct.items():

        if kw == "categories":
            categories = []
            for id in arg:
                categories.append(DBSession.query(Category).filter(Category.id == id).first())
            arg = categories

        setattr(self, kw, arg)

rawDescription: Working with Many to Many Relationships in Deform/Colander HTML Select Field


code: np.take(myarray, i, axis=3)

rawDescription: Indexing ndarray of variable number of dimensions


code:
import cherrypy
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))

class Root:
    @cherrypy.expose
    def index(self):
        tmpl = env.get_template('index.html')
        return tmpl.render(salutation='Hello', target='World')

cherrypy.config.update({'server.socket_host': '127.0.0.1',
                         'server.socket_port': 8080,
                        })

cherrypy.quickstart(Root())

rawDescription: Getting started with Cherrypy and Jinja2


code:
from mpl_toolkits.axes_grid1 import anchored_artists
from matplotlib.patheffects import withStroke
txt = anchored_artists.AnchoredText("SC",
                                    loc=2,
                                    frameon=False,
                                    prop=dict(size=12))
if withStroke:
    txt.txt._text.set_path_effects([withStroke(foreground="w",
                                               linewidth=3)])
ax1.add_artist(txt)

## Draw a line to separate the two different wave lengths, and name each region
l1 = plt.Line2D([-1,10],[5,5],ls='-',color='black',lineswidth=10)
ax1.add_line(l1)

rawDescription: How to add a single colobar that will show the data from 2 different subplot

description: Add a single colobar that will show the data from 2 different subplot


code:
from com import Communicator
from log import setup_logger

logger = setup_logger(__name__)

def bar():
    c = Communicator(logger)
    c.send('bar')

rawDescription: How to structure the Logging in this case (python)

description: Structure the Logging in this case (python)


code: result = re.findall(r'\w+:?(?=/)',data)

rawDescription: Regular expression to extract words before a slash


code: next((d['age'] for d in data if d['name'].lower() == 'john'), -1)

rawDescription: How to search for the value of an element in a list of dict based on another value from the same element?

description: Search for the value of an element in a list of dict based on another value from the same element


code:
import os.path

# import global settings
from settings import *

# this is barely just the name of the client dir, you might want to use that
SITE_NAME = __file__.split('/')[-2]
# this is the directory of the client website
CLIENT_ROOT = os.path.abspath(os.path.dirname(__file__))

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': SITE_NAME,
        'USER': SITE_NAME,
        'PASSWORD': 'some random password',
    }
}

# you might want this too so that each client have his own MEDIA_ROOT
MEDIA_ROOT = os.path.join(CLIENT_ROOT, 'upload')

rawDescription: Django and SaaS. How to use separate database for each Django site?


code: result = [stem_lookup.get(original,original) for original in queries] #uses original itself if it's not a synonym

rawDescription: arrays using python

description: Arrays using python


code:
[int(''.join(map(str, (([x]+list(ys)+[z]+list(ys)[::-1]+[x]) if k%2
                  else ([x]+list(ys)+list(ys)[::-1]+[x])))))
            for x in range(1,10)
            for ys in itertools.permutations(range(10), k/2-1)
            for z in (range(10) if k%2 else (None,))]

rawDescription: Generate list of all palindromic numbers of 3 digits in python


code:
parser.add_argument('--carpark',
                    type=lambda s: map(int, s.split(",")),
                    dest='carpark_ids',
                    default=[],
                    help="One or more carpark IDs"
)

rawDescription: Argparse nargs="+" is eating positional argument


code:
#heatmap
im = plt.imshow(hcpv, origin='lower',extent=[min(poro)-EPS,max(poro)
                                    +EPS,min(sw)-EPS,max(sw)+EPS],aspect='auto')

#contours
levels = np.array([p10,p50,p90])
cset = plt.contour(hcpv,levels,linewidths=2,cmap=pylab.cm.hot,
      origin='lower',extent=[min(poro),max(poro),min(sw),max(sw)],aspect='auto')
plt.clabel(cset,inline=True,fmt='%1.1f',fontsize=20)

rawDescription: Python heatmap from 3d coordinates

description: Python heatmap from 3d coordinates


code: reverselookup = {thedict['value']:thedict for thedict in test_data}

rawDescription: How do I compare multiple key values from a list of dictionaries?

description: Compare multiple key values from a list of dictionaries


code:
from rpy2.rinterface import parse
p = ggplot2.ggplot(mydata) + scale_x_continuous(parse("alpha"))

rawDescription: Plotting greek letters and plain text in ggplot2 graphs via Rpy2


code:
df = DataFrame(randn(200,1),columns=['A'],index=pd.date_range('2000',periods=200,freq='M'))
df['month'] = df.index.month
df['year'] = df.index.year
df = df.reset_index(drop=True).set_index(['year','month'])
df
df.head()

rawDescription: How to change a groupby DF to a monthly datetime series in Python Pandas

description: Change a groupby DF to a monthly datetime series in Python Pandas


code:
def test():
    exec('pass')
    locals()['output'] = True
    print(output)

test()
def test():
    locals()['output'] = True
    print(output)

test()

rawDescription: One-liner to set a variable value with signal handler function in response to a signal from GUI?


rawDescription: How to select only integers in a list of strings/integers?

description: Select only integers in a list of strings/integers


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://jsfiddle.net/user/login/")
driver.find_element_by_id("id_username").send_keys("user")
driver.find_element_by_name("password").send_keys("password")
driver.find_element_by_xpath("//input[@value = 'Log in']").click()

driver.get("https://jsfiddle.net/")

js_panel = driver.find_element_by_id("panel_js")

code_mirror_element = js_panel.find_element_by_css_selector(".CodeMirror")
driver.execute_script("arguments[0].CodeMirror.setValue(arguments[1]);", code_mirror_element, "alert('test');")

driver.find_element_by_id("run").click()

rawDescription: ElementNotVisibleException: Message: Element is not currently visible... selenium (python)


code: ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=200)

rawDescription: Python multi-body animation does not work


code:
import re

content="""\\[-16pt]
x = 10
print ("hi")
\\
thinhline
\\[-16pt]
y = 3
print ("bye")
\\
thinhline
\\[-16pt]
z = 7
print ("zap")
\\
thinhline
This is random text.
"""

pattern = re.compile(r"""(\\\[-16pt]\n)    # Start. Don't technically need to capture.
                         (.*?)             # What we want. Must capture ;)
                         (\n\\\nthinhline) # End. Also don't really need to capture
                      """, re.X | re.DOTALL)

for m in pattern.finditer(content):
    print("Matched:\n----\n%s\n----\n" % m.group(2))

rawDescription: python- re.findall how to separate content into groups

description: Python- re.findall how to separate content into groups


code:
my_dict[seq][0].append(read_seq)
#And now your two strings:
my_dict[seq][1] = 'string1'
my_dict[seq][1] = 'string2'

rawDescription: Add multiple values to python dictionary


rawDescription: How to create identity matrix with numpy

description: Create identity matrix with numpy


rawDescription: Setting axis limits on pandas scatter_matrix from editor vs console


code:
two_zeros = [x for x in lst if x.count(0) == 2]
one_zero = [x for x in lst if x.count(0) == 1]

rawDescription: check two values in list element python

description: Check two values in list element python


rawDescription: Is it possible to speed up interactive IPython Notebook plots by not generating new figures every time?


code:
from collections.abc import MutableSet  # On Py2, collections without .abc

class keyedset(MutableSet):
    def __init__(self, it=(), key=lambda x: x):
        self.key = key
        self.contents = {}
        for x in it:
            self.add(x)

    def __contains__(self, x):
        # Use anonymous object() as default so all arguments handled properly
        sentinel = object()
        getval = self.contents.get(self.key(x), sentinel)
        return getval is not sentinel and getval == x

    def __iter__(self):
        return iter(self.contents.values())  # itervalues or viewvalues on Py2

    def __len__(self):
        return len(self.contents)

    def add(self, x):
        self.contents.setdefault(self.key(x), x)

    def discard(self, x):
        self.contents.pop(self.key(x), None)

rawDescription: Is there a comparison key for set objects?


code:
word="100011010"
count=1
length=""
for i in range(1,len(word)):
    if word[i-1]==word[i]:
       count+=1
    else :
        length += word[i-1]+" repeats "+str(count)+", "
        count=1
length += ("and "+word[i]+" repeats "+str(count))
print (length)

rawDescription: Count consecutive characters

description: Count consecutive characters


code:
for x in reflist:
    for y in x:
        y.extend([] for _ in range(41))

rawDescription: For loops in nested list with variable numbers of indices


code:
from collections import Counter

integer_counts = Counter(int(num) for num in inputlist)
list_sorted = sorted(inputlist, key=lambda n: (integer_counts[int(n)] == 1, n))

rawDescription: How to sort a list firstly writing same elements, and then - by ascending order

description: Sort a list firstly writing same elements, and then - by ascending order


rawDescription: custom location for templates and static resources in flask

description: Custom location for templates and static resources in flask


code:
integer1 = eval(input('Enter the first integer between -10 and 10: '))

integer2 = eval(input('Enter the second integer between -10 and 10: '))

while (integer1 >= 10 or integer1 <= -10):
    integer1 = eval(input('Integer 1 is invalid, Please enter a valid number: '))

while (integer2 > 10 or integer2 < -10):
    integer2 = input('Integer2 is invalid, Please enter a valid number: ')

rawDescription: I can't figure out why this while loop isn't functioning properly


code:
input  = open('inp.txt', 'r')
output = open('out.txt', 'w')
clean  = input.read().replace("ATOM", "1").replace("# ORB", " ")
output.write(clean)

rawDescription: Replacing a word in a text file with a value using python


code:
#!/usr/bin/env python
import random
import sys
from itertools import chain, groupby

def choose_random(iterator, fraction, random=random.random):
    """Lazy analog of:

        L = list(iterator)
        k = int(len(L) * fraction + .5) or 1 # get at least one
        result = random.sample(L, k)

    Note: this function doesn't randomize the order of elements
          that would require to keep selected elements in memory
          and number of output elements is not exactly k
    """
    # always yield at least one item if input is not empty
    item = next(iterator)
    it = (x for x in chain([item], iterator) if random() < fraction)
    for x in chain([next(it, item)], it):
        yield x

def getkey(line):
    return line.split("\t")[1] # 2nd column

for key, group in groupby(sys.stdin, key=getkey):
    sys.stdout.writelines(choose_random(group, fraction=0.25))

rawDescription: text file reduction with randomization in Python

description: Text file reduction with randomization in Python


code:
def keep_none(func):
    def _exec(*args, **kw):
        return None if args[0] is None else func(*args, **kw)

    return _exec

rawDescription: Nice Python Decorators

description: Nice Python Decorators


code:
class PrintMacro(Macro):
  ...
  def handle(self, syntaxtree, vars):
    return Printnl(vars, None)

rawDescription: Pythonic macro syntax

description: Pythonic macro syntax


code: for it in xrange(T): arr[:,:,it] -= np.sum(arr[:,:,:it], axis=2)

rawDescription: python: multiple arithmetic operations for numpy array

description: Python: multiple arithmetic operations for numpy array


code: passphrase

rawDescription: Can I 'wrap' an USB stick with Python?

description: 'wrap' an USB stick with Python


code:
def view1(request, form_class=MyForm, template_name='myapp/page.html'):
    # app code here
    this_url = reverse('view1')
    render_to_response(template_name, locals(), RequestContext(request))

def view2(request, form_class=MyForm, template_name='myapp/page.html'):
    # app code here
    this_url = reverse('view2')
    render_to_response(template_name, locals(), RequestContext(request))

rawDescription: Getting current url

description: Getting current url


code:
import numpy as np
arr = np.array([(1,2,3),(3,4,5)])
arr
arr.shape
arr.dtype=[('a',int),('b',int),('c', int)]
arr  # Notice that tuples inside the elements
arr.shape

rawDescription: why setting dtype on numpy array changes dimensions?

description: Why setting dtype on numpy array changes dimensions


code:
myRectangle = canvas.create_rectangle(x0, y0, x1, y1)
canvas.delete(myRectangle)

rawDescription: How do I selectively delete drawings in Tkinter?

description: Selectively delete drawings in Tkinter


code:
ix = np.unravel_index(a.argsort(axis=None), dims=a.shape)
zip(*ix)[-3:]

rawDescription: Getting the indices of the top k numbers by value in a numpy array?


code:
a = np.rollaxis(a, 0, 3)
a

rawDescription: Numpy: efficient way to generate combinations from given ranges


code:
con = sqlite3.connect(':memory:')
repr(con)

rawDescription: When __repr__() is called?

description: When __repr__() is called


code:
for i in range(len(list1)):
    list4.extend([list1[i], list2[i]])

rawDescription: Adding elements to a list in Python 3.3 by extracting consecutive elements from two other lists


code: a

rawDescription: How to group elements of a numpy array with the same value in separate numpy arrays

description: Group elements of a numpy array with the same value in separate numpy arrays


rawDescription: Algorithm - Grouping List in unique pairs


code:
import telnetlib

port = 9000
host = "127.0.0.1"

tn = telnetlib.Telnet(host, port)
r = tn.read_until("""\nWelcome to EULER!
=================
Answer 100 simple questions to authenticate yourself\n""")

tn.read_until("What is your name?\n")
tn.write("foo\n") # The client sends `\n`, notice the server may expects `\n\r`.
print("Question 1 answered.")

tn.read_until("How old are you?\n")
tn.write("100\n")
print("Question 2 answered.")

tn.read_until("Do you use Python?\n")
tn.write("yep\n")
print("Question 3 answered.")

tn.close()

rawDescription: connect to telnet in python with a quizz as login?

description: Connect to telnet in python with a quizz as login


code:
def unpack_until(data, type_):
    for entry in data:
        if isinstance(entry, type_):
            yield entry
        else:
            yield from unpack_until(entry, type_)

rawDescription: Is there a way of avoiding so many list(chain(*list_of_list))?


code:
def bitlen(x):
    """The bit length of the integer x."""
    try:
        return x.bit_length()
    except AttributeError:  # I guess!
        return len(bit(x)) - 2

rawDescription: Cross-version portability in Python

description: Cross-version portability in Python


code:
x1 = cityXvalue[cityOne]
y1 = cityYvalue[cityOne]
x2 = cityXvalue[cityTwo]
y2 = cityYvalue[cityTwo]
addLine(map, x1, y1, x2, y2)

rawDescription: combining distance between pixels during while loop

description: Combining distance between pixels during while loop


code:
keys = set(yourdict.keys())
output = [elem for col in zip(*yourdict.values()) for elem in (keys, set(col))]

rawDescription: accessing individual elements from a python dictionary

description: Accessing individual elements from a python dictionary


code:
def t_or_f(arg):
    ua = str(arg).upper()
    if ua == 'TRUE'[:len(ua)]:
       return True
    elif ua == 'FALSE'[:len(ua)]:
       return False
    else:
       pass  #error condition maybe?

rawDescription: parsing boolean values with argparse

description: Parsing boolean values with argparse


code:
class AKA(type):
    """ 'Also Known As' metaclass to create aliases for a class. """
    def __new__(cls, classname, bases, attrs):
        print('in AKA.__new__')
        class_ = type(classname, bases, attrs)
        globals().update({alias: class_ for alias in attrs.get('aliases', [])})
        return class_

class C(object):
    __metaclass__ = AKA
    aliases = 'C1', 'C2'

print(C)          # <class '__main__.C'>
print(C.aliases)  # ('C1', 'C2')
print(C1)         # <class '__main__.C'>
print(C2)         # <class '__main__.C'>

rawDescription: Defining a python class "alias" within the class definition


code:
def read_config_file():
    config = ConfigParser.ConfigParser()
    cnf_path = 'config_files/php.sr'
    config.read(cnf_path)
    if config.has_section('basic'):
        if config.has_option('basic', 'basic'):
            php_bsc_mdls = config.get('basic', 'basic').split(',')
    if config.has_section('advance'):
        if config.has_option('advance','advance'):
            php_adv_mdls = config.get('advance', 'advance').split(',')

    if php_bsc_mdls and php_adv_bls:
        return php_bsc_mdls,php_adv_mdls
    elif php_bsc_mdls:
        return php_bsc_mdls, None

rawDescription: How to access the variables declared inside functions in python

description: Access the variables declared inside functions in python


code:
def storescores():
    with open("hst.txt") as hs:
        lines = list(hs)
    lines.append(name + " " + score + "\n")
    lines = lines[-10:]
    with open("hst.txt", "w") as hs:
        for line in lines:
            hs.write(line)

rawDescription: Maximum pieces of data appending to a file


code:
dlist = DoublyLinkedList()
print(dlist)
dlist.add_head(1)
dlist.add_tail(2)
dlist.add_tail(3)
dlist.add_head(0)
print(dlist)  # __repr__ is such a nice thing to have
print(dlist.head)
print(dlist.tail)
print(dlist.head.prev is None, dlist.tail.next is None)
print(dlist.tail.prev.next is dlist.tail)
[node.data for node in dlist]
for node in reversed(dlist):
    print(node.data, node)

rawDescription: How could I make this singly linked list into a doubly linked list?


rawDescription: Python Numpy Loadtxt - Convert unix timestamp


rawDescription: numpy reverse multidimensional array

description: Numpy reverse multidimensional array


code:
import nltk
def word_features(sentence):
    features = {}
    for word in nltk.word_tokenize(sentence):
        features['contains(%s)' % word.lower()] = True
    return features

sent = 'This a foobar word extractor function'
word_features(sent)

rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


rawDescription: Numpy subclass attribute slicing

description: Numpy subclass attribute slicing


code: table.put(key, {'cf:id': struct.pack(">q", value)})

rawDescription: Filtering integers with HBase + Python

description: Filtering integers with HBase + Python


code:
from sphinx.ext import autodoc

class SimpleDocumenter(autodoc.MethodDocumenter):
    objtype = "simple"

    #do not indent the content
    content_indent = ""

    #do not add a header to the docstring
    def add_directive_header(self, sig):
        pass

rawDescription: Including docstring in Sphinx Documentation


code: thread.daemon = True

rawDescription: SimpleHTTPServer launched as a thread: does not daemonize


rawDescription: Maintaining point correlation while flattening 2D meshgrid


code:
uniques_dict = {u: [] for u in uniques}

for record in base:
    key, values = record[1], record[2:]
    for unique in uniques_dict.keys() & values:  # the intersection
        uniques_dict[unique].append(key)

rawDescription: Dictionary from associations found in list of lists (performance issue)


rawDescription: Getting last (newest) element with lxml,python


code:
def check(data, key):
    mask = data[key].shift(1) == data[key]
    mask.iloc[0] = np.nan
    return mask

df.groupby(by=['ser_no']).apply(lambda x: check(x, 'CTRY_NM'))

rawDescription: Python: logical comparing with columns in panda's dataframe


code:
for line in file:
    output.write(line) # save as is
    if 'SAMPLE' in line or 'RUNS' in line:
       line = next(file, "") # move to the next line
       output.write(line.replace('AB', 'XX')) # save replacing AB with XX

rawDescription: Search and replace string under specific line


code: ['Hello', 'my', 'name', 'is', 'Apple']

rawDescription: How to turn a string into a list in python?

description: Turn a string into a list in python


code:
class Comment(models.Model):
    # some fields...

    def created_user_is_staff(self):
        return self.created.is_staff()

rawDescription: Link django model attributes between classes


code:
list1 = ['hi', 'state', 'California', 'usa']
list2 = ['moon', 'sun', 'hi', 'flower']
[a+' '+b for a in list1 for b in list2 if a != b]

rawDescription: Joining two list together into one without repeating


code:
branch
delete
events
init
logs
push
start
status
stop
update

rawDescription: AWS EC2: "Invalid command: terminate"

description: AWS EC2: "Invalid command: terminate"


code:
from itertools import groupby
lst = [list(v) for k,v in groupby(l,key=bool) if k]
lst[1]
lst[0]

rawDescription: python: break list into pieces when an empty entry is found

description: Python: break list into pieces when an empty entry is found


code:
from operator import itemgetter
lst = [{'value': 9.99, 'key': 'price'}, {'value': '1.1.1', 'key': 'version'}]
getter = itemgetter('key','value')
dict(getter(dct) for dct in lst)

rawDescription: Pythonic way to make a key/value pair a dictionary


code: def f(): f()

rawDescription: Sorting some code and i need to shorten it


rawDescription: How can I create a list in Python?

description: Create a list in Python


code:
p = psutil.Process(pid)
p.is_running()

rawDescription: Python library for Linux process management


code: pd.DataFrame(data, columns=['id', 'name', 'age']).set_index('id')

rawDescription: Pandas: how to reuse the index information from the data?


code:
def fixed_size_groups(n, iterable):
    return zip(*[iter(iterable)] * n)

rawDescription: Python: using a dict to speed sorting of a list of tuples


code:
child = int(input("How many children do you have?"))
total = 0
if child > 100:
    print("Invalid!")
else:
    for count in range(child): # This start counting from 0
        n = int(input("Enter child #%s" %str(count)+ " age:"))
        total += n

print("Average age:", total/child)

rawDescription: calculating average in python?

description: Calculating average in python


code:
from twisted.application.service import Application

from thatmodule import ThingDoer

application = Application("Do Things")
ThingDoer().setServiceParent(application)

rawDescription: sound way to feed commands to twisted ssh after reactor.run()

description: Sound way to feed commands to twisted ssh after reactor.run()


code:
from itertools import cycle, islice, dropwhile

L = [1, 2, 3, 4]

cycled = cycle(L)  # cycle thorugh the list 'L'
skipped = dropwhile(lambda x: x != 4, cycled)  # drop the values until x==4
sliced = islice(skipped, None, 10)  # take the first 10 values

result = list(sliced)  # create a list from iterator
print(result)

rawDescription: Cycle through list starting at a certain element


code:
lib = CDLL('./cellComplex_lib.so')

lib.dim.restype = c_int
lib.dim.argtypes = [Cell]

lib.new_cellComplex.restype = CellComplex
lib.new_cellComplex.argtypes = [POINTER(c_double * 2), c_size_t]

lib.size_elementsAtSpecifiedDim.restype = c_int
lib.size_elementsAtSpecifiedDim.argtypes = [CellComplex, c_int]

lib.get_elementsAtSpecifiedDim.restype = POINTER(Cell)
lib.get_elementsAtSpecifiedDim.argtypes = [CellComplex, c_int]

rawDescription: ctypes: Correctly sublcass c_void_p for passing and returning custom data types, by example

description: Ctypes: Correctly sublcass c_void_p for passing and returning custom data types, by example


code:
def Criacao():
    name = InputName()               # We are using the returned values here
    courseName = InputCourseName()
    global Fonte, Output, CorTexto, Raw
    base = Image.open(Raw)
    draw = ImageDraw.Draw(base)
    draw.text((5,5), name.upper(), font=Fonte, fill=CorTexto)
    draw.text((6,5), courseName.upper(), font=Fonte, fill=CorTexto)

rawDescription: function set value for another function

description: Function set value for another function


code:
response = br.open("http://www.w3schools.com/html/html_forms.asp")
f = list(br.forms())
f[0].get_value("firstname")
f[0].get_value("lastname")

rawDescription: Getting the key and value of br.forms() in Mechanize


code:
class foo():
    def __init__(self, value, otherstuff):
        self.value = value
        self.otherstuff = otherstuff

    def __sub__(self, other):
        return self.value - other

    def __rsub__(self, other):
        return other - self.value

rawDescription: Overwrite __sub__ for a-b when 'b' is my class


code: dir(types)

rawDescription: Python: How can I check whether a object is a module?


code:
final_dict = {}

# always sort as groupby creates group each time the group value changes
data.sort(key=split_5_min)
for period, data_tuples in itertools.groupby(data, split_5_min):
    group_data = list(data_tuples)
    # sort again
    group_data.sort(key=bucket_floats)
    final_dict[period] = {}
    # do another grouping witin 5 min group
    for bucket, float_tuples in itertools.groupby(data, bucket_floats):
        # pack into a dict
        final_dict[period][bucket] = len(list(float_tuples))

rawDescription: Elegant data processing in Python

description: Elegant data processing in Python


rawDescription: How to get the related_name for a foreign key?

description: Get the related_name for a foreign key


code: {key: value for line in fileobject.readlines() for key, value in [line.split(': ')]}

rawDescription: Convert string from external file to Python dictionary


code:
def foo(a, b, *args, **kwargs):
    pass

rawDescription: Is there a way to check a function's signature in Python?


code:
name = somelist[0]
name = 'other'

rawDescription: Write access for iterators ? Or: sending values to generators of numpy Arrays


code:
listex = range(0, 101, 25)
["https://thisisan{}example.com".format(i) for i in listex]

rawDescription: Python str.format() --- passing in list, outputting list


code:
heapq.heapify
heapq._siftup

rawDescription: Intercepting heapq

description: Intercepting heapq


code:
class Actor(object):    # in Python 3, class Actor:
    _world = None
    def __init__(self, world):
        self._world = world

class Mover(Actor):
    _speed = 0
    def __init__(self, speed, **kwargs):
        super(Mover, self).__init__(**kwargs)    # in Python 3, super().__init__(**kwargs)
        self._speed = speed

class Attacker(Actor):
    _range = 0
    def __init__(self, range, **kwargs):
        super(Attacker, self).__init__(**kwargs) # in Python 3, super().__init__(**kwargs)
        self._range = range

class Human(Mover, Attacker):
    def __init__(self, **kwargs):
        super(Human, self).__init__(**kwargs)    # in Python 3, super().__init__(**kwargs)

rawDescription: One-Many-One Inheritance in Python

description: One-Many-One Inheritance in Python


code:
mapper = {attr_name:getattr(cls, attr_name)  for cls in base.__subclasses__() for attr_name, obj in cls.__dict__.items()
             if isinstance(obj, classmethod) }

rawDescription: Inverse of hasattr in Python

description: Inverse of hasattr in Python


code:
class User(models.Model):
    name = models.CharField(max_length=4)

class Group(models.Model):
    Member_list = models.ManyToManyField(User, through='Member', related_name="Member_list")

class Member(models.Model):
    group = models.ForeignKey(Group)
    user = models.ForeignKey(User)

rawDescription: Queryset for ManyToMany relation in Django


rawDescription: Finding neighbors in a list

description: Finding neighbors in a list


code:
T(lambda : without_else()).repeat()
T(lambda : with_else()).repeat()
T(lambda : without_else(True)).repeat()
T(lambda : with_else(True)).repeat()

rawDescription: Why is early return slower than else?

description: Why is early return slower than else


rawDescription: Python: How can I increment a char?

description: Python: How can I increment a char


code:
import numpy as np
from shapely.geometry import Polygon, Point

def spatial_contour_frequency_shapely(paths,lon,lat):

    frequency = np.zeros(lon.shape)
    contours = [Polygon(path) for path in paths]

    for (i,j),v in np.ndenumerate(frequency):
        pt = Point([lon[i,j],lat[i,j]])
        for contour in contours:
            if contour.contains(pt):
                frequency[i,j] += 1

    return frequency

rawDescription: count how often each field point is inside a contour

description: Count how often each field point is inside a contour


code:
arr = [1, 2, 3]
index = 0
arr[:-index or None]
index = 1
arr[:-index or None]

rawDescription: List slicing with dynamic index on [:index]


code: s.sendall("GET / HTTP/1.1\r\n\r\n")

rawDescription: python socket GET

description: Python socket GET


code:
from reikna.core import Type
from reikna.cbrng import CBRNG
from reikna.cluda import any_api
import numpy as np

# Get any supported API for this system, or an exception
_api = any_api()
# The global CLUDA Thread, wrapping context, shared by all
# reikna_norm_rng's
_thr = _api.Thread.create()

def reikna_norm_rng(seed, rows, cols, mean, std,
                    dtype=np.float32,
                    generators_dim=1):
    """
    A do-all generator function for creating a new Computation
    returning a stream of pseudorandom number arrays.
    """
    # The Type of the output array
    randoms_arr = Type(dtype, (rows, cols))
    # Shortcut for creating a Sampler for normally distributed
    # random numbers
    rng = CBRNG.normal_bm(randoms_arr=randoms_arr,
                          generators_dim=generators_dim,
                          sampler_kwds=dict(mean=mean, std=std),
                          # Reikna expects a positive integer. This is a
                          # quick and *dirty* solution.
                          seed=abs(hash(seed)))
    compiled_comp = rng.compile(_thr)
    # RNG "state"
    counters = _thr.to_device(rng.create_counters())
    # Output array
    randoms = _thr.empty_like(compiled_comp.parameter.randoms)

    while True:
        compiled_comp(counters, randoms)
        yield randoms.get()

rawDescription: Regenerate vector of randoms in Python

description: Regenerate vector of randoms in Python


code:
count = 0
current = None

with open(filename) as fo:
   for line in fo:
       if line.startswith('>'):
           if current and count:
               print('{} {:2d}'.format(entry, count))
           current = line.strip()
           counts = 0
       else:
           count += 1
   if current and count:
       print('{} {:2d}'.format(entry, count))

rawDescription: Count lines after line with specific character


code:
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
training_idx = numpy.random.randint(x.shape[0], size=80)
test_idx = numpy.random.randint(x.shape[0], size=20)
training, test = x[training_idx,:], x[test_idx,:]

rawDescription: Numpy: How to split/partition a dataset (array) into training and test datasets for, e.g., cross validation?


rawDescription: Keep the order of list used in $in query in Mongo


rawDescription: Executing code through python eval

description: Executing code through python eval


code: txt = read_file(files[0])

rawDescription: parse blocks of text from text file using Python

description: Parse blocks of text from text file using Python


code: any(isinstance(i, np.ndarray) for i in [a, b])

rawDescription: isinstance check if any of the variables has a certain class

description: Isinstance check if any of the variables has a certain class


code: photo_image = PhotoImage(filename)

rawDescription: Tkinter create_image not displaying

description: Tkinter create_image not displaying


rawDescription: Django:how to concatenate the seperated integer field (Year, month) as date range to filter the database


code:
setattr(type(self), "blah", property(self.get_blah, self.set_blah,
        self.del_blah, "bleh blih"))

rawDescription: How to create a property with its name in a string?

description: Create a property with its name in a string


rawDescription: Concatenating strings faster than appending to lists


code:
def test(self, boss, data):
  namespace = globals().copy()
  local_copy = locals().copy()
  namespace.update(local_copy)
  x = 'def foo(): pass'
  exec(x, namespace)

rawDescription: Closure lost during callback defined in exec()


code: {'a': 'happy', 'g': 'birthday'}

rawDescription: Python - Database query function with non-consistent arguments


code:
a=list(range(3)).reverse()
print(a)

rawDescription: The usage of reverse() in Python

description: The usage of reverse() in Python


code: geturl()

rawDescription: Python - POSTing with a urllib2 opener

description: Python - POSTing with a urllib2 opener


rawDescription: Python: I have a dual key list, which is the most effective storage object for retreival


rawDescription: Matrix addition/multiplication in numpy

description: Matrix addition/multiplication in numpy


code:
f = open('test25.pyc')
magic = f.read(4)
magic.encode('hex')
f = open('test26.pyc')
magic = f.read(4)
magic.encode('hex')

rawDescription: Is there a way to know by which Python version the .pyc file was compiled?


code:
for fileName in filelist:

    # open in read mode
    with open(fileName, 'r') as data_file:
        data_list = data_file.readlines()

        # list modification
        data_list = [ s.lstrip() for s in data_list ]
        data_list[4] = data_list[4][1:]

    # reopens file in write mode, deletes contents
    with open(fileName, 'w') as data_file:

        # overwriting
        for line in data_list:
            data_file.write(line)

rawDescription: Removing specific characters from multiple lines in a list by indexing


code: p.imap(f.f, jobs)

rawDescription: function initialize and object initialization (multiprocessing)

description: Function initialize and object initialization (multiprocessing)


code:
import pandas as pd
import StringIO

rawDescription: How do I create a pandas dataframe in python from a csv with additional delimiters?

description: Create a pandas dataframe in python from a csv with additional delimiters


code:
num=raw_input ("enter the numbers : ")
l=[int(i) for i in num.split(',')]
l

rawDescription: Python parsing, convert string to list of integers


code:
class MySpinBox(QDoubleSpinBox):
    def __init__(self, parent=None):
        super(MySpinBox, self).__init__(parent)
        # any RegExp that matches the allowed input
        self.validator = QRegExpValidator(QRegExp("\\d+[\\.]{0,1}[02468]{0,1}"), self)

    def validate(self, text, pos):
        # this decides if the entered value should be accepted
        return self.validator.validate(text, pos)

rawDescription: Fix values that are typed into a doublespinbox in PyQt


code: print("Lotto number {} is {} !".format(index, lotto[index]))

rawDescription: Sequence elements will not modify (Python 3.4)


code:
new.attach( MIMEMessage(original) )

s = smtplib.SMTP()
s.sendmail("me@mysite.com", [new["To"]], new.as_string())
s.quit()

rawDescription: How do I reply to an email using the Python imaplib and include the original message?

description: Reply to an email using the Python imaplib and include the original message


code:
'9 December, Wednesday', '12:30', 'http://www.test.com', '3D'
'9 December, Wednesday', '15:30', 'http://www.test.com', '3D'
'9 December, Wednesday', '18:30', 'http://www.test.com', '3D'
'10 December, Thursday', '12:30', 'http://www.test.com', '2D'
'10 December, Thursday', '15:30', 'http://www.test.com', '3D'

rawDescription: No nested nodes. How to get one piece of information and then to get additional info respectively?


rawDescription: SQLAlchemy: filter by membership in at least one many-to-many related table


code:
l=[u"P&G's Pamela's Diner", u'Pittsburgh', 40.451723, -79.932833]
[i.encode('unicode-escape') if isinstance(i,unicode) else i for i in l]

rawDescription: Python array printing in unicode and csv issue


code:
def bareWordHandler(type_, value, traceback_):
    if isinstance(value, SyntaxError):
        import traceback

        # You can probably modify this next line so that it'll work within blocks, as well as outside them:
        bareWords = traceback.format_exception(type_, value, traceback_)[1].split()

        # At this point we have the raw string that was entered.
        # Use whatever logic you want on it to decide what to do.
        if bareWords[0] == 'Awesome':
            print(' '.join(bareWords[1:]).upper() + '!')
            return
    bareWordsHandler.originalExceptHookFunction(type_, value, traceback_)

import sys
bareWordsHandler.originalExceptHookFunction = sys.excepthook
sys.excepthook = bareWordsHandler

rawDescription: Bare words / new keywords in Python

description: Bare words / new keywords in Python


code: arr = [num, score, ping, guid, name, lastmsg, address, qport, rate]

rawDescription: How to parse this string

description: Parse this string


code:
I1,J1 = np.where(mask1)
I2,J2 = np.where(mask2)
res12=np.concatenate((res1,res2))
I12=np.concatenate((I1,I2))
J12=np.concatenate((J1,J2))
M12=sparse.coo_matrix((res12,(I12,J12)), r.shape)
M12.A

rawDescription: How can I create a sparse matrix instead of a dense one in this program?

description: Create a sparse matrix instead of a dense one in this program


rawDescription: indexing one array and doing operation on another

description: Indexing one array and doing operation on another


rawDescription: Fast process each line of one file for each line in another file


code:
store = {'A':np.array([1,2,3]), 'B':np.array([3,4,5])}
np.concatenate(store.values(),1)

rawDescription: Python: concatenate arrays stored in a dictionary


code:
class CourseSubjectList(APIView):
    def get(self, request, pk, format=None):
        subs = Course.objects.all()
        serialized_subs = CourseWrapperSerializer(subs, many=True)
        return Response(serialized_subs.data)

rawDescription: Django tweak the rest framework serializer to getting a different json structure


code:
def _reverse_pointer(self):
    """Return the reverse DNS pointer name for the IPv6 address.

    This implements the method described in RFC3596 2.5.

    """
    reverse_chars = self.exploded[::-1].replace(':', '')
    return '.'.join(reverse_chars) + '.ip6.arpa'

rawDescription: python ipaddress()reverse_pointer equivalent for 3.4

description: Python ipaddress()reverse_pointer equivalent for 3.4


code:
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
glBegin(GL_TRIANGLES)
glVertex2f(0, 0)
glVertex2f(window.width, 0)
glVertex2f(window.width, window.height)
glEnd()

rawDescription: Pyglet not running properly on AMD HD4250


code:
def monitor(request):
  items = []
  for x in range(item):
    items_dict = {
    'itemNumber': parsResults['innerSet'][0]['rpasState'][x]['rpaUID']['rpaNumber'],
    'itemStatus': parsResults['innerSet'][0]['rpasState'][x]['status'],
    'itemVersion': parsResults['innerSet'][0]['rpasState'][x]['version']['version']
    }
    items.append(items_dict)
return render(request, 'monitorLabs.html', {'items' : items})

rawDescription: return all values from a for loop to a template on django

description: Return all values from a for loop to a template on django


code:
unq_val, unq_idx, unq_count = np.unique(B.ravel(), return_inverse=True,
                                        return_counts=True)

rawDescription: Plotting Histogram using data from 2 numpy matrices


code:
import operator
import functools

def sumproduct(*lists):
    return sum(functools.reduce(operator.mul, data) for data in zip(*lists))

rawDescription: sum of products for multiple lists in python

description: Sum of products for multiple lists in python


code:
var1 = request.POST.get('var1')
var2 = request.POST.get('var2')
var3 = request.POST.get('var3')

rawDescription: How to create a method in Python

description: Create a method in Python


code:
gio = gene(12)
next(gio)
next(gio)
next(gio)
next(gio)
next(gio)

rawDescription: Can't understand generator

description: Can't understand generator


code:
import re

repl1='k1'
repl2='k2'
pattern=re.compile('(CN=Root,Model=.*,Vector=Reactions\[)(.*)(\],ParameterGroup=Parameters,Parameter=)(.*)(,Reference=Value)')
target = 'CN=Root,Model=something,Vector=Reactions[somethingelse],ParameterGroup=Parameters,Parameter=1234,Reference=Value'

rawDescription: How to replace only elements found using a python re.findall rather than entire string?

description: Replace only elements found using a python re.findall rather than entire string


code: ret = redirect('/signupform/?resp=%s'%msg) # pass as query parameter

rawDescription: Django - dictionary passed in redirect is not showing in template


code: df['returned_on'] = df.index + pd.to_timedelta(df.days_delinquent, 'D')

rawDescription: Adding days to column in pandas using separate column integers


code: last_list = [tuple(x) for x in Long_list]

rawDescription: Convert a list of lists back into a list of tuples


code: c = f(a,b)

rawDescription: numerical operation on two numpy ndarrays

description: Numerical operation on two numpy ndarrays


code: (equation(value) for value in d.values())

rawDescription: How do I get values from a dictionary run them through an equation and return the key with the greatest value

description: Get values from a dictionary run them through an equation and return the key with the greatest value


rawDescription: Writing to a particular cell using csv module in python


code:
from pandas import Series, DataFrame, date_range
import matplotlib.pyplot as plt
import numpy as np

ts = Series(np.random.randn(1000), index=date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

df = DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()

ax = df.plot(subplots=True, style=['r','g','b','r'], sharex=True)
plt.legend(loc='best')
plt.tight_layout()
plt.show()

rawDescription: Change subplot color in DataFrame?

description: Change subplot color in DataFrame


code:
def rep_sum(c, *L):
  d = Counter(L)
  return sum(k for k in d if d[k]<=c)

rawDescription: Python sum of non duplicate int

description: Python sum of non duplicate int


rawDescription: Removing repeated element from a list

description: Removing repeated element from a list


rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


code:
import pytz
import datetime as dt

def to_utc(localdt,tz):
    timezone=pytz.timezone(tz)
    utc=pytz.utc
    return timezone.localize(localdt).astimezone(utc)

if __name__=='__main__':
    for tz in ('Europe/Berlin','Africa/Lagos'):
        for date in (dt.datetime(2011,1,1,10,0,0),
                 dt.datetime(2011,7,1,10,0,0),
                 ):
            print('{tz:15} {l} --> {u}'.format(
                tz=tz,
                l=date.strftime('%b %d %H:%M'),
                u=to_utc(date,tz).strftime('%b %d %H:%M %Z')))

rawDescription: Python - From DST-adjusted local time to UTC


rawDescription: Searching in three elements before and after a specific word in list


code: new_list = filter(regex.match, old_list)

rawDescription: Delete all items in a list that don't contain a regular expression string


rawDescription: Pandas Dataframe output to JSON

description: Pandas Dataframe output to JSON


code:
import itertools
ls = [[0, 1], [0, 1], [0, 1]]
list(itertools.product(*ls))

rawDescription: How can I create crossproduct tuple for list of n list?

description: Create crossproduct tuple for list of n list


code:
util.py
class PropertyVoodoo(type):
    """A metaclass. Initializes when the *class* is initialized, not
    the object. Therefore, we are free to muck around the class
    methods and, specifically, descriptors."""

    def __init__(cls, *a):
        # OK, so the list of C++ properties using the style described
        # in the OP is stored in a __properties__ magic variable on
        # the class.
        for prop in cls.__properties__:

            # Get accessor.
            def fget(self):
                # Get the SWIG class using super. We have to use super
                # because the only information we're working off of is
                # the class object itself (cls). This is not the most
                # robust way of doing things but works when the SWIG
                # class is the only superclass.
                s = super(cls, self)

                # Now get the C++ method and call its operator().
                return getattr(s, prop)()

            # Set accessor.
            def fset(self, value):
                # Same as above.
                s = super(cls, self)

                # Call its overloaded operator(int value) to set it.
                return getattr(s, prop)(value)

            # Properties in Python are descriptors, which are in turn
            # static variables on the class. So, here we create the
            # static variable and set it to the property.
            setattr(cls, prop, property(fget=fget, fset=fset))

        # type() needs the additional arguments we didn't use to do
        # inheritance. (Parent classes are passed in as arguments as
        # part of the metaclass protocol.) Usually a = [<some swig
        # class>] right now.
        super(PropertyVoodoo, cls).__init__(*a)

        # One more piece of work: SWIG selfishly overrides
        # __setattr__. Normal Python classes use object.__setattr__,
        # so that's what we use here. It's not really important whose
        # __setattr__ we use as long as we skip the SWIG class in the
        # inheritance chain because SWIG's __setattr__ will skip the
        # property we just created.
        def __setattr__(self, name, value):
            # Only do this for the properties listed.
            if name in cls.__properties__:
                object.__setattr__(self, name, value)
            else:
                # Same as above.
                s = super(cls, self)

                s.__setattr__(name, value)

        # Note that __setattr__ is supposed to be an instance method,
        # hence the self. Simply assigning it to the class attribute
        # will ensure it's an instance method; that is, it will *not*
        # turn into a static/classmethod magically.
        cls.__setattr__ = __setattr__

rawDescription: Python Properties & Swig

description: Python Properties & Swig


code:
def Addzero(value):
    return [0] * max(0,8-len(value)) + value

rawDescription: Prepending zeros to a list

description: Prepending zeros to a list


code:
for header in soup.find_all('h2', text=re.compile('part 2')):
    section = header.parent

rawDescription: Python/Beautiful Soup find particular heading output full div


code: json_data = json.loads('{ ... }')

rawDescription: Parsing the pointers in JSON using python


code:
from functools import partial

objectList.append(DataObject(foo.c, partial(setattr, foo, 'c')))

rawDescription: Set a Python property using a function call


code: # coding=utf-8

rawDescription: Django Form values without HTML escape

description: Django Form values without HTML escape


rawDescription: Disable cursor in TextCtrl - wxPython

description: Disable cursor in TextCtrl - wxPython


code:
import yourdbmodelclassnamehere
m = yourmodelclassnamehere(x='',y='')
m.put()

rawDescription: How to programmatically put data to the Google Appengine database from remote executable?

description: Programmatically put data to the Google Appengine database from remote executable


code:
from functools import wraps

def cache_most_recent(func):
    cache = [None, None]
    @wraps(func)
    def wrapper(*args, **kw):
        if (args, kw) == cache[0]:
            return cache[1]
        cache[0] = args, kw
        cache[1] = func(*args, **kw)
        return cache[1]
    return wrapper

@cache_most_recent
def costly_function_a(x):
    print("costly_function_a has been called.")
    return x #Dummy operation.

@cache_most_recent
def costly_function_b(x):
    print("costly_function_b has been called.")
    return 5.*x #Dummy operation.

rawDescription: Minimizing the number of costly function calls when the parameters remain the same (python)


code:
non_fixed = [c for c in dataset.columns if not c.startswith("fixed")]
dataset.ix[:, non_fixed]

rawDescription: Filter out columns containing specific word


code:
import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

rawDescription: Open File in Another Directory (Python)

description: Open File in Another Directory (Python)


code:
def namer(name):
    return name + ".gz"

def rotator(source, dest):
    with open(source, "rb") as sf:
        data = sf.read()
        compressed = zlib.compress(data, 9)
        with open(dest, "wb") as df:
            df.write(compressed)
    os.remove(source)

rh = logging.handlers.RotatingFileHandler(...)
rh.rotator = rotator
rh.namer = namer

rawDescription: How to mix logging Handlers (File & Timed) and compress log in the same config file?

description: Mix logging Handlers (File & Timed) and compress log in the same config file


code:
enlst = rexBackticked.findall(enpara)
cslst = rexBackticked.findall(cspara)

rawDescription: Synchronizing markdown automatically in the translated text (ProGit book, sources available)


rawDescription: How does Python handle equality checking?


rawDescription: Truncate the length of a Python dictionary


code:
tk.Button(self,text=b[0],width=5,height=2, bg="grey",
command=lambda text=b:[self.name(text[1]), self.info(text[2])] ).grid(row=r,column=c)

rawDescription: Using Lambda and tuples to send to Multiple Functions: Python, Tkinter


code:
import contextlib
import numpy as np
import pandas as pd
import pandas.core.format as pf
np.random.seed(2015)

@contextlib.contextmanager
def custom_formatting():
    orig_float_format = pd.options.display.float_format
    orig_int_format = pf.IntArrayFormatter

    pd.options.display.float_format = '{:0,.2f}'.format
    class IntArrayFormatter(pf.GenericArrayFormatter):
        def _format_strings(self):
            formatter = self.formatter or '{:,d}'.format
            fmt_values = [formatter(x) for x in self.values]
            return fmt_values
    pf.IntArrayFormatter = IntArrayFormatter
    yield
    pd.options.display.float_format = orig_float_format
    pf.IntArrayFormatter = orig_int_format

df = pd.DataFrame(np.random.randint(10000, size=(5,3)), columns=list('ABC'))
df['D'] = np.random.random(df.shape[0])*10000

with custom_formatting():
    print(df)

rawDescription: Format pandas integers for display

description: Format pandas integers for display


code:
def decimal_default(obj):
    if isinstance(obj, decimal.Decimal):
        return float(obj)
    raise TypeError

json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)

rawDescription: Python to JSON Serialization fails on Decimal


code:
import pygame
import os

# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('C:\Python27', 'player.png')

class Bird(object):  # represents the bird, not the game
    def __init__(self):
        """ The constructor of the class """
        self.image = pygame.image.load(img_path)
        # the bird's position
        self.x = 0
        self.y = 0

    def handle_keys(self):
        """ Handles Keys """
        key = pygame.key.get_pressed()
        dist = 1 # distance moved in 1 frame, try changing it to 5
        if key[pygame.K_DOWN]: # down key
            self.y += dist # move down
        elif key[pygame.K_UP]: # up key
            self.y -= dist # move up
        if key[pygame.K_RIGHT]: # right key
            self.x += dist # move right
        elif key[pygame.K_LEFT]: # left key
            self.x -= dist # move left

    def draw(self, surface):
        """ Draw on surface """
        # blit yourself at your current position
        surface.blit(self.image, (self.x, self.y))

pygame.init()
screen = pygame.display.set_mode((640, 400))

bird = Bird() # create an instance
clock = pygame.time.Clock()

running = True
while running:
    # handle every event since the last frame.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit() # quit the screen
            running = False

    bird.handle_keys() # handle the keys

    screen.fill((255,255,255)) # fill the screen with white
    bird.draw(screen) # draw the bird to the screen
    pygame.display.update() # update the screen

    clock.tick(40)

rawDescription: How to move Sprite in Pygame

description: Move Sprite in Pygame


code:
before_pickle1 = data1[0]
before_pickle2 = data1[1]
before_pickle1 is before_pickle2
before_pickle1[0] is before_pickle2[0]
after_pickle1 = pickle.loads(pickle.dumps(before_pickle1))
after_pickle2 = pickle.loads(pickle.dumps(before_pickle2))
after_pickle1[0] is after_pickle2[0]
before_pickle1 = data2[0]
before_pickle1[0][0] is before_pickle1[1][0]
after_pickle1 = pickle.loads(pickle.dumps(before_pickle1))
after_pickle1[0][0] is after_pickle1[1][0]

rawDescription: python multiprocessing peculiar memory management

description: Python multiprocessing peculiar memory management


code:
def decodeEmail(e):
    de = ""
    k = int(e[:2], 16)

    for i in range(2, len(e)-1, 2):
        de += chr(int(e[i:i+2], 16)^k)

    return de

rawDescription: Scraping of protected email

description: Scraping of protected email


code:
a = [706, 835, 160, 432, 148, 472, 26, 917, 736, 342, 442, 479, 95, 800, 956]
k = 4
mem = dict()
INF = 1e10

def get_variance(partition):
    size = len(partition)
    s = sum(partition)
    mean = float(s) / size
    variance = 0
    for n in partition:
        temp = round(n - mean, 14) ** 2
        variance += temp
    variance /= size
    return variance

def calc(pos, cnt):
    if (pos, cnt) in mem.keys():
        return mem[(pos, cnt)]
    if pos == 0 and cnt >= 0:
        return 0.0
    if cnt < 0:
        return INF
    res = INF
    for old_pos in range(0, pos):
        res = min(res, calc(old_pos, cnt - 1) + get_variance(a[old_pos: pos]))
    mem[(pos, cnt)] = res
    return res

if __name__ == '__main__':
    a.sort()
    print(calc(len(a), k))

rawDescription: a strategy to partition a set to get the minimum sum of variances from subsets

description: A strategy to partition a set to get the minimum sum of variances from subsets


code:
with open(ifile_name,"r") as in_file, open(ofile_name, "w+") as out_file:
    for line in file:
        list_of_words = line.split(' ')
        for key, word in enumerate(list_of_words):
            if 'l' in word:
                list_of_words[key] = ''

        out_file.write(' '.join(w for w in list_of_words if w != ''))

rawDescription: Python remove word containing "l"

description: Python remove word containing "l"


rawDescription: How many samples needed for a collision (birthday paradox)


rawDescription: How do I compile a Visual Studio project from the command-line?

description: Compile a Visual Studio project from the command-line


code:
# Right here is where I am stuck
for i in names:
    box.insert(END, i)

rawDescription: Separating Words in a List Tkinter Listbox Python


code:
from collections import defaultdict
from itertools import product
from pprint import pprint

cities = [
    'Copenhagen',
    'Berlin',
    'Stockholm'
]

sentences = [
    'Hello world',
    'Hello Copenhagen',
    'Hello Berlin',
    'Bye Berlin',
]

res = defaultdict(list)

for city, sentence in product(cities, sentences):
    if city in sentence:
        res[city].append(sentence)

pprint(res)

rawDescription: Texts intersection in Python

description: Texts intersection in Python


code:
def set_active_border(self, window):
    border_color = self.colormap.alloc_named_color(\
        "#ff00ff").pixel
    window.configure(border_width = 2)
    window.change_attributes(None,border_pixel=border_color,
         border_width = 2)
    self.dpy.sync()

rawDescription: Drawing window border in Python xlib

description: Drawing window border in Python xlib


code:
rows, cols = 3, 5
v = np.random.rand(rows)
c = np.random.rand(cols)
X = sps.rand(rows, cols, density=0.5, format='csr')

rawDescription: Scipy Sparse Matrix special substraction


code: [elem.get_text() for elem in soup.select('div.dinner p.first')]

rawDescription: Adding elements to BeautifulSoup's find_all list as a string


code:
import re

nonspaces = re.compile(r'\S+') # To extract the first word

def search_and_replace(filepath, replacement):
    def replace_sentence(match):
        def replace_name(match):
            name = match.group()
            return replacement.get(name, name)
        return nonspaces.sub(replace_name, match.group(), count=1)
        # count=1: to change only the first word.
    with open(filepath, 'r+') as f:
        replaced = re.sub('[^.!?]+', replace_sentence, f.read())
        f.seek(0)
        f.write(replaced)
        f.truncate() # NOTE: If name shrinks, unwanted string remains.

start_replacement = {
    'Bob': 'John',
    'Sam': 'Jack',
    'Tom': 'Kevin',
}
search_and_replace('start_words.txt', start_replacement)

rawDescription: Possible to match at the start of a textfile without using regex?


code: [ord(i)-ord('a') for i in s2.lower()]

rawDescription: working with lists and strings

description: Working with lists and strings


code:
# Consider each row as indexing tuple & get linear indexing value
lid = np.ravel_multi_index(x.T,x.max(0)+1)

# Get counts and unique indices
_,idx,count = np.unique(lid,return_index=True,return_counts=True)

# See which counts are exactly 1 and select the corresponding unique indices
# and thus the correspnding rows from input as the final output
out = x[idx[count==1]]

rawDescription: Get non-duplicate rows from numpy array

description: Get non-duplicate rows from numpy array


code:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)

rawDescription: How to recover matplotlib defaults after setting stylesheet

description: Recover matplotlib defaults after setting stylesheet


code:
from pyspark.sql.functions import explode

df.select(explode("sample.persons").alias("person")).select("person.id")

rawDescription: PySpark sqlContext JSON query all values of an array


code:
import itertools as it

def func(s):
   if not s:
       return [s]
   binary = it.product(['',' '], repeat=len(s)-1)
   zipped = (it.izip_longest(s , comb, fillvalue='') for comb in binary)
   return [''.join(it.chain.from_iterable(x)) for x in zipped]

func('foobar')

rawDescription: How do I generate all possible combinations of a string with spaces between the characters? Python

description: Generate all possible combinations of a string with spaces between the characters? Python


code:
from multiprocessing import Pool
from itertools import islice

# The function to be run in parallel :
def my_func(strings):
    return [j+i for i in strings for j in listSubstrings if i.find(j)>-1]

# A small recipe from itertools to chunk an iterable :
def chunk(it, size):
    it = iter(it)
    return iter(lambda: tuple(islice(it, size)), ())

# Generating some fake & random value :
from random import randint
listStrings = \
    [''.join([chr(randint(65, 90)) for i in range(randint(1, 500))]) for j in range(10000)]
listSubstrings = \
    [''.join([chr(randint(65, 90)) for i in range(randint(1, 100))]) for j in range(1000)]

# You have to prepare the searches to be performed:
prep = [strings for strings in chunk(listStrings, round(len(listStrings) / 8))]
with Pool(4) as mp_pool:
    # multiprocessing.map is a parallel version of map()
    res = mp_pool.map(my_func, prep)
# The `res` variable is a list of list, so now you concatenate them
# in order to have a flat result list
result = res.pop(0)
_ = list(map(lambda x: result.extend(x), res))

rawDescription: Python: optimal search for substring in list of strings


code:
while event_handling is True:
    win32gui.PumpMessages()     # Check for events, needs to be sent a WM_QUIT message to stop, handled in disable_event_handling()
    time.sleep(0.1)             # Check every 0.1 seconds

rawDescription: Python - Constantly running an event handler without wxPython?


code:
for i in solution():
    print(i, end= ' ')

rawDescription: More elegant/Pythonic way of printing elements of tuple?


rawDescription: Iterate over double values to produce page numbers


code: df1.add(freqs, fill_value=0)

rawDescription: How to set the values of a dataframe given a series of indices and corresponding column names?

description: Set the values of a dataframe given a series of indices and corresponding column names


code: '0x' + ''.join([format(int(c, 16), '02X') for c in reversed(inputlist)])

rawDescription: How to append a list of Hex to one Hex number

description: Append a list of Hex to one Hex number


code:
def spellable(word, rack):
    return all( [rack.count(letter) >= word.count(letter) \
                 for letter in set(word)] )

rawDescription: How can this Python Scrabble word finder be made faster?


code:
import transaction

@expose('mytemplate')
def my_controller(self):
    object = model.DBSession.query(model.Object).filter_by( field = value ).first()
    object.field = 'Hello'

    transaction.doom()  # This will prevent changes to be committed.
    return dict(value=object.field)

rawDescription: sqlalchemy object saved to complete action

description: Sqlalchemy object saved to complete action


code: list[1]['key-B'] = 'value-B'

rawDescription: How do I add keys to a dictionary in a list of dictionaries?

description: Add keys to a dictionary in a list of dictionaries


rawDescription: Is there a direct approach to format numbers in jinja2?


code:
def iter_from_middle(lst):
    try:
        middle = len(lst)/2
        yield lst[middle]

        for shift in range(1, middle+1):
            # order is important!
            yield lst[middle - shift]
            yield lst[middle + shift]

    except IndexError: # occures on lst[len(lst)] or for empty list
        raise StopIteration

rawDescription: Python - iterating beginning with the middle of the list and then checking either side


code:
user_high_scores = {}
for name in user_scores:
    user_high_scores[name] = max(user_scores[name])   # Find the highest of the 3 most recent scores

rawDescription: Displaying only the highest of a person's 3 most recent scores, saved in a .txt file


rawDescription: Export Gmail using Python imaplib - text mangled with newline issues


code: fl = {(name, id(value)) for name, value in f.f_locals.items()}

rawDescription: Getting name of local variable at runtime in Python


rawDescription: Python schedule repeating multiple threads


rawDescription: fast, large-width, non-cryptographic string hashing in python

description: Fast, large-width, non-cryptographic string hashing in python


code:
string = 'Today is my birthday'
string.find('my') #Out: 9
string[9:] #Out: 'my birthday'

rawDescription: Position of query word

description: Position of query word


code:
self.worker = Worker()
self.worker.updateProgress.connect(self.setProgress)

rawDescription: Python PySide and Progress Bar Threading


code:
button1 = Button(..., command=lambda widget="button1": DoSomething(widget))
button2 = Button(..., command=lambda widget="button2": DoSomething(widget))

rawDescription: Python Tkinter one callback function for two buttons


code:
for fieldchild in field.findall('field'):
    return findXXX(fieldchild)

rawDescription: recursion None python

description: Recursion None python


code:
import pandas as pd

pd.pivot_table(txt_file, rows=['msisdn','prob'], cols='desc',aggfunc=len)

rawDescription: pandas dataframe : creating pivot_table on a data frame without giving values

description: Pandas dataframe : creating pivot_table on a data frame without giving values


code:
def deepReplace(d, key, value):
    if isinstance(d, dict):
        if key in d:
            d[key] = value
            return True
        else:
            for k,v in d.iteritems():
                if deepReplace(v, key, value):
                    return True
    return False

rawDescription: Python: Elegant way to replace a given dictionary by child key somewhere in a tree?


code: [(i, x) for i, x in enumerate(some_list, 1) if x != 'p']

rawDescription: Maintain count in python list comprehension


code:
list1_used = sum((((x,) * line.count(x)) for x in list1), ())
list2_used = sum((((y,) * line.count(y)) for y in list2), ())

rawDescription: Find combination of items in the same line in one file text and thei frequency


code: print("| " + "".join(["{:^3}".format(x) for x in list]) + "\n")

rawDescription: format list depending on number of items in it

description: Format list depending on number of items in it


code:
import pandas as pd
df = pd.read_csv(your_file)
df.groupby('Time [s]').apply(lambda x: x.to_csv(str(x.name) + '.csv'))

rawDescription: Splitting csv file of multiple objects over time by time-point


code:
xyz
mass
xyz_unique
mass_unique

rawDescription: Find indices of unique values of a 3-dim numpy array


rawDescription: Basic savegames for a text based game

description: Basic savegames for a text based game


code:
now_ts = datetime.now(pytz.timezone('Europe/Istanbul'))
now_naive = make_naive(now_ts, pytz.timezone('Europe/Istanbul'))
now_naive > campaingObject.publish_end

rawDescription: How to make a time object TZ aware without changing the value?

description: Make a time object TZ aware without changing the value


code: MyClass = metaclass(name, bases, **kargs)

rawDescription: Metaclass Arguments for Python 3.x

description: Metaclass Arguments for Python 3.x


code:
def testFunc():
    print('this is a test')

for i in range(5):
    print('test')
    testFunc()
print("Have any test funcs been called")

rawDescription: Will a for loop that calls a function finish before any of the functions are called?


code:
test_string = 'Hello, two is a number'
new_string = test_string[7:12]

rawDescription: python copy string from position to position

description: Python copy string from position to position


code:
def a(i): return 'function a: {}'.format(i)
def b(i): return 'function b: {}'.format(i)
def c(i): return 'function c: {}'.format(i)
def d(i): return 'function d: {}'.format(i)
arguments = [1, 2, 3, 4]
functions = [a, b, c, d]
[func(arg) for func, arg in zip(functions, arguments)]

rawDescription: Call different function for each list item


code:
import cPickle
import shelve
import os

class PickleManager(object):
    def store(self,name,value):
        with open(name,'w') as f:
            cPickle.dump(value,f)
    def load(self,name):
        with open(name,'r') as f:
            return cPickle.load(f)

class ShelveManager(object):
    def __enter__(self):
        if os.path.exists(self.fname):
            self.shelf=shelve.open(self.fname)
        else:
            self.shelf=shelve.open(self.fname,'n')
        return self
    def __exit__(self,ext_type,exc_value,traceback):
        self.shelf.close()
    def __init__(self,fname):
        self.fname=fname
    def store(self,name,value):
        self.shelf[name]=value
    def load(self,name):
        return self.shelf[name]

def write(manager):
    for i in range(100):
        fname='/tmp/{i}.dat'.format(i=i)
        data='The sky is so blue'*100
        manager.store(fname,data)
def read(manager):
    for i in range(100):
        fname='/tmp/{i}.dat'.format(i=i)
        manager.load(fname)

rawDescription: Does linux disk buffer cache make python cPickle more efficient than shelve?


code: singleitem = mylist.pop()

rawDescription: Getting only element from a single-element list in Python?


code:
from sympy.mpmath import *
pi = mpf(0)
mp.dps = 50;
for n in range(0,50000):
    u = mpf(4)/mpf(8*n+1)-mpf(2)/mpf(8*n+4)-mpf(1)/mpf(8*n+5)-mpf(1)/mpf(8*n+6)
    d = mpf(16.0)**n
    pi += u/d

print(pi)

rawDescription: BBP-Algorithm in Python - Working with Arbitrary-precision arithmetic


code:
import urllib2

data = "x"*100000000 # 100MB beefy chunk
urllib2.urlopen("http://localhost:12346", data=data, timeout=4)

rawDescription: How to prevent blocking forever on urlopen

description: Prevent blocking forever on urlopen


code:
import os
def touch(fname, times=None):
    fhandle = open(fname, 'a')
    try:
        os.utime(fname, times)
    finally:
        fhandle.close()

rawDescription: Implement touch using Python?

description: Implement touch using Python


code:
import datetime
d = datetime.date.today()
type(d.month)
type(d.day)

rawDescription: python datetime extract double digit month and day values

description: Python datetime extract double digit month and day values


code:
import numpy as np
plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))

rawDescription: Bin size in Matplotlib (Histogram)

description: Bin size in Matplotlib (Histogram)


code: sourcefile = sourcefile.replace(line, l)

rawDescription: How can i print the result in a file after for loop

description: Print the result in a file after for loop


code: y.extend(v for z in ('a', 'b\nc', 'd') for v in z.splitlines())

rawDescription: Can this generator expression be modified to match for loop result?


code:
@register.filter
def is_string(val):
    return isinstance(val, basestring)

rawDescription: How can I tell if a value is a string or a list in Django templates?

description: Tell if a value is a string or a list in Django templates


code: ['stack', 'overflow', 'at', 'not', 'mat', 'eyes', 'spoon', 'eatery', 'cart', 'clam', 'water']

rawDescription: Find all words placed on a Scrabble board


code: sorted(DISKIMAGES, key=lambda x: (x.epoch, x.size), reverse=True)

rawDescription: Can I sort a list of objects by 2 keys?

description: Sort a list of objects by 2 keys


code:
def getDTO(self):
  return self._dto

rawDescription: How can I change in Python the return/input type of a list that is implemented as an class attribute?

description: Change in Python the return/input type of a list that is implemented as an class attribute


code:
import string
import itertools

chars = string.ascii_letters + string.digits

def alpha_perms(index):

    for perm in itertools.permutations(chars[index:]):
         yield perm

rawDescription: How can i start itertools combinations from specific letter/digit?

description: Start itertools combinations from specific letter/digit


code:
class User(Base):
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(50), nullable=False, unique=True)

class Group(Base):
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(50), nullable=False, unique=True)

class Membership(Base):
    user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
    group_id = Column(Integer, ForeignKey(Group.id), primary_key=True)
    joined_on = Column(DateTime, nullable=False, default=datetime.utcnow, server_default=func.current_timestamp())

    user = relationship(User, backref=backref('memberships', collection_class=set))
    group = relationship(Group, backref=backref('memberships', collection_class=set))

User.groups = association_proxy('memberships', 'group')
Group.users = association_proxy('memberships', 'user')

rawDescription: make query ManyToMany in sqlalchemy?

description: Make query ManyToMany in sqlalchemy


code:
from rdiff_backup.Main import Main as backup
task=['/etc', '/tmp/backup']
backup(task)

rawDescription: Scripting Python for Linux commands

description: Scripting Python for Linux commands


code:
from PIL.ImageColor import getcolor

overlay = 'yellow'
fill_color = getcolor(overlay, primaryImage.mode)

rawDescription: Overlaying coloured pixels on top of an image using Python Imaging Library


code: dt2 = np.dtype(dict(names=('t', 'x'), formats=(np.int16, np.int8), offsets=(0, 2)))

rawDescription: Python numpy recarray: Can one obtain a view into different fields using pointer arithmetic?


code:
def foo():
    print('bar')

rawDescription: Reloading a changed python file in emacs python shell


code: logger.debug('Message with %s', arguments, extra={'sim_time': sim_time})

rawDescription: Best way to add custom information to for logging

description: Add custom information to for logging


code:
def get_scraper(name):
    mod = __import__(name)

    parser = mod.Parser()
    pages = mod.pages() # Pass whatever args you need to figure out the urls

    return Scraper(parser, pages)

rawDescription: Pattern and design for functions that differ greatly from each other but are processed similarly


code:
(1, 'Boca Raton', 0, 'Boca Raton')
(2, 'Boynton Beach', 0, 'Boynton Beach')
(3, 'Bradenton', 0, 'Bradenton')
(4, 'Cape Coral', 0, 'Cape Coral')
(5, 'Deltona', 0, 'Deltona')

rawDescription: Python Loop for mysql statement

description: Python Loop for mysql statement


rawDescription: Xor Hex/ASCII/Conversion Issue

description: Xor Hex/ASCII/Conversion Issue


code:
from pyramid.i18n import get_localizer

@view_config(route_name='transtest', renderer='json')
def transtest_view(request):
    message = _('temp-test', default='Temporary test', domain='myapp')
    return {'myvar': get_localizer(request).translate(message)}

rawDescription: Pyramid TranslationString not working on json renderer


code:
import getopt
import shlex
args = shlex.split('-n tdelane -s 10.1.213.226 -p xxx -v')
getopt.getopt(args, "cs:np:hv")
getopt.getopt(args, "cs:n:p:hv")

rawDescription: Why does my getopts fail if I specify a username?


code:
def dfs(nodes):
    if nodes is not None:
        for node in nodes:
            yield node
            for child in dfs(node['children']):
                yield child

for node in dfs(tree):
    if node['id'] in selected:
        node['selected'] = true

rawDescription: Traversing and modifying a tree-like list of dict structure


code:
def parse_quoted_strings_list(s):
    import csv
    return next(csv.reader([s],
        skipinitialspace=True,
        quoting=csv.QUOTE_NONNUMERIC,
        escapechar='\\',
        doublequote=False,
        quotechar="'"))

rawDescription: How to parse a simple quoted string (handling escapes)

description: Parse a simple quoted string (handling escapes)


code:
len=(last-first).days
dates=[first+datetime.timedelta(n) for n in range(len+1)]

rawDescription: Enumerate a DateRange

description: Enumerate a DateRange


code:
import collections

raw_data = []
idx_maintenance = collections.defaultdict(set)
idx_supplychain = collections.defaultdict(set)

Datum = collections.namedtuple('Datum', 'floorid robotid partnum')

def add_data(floorid, robotid, partnum):
    datum = Datum(floorid, robotid, partnum)
    raw_data.append(datum)

    idx_maintenance[(floorid, robotid)].add(datum)
    idx_supplychain[partnum].add(datum)
    # whatever other indexes you need

# so you can add stuff
add_data(1, 1, 1)
add_data(1, 1, 2)
add_data(1, 1, 3)
add_data(1, 2, 1)

# then you can use the indexes to do lookups
set_of_data = idx_maintenance[(1, 1)]

rawDescription: How to manage multiple indexes to same data?

description: Manage multiple indexes to same data


code:
import numpy as np

# Size parameters
N = anArray.size
M = anArray.max()+1

# Setup output array
resultArray = np.zeros((N,M),int)

# Find out the linear indices where 1s would be put
idx =  (np.arange(N)*M) + anArray

# Finally, put 1s at those places for the final output
resultArray.ravel()[idx] = 1

rawDescription: How to convert a series of index/category, into a classification array

description: Convert a series of index/category, into a classification array


rawDescription: Python Version Specific Code

description: Python Version Specific Code


code:
Chloe
attribute6

rawDescription: Python Splitting a file into many files and adding in extra info


code:
def is_sorted(x,i):
    if i >= len(x):
        return True
    elif x[i] <= x[i-1]:
        return False
    else:
        return is_sorted(x,i+1)

rawDescription: Why do I get None instead of True/False in python?


code:
s1 = zerorpc.Server(objectA)
s1.bind("tcp://0.0.0.0:4242")
s2 = zerorpc.Server(objectB)
s2.bind("tcp://0.0.0.0:8686")

gevent.spawn(s1.run)
s2.run()

rawDescription: ZeroRPC: How to expose a module

description: ZeroRPC: How to expose a module


rawDescription: Obtaining dictionary value in Python

description: Obtaining dictionary value in Python


rawDescription: How to unzip lists in lists in a list

description: Unzip lists in lists in a list


code:
htOldRating = ratings[ht][-1]
atOldRating = ratings[at][-1]
print(htOldRating)
print(atOldRating)

rawDescription: Python: How to have a user reference and access a variable?


code:
def convert_mills_GMT(milliseconds,
                      utc=pytz.utc,
                      eastern=pytz.timezone('US/Eastern')
):
    converted_raw = DT.datetime.fromtimestamp(milliseconds/1000.0)
    date_eastern = eastern.localize(converted_raw, is_dst=True)
    date_utc = date_eastern.astimezone(utc)
    timestamp = ...
    return int(timestamp) * 1000

rawDescription: Convert EST timestamp to GMT taking into account Daylight Savings


code: format_float(0.0001, 4)

rawDescription: Decimal formatting based on number of digits in integer and decimal parts


rawDescription: sort files on the filesystem using a cutom sort

description: Sort files on the filesystem using a cutom sort


code:
numbers = []
for line in open("data.txt").readlines():
    numbers.extend([int(n) for n in line.split()])
print(numbers)

rawDescription: Splitting a list of numbers from txt file on both spaces and new lines, Python


rawDescription: Python: Remove 0s from floats in string

description: Python: Remove 0s from floats in string


code:
class BackgroundImage(models.Model):
    url = models.PositiveSmallIntegerField()
    name = models.CharField(max_length=25)

class User(models.Model):
    ...
    bgpic = models.ForeignKey(BackgroundImage)

rawDescription: Django: Reference Database Entry

description: Django: Reference Database Entry


code: m_sum = sum(range(num1, num2 + 1)) #[num1, num2]

rawDescription: Need to add all the integers between 2 other integers


code: any( x == someElement for x in someList )

rawDescription: How does Python check if an element exists in a list?


code:
def add_attribute_block(toybox = None, key = "", glob = None ):
    if glob is None:
        glob = AttributeBlock.objects
    if toybox is not None:
        if key in glob:
            toybox.attributes.append(AttributeBlock.objects[key].copy())

rawDescription: creating a new copy of a python class each time it's called

description: Creating a new copy of a python class each time it's called


code:
for col in columns:
  dataname = currec['Fields'][col]['name']
  dataval = currec['Fields'][col]['Values']['value']

rawDescription: Opening A large JSON file in Python with no newlines for csv conversion Python 2.6.6


code:
left = bottom = float('inf')
right = top = float('-inf')
for x in rect:
    if x.left < left:     left = x.left
    if x.bottom < bottom: bottom = x.bottom
    if x.right > right:   right = x.right
    if x.top > top:       top = x.top

rawDescription: How to simplify repetitive list comprehensions in python?

description: Simplify repetitive list comprehensions in python


code: {names: {1: "count at rank 1", 2: "Counter for rank 2"}}

rawDescription: How to find reoccuring string groups (order does not matter) in a dictionary of lists?

description: Find reoccuring string groups (order does not matter) in a dictionary of lists


rawDescription: Distinguish matches in pyparsing

description: Distinguish matches in pyparsing


code:
for key, value in sorted(starters.items(), key=lambda x: x[1][1]):
    ...

rawDescription: I am having difficulty sorting a dictionary by value


code:
import inspect
from sympy import *

def get_derivatives(func):
    arg_symbols = symbols(inspect.getargspec(func).args)
    sym_func = func(*arg_symbols)

    return [lambdify(arg_symbols, sym_func.diff(a)) for a in arg_symbols]

rawDescription: Take Python Function and Generate All Derivatives


code:
import numpy as np
import tables

# Generate some data
x = np.random.random((100,100,100))

# Store "x" in a chunked array...
f = tables.openFile('test.hdf', 'w')
atom = tables.Atom.from_dtype(x.dtype)
ds = f.createCArray(f.root, 'somename', atom, x.shape)
ds[:] = x
f.close()

rawDescription: Python: how to store a numpy multidimensional array in PyTables?


code:
import your_module
your_module.parameter1 = 23
your_module.parameter2 = 46
the_result = your_module.f_var_2

rawDescription: Get values from module

description: Get values from module


code:
from random import random

result = []

# Return 100 results (for instance)
for i in range(100):

    res = random()

    if res < 0.8:
        result.append(1)
    elif res < 0.95:
        result.append(2)
    else:
        result.append(3)

return result

rawDescription: How to generate random sequence of numbers in python?

description: Generate random sequence of numbers in python


code: [syns.get(word, [word]) for word in phrase.split(' ')]

rawDescription: Return a list of matches by given phrase


code:
import re

def remove(reg, s, multiline=False):
    flags = [re.M, re.M | re.DOTALL][multiline]
    s,num = re.subn(reg, "", s, flags=flags)
    return s

def classname(s):
    s = remove("\"\"\".*?\"\"\"", s, multiline=True)
    s = remove("\'\'\'.*?\'\'\'", s, multiline=True)
    s = remove("\".*?\"", s)
    s = remove("\'.*?\'", s)

    res = re.search("(^|\s)class\s+(\w+)", s, flags=re.M)
    # print "*** {} -> {}".format(s, res.groups() if res else None)
    if res is None:
        return None
    else:
        return res.group(2)

rawDescription: Looking for a way to get a word after another word, Python


code: pprint([item for c_list in lists for item in c_list])

rawDescription: Split lists within list

description: Split lists within list


code:
def helloFunc():
    pass

hello_func = helloFunc

rawDescription: Renaming of functions with preservation of backward compatibility


code:
from operator import itemgetter

def merge_join_kv(leftGen, rightGen):
    # assuming that kyotocabinet.Cursor has a copy initializer
    leftIter = IterableCursor(leftGen)
    rightIter = IterableCursor(rightGen)

    return orderedMerge(leftIter, rightIter, key=itemgetter(0), unique=True)

rawDescription: merge join two generators in python

description: Merge join two generators in python


code: fitfunc = lambda params, x: params[0] * x

rawDescription: How to force zero interception in linear regression?

description: Force zero interception in linear regression


code:
handle = __import__('geopy')
print(handle)

rawDescription: Python: include a third party library in a personal Python package


code:
keys = ('pos', 'call', 'father', 'mother')

with open(outputfilename, 'w') as output:
    for name in d:
        output.write(name + '\n')
        for entry in d['name']:
            output.write(' '.join([entry[k] for k in keys]) + '\n')

rawDescription: Save dictionary to file

description: Save dictionary to file


code:
from mwlib.uparser import simpleparse
simpleparse("=h1=\n*item 1\n*item2\n==h2==\nsome [[Link|caption]] there\n")

rawDescription: How to parse/extract data from a mediawiki marked-up article via python

description: Parse/extract data from a mediawiki marked-up article via python


rawDescription: How to find a substring using partial matching

description: Find a substring using partial matching


code:
p = isprime(x)
if p is not None:
    print(p)

rawDescription: removing "none" result from the function which prints the prime number

description: Removing "none" result from the function which prints the prime number


code:
with conn:
    cur.executemany('insert into Counts (email, count) values (?,?)',Counts)

rawDescription: Python - Inserting list of tuples into SQLite


code:
def week_difference(start, end):
    assert start <= end
    start_year, start_week, start_dayofweek = start.isocalendar()
    end_year, end_week, end_dayofweek = end.isocalendar()

    return ((end_year - start_year) * 52) - start_week + end_week

rawDescription: python count business weeks

description: Python count business weeks


code: [x.split(",") for x in strs.splitlines()]

rawDescription: How to split on two items in a string?

description: Split on two items in a string


code: print((lambda a:sum(([i for i in [[ord(i.lower())-96 for i in a.replace(' ','')]] if len(i)>=10][0])) if len(a) >= 10 else 0)(raw_input("Enter: ")))

rawDescription: Semicolon alternative in python

description: Semicolon alternative in python


code:
def fun(x1, y1, x2, y2, n, r=None):
    r = [] if r is None else r

rawDescription: How can I rewite this Python code using iteration?

description: Rewite this Python code using iteration


code:
import zipfile
import configparser
import io

zf = zipfile.ZipFile("compressed.zip")
zf_config = zf.open("config_data.conf", "rU")
zf_config = io.TextIOWrapper(zf_config)

config = configparser.ConfigParser()
config.read_file(zf_config)
assert config['today']['lunch']=='cheeseburger'

rawDescription: configparser loading config files from zip

description: Configparser loading config files from zip


code:
import py

def test_skip_line(line):
    """decide which lines to skip, the code below will also skip the next line if this returns true"""
    return 'unittest' in line

class PatchedReprEntryNative(py._code.code.ReprEntryNative):
    def __init__(self, tblines):
        self.lines = []
        while len(tblines) > 0:
            line = tblines.pop(0)
            if test_skip_line(line):
                # skip this line and the next
                tblines.pop(0)
            else:
                self.lines.append(line)
py._code.code.ReprEntryNative = PatchedReprEntryNative

rawDescription: py.test: hide stacktrace lines from unittest module

description: Py.test: hide stacktrace lines from unittest module


code:
import MySQLdb
import config

def show_table(cursor):
    select = 'SELECT * FROM Testing'
    cursor.execute(select)
    for row in cursor:
        print(row)

def create_table(cursor):
    sql = 'DROP TABLE Testing'
    cursor.execute(sql)
    sql = '''CREATE TABLE `Testing` (
             `id` INT(11) NOT NULL AUTO_INCREMENT,
             `number` INT(11),
             PRIMARY KEY (id))'''
    cursor.execute(sql)

with MySQLdb.connect(host=config.HOST, user=config.USER,
                     passwd=config.PASS, db='test') as cursor:

    create_table(cursor)

rawDescription: MySQL database updates to the round decimal


code:
classes = df.groupby('Number').Landform.apply(determineClass)
df['Class'] = df.Number.map(classes)
df

rawDescription: Conditional function on multiple rows

description: Conditional function on multiple rows


code:
def switchFiles(args):
    f, d = {}, {}
    for root1, dirs1, files1 in os.walk(args.folder):
        for f1 in files1:
            f[f1] = os.path.join(root1, f1)
    for root2, dirs2, files2 in os.walk(args.database):
        for f2 in files2:
            d[f2] = os.path.join(root2, f2)
    ns = set(f.keys()) & set(d.keys())
    for n in ns:
        shutil.copyfile(f[n], d[n])

rawDescription: Optimizing simple Python file matching & replacement script


code:
x1[:x.shape[0], :x.shape[1]] = x
y1 = np.zeros(shape)
y1[:y.shape[0], :y.shape[1]] = y

rawDescription: Extend different shapes/dimension matrices in python


code:
solution = (0,0,0)
for a in range(0,n):
    for b in range(0,n):
        for c in range(0,n):
            if 6*a + 9*b + 20*c == n:
                solution = (a,b,c)

rawDescription: MIT OCW 6.00's Chicken McNugget program... again


code:
import logging
logger = logging.getLogger('django.db.backends')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
ic = IC.objects.get(id='21')
ic.partno
ic.sups

rawDescription: When django model access DB

description: When django model access DB