code:
hello = r'\
'
hello
len(hello)
list(hello)

rawDescription: I do not understand Python raw string

description: I do not understand Python raw string


code:
import Settings
import tornado.web
import tornado.httpserver

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler)
        ]
        settings = {
            "template_path": Settings.TEMPLATE_PATH,
            "static_path": Settings.STATIC_PATH,
        }
        tornado.web.Application.__init__(self, handlers, **settings)

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")

def main():
    applicaton = Application()
    http_server = tornado.httpserver.HTTPServer(applicaton)
    http_server.listen(9999)

    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

rawDescription: is there a better way to handle index.html with Tornado?

description: Is there a better way to handle index.html with Tornado


code:
from zope import component

class ITestFactory(component.interfaces.IFactory):
    """Creates objects providing the ITest interface"""
    def __call__(a, b):
        """Takes two parameters"""

testFactory = component.Factory(Test, 'ITest Factory', ITestFactory.__doc__)
interface.directlyProvides(testFactory, ITestFactory)

rawDescription: Can zope.interface define how a class' __init__ method should look?


code:
import pygame, sys
from PIL import Image
pygame.init()

def displayImage( screen, px, topleft):
    screen.blit(px, px.get_rect())
    if topleft:
        pygame.draw.rect( screen, (128,128,128), pygame.Rect(topleft[0], topleft[1], pygame.mouse.get_pos()[0] - topleft[0], pygame.mouse.get_pos()[1] - topleft[1]))
    pygame.display.flip()

def setup(path):
    px = pygame.image.load(path)
    screen = pygame.display.set_mode( px.get_rect()[2:] )
    screen.blit(px, px.get_rect())
    pygame.display.flip()
    return screen, px

def mainLoop(screen, px):
    topleft = None
    bottomright = None
    runProgram = True
    while runProgram:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False
            elif event.type == pygame.MOUSEBUTTONUP:
                if not topleft:
                    topleft = event.pos
                else:
                    bottomright = event.pos
                    runProgram = False
        displayImage(screen, px, topleft)
    return ( topleft + bottomright )

if __name__ == "__main__":
    screen, px = setup(sys.argv[1])
    left, upper, right, lower = mainLoop(screen, px)
    im = Image.open(sys.argv[1])
    im = im.crop(( left, upper, right, lower))
    im.save(sys.argv[2])

rawDescription: Digital Image cropping in Python

description: Digital Image cropping in Python


rawDescription: How to call a static method of a class using method name and class name

description: Call a static method of a class using method name and class name


code:
any(sublist[1] == "ny" for sublist in lst)
any(sublist[1] == "xy" for sublist in lst)

rawDescription: serching for nested item in nested list [python]

description: Serching for nested item in nested list [python]


code:
def gcd2(a, b):
    if (0 == b):
        return a, 1, -1
    else:
        g, s, t = gcd2(b, a % b)
        # calculate new_s and new_t
        return g, new_s, new_t

rawDescription: Calculate the extended gcd using a recursive function in Python


rawDescription: Python Calculator, No Answer

description: Python Calculator, No Answer


rawDescription: compare string to list elements python

description: Compare string to list elements python


code:
p = Post.query.get(1)
url_for('post', post_id=p.id, slug=p.slugified_title)

rawDescription: add slugified title to url

description: Add slugified title to url


code:
@app.route('/vote_up/<this_record>')
def vote_up(this_record):
    if already_voted_for(this_record):
        return """<script type="text/javascript">
                       alert('You can only vote once');
            </script>{0}""".format(count_votes_for(this_record))

    vandalisms.update({'_id':bson.objectid.ObjectId(this_record)},
              {"$inc" : { "votes": 1 }}, upsert=True)

    return count_votes_for(this_record)

rawDescription: AJAX for updating Flask template after data goes from link action or form to mongodb collection


rawDescription: How to calculate mean of values in the list omitting a special value?

description: Calculate mean of values in the list omitting a special value


code:
p = Popen(["sort"], stdin=PIPE, stdout=PIPE)
p.communicate("4\n3\n1")
p.returncode

rawDescription: Proper way of re-using and closing a subprocess object


code:
import re
from pprint import pprint

filenames = ['mywords.txt', 'apple.txt', 'banana.txt', 'something.txt']
bad_words = ['pie', 'vegetable', 'fatigue', 'something']

classified_files = {} # filename -> good/bad
has_bad_words = re.compile(r'\b(?:%s)\b' % '|'.join(map(re.escape, bad_words)),
                           re.I).search
for filename in filenames:
    with open(filename) as file:
         for line in file:
             if has_bad_words(line):
                classified_files[filename] = 'bad'
                break # go to the next file
         else: # no bad words
             classified_files[filename] = 'good'

pprint(classified_files)

rawDescription: Classifying List Entries in Python

description: Classifying List Entries in Python


code:
import os.path
def nesting(path):
    """ counts how often `os.path.split` works on `path` """
    c = 0
    head = tail = path
    while head and tail:
        head, tail = os.path.split(head)
        c +=1
    return c

def longest_path( paths ):
        return max(paths, key=nesting)

rawDescription: Find deepest nested path?

description: Find deepest nested path


code:
from django.db.models import Q

myQuery = Q()
for i in range(0,(searchDiff+1)):
    filterString = str(int(searchRange[0]) + i)
    myQueryTwoD.append(Q(asn=filterString))
    for j in range(0,(len(myQueryTwoD)-1)):
        myQuery = myQuery | myQueryTwoD[j]

myQuerySet = my.objects.filter(myQuery)

rawDescription: Is it possible to concatenate QuerySets?

description: Is it possible to concatenate QuerySets


code:
import datetime
from pandas import *

start = datetime(2000, 1, 1)
end = datetime(2012, 12, 1)
d = DateRange(start, end, offset=datetools.Hour())
t_df = DataFrame({'field_1': np.array(['OFF', 'ON'])[np.random.random_integers(0, 1, d.size)], 'field_2': np.random.random_integers(0, 1, d.size)}, index=d)

rawDescription: Python Pandas: What is the fastest way to create a datetime index?


code:
if x < lb:
    x = lb
elif x > ub:
    x = ub

rawDescription: How to force a value to be within a range?

description: Force a value to be within a range


code: df.columns = [column + 'col' for column in df.columns]

rawDescription: How to automate renaming columns in Pandas

description: Automate renaming columns in Pandas


code:
def grouper(iterable):
    prev = None
    group = []
    for item in iterable:
        if not prev or item - prev <= 15:
            group.append(item)
        else:
            yield group
            group = [item]
        prev = item
    if group:
        yield group

numbers = [123, 124, 128, 160, 167, 213, 215, 230, 245, 255, 257, 400, 401, 402, 430]
dict(enumerate(grouper(numbers), 1))

rawDescription: Finding clusters of numbers in a list

description: Finding clusters of numbers in a list


code:
ChildB.x = None
ChildB.x

rawDescription: Python: Class attribute which defaults to parent's value and is collectible for entire hierarchy


code:
import os
os.path.relpath('C:\Folder\OtherFolder\AnotherFolder\file.txt', 'C:\Folder\OtherFolder')

rawDescription: Get parents directories of a file, up to a point


code:
def sxor(s1,s2):
    # convert strings to a list of character pair tuples
    # go through each tuple, converting them to ASCII code (ord)
    # perform exclusive or on the ASCII code
    # then convert the result back to ASCII (chr)
    # merge the resulting array of characters as a string
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))

rawDescription: how to do bitwise exclusive or of two strings in python?

description: Do bitwise exclusive or of two strings in python


code:
def sim(*params,**kwargs):
    timerange = kwargs.get('timerange',default_timerange)
    K1,K2,N = params #assuming you know you have exactly 3

#then call it like so
sim(k1,k2,N,timerange=(-100,100))

rawDescription: Unpacking parameters for a simulation

description: Unpacking parameters for a simulation


rawDescription: Linking ipython widget button and slider values


code:
import csv
import re
from itertools import islice

row_split = re.compile('\s*\*\s*')

with open(someinputfile, 'rb') as infile, open(outputfile, 'wb') as outfile:
    writer = csv.writer(outfile, delimiter='\t')

    next(islice(infile, 3, 3), None) # skip the first 3 lines in the input file

    for line in infile:
        row = row_split.split(line)[1:-1]
        if not row: continue
        writer.writerow(row[8::7])

rawDescription: Python, remove specific columns from file


code:
from twisted.application import internet

class TwoServers(TCPServer):
    def __init__(self):
        internet.TCPServer.__init__(self,9000, WebSocketFactory(factory))
        internet.TCPServer.__init__(self,80, server.Site(HandlerHTTP))

rawDescription: Run two webservers with twisted

description: Run two webservers with twisted


code: df[df.index.levels[1] <= cutoff].groupby(level=['id']).apply(lambda x: x.index.get_level_values(1).max())

rawDescription: pandas index.asof with multiindex

description: Pandas index.asof with multiindex


code:
if self.build_type == 'default':
    threads = []
    funcs = {0: vmware_create, 1: openstack_create}
    for i, t in enumerate(self.template):
        modify_template(t)
        build_flavor = self.getmatch(t)
        func = funcs.get(i, None)
        thread = MyThread(packer, t, self.new_env, build_flavor,
                          self.logger, func=func)
        thread.setName(build_flavor)
        thread.start()
        threads.append(thread)
    for thread in threads:
        thread.join()

rawDescription: Python threading: monitoring threads and executing additional code after threads complete


code:
import re
somestring = "987kjh"
re.match(r"\d*", somestring).group()
somestring = "kjh"
re.match(r"\d*", somestring).group()

rawDescription: Regular expression to group a pattern OR group empty string as ""


code:
class Foo(object):
    def __init__(self):
        pass

    from methods import baz, bar, quux

rawDescription: How to share behavior b/w classes in python?

description: Share behavior b/w classes in python


code:
for A in a:
    print('%.30f' % A.time)

rawDescription: Higher timestamp precision with scapy

description: Higher timestamp precision with scapy


rawDescription: How do I get another field from a Pandas Group By?

description: Get another field from a Pandas Group By


rawDescription: Sympy - Display Full Equation in Dense Matrix Form


rawDescription: Xenserver API - Create VM's with local storage?


code:
lines = iter(range(20))

for l in lines:
    if l == 10:
        [next(lines) for _ in range(5)]
    print(l)
0
1
2
3
4
5
6
7
8
9
10
16
17
18
19

rawDescription: Skip iterations in enumerated list object (python)


rawDescription: Pyparsing: word with at least one non-digit character


code: midday_today = datetime.datetime.combine(today, midday)

rawDescription: get time in past from current time

description: Get time in past from current time


rawDescription: How to sort a list of strings with a different order?

description: Sort a list of strings with a different order


rawDescription: remove empty last line from string (output from pipe)

description: Remove empty last line from string (output from pipe)


code:
@has_prop1
@has_prop2
class B(object):
    pass

rawDescription: How to share attributes without an is-a relationship in Python?

description: Share attributes without an is-a relationship in Python


code:
class MyViewMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MyViewMixin, self).get_context_data(**kwargs)
        context['foo'] = 'bar'
        return context

class MyView1(MyViewMixin, DetailView):
    ...

class MyView2(MyViewMixin, ListView):
    ...

rawDescription: Django: Views within views

description: Django: Views within views


code:
from bs4 import BeautifulSoup
from urllib2 import urlopen

url = 'http://search.yahoo.com/search?p=dog'
content = urlopen(url).read()
soup = BeautifulSoup(content)

soup.find(id="link-1")
soup.find(id="link-1").get("href")

rawDescription: Extracting a Link from a String using Python


code:
import string
string.ascii_lowercase

rawDescription: Alphabet range python

description: Alphabet range python


code: p = loc0 + Lx*locx + Ly*locy

rawDescription: Getting local 2D coordinates of vertices of a planar polygon in 3D space


code:
key = map(ord,decrypt)
print(list(key))

rawDescription: Python: Sum of numbers

description: Python: Sum of numbers


code:
def showWindow(self):
    self.child = Window(self)
    self.child.show()

rawDescription: PyQt4, Generating multiple Instances of the same widget?


code:
with open('c:\file.txt', 'w') as file:
    file.write('\n'.join(list_a))
    file.write('\n'.join(list_b))

rawDescription: output list of special letters string with python

description: Output list of special letters string with python


code:
import urllib2
import json

data = []

url1 ='https://en.wikipedia.org/w/api.php?\
action=query&format=json&list=categorymembers\
&cmtype=page&cmtitle=Category:Geography&cmlimit=100'

json_obj = urllib2.urlopen(url1)
data1 = json.load(json_obj)

for item in data1['query']:
    for i in data1['query']['categorymembers']:
        title = (i['title'].encode('utf8')+"\n")

        with open('WordsInCategory.text', 'r') as title_check:
            if title not in title_check:
                data.append(title)

with open('WordsInCategory.text', 'a') as f1:
    f1.write(''.join(set(data)))

# Handle additional requests

rawDescription: How to prevent writing into txt file the same words using open(text.txt,a)?

description: Prevent writing into txt file the same words using open(text.txt,a)


code:
if listbox.curselection():
    item = listbox.get(ACTIVE)

rawDescription: Python Tkinter Listbox Unbind the Default Selection


code:
# Put the Filter on the Handler so only INFO and higher is handled
extraHandler.addFilter(LevelFilter(logging.INFO))

# Let the Logger process everything (so it can propagate records to root)
extraLogger.setLevel(logging.DEBUG)

rawDescription: Python logging: propagate messages of level below current logger level


code:
class Timeout(object):
    def __init__(self, timeout_seconds):
        self.timeout = datetime.timedelta(0, timeout_seconds)
        self.reset()
    def reset(self):
        self.start = datetime.datetime.now()
        self.stop = self.start + self.timeout
    def check(self):
        if datetime.datetime.now() > self.stop:
            raise Exception('Timeout!')

rawDescription: Check for idle condition in running python program - Euler #41


rawDescription: combining two python dictionaries into one when the net values are not positive

description: Combining two python dictionaries into one when the net values are not positive


code: set2 = [x[0] for x in set1]

rawDescription: List type conversion python

description: List type conversion python


code:
create_district(
    name="Arc de Triomphe",
    transports=[tr_m1, tr_m2],
    schools=[sc_dauph],
)

rawDescription: Django: how to chain 2 add() calls in 1 create()?


code:
import csv

with open('input.txt', 'rb') as f_input, open('output.txt', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    csv_output.writerows([cols[1], cols[13], cols[15]] for cols in csv_input)

rawDescription: Extract columns from file to another file


code:
apple_fplot = df.groupby(['Year','Fungicide'])['Value'].sum()
plot_df = apple_fplot.unstack('Fungicide').loc[:, 'Value']
plot_df.index = pd.PeriodIndex(plot_df.index.tolist(), freq='A')
plot_df.plot()

rawDescription: groupby multiple values, and plotting results

description: Groupby multiple values, and plotting results


code:
import math               # from math import * for such common functions
def isTriangle(x, y, z):  # better to pass in a tuple or object, but this works
    if x>0 and y>0 and z>0:  # (then you could do all(s>0 for s in sides))
                             # (you could also do isTriangle(*sides))
                             # (you might need to add checks len(sides)==3
                             #  if your input data might include e.g. squares)
        if x > y and x > z:    # \
            c = x              #  |
        elif y > x and y > z:  #  > This is the same as c = max(x,y,z)
            c = y              #  |
        else:                  #  |
            c = z              # /
        if c == math.sqrt(x**2 + y**2): # \
            return True                 #  | Same as return c==sqrt(x**2+y**2)
        else:                           #  |
            return False                # /
    else:
        return False

rawDescription: Logic of triangle inequality as python conditionals?


code:
data1 = ... # contents of file1
data2 = ... # contents of file2

data = [data1, data2]
# use [1:] to filter column headers
data_cells = [[line.split() for line in datum.split('\n')][1:]
              for datum in data]

result = []
for line_sequence in zip(*data_cells):
    col1 = line_sequence[0][0] # get row header
    result.append([col1]) # and put it in a list
    for line in line_sequence:
        result[-1].append(line[-1])

out = '\n'.join(['    '.join(line) for line in result])
print(out)

rawDescription: Making a directory from multiple files in python


code:
import csv
import random

def some_condition(line):
    return random.random() < 0.5 # delete lines randomly with 50% probability

data = """Jan-20,Data,Class xpv,4,11yo+,4,more data....
Jan-20,Data,Class xpv,4,11yo+,4,more data....
Jan-20,Data,Class xpv,4,11yo+,4,more data....
Jan-20,Data,Class xpv,4,11yo+,4,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-30,Data,Class tn2,4,10yo+,12,more data....
Jan-50,Data,Class 22zn,2,10yo+,6,more data....
Jan-50,Data,Class 22zn,2,10yo+,6,more data....
Jan-50,Data,Class 22zn,2,10yo+,6,more data....
Jan-50,Data,Class 22zn,2,10yo+,6,more data....
Jan-50,Data,Class 22zn,2,10yo+,6,more data....
Jan-50,Data,Class 22zn,2,10yo+,6,more data....""".splitlines()

for line in filter_data(csv.reader(data)):
    print(line)

rawDescription: How to recount number in each class from a read csv

description: Recount number in each class from a read csv


code:
latex_elements = {
  # Additional stuff for the LaTeX preamble.
  'preamble': '\\usepackage{typo3}'
}

rawDescription: Table of contents sidebar in Sphinx LaTeX PDF


rawDescription: In Python, how to initialize a class attribute from the return value of a class method?


code:
import numpy as np
from numpy.random import rand, randint

cm = rand(50, 100)
cm[randint(0, 50, 4000), randint(0, 100, 4000)] = np.nan

temp1 = max(value for (x, y), value in np.ndenumerate(cm) if x * y < 100 and (x, y) != (0, 0) and not np.isnan(value))

x, y = np.indices(cm.shape)
mask = (x * y < 100) & (x + y != 0) & (~np.isnan(cm))
temp2 = np.max(cm[mask])

assert temp1 == temp2

rawDescription: Is there a better way to rewrite this NumPy Snippet


code:
[Song(artist='Mozart', title='Don Giovanni', length=3.5),
 Song(artist='Bach', title='Toccata in D Minor', length=12.44),
 Song(artist='Beethoven', title='Für Elise', length=2.47),
 Song(artist='Mozart', title='Serenata Notturna', length=2.98),
 Song(artist='Bach', title='Air', length=6.18),
 Song(artist='Mozart', title='Violin Concerto No. 3 in G, 1st Movement', length=8.43)]

rawDescription: Arrange elements in a list so that similar elements are farthest apart


code:
import mock
import module

def test_function():
    with mock.patch.object(__builtin__, 'input', lambda: 'some_input'):
        assert module.function() == 'expected_output'

rawDescription: Pytest: How to test a function with input call?


code:
def reallyiterable(x):
  return not isinstance(x, basestring) and isinstance(x, collections.Iterable)

rawDescription: How can I check if an object is an iterator in Python?

description: Check if an object is an iterator in Python


code:
f = open('fileToWriteTo', 'ab')
nextSubstream.tofile(f)

rawDescription: Save a bitstream to a file using python

description: Save a bitstream to a file using python


code:
reader = csv.reader(idata.split("\r\n"))

stocks = {}
for line in reader:
    if line == '':
        continue

    stock, price, volume, stime = line
    price = float(price)
    volume = int(volume)

    stocks[stock] = (price, volume, stime)

rawDescription: Python change data into sequence

description: Python change data into sequence


rawDescription: list comprehension with np.where to compare two arrays and combine them it first entry is equal

description: List comprehension with np.where to compare two arrays and combine them it first entry is equal


code:
srcs, dests = zip(* [(fr, to) for (fr, to) in hrc_dict.keys()])
G.add_nodes_from(srcs+dests)

rawDescription: How to add nodes and edges to a network analysis graph in Networkx?

description: Add nodes and edges to a network analysis graph in Networkx


code: re.split('[.!]', text)

rawDescription: Separating a string using predefined characters


code:
# models.py
class Profile(models.Model):
    name = models.CharField('profile name', max_length=10)

    def __unicode__(self):
        return u'%d' % self.id

class Plan(models.Model):
    name = models.CharField('plan name', max_length=10)
    profile = models.ForeignKey(Profile, related_name='profiles')

    def __unicode__(self):
        return self.name

# forms.py
class PlanForm(forms.ModelForm):
    profile = forms.ModelChoiceField(queryset=Profile.objects.all(),
            widget=forms.HiddenInput())

    class Meta:
        model = Plan

# views.py
def add_plan(request):

    if request.method == 'POST':
        return HttpResponse(request.POST['profile'])

    profile = Profile.objects.all()[0]
    form = PlanForm(initial={'profile':profile})
    return render_to_response('add_plan.html',
            {
                'form':form,
            },
            context_instance=RequestContext(request))

rawDescription: Another Django Forms : Foreign Key in Hidden Field


code:
[{'newtitle': 'google', 'sumvalue': 90, 'newurl': 'google.com'},
 {'newtitle': 'google', 'sumvalue': 104, 'newurl': 'fb.com'}]

rawDescription: get keys value's from dictionary in python

description: Get keys value's from dictionary in python


code: tuple([x1, y1, x2, y2] for x1 in range(0, 8) for x2 in range(0, 8) for y1 in range(0, 8) for y2 in range(0, 8))

rawDescription: Any better way to generate a tuple of all possible tuples in form of (x1,y1,x2,y2)?


code:
import datetime
stop_time = datetime.datetime.now() + datetime.timedelta(hours=1)

# ...

# in relevant function ...
if datetime.datetime.now() > stop_time:
    stop_streaming()

rawDescription: How to have a function exit after 1 hour in Python

description: Have a function exit after 1 hour in Python


code:
from collections import Counter
reader = csv.reader(sample)
counts = Counter((r[0], r[1], r[2]) for r in reader)
writer = csv.writer(sys.stdout)
for (sender, receiver, id), count in counts.most_common():
    writer.writerow([sender, receiver, id, count])

rawDescription: Python - order columns and compare rows in csv


code:
print (player1_name + 'wins')
print (player2_name + 'wins')

rawDescription: Python Rock/Paper/Scissors with name input


code:
def db_schema(self):
    cur= self._db.cursor()
    with io.open(self.SQLPATH, "r") as fp:
        sql_statement= ""
        for line in fp:
            line= line.rstrip()
            if line.startswith('#'): continue
            sql_statement+= line
            if line.endswith(";"):
                try:
                    cur.execute(sql_statement)
                except sql.OperationalError:
                    print("Failed:\n%s" % sql_statement)
                sql_statement= ""
    # file is done
    cur.close()

rawDescription: Check that a database file is valid and what the program is expecting?


rawDescription: Copying file without previous meta data

description: Copying file without previous meta data


code:
from mock import Mock

def BaseMock():
    mock = Mock(spec=Base, name='BaseMock')
    mock.one.return_value = 'uno'
    mock.two.return_value = 'dos'
    return mock

rawDescription: How to mock a class hierarchy

description: Mock a class hierarchy


code:
def saythread(engine, location, text):
    engine.say(text)
    engine.runAndWait()

# ...later...

engine = pyttsx.init()                 #(CHANGED) ADDED VARIABLE
t = threading.Thread(target=saythread,args=(engine, 1, "here we go"),name='sayitthread')
t.start()

rawDescription: Scoping rules and threads

description: Scoping rules and threads


code:
def match_previous(lst, word):
    # keep matches_count of how many times we find a match and total lengths
    matches_count = total_length_sum = 0.0
    # pull first element from list to use as preceding word
    previous_word = lst[0]
    # slice rest of words from the list
    # so we always compare two consecutive words
    rest_of_words = lst[1:]
    # catch where first word is "word" and add 1 to matches_count
    if previous_word == word:
        matches_count += 1
    for current_word in rest_of_words:
        # if the current word matches our "word"
        # add length of previous word to total_length_sum
        # and increase matches_count.
        if word == current_word:
            total_length_sum += len(previous_word)
            matches_count += 1
        # always update to keep track of word just seen
        previous_word = current_word
    # if  matches_count is 0 we found no word in the text that matched "word"
    return total_length_sum / matches_count if matches_count else False

rawDescription: Preceding Word Length

description: Preceding Word Length


rawDescription: How to sort pandas pivot_table based on newest date within level?

description: Sort pandas pivot_table based on newest date within level


code: U.subs(phi, atan2(y, x))

rawDescription: Exact user defined expressions in Sympy derivatives


code:
a.iloc[lind] = 1 - a.iloc[lind]
a

rawDescription: Change values over specific indexes in DataFrame


code:
sword.name
sword.high
sword.low

rawDescription: Python Dict w/Array Values Passed as Params?


code:
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.safebrowsing.enabled', True)
profile.set_preference('browser.safebrowsing.malware.enabled', True)

driver = webdriver.Firefox(profile)
driver.get("http://addonrock.ru/Debugger.js")

rawDescription: Selenium: page displayed differently

description: Selenium: page displayed differently


code: df = pd.read_csv('filename',  parse_dates=['Dates'])

rawDescription: Datetime strptime in Python pandas : what's wrong?


code:
symbol = 'ZYDUSWELL'
auction.symbol, created = Sttlmnt_typ_Master.objects.get_or_create(
                             symbol=symbol, defaults={'symbol_name': symbol})

rawDescription: Django foreign key in model

description: Django foreign key in model


code:
# Build dictionary with prefix:list pairs
targets = {
    'student_': [],
    'subject_': [],
    'ass_': []
}

for i in mylist:
    # Try to find matching prefix
    for prefix in targets:
        if i.startswith(prefix):
            targets[prefix].append(i)
            break

rawDescription: How can i convert the list into three lists based on criteria and put in dictionary

description: Convert the list into three lists based on criteria and put in dictionary


code:
A
A/bar
A/bar/x
A/bar/y
A/bar/z
A/foo
A/foo/a
A/foo/b
A/foo/c

rawDescription: Manipulation of directories java/python

description: Manipulation of directories java/python


code:
# Make the cumulative counts array
counts = np.array(counts, dtype=np.int64)
sum_counts = np.cumsum(counts)

# Decide how many counts to include in the sample
frac_select = 0.30
count_select = int(sum_counts[-1] * frac_select)

# Choose unique counts
ind_select = sorted(random.sample(xrange(sum_counts[-1]), count_select))

# A vector to hold the new counts
out_counts = np.zeros(counts.shape, dtype=np.int64)

# Perform basically the merge step of merge-sort, finding where
# the counts land in the cumulative array
i = 0
j = 0
while i<len(sum_counts) and j<len(ind_select):
    if ind_select[j] < sum_counts[i]:
        j += 1
        out_counts[i] += 1
    else:
        i += 1

# Rebuild the matrix using the `keys` list from before
out_mat = np.zeros(mat.shape, dtype=np.int64)
for i in range(len(out_counts)):
    out_mat[keys[i]] = out_counts[i]

rawDescription: Subsample a matrix python

description: Subsample a matrix python


rawDescription: What data structure container can be sorted by date


code: {{ form.hidden_tag() }}

rawDescription: Flask - WTForm - save form to db

description: Flask - WTForm - save form to db


rawDescription: Grabbing multiple documents with flask-mongoengine


rawDescription: Subtract letters in Python

description: Subtract letters in Python


code:
import bge
from random import random

def main():
    cont = bge.logic.getCurrentController()
    own = cont.owner
    scene = bge.logic.getCurrentScene()

    #direct access
    entity = scene.objects['obj']
    add = scene.addObject(obj,loc,0)
    add(entity,' location',0)

rawDescription: How to access objects from specific layer in blender game engine

description: Access objects from specific layer in blender game engine


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

x = np.random.random((10, 20))
x = x.cumsum(axis=1)

fig, ax = plt.subplots()
for i, row in enumerate(x):
    ax.plot(row, i * np.ones_like(row), 'ko')

ax.set_ylim([-0.5, 9.5])
ax.set_yticks(range(10))
ax.invert_yaxis()
plt.show()

rawDescription: How do I plot series of points on rows in matplotlib?

description: Plot series of points on rows in matplotlib


code: setbuf(stdout, NULL);

rawDescription: Python program not receiving output of printf


rawDescription: Intersection of subelements of multiple list of lists in dictionary


code:
from tkinter import *
from random import randint
def roll():
    text.delete("1.0", END)  # indent inserted by first editor
    text.insert(END, str(randint(1, 6)))  # ditto
# but first editor mistakenly added indents below.
window = Tk()
text = Text(window, width=1, height=1)  # insert ','
button = Button(window, text='Press to roll!', command=roll)  # delete 'A', ')'
text.pack()
button.pack()  # replace 'ButtonA' with 'button'

rawDescription: height not working python (3.4)

description: Height not working python (3.4)


code: super().setText('Hello')  # calls QLineEdit.setText

rawDescription: PyQt4: why do we need to pass class name in call to super()


code: plt.imshow(Image1, cmap='gray') # I would add interpolation='none'

rawDescription: Overlay an image segmentation with numpy and matplotlib


rawDescription: Pandas idiomatic way to do a dictionary lookup


code:
def subsequence(seq):
    if not seq:
        return seq

    M = [None] * len(seq)    # offset by 1 (j -> j-1)
    P = [None] * len(seq)

    # Since we have at least one element in our list, we can start by
    # knowing that the there's at least an increasing subsequence of length one:
    # the first element.
    L = 1
    M[0] = 0

    # Looping over the sequence starting from the second element
    for i in range(1, len(seq)):
        # Binary search: we want the largest j <= L
        #  such that seq[M[j]] < seq[i] (default j = 0),
        #  hence we want the lower bound at the end of the search process.
        lower = 0
        upper = L

        # Since the binary search will not look at the upper bound value,
        # we'll have to check that manually
        if seq[M[upper-1]] < seq[i]:
            j = upper

        else:
            # actual binary search loop
            while upper - lower > 1:
                mid = (upper + lower) // 2
                if seq[M[mid-1]] < seq[i]:
                    lower = mid
                else:
                    upper = mid

            j = lower    # this will also set the default value to 0

        P[i] = M[j-1]

        if j == L or seq[i] < seq[M[j]]:
            M[j] = i
            L = max(L, j+1)

    # Building the result: [seq[M[L-1]], seq[P[M[L-1]]], seq[P[P[M[L-1]]]], ...]
    result = []
    pos = M[L-1]
    for _ in range(L):
        result.append(seq[pos])
        pos = P[pos]

    return result[::-1]    # reversing

rawDescription: Longest increasing subsequence

description: Longest increasing subsequence


code: self.nested_list.extend([] for i in range(num_of_lists))

rawDescription: Python - Adding to a nested list

description: Python - Adding to a nested list


code:
from email.mime.text import MIMEText
fromaddr = 'XXXX@gmail.com'
toaddrs = 'jason@XXX.com'
subject = 'This is an important message'
content = 'Portal Test had an error'
# constructing a RFC 2822 message
msg = MIMEText(content)
msg['From'] = fromaddr
msg['To'] = toaddrs
msg['Subject'] = subject

rawDescription: python mail no subject coming through

description: Python mail no subject coming through


code:
import codecs, sys
writer = codecs.getwriter('utf8')(sys.stdout.buffer)

rawDescription: Python 3 CGI: how to output raw bytes

description: Python 3 CGI: how to output raw bytes


code:
def rgb_to_something(pixels):
    return pixels.sum(axis=1)

rawDescription: Numpy: vectorization for multiple values


code: res.reindex(np.arange(res.index[0], res.index[-1] + 1))

rawDescription: Filling gaps for cumulative sum with Pandas


code: f.extra_attribute = attr_value

rawDescription: Django model object with dynamically added attributes


code:
class ProjectResource(ModelResource):
  milestones = fields.ToManyField('ProjectTrackerServer.projects.api.MilestoneResource', 'projects', full=True)
class Meta:
    queryset = Project.objects.all()
    resource_name = 'project'

class MilestoneResource(ModelResource):
    project = fields.ForeignKey(Project, 'project')

    class Meta:
        queryset = Milestone.objects.all()
        resource_name = 'milestone'

rawDescription: Unable to get ToMany to work in Tastypie


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

sentences = ["Pig qoph an egg.",
             "Quiet European rhythms.",
             "My nth happy hour.",
             "Herb unit -- a dynasty heir."]
for sent in sentences:
    entsay = " ".join(["".join(map(to_piglatin, re.split("(\W+)", nonws)))
                       for nonws in sent.split()])
    print(u'"{}" → "{}"'.format(sent, entsay))

rawDescription: Pig Latin Translator

description: Pig Latin Translator


code:
from itertools import groupby, zip_longest

x = (list(v) for k,v in groupby(data, lambda x: x < 0))
l = list(zip_longest(x, x, fillvalue=[]))

rawDescription: Python creating tuple groups in list from another list


code:
def doStuff():
    returnDeferred = defer.Deferred()
    def gotNextResult(nextResult):
        returnDeferred.callback(nextResult / 10)
    def gotResult(result):
        takesTenSeconds(result * 10).addCallback(gotNextResult)
    takesTwoSeconds().addCallback(gotResult)
    return returnDeferred

rawDescription: python generator "send" function purpose?

description: Python generator "send" function purpose


code:
df = pd.read_csv('data.txt', index_col=0, delim_whitespace=True, header=None)
df2 = pd.DataFrame({'attributes': list(df.values)}, index=df.index)

rawDescription: How to read part of the line into array with python-pandas?

description: Read part of the line into array with python-pandas


code:
result['list_string'] = ', '.join(['i._name' % i._id\
         for i in objects])
return result

rawDescription: Build list of links using Jinja2

description: Build list of links using Jinja2


rawDescription: How to find the numbers in between the numbers that the user has input?

description: Find the numbers in between the numbers that the user has input


code: b, c, d = [a.copy() for _ in range(3)]

rawDescription: Create multiple unique copies of an array


code:
import numpy as np
import pandas as pd

bom2 = pd.DataFrame(
    [
        ['A', 'F'],
        ['AF', 'F'],

        ['AF2', 'F'],
        ['A', 'AF2'],

        ['A', 'AF'],
        ['A2', 'AF'],

    ], columns=['ASS', 'FIN'])

print(bom2)
#    ASS  FIN
# 0    A    F
# 1   AF    F
# 2  AF2    F
# 3    A  AF2
# 4    A   AF
# 5   A2   AF

rawDescription: Pandas boolean indexing vs comparision of two lists: Same (?) methods, different results


code:
list_of_items
import numpy
1.2738 * numpy.array(list_of_items)

rawDescription: Matrix scalar multiplication

description: Matrix scalar multiplication


code:
stats.hypergeom.ppf([0, 1], 20, 15, 10)
stats.hypergeom.a, stats.hypergeom.b
stats.hypergeom(20, 16, 10).dist.a, stats.hypergeom(20, 16, 10).dist.b
stats.hypergeom(20, 16, 10).ppf(0)
stats.hypergeom(20, 16, 10).dist.a, stats.hypergeom(20, 16, 10).dist.b

rawDescription: Given a "frozen" SciPy discrete random variable, how can I know its support?


rawDescription: Printing text once sprite meets position


code:
from collections import Counter
from nltk import FreqDist, word_tokenize

with open('myfile.txt', 'r') as fin:
    # Using Counter.
    x = Counter(word_tokenize(fin.read()))
    uniq = x.keys()
    # Using FreqDist
    x = Counter(word_tokenize(fin.read()))
    uniq = x.keys()
    # Using Set
    uniq = set(word_tokenize(fin.read()))

rawDescription: How to quickly get the collection of words in a corpus (with nltk)?

description: Quickly get the collection of words in a corpus (with nltk)


code: g = df.groupby((df.Time.diff() > 2).cumsum())

rawDescription: Pandas to form clusters based on diff column


code:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Compiler.Main import default_options
default_options['emit_linenums'] = True
from Cython.Distutils import build_ext

ext_modules = [ Extension("warn", ["warn.pyx"]) ]

setup(
        name = "warn",
        cmdclass = {"build_ext": build_ext},
        ext_modules = ext_modules
)

rawDescription: Emitting Cythonic warnings?

description: Emitting Cythonic warnings


rawDescription: Python bank game won't go back up

description: Python bank game won't go back up


rawDescription: dividing floating points into buckets

description: Dividing floating points into buckets


code: re.findall(r'((.)\2+)', strin)

rawDescription: Find all countinuous repeating characters using a simpler solution or preferably a regex


code: gedit .config/autostart/auto.desktop

rawDescription: how to create auto run file using python on ubuntu?

description: Create auto run file using python on ubuntu


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

# Evil!!
colors.colorConverter.to_rgb = lambda x: tuple(np.random.random(3))

plt.plot(range(10), color='pink')
plt.show()

rawDescription: Modifying the built-in colors of matplotlib


code:
chart.add_series({
    'categories': '=Sheet1!$A$1:$A$5',
    'values':     '=Sheet1!$B$1:$B$5',
    'line':       {'color': 'red'},
})

# Or using a list of values instead of category/value formulas:
#     [sheetname, first_row, first_col, last_row, last_col]
chart.add_series({
    'categories': ['Sheet1', 0, 0, 4, 0],
    'values':     ['Sheet1', 0, 1, 4, 1],
    'line':       {'color': 'red'},
})

rawDescription: Pass string in add_series in xlsxwriter

description: Pass string in add_series in xlsxwriter


code:
import inspect

def get_user_attributes(cls):
    boring = dir(type('dummy', (object,), {}))
    return [item
            for item in inspect.getmembers(cls)
            if item[0] not in boring]

rawDescription: Inspect python class attributes

description: Inspect python class attributes


rawDescription: How to conditionally delete elements from list-of-tuples?

description: Conditionally delete elements from list-of-tuples


code:
import order
o = order.foo()

rawDescription: python MySQL module class file name

description: Python MySQL module class file name


code:
tweet_list = []
for id in idList:
    tweet = api.get_status(id)
    tweet_list.append(tweet)

rawDescription: Downloading Full JSON data from Tweets Using Rest API and Tweepy, Querying by Tweet ID


code:
def CoolWordScramble(string, factor = .5):
    if len(string) < 2:
        return string
    first, string, last = string[0], string[1:-1], string[-1]

    return first + shuffle(string, factor) + last

rawDescription: How can I scramble a word with a factor?

description: Scramble a word with a factor


code:
def simpledist(speclist,totalbugs,a):
    data = [float(spec.pop)/float(totalbugs) for spec in speclist]
    p.clf()
    p.hist(data)
    p.savefig('/Home/s1215235/Documents/python/newfolder/' + str(a) + '.png')

rawDescription: Stop pylab overlaying plots?

description: Stop pylab overlaying plots


rawDescription: Match and index all substrings, including overlapping ones


code:
def tap(x, f):
    f(x)
    return x

rawDescription: Ruby's tap idiom in Python

description: Ruby's tap idiom in Python


code: uri = resolve(entry_obj, 'media$group', 'media$content', 0, 'url')

rawDescription: Concise replacement for long list of Try-Except statement in Python?


code: distribution = Counter(counts[v] for v in set(test))

rawDescription: Python loop improvements

description: Python loop improvements


rawDescription: Filling missing values pandas dataframe

description: Filling missing values pandas dataframe


code: namelist.write("\n".join("KPLR%09i-2009131105131"%int(line.split()[0]) for line in file_P))

rawDescription: Looping a write command to output many different indices from a list seperately in Python


code:
def convertType(value):
   if value.strip().isdigit():
       return int(value)
   try:
       return float(value)
   except:
       pass
   return value

rawDescription: Python - Assign a type to a value in a dictionary


code:
import sys;sys.version
print()

rawDescription: python IDLE vs Mac Terminal print statement

description: Python IDLE vs Mac Terminal print statement


code: difflib.get_close_matches('F00', ['FOO', 'BAR', 'BAZ'], cutoff=0.3)

rawDescription: Comparing strings in python to find errors


code:
data = sqlContext.createDataFrame([("Alberto", 2), ("Dakota", 2)],
                                  ["Name", "askdaosdka"])
data.show()
data.printSchema()

# Output
#+-------+----------+
#|   Name|askdaosdka|
#+-------+----------+
#|Alberto|         2|
#| Dakota|         2|
#+-------+----------+

#root
# |-- Name: string (nullable = true)
# |-- askdaosdka: long (nullable = true)

df = data.selectExpr("Name as name", "askdaosdka as age")
df.show()
df.printSchema()

# Output
#+-------+---+
#|   name|age|
#+-------+---+
#|Alberto|  2|
#| Dakota|  2|
#+-------+---+

#root
# |-- name: string (nullable = true)
# |-- age: long (nullable = true)

rawDescription: How to change dataframe column names in pyspark?

description: Change dataframe column names in pyspark


rawDescription: Python library for creating tree graphs out of nested Python objects (dicts)


code:
responce = {
    'knight': foo.knight,
    'bunny': foo.bunny,
    'pesant': foo.pesant,
    'dingo': foo.dingo,
}

rawDescription: Long elif chains vs dictionary with exec()


code: sorted(a, key=lambda L: L[1], reverse=True)

rawDescription: Ordering a multidimensional array in python


code:
with open(infilepath) as infile:
  answer = {}
  name = None
  for line in infile:
    line = line.strip()
    if line.startswith("NGC"):
      name = line
      answer[name] = {}
    else:
      var, val = line.split(':', 1)
      answer[name][var.strip()] = val.strip()

answer

rawDescription: Opening a text file and then storing the contents into a nested dictionary in python 2.7


code:
dct['wassup']['termfreq']
# 'daily'

rawDescription: positional index using python

description: Positional index using python


rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


code: ts = ts.interpolate(method='time')

rawDescription: Python pandas time series interpolation and regularization


code: filter (lambda i: i >=0, some_list)

rawDescription: Screening out negatives before taking average


code:
#!/usr/bin/env python3
import multiprocessing, multiprocessing.pool, time, random, sys
from PySide.QtCore import *
from PySide.QtGui import *

def compute(num_row):
    print("worker started at %d" % num_row)
    random_number = random.randint(1, 10)
    for second in range(random_number):
        progress = float(second) / float(random_number) * 100
        compute.queue.put((num_row, progress,))
        time.sleep(1)
    compute.queue.put((num_row, 100))

def pool_init(queue):
    # see http://stackoverflow.com/a/3843313/852994
    compute.queue = queue

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.toolBar = self.addToolBar("Toolbar")
        self.toolBar.addAction(QAction('Add Task', self, triggered=self.addTask))
        self.table = QTableWidget()
        self.table.verticalHeader().hide()
        self.table.setColumnCount(2)
        self.setCentralWidget(self.table)

        # Pool of Background Processes
        self.queue = multiprocessing.Queue()
        self.pool = multiprocessing.Pool(processes=4, initializer=pool_init, initargs=(self.queue,))

        # Check for progress periodically
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateProgress)
        self.timer.start(2000)

    def addTask(self):
        num_row = self.table.rowCount()
        self.pool.apply_async(func=compute, args=(num_row,))
        label = QLabel("Queued")
        bar = QProgressBar()
        bar.setValue(0)
        self.table.setRowCount(num_row + 1)
        self.table.setCellWidget(num_row, 0, label)
        self.table.setCellWidget(num_row, 1, bar)

    def updateProgress(self):
        if self.queue.empty(): return
        num_row, progress = self.queue.get() # unpack
        print("received progress of %s at %s" % (progress, num_row))
        label = self.table.cellWidget(num_row, 0)
        bar = self.table.cellWidget(num_row, 1)
        bar.setValue(progress)
        if progress == 100:
            label.setText('Finished')
        elif label.text() == 'Queued':
            label.setText('Downloading')
        self.updateProgress() # recursion

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

rawDescription: multiprocessing GUI schemas to combat the "Not Responding" blocking

description: Multiprocessing GUI schemas to combat the "Not Responding" blocking


rawDescription: Python - Perform an operation on an element of a tuple


code:
import itertools as IT
import networkx as nx

l1 = [{'fruit':'apple','category':'A'},{'fruit':'banana','category':'B'}]
l2 = [{'type':'new','category':'A'},{'type':'old','category':'B'}]
l3 = [{'order':'1','type':'new'},{'order':'2','type':'old'}]

data = [l1, l2, l3]
G = nx.Graph()
for dct in IT.chain.from_iterable(data):
    items = list(dct.items())
    node1 = node1[0]
    for node2 in items:
        G.add_edge(node1, node22)

for cc in nx.connected_component_subgraphs(G):
    print(dict(IT.chain.from_iterable(cc.edges())))

rawDescription: How to merge multiple dictionaries from separate lists if they share any key-value pairs?

description: Merge multiple dictionaries from separate lists if they share any key-value pairs


rawDescription: scrapy with newline characters and nested tags

description: Scrapy with newline characters and nested tags


rawDescription: Using keyframe() to display nested dictionary info using Python in Maya


rawDescription: Unsure how/where to manipulate Django objects


code: myNode = xmlDoc.find('node2/myNode')

rawDescription: Choosing a specific XML node using lxml in Python


code:
input_set = {'1438789225', '1438789230'}
output_dict = {item:val for val,item in enumerate(input_set)}

rawDescription: how to convert a set in python into a dictionary

description: Convert a set in python into a dictionary


code: np.einsum('ijk,jk->ik', Q, v)

rawDescription: How to generalize elementwise matrix operations in numpy

description: Generalize elementwise matrix operations in numpy


code:
result = ['Addres_4','Extra info','Mr T. Jamal(Name)','Related info']
result = ['Addres_4','Extra info','T. Jamal(Name)','Related info']

rawDescription: Arranging the string of a list in a required format in python


code:
def method(self, name='Thomas', age=27):
  self.submethod(name, age=age)

rawDescription: python - get attribute to subclass

description: Python - get attribute to subclass


code:
import csv

with open('test.txt', 'rb') as infh:
    reader = csv.reader(infh, delimiter='\t')
    data = [(row[0], set(row[2].split(','))) for row in reader]

rawDescription: Creating iterators with counting intersection


code:
def stream(nxt, safe, prod, cons, state, inputs):
    while True:
        x = next(inputs)   # obtain x
        # xs = inputs
        y = nxt(state)
        if safe(state, y):
            yield y
            inputs = it.chain([x], inputs)   # put x back in the input
            state = prod(state, y)
        else:
            state = cons(state, x)

rawDescription: Convert a Haskell code to Python or pseudocode


code:
from sqlalchemy import (
    create_engine, Column, Integer, String,
    CheckConstraint, UniqueConstraint, ForeignKeyConstraint
)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exc import IntegrityError

Base = declarative_base(metadata=metadata)

class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)
    type = Column(String, nullable=False)
    name = Column(String, nullable=False)

    __mapper_args__ = {'polymorphic_on': type}
    __table_args__ = (UniqueConstraint('id', 'name'),)

class Child(Parent):
    __tablename__ = 'child'

    id = Column(Integer, primary_key=True)
    parent_name = Column(String, nullable=False)
    child_name = Column(String, nullable=False)

    __mapper_args__ = {'polymorphic_identity': 'child'}
    __table_args__ = (
        ForeignKeyConstraint(
            ['id', 'parent_name'], ['parent.id', 'parent.name'],
            onupdate='CASCADE', ondelete='CASCADE'
        ),
        CheckConstraint('parent_name != child_name'),
    )

engine = create_engine(...)
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine, autocommit=True)()

print('Works without error:')
print('--------------------')

with session.begin():
    session.add(Child(name='a', child_name='b'))

print(session.query(Child).one().__dict__)

with session.begin():
    child = session.query(Child).one()
    child.name = 'c'

print(session.query(Child).one().__dict__)

print('\nFails due to IntegerityError:')
print('-------------------------------')
try:
    with session.begin():
        session.add(Child(name='a', child_name='a'))
except IntegrityError as e:
    print(e.orig)
    print(e.statement)

rawDescription: How can I define a constraint on an inherited column in SQLAlchemy?

description: Define a constraint on an inherited column in SQLAlchemy


rawDescription: Regex expression to take text in double quotations except when ending with specifc word


code:
def compress(string):

    res = ""

    count = 1

    #Add in first character
    res += string[0]

    #Iterate through loop, skipping last one
    for i in range(len(string)-1):
        if(string[i] == string[i+1]):
            count+=1
        else:
            if(count > 1):
                #Ignore if no repeats
                res += str(count)
            res += string[i+1]
            count = 1
    #print last one
    if(count > 1):
        res += str(count)
    return res

rawDescription: Create a compress function in Python?

description: Create a compress function in Python


rawDescription: pandas selects a set of columns from a dataframe

description: Pandas selects a set of columns from a dataframe


code:
x = [1,2,3]
y = x         #this simply creates a new referece to the same list object
y is x
y.append(4)  # appending to y, will affect x as well
x,y
x = [1,2,3]
y = list(x)                #y is a shallow copy of x
x is y
y.append(4)                #appending to y won't affect x and vice-versa
x,y

rawDescription: Python list([]) and []

description: Python list([]) and []


code:
dfna.loc[:, numeric_cols] = \
    dfna[numeric_cols].apply(lambda col: col.fillna(col.mean()))

dfna.loc[:, nonnumeric_cols] = \
    dfna[nonnumeric_cols].apply(lambda col: col.fillna(col.value_counts().head(1).index[0]))

rawDescription: Pandas fill np.nan issue

description: Pandas fill np.nan issue


rawDescription: In the context of a buildbot master.cfg file, how do I instantiate a class based on a string using native modules


code:
a = [('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88)]
sorted(a,key=lambda x: x[1])

rawDescription: unsupported operand type(s) for +: 'int' and 'tuple'

description: Unsupported operand type(s) for +: 'int' and 'tuple'


code: func(foo = 'bar')

rawDescription: Python Basics: How can i set two function parameters in equations?


code: match('(?:(.*?), ){2}', 'some string, another string, ').groups()

rawDescription: python regex: capture parts of multiple strings that contain spaces

description: Python regex: capture parts of multiple strings that contain spaces


rawDescription: Python for loop overwriting

description: Python for loop overwriting


code: server = UnixHTTPServer("/tmp/http.socket", ...)

rawDescription: Setting up an HTTP server that listens over a file-socket


code: method = Class2.method

rawDescription: Is it possible to do partial inheritance with Python?


rawDescription: Problems printing weight in a NetworkX graph


code:
from string import Template

template = Template('''\
URL GOTO=https://www.url.com/$user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27''')

with open('users.txt') as file:
    for line in file:
        print(template.substitute({'user1': line.strip()}))

rawDescription: Print from txt file

description: Print from txt file


code:
dictionary = {u"Hello" : u"你好"}
for key,value in dictionary.iteritems():
    print(u'{k} --> {v}'.format(k=key,v=value))

rawDescription: Using Chinese to build a dictionary in Python


code:
x=cat
if len(BestX) > 0 or (starcount) > 0:
  x=dog

rawDescription: If conditions are met define variable as _____


code:
from pprint import PrettyPrinter, _recursion

class MyPrettyPrinter(PrettyPrinter):
    def format(self, object, context, maxlevels, level):
        if isinstance(object, OrderedDict):
            if not object:
                return "()", True, False

            objid = id(object)
            if maxlevels and level >= maxlevels:
                return "(...)", False, objid in context
            if objid in context:
                return _recursion(object), False, True
            context[objid] = 1
            readable = True
            recursive = False
            components = []
            append = components.append
            level += 1
            selfformat = self.format
            for k, v in sorted(object.items()):
                krepr, kreadable, krecur = selfformat(k, context, maxlevels, level)
                vrepr, vreadable, vrecur = selfformat(v, context, maxlevels, level)
                append('({}, {})'.format(krepr, vrepr))
                readable = readable and kreadable and vreadable
                if krecur or vrecur:
                    recursive = True
            del context[objid]
            return '({})'.format(', '.join(components)), readable, recursive

        formatted, readable, recursion = PrettyPrinter.format(self, object, context, maxlevels, level)
        if isinstance(object, unicode):
            formatted = formatted.lstrip('u')

        return formatted, readable, recursion

rawDescription: Using pprint and skipping the types name


code:
['red', 'blue', 'green', 'yellow', 'white']
["red", "blue", "green", "yellow", "white"]
['red', 'blue', 'green', 'yellow', 'white', 'orange']
['red', 'blue', 'green', 'yellow', 'white', 'orange']
['red', 'blue', 'green', 'yellow', 'white']
['red', 'blue', 'green', 'yellow', 'white']

rawDescription: Python 2.7 - add and remove items from a list in a text file


code:
groups_of_dates = Grouper.groupby(list_of_dates,
                    relation= Grouper.AND(Grouper.time_delta(hours = 3),
                               Grouper.difference(3,attr="loc")),
                    as_iterable=False)

rawDescription: How to find two close events (that have a datetime component) in python

description: Find two close events (that have a datetime component) in python


code:
s
pd.DataFrame(s.sum())
s.sum()

rawDescription: Filling a dataframe with high speed

description: Filling a dataframe with high speed


code:
import re
res = [re.split(r'[(==)(>=)]', x)[0].strip() for x in re.split('[&($#$)]', whereFields)]

rawDescription: find the field names from a search query

description: Find the field names from a search query


rawDescription: Sending http headers with python

description: Sending http headers with python


code:
gs = df.groupby(["USER_ID", "CONTRACT_REF"])["SUBMISSION_DATE"]
gs

rawDescription: How to calculate difference on previous within set of grouped rows in a dataframe

description: Calculate difference on previous within set of grouped rows in a dataframe


code:
def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

rawDescription: Pythonic solution to drop N values from an iterator


rawDescription: Getting the maximum value from dictionary


code:
def replace(t, a, b):
    # Flatten the list
    t = [elem for sub in t for elem in sub]
    replaced = []
    # Iterate the elements of the flattened list
    # Let the elements that do not match a in and replace the ones that
    # do not match with the elements of b
    for elem in t:
        if elem == a:  # this element matches, replace with b
            replaced.extend(b)
        else:          # this element does not, add it
            replaced.append(elem)
    # break up the replaced, flattened list with groups of 2 elements
    return [replaced[x:x+2] for x in range(len(replaced)-1)]

rawDescription: Digram list manipulation with Python

description: Digram list manipulation with Python


code:
indices = np.unique(np.random.randint(2e8,size=(12000,)))
values = np.random.rand(len(indices))

rawDescription: Efficiently take moving average of sparse data and filter above threshold in python


code:
from django.db.models import Q

qname = Q()
for i in lst:
    qname &= Q(name__contains=i)

qfamily = Q()
for i in lst:
    qfamily &= Q(family__contains=i)

queryset = Data.objects.filter(qname | qfamily)

rawDescription: How to perform AND condition in django queryset?

description: Perform AND condition in django queryset


rawDescription: Read a term-document matrix from csv using python


code:
import json
list_of_strings = ['a','b','c']
json_array = json.dumps(list_of_strings)
"function findTexts(%s){//code here}" % json_array

rawDescription: Splinter: How to pass argument to execute_script?


code: b = [].append(1)

rawDescription: Unexpected behavior with list.append

description: Unexpected behavior with list.append


code:
data = np.zeros((256, 256, 256), dtype=np.int)
data[temp['X'], temp['Y'], temp['Z']] = temp['intensity']

rawDescription: create np array index from 3 seperate columns of a pd dataframe

description: Create np array index from 3 seperate columns of a pd dataframe


rawDescription: Reading a string of data (with a particular format) into a list, in Python


rawDescription: reindex pandas MultiIndex on specific level

description: Reindex pandas MultiIndex on specific level


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

rawDescription: Alternative way to split a list into groups of n


code: d.isoweekday() % 7

rawDescription: Python retreive DayOfWeek as integer

description: Python retreive DayOfWeek as integer


rawDescription: how to delete empty dict inside list of dictionary?

description: Delete empty dict inside list of dictionary


code: [x for x in dir(ns) if not (x.startswith('__') and x.endswith('__'))]

rawDescription: How to get all user defined attributes in types.SimpleNamespace type?

description: Get all user defined attributes in types.SimpleNamespace type


code:
@login_required
def search_incidents_query(request):
    form = IncidentSearchForm(request.GET or None)
    incident_list = None
    if 'equipment' in request.GET or 'incident' in request.GET:
         incident_list = None  # Or maybe Incident.objects.none()
         if form.is_valid():
            incident_list = form.search()

    return render(request, 'search_incidents_query.html', {'form' : form})

rawDescription: Django form for querying database. Is form.py needed and how to leave fields empty for query?


code:
def findMarkup(str, mainlist):
    markup = re.search('<([^>]*)>', str)
    if markup:
        markup_content = markup.group(1)
        begin = markup.end()
        name = markup_content.split(' ')[0]
        #we check if the markup ends itself
        if markup_content.find('/')!=-1:
            end = begin+1
        else:
            end = str.find('</{0}>'.format(name))
        if begin+1<end:
            #the node has child, its content is theirs
            inner_value = []
            findMarkup(str[begin:end], inner_value)
        else:
            #the content of the current node is its attributes
            inner_value = getAttr(markup_content)
        #we add the content of the current node
        mainlist.append({name:inner_value})

    #we iterate on the rest of the string for same level markups
    findMarkup(str[end+2:],mainlist)

def getAttr(markup_content):
    attr_list = re.finditer('(\w*)="(\w*)"', markup_content)
    attr_dict = dict()
    for attr in attr_list:
        attr_dict[attr.group(1)] = attr.group(2)
    return attr_dict

rawDescription: Parsing XML file to Python list of dictionaries


code:
from Bio.PDB import *
parser = PDBParser()
structure = parser.get_structure('1IAH', '1iah.pdb')
print(structure.header['name'])

rawDescription: Biopython: How to get the compound name of the pdb file of a protein?


code:
def foo(bar):
    return bar

rawDescription: Can a function in python behave like a class?


code:
class Setting(models.Model):
    domain = models.ForeignKey(Domain)
    name = models.CharField(null=False, max_length=255)
    value = models.CharField(null=False, max_length=255)

    objects = SettingManager()

rawDescription: Returning a custom model instance from a manager


rawDescription: rearranging list based on order of another list in python

description: Rearranging list based on order of another list in python


code:
resp = Response(json.dumps({'data': stories}, default=json_util.default),
                mimetype='application/json')

rawDescription: PyMongo and Flask's Jsonify contains escape slashes


rawDescription: Deleting the first item of every element in a string in Python


code:
mylist = []
for i in range(random_number):
    mylist.append(Item(1,2,3))

rawDescription: Creating a random number of class objects in python


code: dict(key1, set()).add(Entry(t, a, c))

rawDescription: Python: how to work with list to have unique values


code:
c = '\u00B2'
c.isdecimal()
c.isdigit()

rawDescription: str.isdecimal() and str.isdigit() difference example

description: Str.isdecimal() and str.isdigit() difference example


code:
sumVal = tz.normalize(sumVal)
print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 2, 30, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)

rawDescription: Python DST & Time Zone Detection After Addition


code:
{u'PalletPosition': u'sample', u'HolderJob': u'sample', u'RunNumber': u'sample', u'ProcessToolName': u'sample', u'RecipeName': u'sample', u'IsControl': u'sample', u'PalletName': u'sample', u'LoadPosition': u'sample', u'MeasurementType': u'sample', u'Holder': u'sample', u'IsSPC': u'sample'}
{u'PalletPosition': u'sample', u'HolderJob': u'sample', u'RunNumber': u'sample', u'ProcessToolName': u'sample', u'RecipeName': u'sample', u'IsControl': u'sample', u'PalletName': u'sample', u'LoadPosition': u'sample', u'MeasurementType': u'XRF', u'Holder': u'sample', u'IsSPC': u'sample'}

rawDescription: parsing nested xml in python

description: Parsing nested xml in python


code:
def invnorm (x):
    return math.exp(-x)

rawDescription: Normalizing a random unending unknown series?


code:
b.py
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)

def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
    if isinstance(s, bool): # make boolean into a 0/1 value
            if s:
                result = 1
            else:
                result = 0
    elif isinstance(s, NumberTypes): # keep numbers as/is
        result = s
    else: # convert a string
        # prepare the string for conversion
        if currency_sign:
            s = s.replace(currency_sign, '')
        if thousand_sep:
            s = s.replace(thousand_sep, '')
        if decimal_sep != '.':
            s = s.replace(decimal_sep, '.')
        s = s.strip()
        # convert the string
        if not s: # if the string is empty, it's not a number
            result = None
        else:
            try: # try int
                result = int(s)
            except ValueError:
                try: # if there's an error, try float
                    result = float(s)
                except ValueError:
                    # if the conversion gave an error, the string is not a number
                    result = None
    return result

rawDescription: Fastest and/or most pythonic way to convert string into a number


code:
class SuperClass():
    def print_hello(self):
        print('Hello, world!')
class WrapperClass():
    pass
wrapper = WrapperClass()
setattr(wrapper, 'clarence', SuperClass())
wrapper.clarence.print_hello()

rawDescription: Instantiate a class to an unknown variable name in python3


rawDescription: Replace a value based on specific criteria


code:
import itertools

replacements = [
['pulka', 'butter kp', 'wheat parota', 'chapati', 'gobi parota', 'onion parota', 'paneer parota', 'kerala parota', 'aloo parota', 'plain naan', 'butter naan', 'garlic naan', 'plain kulcha', 'butter kulcha', 'lacha parota', 'tandoori roti', 'tandoori butter roti', 'roti'],
['paneer butter masala', 'palak paneer', 'kadai paneer', 'hydrabadi paneer', 'kadai gobi', 'aloo gobi', 'aloo mattar', 'mix veg curry', 'baby corn masala', 'dal fry', 'palak dal', 'dal tadka', 'mushroom masala', 'gobi masala', 'paneer tikka masala', 'mushroom tikka masala', 'aloo gobhi']
]

all_combos = itertools.product(*replacements)

all_sentences = ['Can I have some {} and {}?'.format(*combo) for combo in all_combos]

rawDescription: Python multiple string replacement

description: Python multiple string replacement


code:
import datetime
now = datetime.datetime.now()
year = now.year
datestring = "9:09am Jan 23 " + year
dt = datetime.datetime.strptime(datestring, "%H:%M%p %b %d %Y")

rawDescription: Converting string to datetime then comparing it with datetime.now


code:
def print_tic_tac_toe(horiz_char, vert_char):
    print(('\n'+(horiz_char*5)+'\n').join(vert_char.join(['x']*3) for _ in range(3)))

rawDescription: How To Print Character During Parameter Passing


rawDescription: My output is exactly what is asking but is still incorrect... Why?


rawDescription: Inserting in order to a nested list

description: Inserting in order to a nested list


rawDescription: Filter with Array column with Postgres and SQLAlchemy


rawDescription: Getting a Python Modules Dierctory from Inside Itself


code:
import re
t = "#{king} for a ##{day}, ##{fool} for a #{lifetime}"
re.findall(r'(?<!#)#{([a-z]+)}', t)

rawDescription: Retrieve text inside #{ }

description: Retrieve text inside #{ }


code: db.mytable.datetime_field.represent = lambda value, row: value.strftime("format-here")

rawDescription: Formating date in Web2py Python

description: Formating date in Web2py Python


code:
import pandas as pd
import decimal
D = decimal.Decimal

data = pd.read_csv('data', parse_dates=[[0,1]], infer_datetime_format=True)

for col in ('active_accounts', 'transaction_count'):
    data[col] = data[col].str.replace(r',', '').astype(int)

data['transaction_amount'] = (data['transaction_amount']
                              .str.replace(r'[^-+\d.]', '').astype(D))

print(data.dtypes)
# date_begin_date_end    object
# name                   object
# name_code               int64
# active_accounts         int64
# transaction_amount     object
# transaction_count       int64
# dtype: object

print(data)

rawDescription: Importing financial data into Python Pandas using read_csv


rawDescription: Non-ASCII attribute values in ElementTree


code: number = filter(str.isdigit, filename)

rawDescription: How do I find one number in a string in Python?

description: Find one number in a string in Python


code:
import copy
B = copy.deepcopy(A[0])

rawDescription: Deleting elements in a given list only?

description: Deleting elements in a given list only


code:
b = []
for x in j:
    inner = []
    for y in k:
        c = [h for h in x if h in y]
        inner.append(c)
    b.append(inner)
b

rawDescription: Create a list of items after every iteration in python


code:
import pytz
import datetime as DT

NOW = DT.datetime.now()
ZERO = DT.timedelta(0)

for tname in pytz.common_timezones:
    tzone = pytz.timezone(tname)
    std_date = None
    try:
        for utcdate, info in zip(
                tzone._utc_transition_times, tzone._transition_info):
            utcoffset, dstoffset, tzname = info
            if dstoffset == ZERO:
                std_date = utcdate
            if utcdate > NOW:
                break
    except AttributeError:
        std_date = NOW
    std_date = tzone.localize(std_date)
    print('{n} UTC{z}'.format(n=tname, z=std_date.strftime('%z')))

rawDescription: STD offset for pytz timezones

description: STD offset for pytz timezones


code:
vector_a = input_one.split()
vector_b = input_two.split()

rawDescription: Append input to list as integers

description: Append input to list as integers


code:
timeit.timeit('from __main__ import pad_list as f; f([[ 1, 2, 3], [2], [2, 4]])', number = 10000)
timeit.timeit('from __main__ import apply_to_zeros as f; f([[ 1, 2, 3], [2], [2, 4]])', number = 10000)

rawDescription: zero padding numpy array

description: Zero padding numpy array


code:
{{ sc.name }}
{{ sc.id }}

rawDescription: Displaying dictionary value in django template


code:
choice = input()
if choice == "Yes" or choice == "Sure" or choice == "Yep":
    print("You chose yes")

elif choice == "No" or choice == "Nah" or choice == "Nope":
    print("You chose no")

rawDescription: How can I make the if statement contain more than one item?

description: Make the if statement contain more than one item


rawDescription: Summing a 1D array with a col of a 2D array


code: ['First', 'First2']

rawDescription: How to extract non-uppercase string elements for first and last names?

description: Extract non-uppercase string elements for first and last names


code:
nodes.extend(thelist)
nodes

rawDescription: A Pythonic way to insert elements of a list into a list of lists?


code:
def lookup2(s):
    '''uses .map() to apply changes'''
    dates = {date:pd.to_datetime(date) - pd.Timedelta('11 hours') for date in s.unique()}
    return s.map(dates)

rawDescription: Arithmetic on array of timestamps without year, month, day


code:
from collections import defaultdict

a = defaultdict(list)
a[ID1].append(10)
a[ID2].append(10)

id, val = (ID2, 13)
a[id].append(val)
if len(a[id]) > 2:
    a[id].pop(0)

def count(a, id):
    return len(a[id])

rawDescription: python list, working with multiple elements

description: Python list, working with multiple elements


code:
def my_factory():
    aDict = {'counter': Counter(), 'name':''}
    return aDict
d = defaultdict(my_factory)

rawDescription: How to use a specific data structure as the default_factory for a defaultdict?

description: Use a specific data structure as the default_factory for a defaultdict


code:
root = Tk()
root.wm_title("Main")
ttk.Button(root, text="Add new student").grid(row = 0, column = 0)
ttk.Button(root, text="Edit Student").grid(row = 0, column = 1)
ttk.Button(root, text="Edit Student").grid(row = 0, column = 2)

columns = ['ID', 'First Name', 'Last Name', 'Registration No']
rows = server.select("Student")

# create an instance of the TableView widget
tableview = TableView(root, columns, rows)

# ... and add it to the root window
tableview.grid(row=1, column=0, columnspan=3)

root.mainloop()

rawDescription: Making a class a widget - Tkinter

description: Making a class a widget - Tkinter


code:
sents = nltk.sent_tokenize(text)
for s in sents:
    pre, _, post = text.partition(s)
    if "\n" in pre:
        print("\n", end="")
    process_sent(s)
    text = post  # Advance to the next sentence -- munges `text` so use another var if it matters.

if "\n" in post:
    print("\n", end="")

rawDescription: Map line breaks in sentence to another list


rawDescription: in Numpy, how to zip two 2-D arrays?

description: In Numpy, how to zip two 2-D arrays


code: import win32com.client

rawDescription: .doc to pdf using python

description: .doc to pdf using python


code:
def info(self, request, pk=None):
    if pk:
        obj = SomeClass.objects.get(pk=pk)
        return Response({'info': obj.info()})
    else:
        objs = SomeClass.objects.filter(pk__in=request.GET.getlist('pk'))
        return Response({'infos': [obj.info() for obj in objs]})

rawDescription: Django Rest Framework add class level method to api


code:
from functools import partial

def execute_function(function_name, arg1, arg2, arg3):
    return {
        'func1': partial(func1, arg1),
        'func2': partial(func2, arg1, arg3),
        'func3': partial(func3, arg2),
    }[function_name]()

rawDescription: Choose which function to execute, based on a parameter - its name - Python3.3


code:
from turtle import Turtle

class SolarElement(Turtle):
    def __init__(self, name, radius, mass, colour, shape='circle'):
        # or Turtle.__init__(self, shape=shape)
        super(SolarElement, self).__init__(shape=shape)
        self.name = name
        self.radius = radius
        self.mass = mass
        self.colour = colour
        self.color(self.colour)
        self.shapesize(self.radius / 50)

class Star(SolarElement):
    def __init__(self, name, radius, mass, colour,
                 shape='circle'):
        SolarElement.__init__(self, name, radius, mass, colour,
                              shape=shape)

class Planet(SolarElement):
    def __init__(self, name, radius, mass, colour, dist, vel_x, vel_y,
                 shape='circle'):
        SolarElement.__init__(self, name, radius, mass, colour,
                              shape=shape)
        self.dist = dist
        self.vel_x = vel_x
        self.vel_y = vel_y
        self.x_pos = sun.radius + self.dist + self.radius
        self.y_pos = 0

sun = Star('myStar', 500.0, 15000.0, "yellow")
earth = Planet('P1', 150.0, 1000.0, "green", 0.25, 0.5, 2.0)

rawDescription: How to use a turtle superclass

description: Use a turtle superclass


code:
#You initialize it:
Time = time.strftime('%H:%M%p')
# Then you overwrite it:
Time = Entry(root, relief = RIDGE, bd = 5, width = 16, cursor = 'plus', fg = 'red', selectforeground = 'red', selectbackground = 'black')

rawDescription: How to INSERT current time in an Entry Widget

description: INSERT current time in an Entry Widget


code:
[x[4] for x in data["interactions"][0]["input"]]

[x[9] for x in data["interactions"][0]["input"]]

rawDescription: Python extract values from JSON

description: Python extract values from JSON


code: myform = MyForm(request.POST, request=request)

rawDescription: How do I access the request object or any other variable in a form's clean() method?

description: Access the request object or any other variable in a form's clean() method


code: low, high = [int(x) for x in lohi.split()]

rawDescription: get raw input that is between a set of numbers with some checks

description: Get raw input that is between a set of numbers with some checks


rawDescription: Python. Remove from array (presented as list of lists) rows and columns by condition


code:
def make_index_list(start, stop):
    lens = stop - start
    cum_lens = np.cumsum(lens)
    # Sequential indices the same length as the expected output
    out = np.arange(cum_lens[-1])
    # Starting index for each section of `out`
    cum_lens = np.concatenate(([0], cum_lens[:-1]))
    # How much each section of `out` is off from the correct value
    deltas = start - out[cum_lens]
    # Apply the correction
    out += np.repeat(deltas, lens)

    return out

rawDescription: Simple Numpy Vectorization

description: Simple Numpy Vectorization


rawDescription: Find which row/sublist a value is in

description: Find which row/sublist a value is in


code:
from collections import Counter, OrderedDict
OrderedDict(sorted((Counter(d1) | Counter(d2) | Counter(d3)).items()))

rawDescription: Python Concatenate N dictionaries with highest values for each key


code: p,ier = leastsq(residuals, k_abn, args=(ph, tp, hl_obs), maxfev=2000000)

rawDescription: SciPy LeastSq Failed to Provide Best Solution


code:
text = "taj mahal is in india"
my_dict = { 'taj mahal':'url1', 'india':'url2' }
for key, value in my_dict.iteritems():
    text = text.replace(key, value)

text

rawDescription: Insert hyperlink into text using django

description: Insert hyperlink into text using django


code:
def count_Trues(b_list):
    i = 0
    ml = []
    prev = False
    for el in b_list:
        if el:
            i += 1
            prev = el
        else:
            if prev is not el:
                ml.append(i)
                i = 0
            prev = el
    if el:
        ml.append(i)
    return m

rawDescription: Count the number of occurrences between markers in a python list


code: regex = re.compile(r"[^\W\d_]", re.UNICODE)

rawDescription: shorthand for [:alpha:] in python regex

description: Shorthand for [:alpha:] in python regex


code:
with open('A', 'r') as f:
    text = f.read()

with open('B', 'w') as f:
    f.write(text)

rawDescription: Write file A to file B in python

description: Write file A to file B in python


code:
class UploadForm(forms.Form):

    file = forms.FileField()

    def process(self):
        file = self.cleaned_data.get('file')
        # do whatever you need here to process the file
        # e.g. data = file.read()

rawDescription: Django upload for processing

description: Django upload for processing


rawDescription: Python: flip a precise bit in a double

description: Python: flip a precise bit in a double


code:
sample.mean()
sample.std()

rawDescription: Initialize a 200 by 785 numpy matrix with values from a Gaussian distribution with mean 0, std. deviation 0.01


rawDescription: Modifying a shared dict object among processes doesn't work


code:
Model_1_Dict = {'key1':Data('value1','value2','value3') }

Model_1_Dict
Model_1_Dict["key1"].beta = "NewValue"
Model_1_Dict

rawDescription: Using namedtuples to consolidate multiple dictionaries


code: label, pixel_1_1, pixel_1_2, ...

rawDescription: Visualize MNIST dataset using OpenCV or Matplotlib/Pyplot


code:
# syntax/Block.py (this file really ought to be lowercase, leave PascalCase to class names)
class Block(object):
    pass

rawDescription: Conveniently import several classes from modules in a Python package


code: {{ var_name|safe }}

rawDescription: Using a flask variable as data source for highcharts


code:
def download_button(self, text):
    irvLang = text

rawDescription: PYQT Qcombobox set value selected to a variable


code: df = pd.concat([df, df.iloc[:2, :]], ignore_index=True)

rawDescription: getting pandas Setting With Enlargement right

description: Getting pandas Setting With Enlargement right


code: MyArray3 = MyArray2[['a','b','c','d']]

rawDescription: Numpy recarray sort of columns and stack


code:
with open('concat_file.txt', "w") as concat_file:
    for my_file in glob.iglob('/Users/me/Desktop/*.txt'):
        shutil.copyfileobj(open(my_file, "r"), concat_file)

rawDescription: Problem with file concatenation in Python?


code:
reduce(set.intersection, [fruit, nature])
reduce(set.intersection, [fruit, nature, green])
reduce(set.intersection, [green, wood, nature])
reduce(set.intersection, [green, wood, nature, tree])

rawDescription: Python: data structure to index sets to find supersets?


code:
class Bar:
    def bar(self):
        return type(self)

rawDescription: Class Function and Static Method at the Same Time? (Python)


code:
s = 'mqRMRsL'
result = ''.join(sorted(s, key=str.lower))
# LmMqRRs

rawDescription: How to alphabetize characters in a string, disregarding upper and lower case?

description: Alphabetize characters in a string, disregarding upper and lower case


code:
def list_gen(n):
    i=0
    while i<n:
        yield i
        i += 1

rawDescription: In Python, When yield cost over the return an list?


code:
import asyncio
import functools
import uuid
from textwrap import dedent

def wrap_coroutine(coro, name_prefix='__' + uuid.uuid4().hex):
    """Like functools.wraps but preserves coroutine names."""
    # attribute __name__ is not writable for a generator, set it dynamically
    namespace = {
        # use name_prefix to avoid an accidental name conflict
        name_prefix + 'coro': coro,
        name_prefix + 'functools': functools,
        name_prefix + 'asyncio': asyncio,
    }
    exec(dedent('''
        def {0}decorator({0}wrapper_coro):
            @{0}functools.wraps({0}coro)
            @{0}asyncio.coroutine
            def {wrapper_name}(*{0}args, **{0}kwargs):
                {0}result = yield from {0}wrapper_coro(*{0}args, **{0}kwargs)
                return {0}result
            return {wrapper_name}
        ''').format(name_prefix, wrapper_name=coro.__name__), namespace)
    return namespace[name_prefix + 'decorator']

rawDescription: How to decorate an asyncio.coroutine to retain its __name__?

description: Decorate an asyncio.coroutine to retain its __name__


code:
_id_to_mathematica = lambda x: str(x)

def _float_to_mathematica(x):
    return ("%e" % x).replace('e', '*10^')

def _complex_to_mathematica(z):
    return 'Complex' + ('[%e,%e]' % (z.real, z.imag)).replace('e', '*10^')

def _str_to_mathematica(s):
    return '\"%s\"' % s

def _iter_to_mathematica(xs):
    s = '{'
    for x in xs:
        s += _python_mathematica[type(x)](x)
        s += ','
    s = s[:-1]
    s += '}'
    return s

_python_mathematica = {bool: _id_to_mathematica,
                       type(None): _id_to_mathematica,
                       int: _id_to_mathematica,
                       float: _float_to_mathematica,
                       long: _id_to_mathematica,
                       complex: _complex_to_mathematica,
                       iter: _iter_to_mathematica,
                       list: _iter_to_mathematica,
                       set: _iter_to_mathematica,
                       xrange: _iter_to_mathematica,
                       str: _str_to_mathematica,
                       tuple: _iter_to_mathematica,
                       frozenset: _iter_to_mathematica}

l = [[1, 2, 3], 1, [1, 5, [7, 3, 7, 8]]]
print(_iter_to_mathematica(l))

rawDescription: Save list of table of numbers from Python into format easily readable by Mathematica?


code:
m = re.search(r'(?s)\bIdaho\n*(?:(?!\n\n).)*?MoreSpuds\s+(\S+)', s)
m.group(1)

rawDescription: Python multiline regex search between sections


code:
from subprocess import Popen, PIPE

fw = open("tmpout", "wb")
fr = open("tmpout", "r")
p = Popen("./a.out", stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)
p.stdin.write("1\n")
out = fr.read()
p.stdin.write("5\n")
out = fr.read()
fw.close()
fr.close()

rawDescription: Interactive input/output using python

description: Interactive input/output using python


code:
@inlineCallbacks
def authorize(self, session, uri, action):
    authid = session._authid
    if authid is None:
        authid = 1
    log.msg("AuthorizeRouter.authorize: {} {} {} {} {}".format(authid,
        session._session_id, uri, IRouter.ACTION_TO_STRING[action], action))
    if authid != 1:
        rv = yield self.check_permission(authid, uri, IRouter.ACTION_TO_STRING[action])
    else:
        rv = yield True

    log.msg("AuthorizeRouter.authorize: rv is {}".format(rv))

    if not uri.startswith(self.svar['topic_base']):
        self.sessiondb.activity(session._session_id, uri, IRouter.ACTION_TO_STRING[action], rv)

    returnValue(rv)

    return

rawDescription: How to limit Autobahn python subscriptions on a per session basis

description: Limit Autobahn python subscriptions on a per session basis


code:
a = "Hello all please help #me "
filter(lambda x:x[0]!='#', a.split())

rawDescription: Python, Remove word start with specific character


code:
df
g = df.groupby(['Province', 'City']).sum().reset_index()
g

rawDescription: pandas: filtering by group size and data value

description: Pandas: filtering by group size and data value


code: unicode_letters = set(unicode_letters)

rawDescription: An equivalent to string.ascii_letters for unicode strings in python 2.x?


code: hex_string = "deadbeef"

rawDescription: hexadecimal string to byte array in python

description: Hexadecimal string to byte array in python


code:
day_indexes = {name:i for i, name in enumerate(calendar.day_name)}
def weekdays_consecutive(days):
    indexes = [day_indexes[d] for d in days]
    expected = range(indexes[0], indexes[-1] + 1)
    return indexes == expected

rawDescription: Python: Converting ('Monday', 'Tuesday', 'Wednesday') to 'Monday to Wednesday'


code:
def event_handle(turn):
    if turn == 1:
        c_s = p1
    elif turn == 2:
        c_s = p2
    else:
        return None
    key = pygame.key.get_pressed()
    # next_pos
    if key[pygame.K_q]:
        c_s.next_x -= 1
    if key[pygame.K_e]:
        c_s.next_x += 1
    # angle
    if key[pygame.K_w]:
        c_s.angle += radians(10)
    if key[pygame.K_s]:
        c_s.angle -= radians(10)
    # power (speed)
    if key[pygame.K_d]:
        c_s.speed += 0.1
    if key[pygame.K_a]:
        c_s.speed -= 0.1

rawDescription: pygame - KEYDOWN event - line not updating position

description: Pygame - KEYDOWN event - line not updating position


code:
def loop_gemm(a, b, c=None, chunksize=100):

    size_i = a.shape[0]
    size_zip = a.shape[1]

    size_j = b.shape[1]
    size_alt_zip = b.shape[0]

    if size_zip != size_alt_zip:
        ValueError("Loop GEMM zip index is not of the same size for both tensors")

    if c is None:
        c = np.zeros((size_i, size_j))

    istart = 0
    for i in range(int(np.ceil(size_i / float(chunksize)))):

        left_slice = slice(istart, istart+chunksize)
        left_view = a[left_slice]

        jstart = 0
        for j in range(int(np.ceil(size_j / float(chunksize)))):

            right_slice = slice(jstart, jstart+chunksize)
            right_view = b[:, right_slice]

            c[left_slice, right_slice] = np.dot(left_view, right_view)
            jstart += chunksize

        istart += chunksize

    return c

rawDescription: numpy dot product in steps

description: Numpy dot product in steps


code: out2 = np.mean(np.mean(out, axis = 0), axis = 0)

rawDescription: Python time-lat-lon array manipulation and grouping


code:
b = sys.intern('why do pangolins dream of quiche')
b

rawDescription: What does python sys.intern do, and when should it be used?


code:
BROKER_TRANSPORT = 'amqp'
BROKER_USER = 'user'
BROKER_PASSWORD = 'password'
BROKER_HOST = 'remote.server.com'
BROKER_PORT = 123
#...

rawDescription: How to pass connection details in Celery

description: Pass connection details in Celery


code:
def highest_strength(graph):
    return max((s, x, y) for x, links in graph.items() for y, s in links.items())

rawDescription: A more pythonic way

description: A more pythonic way


code:
import re

fi = re.finditer(r"\S+", line)
next(fi)
next(fi)
var_needed = next(fi).group()
next(fi)
next(fi)
another_var_needed = next(fi).group()
# we don't care about the last match so we don't ask for it

rawDescription: Prolog singleton variables in Python

description: Prolog singleton variables in Python


rawDescription: subset and transpose python arrays

description: Subset and transpose python arrays


code:
def lcsubstring_length(a, b):
    table = {}
    l = 0
    for i, ca in enumerate(a, 1):
        for j, cb in enumerate(b, 1):
            if ca == cb:
                table[i, j] = table.get((i - 1, j - 1), 0) + 1
                if table[i, j] > l:
                    l = table[i, j]
    return l

rawDescription: Python: Length of longest common subsequence of lists


rawDescription: Script to assign varying numbers to ascii characters


code:
from collections import defaultdict
d = defaultdict(lambda: defaultdict(list))
d['s1']['port1'].append([0, 0, 0])
d['s1']['port1'].append([1, 1, 1])
d['s1']['port2'].append([2, 2, 2])
d

rawDescription: Appending to lists stored in a nested dictionary


code:
def generate_nonce(length=8):
    """Generate pseudorandom number."""
    return ''.join([str(random.randint(0, 9)) for i in range(length)])

rawDescription: What is the standard method for generating a nonce in Python?


code: eval(fnc)(conn_name) # or eval(fnc(conn_name))

rawDescription: Python3: Calling functions saved as values (strings) in a dictionary


code:
import csv
import os

receptors = ['crystal_1', 'modeller_1', 'moe_1',
             'nci5_modeller0000_1', 'nci5_modeller0001_1',
             'nci5_modeller0002_1', 'nci5_modeller0003_1',
             'nci5_modeller0004_1', 'nci5_modeller0005_1',
             'nci5_modeller0006_1', 'nci5_modeller0007_1',
             'nci5_modeller0008_1', 'nci5_modeller0009_1',
             'nci5_modeller0010_1', 'nci5_modeller0011_1',
             'nci5_moe0000_1', 'nci5_moe0001_1', 'nci5_moe0002_1',
             'nci5_moe0003_1', 'nci5_moe0004_1', 'nci5_moe0005_1',
             'nci5_moe0006_1', 'nci5_moe0007_1', 'nci5_moe0008_1',
             'nci5_moe0009_1', 'nci5_moe0010_1', 'nci5_moe0011_1',
             'nci5_moe0012_1', 'nci5_moe0013_1', 'nci5_moe0014_1']

# initialize list of lists holding each ligand and its presence in each receptor
with open('potentiation.txt') as experiment:
    ligands = [[ligand] for ligand in (line.rstrip() for line in experiment)]

for protein in receptors:
    with open(protein + '.txt') as protein_file:
        protein_file_data = protein_file.read()
        for row in ligands:
            # determine if this ligand (row[0]) appears in protein data
            row.append('Found' if row[0] in protein_file_data else 'Not Found')

with open('output.csv', 'wb') as outfile:
    csv_writer = csv.writer(outfile, delimiter='\t')
    csv_writer.writerow(['Ligand'] + receptors)  # header row
    csv_writer.writerows(ligands)

print('output.csv file written')

rawDescription: How can I write output from a for loop in python into a csv-formatted file?

description: Write output from a for loop in python into a csv-formatted file


code:
from itertools import groupby

file_count = 1
with open('INPUT_FILE') as infile:
    for k, lines in groupby(infile, key=lambda line: line.strip() != ''):
        if k:
            with open('output_file_{}.txt'.format(file_count), 'w') as outfile:
                outfile.writelines(lines)
            file_count += 1

rawDescription: Create dynamic text files with data from another CSV file using python


code:
with open('Diccionario.txt', 'r') as input, \
        open('output.txt', 'w') as output:
    for item in input:
        element = driver.find_element_by_id("MainContent_TextBox1")
        element.send_keys(item)

        result = driver.find_element_by_css_selector("table#MainContent_Table1 > tbody > tr > td:nth-of-type(2)").text
        output.write(result)

rawDescription: Sending and Receive data from a web page - Selenium WebDriver API


code:
lines = []
f = open(filename)
for line in f:
    if not line.startswith('com'):
        lines.append(line.strip())

rawDescription: Spliting a file into lines in Python using re.split


code:
B,item_1
A,item_2
D,item_3
C,item_4
G,item_5
F,item_6
E,item_7

rawDescription: Reformat text file to csv that includes two different delimiter in python


code:
df = pandas.DataFrame(dict(row=row, col=col, value=value),
                      columns=['row', 'col', 'value'],
                      copy=False)
df.to_csv('outfile', sep=' ', header=False, index=False)

rawDescription: Speeding up large matrix serialisation in python?


code:
from operator import itemgetter
zip(*sorted(zip(*arr), key = itemgetter(1)))
[('string45', 'string25', 'string3'), (2, 12, 46)]

rawDescription: sorting multidimensional-array in python

description: Sorting multidimensional-array in python


code:
with open("./scriptA_pid.tmp","r") as f:
    scriptA_pid = f.read()
chk_sA = subprocess.Popen(['kill -0 '+str(scriptA_pid)+' > /dev/null 2>&1; echo $?'],stdout=subprocess.PIPE,stderr=devnull,shell=True)
chk_sA.wait()
sA_status = chk_sA.stdout.read()

if int(sA_status) == 0:
    #ScriptA is still running
    pass
else:
    #ScriptA is not running
    sys.exit(0)

rawDescription: Check if second script is running or already finished


code:
if response == 'higher':
    lowBound = randomNumber + 1

rawDescription: PYTHON - Reverse Number Guessing Game -

description: PYTHON - Reverse Number Guessing Game -


code: df.groupby("Date")['Term', 'Month', 's'].apply(lambda rows: np.mean(rows['Term'] + rows['Month'] + rows['s']))

rawDescription: pandas groupby apply function that take N-column frame and returns object

description: Pandas groupby apply function that take N-column frame and returns object


code: print("Enter the rainfall for", '{0:11s}'.format(months[n]+':'), end="")

rawDescription: Python input formatting

description: Python input formatting


rawDescription: What is an efficient way to calculate cost constrained by thresholds


code:
#!/usr/bin/env python
import byteplay, sys, imp, struct, marshal, time
if __name__ == '__main__':
    byteplay.labels = dict([(i, byteplay.Label()) for i in xrange(10000)])
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    asm = sys.stdin.read()
    c = eval(asm, byteplay.__dict__)
    c = byteplay.Code(c, (), (), 0, 0, 0, '', '', 0, '').to_code()
    sys.stdout.write(imp.get_magic())
    sys.stdout.write(struct.pack('<L', time.time()))
    marshal.dump(c, sys.stdout)

rawDescription: How to recompile the Python 2.5 bytecode to 2.7?

description: Recompile the Python 2.5 bytecode to 2.7


code:
shape = (Lmax+1, Lmax+1, maxvalue+1)
posvec = np.arange(1, Lmax+1)

ind_len  = np.tile(Lvec[:,None], [1, Lmax])
ind_pos  = np.tile(posvec,       [n,    1])
ind_val  = data
Y_copied = np.tile(Y[:,None],    [1, Lmax])

mask = posvec <= Lvec[:,None]  # fill-value independent
lin_idx = np.ravel_multi_index((ind_len[mask], ind_pos[mask], ind_val[mask]), shape)
Y_avg = np.bincount(lin_idx, weights=Y_copied[mask], minlength=np.prod(shape)) / n
Y_avg.shape = shape

rawDescription: np.bincount for 1 line, vectorized multidimensional averaging

description: Np.bincount for 1 line, vectorized multidimensional averaging


code:
def compose(f, g):
    def composed(x):
        return f(g(x))
    return composed

rawDescription: testing for equality using itemgetter

description: Testing for equality using itemgetter


code:
['assign (resid 3 and name H ) (resid 18 and name H ) 2.5 2.5 2.5 ! note '
 'string 1',
 'assign (resid 16 and name H ) (resid 5 and name H ) 2.5 2.5 2.5 ! note '
 'string 2',
 'assign (resid 42 and name H ) (resid 55 and name H ) 2.5 2.5 2.5 ! note '
 'string 3',
 'assign (resid 44 and name H ) (resid 53 and name H ) 2.5 2.5 2.5 ! note '
 'string 4 DUPLICATE ! string 5']

rawDescription: Python Find Duplicate with Note String Preservation


rawDescription: Python - Count number of integers in a string?


rawDescription: Store more than 1 value in python array?

description: Store more than 1 value in python array


rawDescription: How to get list of all EBS Snapshots "started" before a certain date?

description: Get list of all EBS Snapshots "started" before a certain date


code: total_img = 255*(min - total_img)/(min - max)

rawDescription: Efficient element-wise multiplication in Python with numpy array


rawDescription: merge items into a list based on index

description: Merge items into a list based on index


code:
global i
i=0
def add_letter():
    global i
    i+=1

rawDescription: tkinter labels in frame using grid

description: Tkinter labels in frame using grid


code:
parts_df = pd.DataFrame(data = [['Type 1', ['A', 'B']], ['Type 2', ['A']], ['Type 1', ['C']]], columns=['Project Type', 'Parts'])
sum(['A' in i for i in parts_df[parts_df['Project Type']=='Type 1']['Parts'].tolist()])

rawDescription: Filtering Pandas dataframe on two criteria where one column is a list