code:
import multiprocessing

class MyClass:
    def __init__(self):
        pass

def example_run(someArbitraryInput):
    foo = [MyClass() for i in range(10000)]
    return foo

if __name__ == '__main__':

    pool = multiprocessing.Pool(processes=5)
    output = pool.map(example_run, range(5))
    pool.close();  pool.join()  # make sure the processes are complete and tidy
    print("Processes completed")

rawDescription: Simple and safe way to wait for a Python Process to complete when using a Queue


code:
@asyncio.coroutine
def make_clients(nb_clients, limit=0):
    futures = FutureSet(maxsize=limit)
    for client_id in range(nb_clients):
        url = WS_CHANNEL_URL.format(client_id=client_id)
        client = WebSocketClient(client_id, url)
        yield from futures.add(client.run())
    yield from futures.wait()

rawDescription: Gradually create async tasks and wait for all of them to complete


rawDescription: Creating my own string functions

description: Creating my own string functions


code:
import logging

handler = logging.handlers.SysLogHandler()
logger = logging.getLogger('myApplication')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

rawDescription: Printing Function Output to Syslog?

description: Printing Function Output to Syslog


rawDescription: Django models queryset with array

description: Django models queryset with array


code:
sys.stdout.write(span.text)
for child in span:
    sys.stdout.write(etree.tostring(child)) # add encoding="unicode" on Python 3

rawDescription: Get the html under a tag using htmlparser python


code:
if self.start == 0.0:
    self.start=time.time()*1000.0

rawDescription: Binding multiple events on Tkinter Entry?


code:
import configparser
from tempfile import TemporaryFile
t = TemporaryFile("w+")
with open("foo.ini") as f:
    t.writelines(line for line in f if not line.startswith("="))
t.seek(0)
par = configparser.ConfigParser()
par.read_file(t)

print(list((par["SESSIONS_id"]).items()))
[('session_a', '{F34B3238-EEE5-4006-B19C-AB8CC233D8F0}'), ('session_b', '{AF2D869B-0FB1-4287-A10E-82B0884E1CFC}'), ('session_c', '{F5A7FA65-2107-4B9B-A7C2-8C89C354D4FF}')]

rawDescription: Reading configfiles with no key but value entries using python configparser


code:
mylistoffiles=[ ] #Somehow generate your list of files to be uploaded.
import multiprocessing
Pool=multiprocessing.Pool(processes=X)   #X is the number of processes you want to use
Pool.map(upload_one,mylistoffiles)

rawDescription: Python FTP Upload Multiple Files at Once


rawDescription: Numpy Indexing - Questions on Odd Behavior/Inconsistencies


code:
JOX = mc.attributeQuery( 'jointOrient', n='L_ShoulderOrient_NODE', le=1 )
mc.joint ('L_Hand_JNT', e=1, oj=mc.getAttr ('L_LowArm_JNT.jot'), sao=JOX[0], zso=1)

rawDescription: How can I query a joints sao (secondary axis world orientation)? Maya Python

description: Query a joints sao (secondary axis world orientation)? Maya Python


code: sumeveryxrows = lambda myarray, x: myarray.reshape((myarray.shape[0] / x, x)).sum(1)

rawDescription: Python numpy: sum every 3 rows (converting monthly to quarterly)


code:
import caffe
solver = caffe.SGDSolver( PATH_TO_SOLVER_PROTOTXT )
net = solver.net

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


code:
import boto.ec2
conn = boto.ec2.connect_to_region('us-west-2')  # or whatever region you want
reservations = conn.get_all_instances()  # could limit results with filters
instances = []
for r in reservations:
    instances.extend(r.instances)

rawDescription: How to get instance ID from reservation ID in boto

description: Get instance ID from reservation ID in boto


rawDescription: Iterate through a dataframe to find number of times a str value appears in an array of tuples


rawDescription: Instantiate two 2D numpy arrays from a list of strings


code:
m2D = measurement[np.arange(N) + np.arange(len(measurement)-N+1)[:,None]]
np.nonzero(np.all((lower_bound < m2D) & (higher_bound > m2D),axis=1))[0][0]

rawDescription: Find range of length N in a numpy array where some condition is satisfied


code:
for point in self.__points:
    x = point.get_x()
    # do something with this x coordinate

rawDescription: Classes in python, get attribute

description: Classes in python, get attribute


rawDescription: how to divide integer and take some part

description: Divide integer and take some part


code: [ a for a in alphastartgen(8) ]

rawDescription: Is there a way to subclass a generator in Python 3?


code:
def eliminate(x, y):
    largest = max(x)
    y[:] = [elem for elem in x if elem != largest]

rawDescription: How to write a function that copies all of the elements of a list except the largest value into another list? Python 3.2

description: Write a function that copies all of the elements of a list except the largest value into another list? Python 3.2


code:
import os, shutil
# lst not list -- naming it list overshadows a builtin
lst = ['cat size', 'house size', 'car size']
# PEP8 - lowercase with underscore here; CamelCase for classes
from_dir = os.path.abspath(os.path.expanduser('~/test'))
copy_dir = os.path.abspath(os.path.expanduser('~/test/copyto'))

to_copy = [f for f in os.listdir(from_dir) if os.path.isfile(f)]
# ['car.size.txt', 'house.size.fromBob.txt', 'cat.size.txt']

for filename in to_copy:
    needle = ' '.join(filename.split('.')[:2])
    if needle in lst:
        dest_dir = os.path.join(copy_dir, needle)
        os.mkdir(dest_dir)
        shutil.copy2(os.path.join(from_dir, filename), dest_dir)

rawDescription: Using python, copy a file to a folder that has almost the same name as the file


code:
import requests
from lxml import etree
response = requests.get(urls[0])
html = etree.HTML(response.text)
text = '\n'.join([el.text for el in html.findall('.//p')])

rawDescription: Python, reading RDF files, scraping Gutenberg books


code: "cat test.txt | grep {}".format(variable)

rawDescription: Variable in subprocess

description: Variable in subprocess


code:
final = [{'name': k, 'total': v} for k, v in res.items()]
print(final)

rawDescription: Getting totals from list of lists and apply it to a dictionary


code: {'John': ['Canada', 'Ottawa'], 'Ron': ['America', 'New York']}

rawDescription: Comparing multiple dictionaries and generating another dictionary using python


code:
import threading

def or_set(self):
    self._set()
    self.changed()

def or_clear(self):
    self._clear()
    self.changed()

def orify(e, changed_callback):
    e._set = e.set
    e._clear = e.clear
    e.changed = changed_callback
    e.set = lambda: or_set(e)
    e.clear = lambda: or_clear(e)

def OrEvent(*events):
    or_event = threading.Event()
    def changed():
        bools = [e.is_set() for e in events]
        if any(bools):
            or_event.set()
        else:
            or_event.clear()
    for e in events:
        orify(e, changed)
    changed()
    return or_event

rawDescription: Python threading: can I sleep on two threading.Event()s simultaneously?


code:
import xml.etree.ElementTree as ET
import csv
with open('test.csv','r') as f:
    cfiles = list(csv.reader(f))
xml = ET.parse('XML.xml')
for row in xml.iterfind('.//Node'):
    name = row.find('./Name').text
    for i in cfiles:
        if i[0] == name:
            j = 1
            while j < len(i):
                if j == 1:
                    g = ET.SubElement(row,'Gate')
                    g.text = i[j]
                elif j == 2:
                    g = ET.SubElement(row,'Parent0')
                    g.text = i[j]
                elif j == 3:
                    g = ET.SubElement(row,'Parent1')
                    g.text = i[j]
                j += 1
print(ET.tostring(xml.getroot()).decode())

rawDescription: Insert XML Value/Element with Python

description: Insert XML Value/Element with Python


code:
def convert_to_decimal():
    return 42

rawDescription: python code for "minute of arc" calculation, completing a latitude and longitude conversion function

description: Python code for "minute of arc" calculation, completing a latitude and longitude conversion function


code:
from scapy.layers.inet import IP, ICMP
from scapy.sendrecv import sr
import sys
sr(IP(dst=sys.argv[1])/ICMP())

rawDescription: Scapy In A Script

description: Scapy In A Script


rawDescription: May I use a integration limit on scipy cumtrapz?


code:
rListObj = {}
for key,val in zip(robjects.r.names(res),res):
  rListObj[key] = [i for i in val] #R Vector to List

rawDescription: Guidance in using rpy2 eval expression

description: Guidance in using rpy2 eval expression


rawDescription: finding colors in Image and redraw on second image(using numpy)

description: Finding colors in Image and redraw on second image(using numpy)


code:
url = "http://example.com/form"
auth=("appuser", "apppass")
req = requests.get(url, auth=auth)

rawDescription: Login, Navigate and Retrieve data behind a proxy with Python


rawDescription: Parsing nested ternary expressions

description: Parsing nested ternary expressions


code:
import imageloader
anotherTile = imageloader.tile_table[2]

rawDescription: calling class/static method from class variable in python

description: Calling class/static method from class variable in python


code:
number = 1234567890
print(''.join(chr(0x2080+int(c)) for c in str(number)))

rawDescription: How to Print Unicode Strings Variably?

description: Print Unicode Strings Variably


code:
x['new'] = x.sourceEncodedID
x
x.ix[x.sourceEncodedID.str.contains('\.'), 'new'] = x.sourceEncodedID.str.split('\.', expand=True)[1]
x

rawDescription: Using split to populate a column in Pandas dataframe


code:
values = ['t', 'br', 'ht']
if all(x in instr for x in values):
    print("Ok!")

rawDescription: Python if this and this and this

description: Python if this and this and this


code: w = wfloat.mean(2)

rawDescription: How do I find Wally with Python?

description: Find Wally with Python


code:
for line in input:
    re.sub('^particular : .*', 'particular : 111222333')

rawDescription: Replace part of string using python regular expression


code: func(42, bar=314, extra=somevar)

rawDescription: Parameter vs Arguments ? finally,what are they?


code: match_string = r"\b" + word + r"\b"

rawDescription: Match a word in a string using regex - python


code:
import pymongo

client = pymongo.MongoClient()
db = client.db
collects = db.collection_names(include_system_collections=False)
cursor = db.get_collection(collects[1]).find()

rawDescription: How to extract collections in Mongo using Python?

description: Extract collections in Mongo using Python


code:
import datetime
mt = 1342993416.0
datetime.datetime.fromtimestamp(mt)

rawDescription: Python : INPUT a microtime float, RESULT a formatted datetime


code:
class parserSAXHandler(handler.ContentHandler):

    def __init__(self):
        self.tagstack   = []
        self.childlist  = []

    def startElement(self, name, attrs):
        if self.tagstack[-1] == "parent":
           self.childlist.append(name)
        self.tagstack.append(name)

    def endElement(self,name):
        if name == self.tagstack[-1]:
            self.tagstack.pop()
        else:
            raise SAXParseException("tag closed without being open")

rawDescription: python sax xml names of the children tags

description: Python sax xml names of the children tags


code:
pat=re.compile('(.*?)', re.DOTALL)
print(pat.findall(fileString))
# ['foo\nbaby foo\nbaby foo\nbaby foo\n', 'bar']

rawDescription: Python RegEx skipping the first few characters?


rawDescription: how to write unreadable ^A into output file in Python?

description: Write unreadable ^A into output file in Python


rawDescription: Parsing a file without BeautifulSoup

description: Parsing a file without BeautifulSoup


rawDescription: Python Pandas Pivot Table - Adding calculated column to multi-index column


code:
sl = list(set(ls))
sl += [4] * (ls.count(4) - 1)

rawDescription: How to remove all duplicates from list except one element in Python?

description: Remove all duplicates from list except one element in Python


code:
'__mro__' in object.__dict__
'__mro__' in type.__dict__
'mro' in object.__dict__
'mro' in type.__dict__

rawDescription: How to find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)

description: Find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)


code:
polly('cracker', True)
polly(*('cracker', True))
polly(*t)
f('cracker', True)
f(*t)

rawDescription: passing a dictionary by reference instead of using eval / how to pass a variable number of arguments

description: Passing a dictionary by reference instead of using eval / how to pass a variable number of arguments


code: filter(lambda n: n % 2, xrange(10))

rawDescription: Python filter() function

description: Python filter() function


code: orig_stdout = sys.stdout

rawDescription: Redirect print to string list?

description: Redirect print to string list


code:
class FileChooser():

    def __init__(self):
        #Stores your path
        self.path = None

        dia = Gtk.FileChooserDialog("Please choose a file", None,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        self.add_filters(dia)

        response = dia.run()

        if response == Gtk.ResponseType.OK:
            print("Open clicked")
            print("File selected: " + dia.get_filename())
            self.path = dia.get_filename()
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dia.destroy()

rawDescription: How to make filename/path from Gtk+ (Python 3.4) FileChooserDialog accessible globally

description: Make filename/path from Gtk+ (Python 3.4) FileChooserDialog accessible globally


rawDescription: parsing returned HTML by beautifulsoup

description: Parsing returned HTML by beautifulsoup


code: dataselector = log_OIII_Hb_NII(data[:,2]) > 0

rawDescription: How do I separate a data set on a scatter plot

description: Separate a data set on a scatter plot


code:
class Example(object):
    def __init__(self):
        self._name = FakeMutableString()

    @property
    def name(self):
        return self._name.get()

    @name.setter
    def name(self, new):
        self._name.set(new)

rawDescription: Data-Binding in Python?

description: Data-Binding in Python


rawDescription: How do I force Python to keep an integer out of scientific notation

description: Force Python to keep an integer out of scientific notation


rawDescription: Where is the default parameter in Python function


code:
def animate(i):
    chosenEnergy = (0.0 + (i-1)*(0.02))
    animate.chosenEnergyLine.remove()
    animate.chosenEnergyLine = ax2.axvline(float(chosenEnergy),0,1, linestyle='dashed')
    return animate.chosenEnergyLine,

animate.chosenEnergyLine = ax2.axvline(0.0,0,1, linestyle='dashed')

ani = animation.FuncAnimation(f, animate, np.arange(1,10),
                interval=25, blit=False, repeat = False)

rawDescription: FuncAnimation() : remove/update old lines


code: "".join([x for x in strs if x.isdigit()])

rawDescription: Is there a more efficient way to convert this phone number to plain text?


code:
mylist = mylist + ...
mylist = mylist[:-2]

rawDescription: How is the iadd operator ( += ) different than simple addition?


code: c, _ = tf.listdiff(test, target)

rawDescription: Check if values are contained within a Tensor


rawDescription: Python: How to open a multisheet .xslx file (with formatting) and edit a few cells and save it as another .xlsx file


code: not {}

rawDescription: Difference between not dict and not dict=={}


code:
from A import *
(foo, _bar)

rawDescription: _func() , any functional use of underscore? (Python)


code:
pairs = np.array(list(pairs))
pairs = np.vstack((pairs, pairs[:, ::-1]))
pairs = pairs[np.argsort(pairs[:, 0])]
is_z_smaller = points[pairs[:, 0], 2] < points[pairs[:, 1], 2]
bins, = np.nonzero(pairs[:-1, 0] != pairs[1:, 0])
bins = np.concatenate(([0], bins+1))
is_maximum = np.logical_and.reduceat(is_z_smaller, bins)
localCoordinateMaxima, = np.nonzero(is_maximum)

rawDescription: Efficient double iteration over array

description: Efficient double iteration over array


code: a = {key: {} for key in range(3)}

rawDescription: Using dict.fromkeys(), assign each value to an empty dictionary


rawDescription: writing tab separated values into a file

description: Writing tab separated values into a file


code:
import csv

def remove_quotes(s):
    return ''.join(c for c in s if c not in ('"', "'"))

with open("fixquote.csv","rb") as infile, open("fixed.csv","wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, quoting=csv.QUOTE_ALL)
    for line in reader:
        writer.writerow([remove_quotes(elem) for elem in line])

rawDescription: Removing in-field quotes in csv file

description: Removing in-field quotes in csv file


rawDescription: Read sparse matrix in python

description: Read sparse matrix in python


rawDescription: python.exe crushed while creating numpy array

description: Python.exe crushed while creating numpy array


code: pairs = {(d['file'], d['ext']) for d in L2 for k in d}

rawDescription: Get dictionaries in a list where the key:value pairs are in another list of dictionaries


code:
import re
s = '300 gm'
re.findall('\d+', s)
s = '300 gm 200 kgm some more stuff a number: 439843'
re.findall('\d+', s)

rawDescription: extract digits in a simple way from a python string

description: Extract digits in a simple way from a python string


code:
import numpy as np
values = ['cat', 'popcorn', 'mescaline']
number_of_members = 2
N = 1000000
random_arrays = np.asarray([values] * N)
_ = [np.random.shuffle(array) for array in random_arrays]
subset = random_arrays[:, :number_of_members]

rawDescription: Create numpy array with random elements from list


code:
import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [2,1,3,6,7]

cluster = ['^','^','^','s','s']

fig, ax = plt.subplots()

for xp, yp, m in zip(x, y, cluster):
    ax.scatter([xp],[yp], marker=m)

plt.show()

rawDescription: How to use different marker for different point in scatter plot pylab

description: Use different marker for different point in scatter plot pylab


code:
x = df.a/df.b
x
x[np.isinf(x)] = np.nan
x

rawDescription: handling zeros in pandas DataFrames column divisions in Python

description: Handling zeros in pandas DataFrames column divisions in Python


code:
with open("essay.txt") as f:
    for line in f:
        if line.startswith('Subject:'):
            pass

rawDescription: How to find a part of string in another string?

description: Find a part of string in another string


rawDescription: Gruber’s URL Regular Expression in Python


code: r = requests.post(url, headers=headers, data=post_data)

rawDescription: Dropbox /delta ignoring cursor

description: Dropbox /delta ignoring cursor


rawDescription: How to get the first digit of the fractional part of a decimal number?

description: Get the first digit of the fractional part of a decimal number


code:
@asyncio.coroutine
def some_coroutine(*args):
    #...
    #...
    yield from tasty.asyncio.function()
    return result

def coroutine_user():
    # data = some_coroutine() will give you a generator object instead of result
    data = yield from some_coroutine()
    return data # data here is a plain result: you can call your .get or whatever

rawDescription: Parallelise web tasks with asyncio in Python


rawDescription: filling last known data with pandas

description: Filling last known data with pandas


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


code:
rules = [ rule1, rule2, rule3, rule4, ... ]
return all( r( solution ) for f in rules )

rawDescription: Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting?


code: match_line(1, 'sales.txt')

rawDescription: Searching a txt file for a character, and returning a character from a line below it


code:
association_table = Table('association', Base.metadata,
    Column('a_id', Integer, ForeignKey('a.id')),
    Column('b_id', Integer, ForeignKey('b.some_id'))
)

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    b_s = relationship("B",
                    secondary=association_table,
                    backref="a_s")

class B(Base):
    __tablename__ = 'b'
    some_id = Column(Integer, primary_key=True)

rawDescription: How can I create a many to many relationship using SQLAlchemy?

description: Create a many to many relationship using SQLAlchemy


code:
out = [OrderedDict(zip(names, line.split()))
           for line in takewhile(lambda x: not x.startswith("-"), f)]

rawDescription: Python convert table to dictionary

description: Python convert table to dictionary


code:
map(int, str(634))        # Python 2
list(map(int, str(634)))  # Python 3

rawDescription: Split three-digit integer to three-item list of each digit in Python


code:
name_callbacks=(('One',self.callback_one),
                ('Two',self.callback_two),
                ...,
                ('Ten',self.callback_ten))
self.button=[]
for i,(name,callback) in enumerate(name_callbacks):
    self.button.append(Button(frame, text=name, command=callback))
    row,col=divmod(i,5)
    self.button[i].grid(sticky=W+E+N+S, row=row, column=col, padx=1, pady=1)

rawDescription: How can I add a lot of Buttons to the tkinter Frame efficiently?

description: Add a lot of Buttons to the tkinter Frame efficiently


code:
import io
from lxml import etree

doc = etree.parse(io.FileIO('input.xsl'))

for tr in doc.findall(".//tr"):
    if tr[0].tag == 'td':
        if tr[0].text == 'customer' :
            if tr[1].tag == 'td' :
                 tr[1].text = 'new value 1'
        elif tr[0].text == 'admin' :
            if tr[1].tag == 'td' :
                tr[1].text = 'new value 2'

print (etree.tostring(doc, pretty_print = True))

rawDescription: Edit XSL file using Python

description: Edit XSL file using Python


rawDescription: Limit of digit-by-digit calculation of square roots


code:
class FunctionObject(object):
    def __call__(self):
        return foo

def f():
    foo = 3
    FunctionObject()() # raises UnboundLocalError

rawDescription: Can someone explain to me the difference between a Function Object and a Closure


rawDescription: Replace values of a numpy array by values from another numpy array


rawDescription: Limit cumsum to only the previous 4 rows


code: self.book_values_list = [bookNode.get(i) for i in book_attribute]

rawDescription: Python - How can I return a list for each xml node I am iterating through using xml.etree.ElementTree?


code:
img_file = open("image1.png", "r")

# read the image file
data = img_file.read()

# build JSON object
outjson = {}
outjson['img'] = data.encode('base64')   # data has to be encoded base64 and decode back in the Android app base64 as well
outjson['leaf'] = "leaf"
json_data = json.dumps(outjson)

# close file pointer and send data
img_file.close()
self.request.sendall(json_data)

rawDescription: Send OpenCV image in JSON from Python to Android


rawDescription: How can I send a URL request to the server with Python without actually opening my browser ("without using the webbrowser module")?

description: Send a URL request to the server with Python without actually opening my browser ("without using the webbrowser module")


rawDescription: Producing Random Pairs From A String

description: Producing Random Pairs From A String


code:
m_highest = combined['Volume_y'] > combined['Volume_x']
roll_date = m_highest[m_highest].index[0]

rawDescription: Build Back Adjusted Continous Futures contract from Historical Data


code:
list1 = [{'position':'child','title':'dave','obj':'obj','created':'2013-11-20'},
         {'position':'child','title':'james','obj':'obj','created':'2013-11-19'},
         {'position':'child','title':'james','obj':'obj','created':'2013-11-18'},
         {'position':'child','title':'ian','obj':'obj','created':'2013-11-17'},
         {'position':'child','title':'dave','obj':'obj','created':'2013-11-16'},
         {'position':'child','title':'dave','obj':'obj','created':'2013-11-15'},
         {'position':'child','title':'dave','obj':'obj','created':'2013-11-14'}]

import itertools
import operator

list1 = [
    x
    for key, grp in itertools.groupby(list1, key=operator.itemgetter('title'))
    for x in [{'position': 'parent', 'title': key + ' root'}]+ list(grp)
]
for x in list1:
    print(x)

rawDescription: Grouping lists in Python but keeping them in order


rawDescription: Counting number of xml tags in python using xml.dom.minidom


code: libfn( **{'foo':'bar'} )

rawDescription: Custom dictionary through **kw

description: Custom dictionary through **kw


code: countlist = {word:allwords.count(word) for word in allwords}

rawDescription: Print frequency of words, in a sentence, in a single line


rawDescription: Randomly replace 2 values in python dictionary


code:
class Department(models.Model):
    slug = models.SlugField(
        verbose_name    = _(u'Slug'),
        help_text           = _(u'Uri identifier for this department.'),
        max_length=255
    )
    name = models.CharField(
        verbose_name    = _(u'Department Name'),
        help_text           = _(u'The department\'s name.'),
        max_length      = 255
    )
    description = models.TextField(
        verbose_name    = _(u'Description'),
        help_text           = _(u'Department\'s description')
    )
    people = models.ManyToManyField(
        Person,
        through             = 'DepartmentPeople',
        related_name    = 'people',
        verbose_name    = _(u'People'),
        help_text           = _(u'People in this Department')
    )
    order_by = models.IntegerField(
        verbose_name    = _(u'Ordering Weight'),
        help_text           = _(u'This item\'s weight within a list.'),
        max_length      = 255
    )

    class Meta:
        verbose_name = _(u"Department")
        verbose_name_plural = _(u"Departments")
        ordering = ['order_by',]

    def people_list(self):
        return [dp.person for dp in DepartmentPeople.objects.filter(department=self).order_by('order')]

    def __unicode__(self):
        return self.name

rawDescription: Define an order for ManyToManyField with django


code: verify_state('TAG1') == 100

rawDescription: How to get atributes and operator from function

description: Get atributes and operator from function


code: pictures = [make_instance(Pictures(), item) for item in picture_dict]

rawDescription: What is the best way to access stored procedures in Django's ORM


rawDescription: scatter plot same point repeated several times python

description: Scatter plot same point repeated several times python


code:
from foo import *

bar1()
bar2()
# etc

rawDescription: Importing Turtle graphics modules

description: Importing Turtle graphics modules


code: names = {'%s %s' % (fn, ln) : _id for _id, (fn, ln) in enumerate(zip(first_names, last_names))}

rawDescription: Python: extract unique id from file name


code:
class HeaderViewFilter(QObject):
    def __init__(self, parent, header, *args):
        super(HeaderViewFilter, self).__init__(parent, *args)
        self.header = header
    def eventFilter(self, object, event):
        if event.type() == QEvent.MouseMove:
            logicalIndex = self.header.logicalIndexAt(event.pos())
            # you could emit a signal here if you wanted

self.filter = HeaderViewFilter()
self.horizontalHeader = yourView.horizontalHeader()
self.horizontalHeader.setMouseTracking(1)
self.horizontalHeader.installEventFilter(self.filter)

rawDescription: PyQt: How to catch mouse-over-event of QTableWidget-headers?


rawDescription: How to get a value from QSpinBox, how to disable NextButton in QWizard

description: Get a value from QSpinBox, how to disable NextButton in QWizard


code:
with open('eggs.bmp', 'wb') as f:
    f.write(data)

rawDescription: working with .bmp files in python 3

description: Working with .bmp files in python 3


code:
query = (df.index.levels[2] >= pd.Timestamp("2013-01-17"))[df.index.labels[2]]
df[query]

rawDescription: Pandas multi-index best way to slice for ranges of subordinate levels


code: py = max(py - movespeed, 5)

rawDescription: Python - How to add then limit a number in python


code:
errorString = "Exception occurred ({}) while executing '{}': {}".format(
    e.__class__.__name__, task.name, str(e)
)

rawDescription: Python string formatting: % vs concatenation


code:
url_dict=shelve.open(html_filename)
#opens webpage
r=br.open(first_url)
for i in range(1,20):
    #navigates upper browser to next page for non-first-pages
    if (i !=1):
        r=br.open(first_url+str(i)+'_p/')
    #collects list of urls to be navigated by sr
    html=r.read()
    soup=BeautifulSoup(html)
    frames=soup.find_all("a",{"class":br_class})#br_class is defined globally
    time.sleep(1)
    for item in frames:
        url_suffix=item['href']
        full_url=url_prefix+url_suffix
        full_url=full_url.encode('ascii','ignore')
        if str(full_url) not in url_dict:
            url_dict[str(full_url)]=get_information(full_url,sr)
        time.sleep(1)

rawDescription: How to extract search results on a website into local file

description: Extract search results on a website into local file


rawDescription: Pandas multiindex and pytables... separate indexes or one concatenated index?


rawDescription: append value in ith list of list

description: Append value in ith list of list


code:
if name is not None and ent is not None and col is not None:
    value.setdefault(name, {})[ent] = col

rawDescription: Adding multiple dictionaries to a key in python dictionary


code:
if cherrypy.engine.state != cherrypy.engine.states.STARTED:
    return

rawDescription: How to detect if cherrypy is shutting down

description: Detect if cherrypy is shutting down


code:
import csv
import re

keyvalue = re.compile(r'([^"= ]+)="([^"]+)"')

with open(filename, 'rb') as infh:
    reader = csv.reader(infh, skipinitialspace=True)
    namedfields = [dict(keyvalue.findall(row[2])) for row in reader]

rawDescription: parsing space delimited, named fields

description: Parsing space delimited, named fields


code:
states_dictionary={
     "CT":["alex","harry"],
     "AK":["liza","alex"],
     "TX":["fred", "harry"]
};

rawDescription: are there dictionaries in javascript like python?

description: Are there dictionaries in javascript like python


code:
inds = [ind for ind, sub in enumerate(myListOfList) if st.issubset(ch[0] for ch in sub)
        and all(ch[-1] == sub[0][-1] for ch in sub)]

print(inds)
[1, 6, 7]

rawDescription: Compare lists of strings regarding the suffixes of their respective elements


code:
def insert(list1, var, i):
    # Unpacking the components sliced as before to a brand new list
    return [*list1[:i], var, *list1[i:-1]]

rawDescription: insert element into list, move pre-existing elements

description: Insert element into list, move pre-existing elements


code:
_whens = {4: 1, 2: 2, 3: 3, 5: 4, 1: 5}
sort_order = case(value=SomeTable.type, whens=_whens)
q = session.query(SomeTable)
q = q.order_by(sort_order)

rawDescription: SQLALchemy custom integer sort order

description: SQLALchemy custom integer sort order


code: [item for item in L if 2 <= item[1] <= 4]

rawDescription: Python: Iterate through a list by value, not by index


rawDescription: Iterating through a numpy array and then indexing a value in another array


code:
import pandas as pd

dmap = {
    'GA': 'TRI_1',
    'CT': 'TRI_1',
    'AG': 'TRI_2',
    'TC': 'TRI_2',
    'GC': 'TRV_1',
    'CG': 'TRV_1',
    'AT': 'TRV_1',
    'TA': 'TRV_1',
    }

lst = [
      ['FHControl', 'G', 'A'],
      ['MNHDosed', 'G', 'C']
      ]

df = pd.DataFrame(lst, columns=['key', 'q', 's'])
df['tr'] = (df['q']+df['s']).map(dmap)

print(df)
#          key  q  s     tr
# 0  FHControl  G  A  TRI_1
# 1   MNHDosed  G  C  TRV_1

print(pd.crosstab(rows=[df['key']], cols=[df['tr']]))

rawDescription: How to bin many category combinations (72 variables) in python lists

description: Bin many category combinations (72 variables) in python lists


code:
def filterNegs(L):
    L = set(L)
    answer = []
    for i in L:
        if -1*i in L:
            answer.append(i)
    return answer

rawDescription: How to "negate"(?) a list - Python

description: "negate"(?) a list - Python


rawDescription: how to write data to a h5py dataset

description: Write data to a h5py dataset


code: random_pts3d = np.random.random(size=(3, 100, 2)) * len(grid)

rawDescription: Using array indexing to apply 2D array function on 3D array


code:
from django.contrib.auth import get_user_model
User = get_user_model()

rawDescription: how to extend model User?

description: Extend model User


code:
miles = -1
while miles != 0:
    miles = float(raw_input ('Enter Miles: '))

rawDescription: cannot create a working loop in python

description: Cannot create a working loop in python


code: res = grouped.apply(func)

rawDescription: Ho to convert a pd data frame to matrix structure in python


code:
post = Post(author=some_author, tags=['app-engine', 'google', 'python'])
post_key = post.put()
# call some method to increment post counts...
increment_tag_post_counts(post_key)

# get posts with a given tag:
matching_posts = Post.all().filter('tags =', 'google').fetch(100)
# or, two tags:
matching_posts = Post.all().filter('tags =', 'google').filter('tags =', 'python').fetch(100)

# get tag list from a post:
tag_stats = Tag.get_by_key_name(post.tags)

rawDescription: parent->child relationships in appengine python (bigtable)

description: Parent->child relationships in appengine python (bigtable)


code:
d = {c: [] for c in colors}
for x in g16.nodes(data=True):
    d[x[1]['color']].append(x[0])

rawDescription: creating dictionary containing list values using a comprehension

description: Creating dictionary containing list values using a comprehension


code:
import re
x = 'some text /Hello how are you/ some more text'
print (re.sub(r'/.*/','', x))

rawDescription: Python Grabbing String in between characters


rawDescription: Python do a lookup between 2 dictionaries


rawDescription: How to find all elements in a numpy 2-dimensional array that match a certain list?

description: Find all elements in a numpy 2-dimensional array that match a certain list


code:
import inspect
if inspect.isclass(X):
   X.f = staticmethod(f)
else:
   X.f = f

rawDescription: Class objects are irregular when assigning functions


code:
from operator import itemgetter
from itertools import groupby

key = itemgetter(0)
bestvalues = {tuple(best[:2]): best[2]
              for key, group in groupby(sorted(information, key=key), key=key)
              for best in (max(group, key=itemgetter(2)),)}

rawDescription: Get the max value for given keys in a dictionary?


code:
body = lxml.html.document_fromstring('
title
')[0]
lxml.html.tostring(body)

rawDescription: parse html body fragment in lxml

description: Parse html body fragment in lxml


code:
class Shape(object):
    def area(self):
        raise NotImplementedError

    def perimeter(self):
        raise NotImplementedError

class Rectangle(Shape):
    def __init__(self, width=0, height=0):
        super(Rectangle, self).__init__() # this is useless in this case, but it's good practice
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * self.height + 2 * self.width

    @property
    def width(self):
        return self.__width

    @property
    def height(self):
        return self.__height

    @width.setter
    def width(self, width):
        self.__width = width

    @height.setter
    def height(self, height):
        self.__height = height

    def getStats(self):
        return "width:      %s\nheight:      %s\narea:      %s\nperimeter: %s" % (self.width, self.height, self.area(), self.perimeter())

rawDescription: Object Oriented Python - rectangle using classes and functions


rawDescription: Pattern matching and compiling

description: Pattern matching and compiling


code:
Output
[
  {
    "summary": "Jonny Smith"
  }
]

rawDescription: parse dates with icalendar and compare to python datetime

description: Parse dates with icalendar and compare to python datetime


code:
new_url_list = list()
for address in old_url_list:
    new_address = address.replace("watch?v=", "embed/")
    new_url_list.append(new_address)

old_url_list = new_url_list

rawDescription: Convert YouTube link into an embed link

description: Convert YouTube link into an embed link


rawDescription: Python: value that occurs the most in a list


rawDescription: Python Regex: Mixed format string duration to seconds


rawDescription: Extracting just a string element from a pandas dataframe


code:
import time
from nltk.tokenize import ToktokTokenizer

import urllib.request
url = 'https://raw.githubusercontent.com/Simdiva/DSL-Task/master/data/DSLCC-v2.0/test/test.txt'
response = urllib.request.urlopen(url)
data = response.read().decode('utf8')

toktok = ToktokTokenizer().tokenize

for _ in range(10):
    start = time.time()
    for line in data.split('\n'):
        toktok(line)
    print ('toktok:\t', time.time() - start)

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


code:
def string_splosion(string):
    i, result = 0, ''
    while i < len(string): # < instead of <=
        i += 1
        result += string[:i]
    return result

rawDescription: python3 string "abcd" print: aababcabcd?

description: Python3 string "abcd" print: aababcabcd


code:
x = ['foo12', 'foo1', 'foo2','foo24']
natsort.natsorted(x)

rawDescription: Not able to sort the unicode numbers in python


code:
self.checkboxes = []
for i in newfp:
        self.checkboxes.append(wx.CheckBox(nexus,-1,i,(30,again),(160,-1)))
        self.checkboxes[-1].Bind(wx.EVT_CHECKBOX, self.lol)
        again+=30

rawDescription: How to record multiple checkboxes in wxPython?

description: Record multiple checkboxes in wxPython


code:
def makeAbbreviations(headers):
    abbreviations = {}
    for header in headers:
        header = header.lower()
        words = header.split()
        n = max(len(w) for w in words)
        i = 2
        starts = [w[:i] for w in words]
        abbrev = ''.join(starts)

        while abbrev in abbreviations and i <= n:
            i += 1
            for j,w in enumerate(words):
                starts[j] = w[:i]
                abbrev = ''.join(starts)
                if not abbrev in abbreviations: break
        abbreviations[abbrev] = header
    return abbreviations

myHeaders = ['Ad Group', 'Annuity Calculator', 'Tax Deferred Annuity',
             'Annuity Tables', 'annuities calculator', 'annuity formula',
             'Annuities Explained', 'Deferred Annuies Calculator',
             'Current Annuity Rates', 'Forbes.com', 'Annuity Definition',
             'fixed income', 'Immediate fixed Annuities',
             'Deferred Variable Annuities', '401k Rollover',
             'Deferred Annuity Rates', 'Deferred Annuities',
             'Immediate Annuities Definition', 'Immediate Variable Annuities',
             'Variable Annuity', 'Aig Annuities', 'Retirement Income', 'retirment system',
             'Online Financial Planner', 'Certified Financial Planner']

d = makeAbbreviations(myHeaders)
for (k,v) in d.items(): print(k,v,sep = " = ")

rawDescription: setting unique abbreviation for every column in python

description: Setting unique abbreviation for every column in python


code:
from sqlalchemy.sql.expression import desc, asc
session.query(Shots) \
    .filter_by(event_id=event_id) \
    .join(User) \
    .order_by(asc(User.name))

rawDescription: How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?

description: Model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)


SuspiciousOperation using sorl-thumbnail


code:
def get_line(line):
    number = find_number(line)
    if number is None:     # No numbers were found
        return line
    else:
        return get_line(find_number(lines[number]))

rawDescription: Numbers in string

description: Numbers in string


code:
def read_device(the_64_array, start=31, end=47):
   # some code
   the_64_array[start:end] = ... #modifies `in_array` in place

rawDescription: Passing subset reference of array/list as an argument in Python


code:
from functools import partial

optfunc = partial(func, X, y)
optimized_alpha = sp.optimize.minimize(optfunc, alpha, method="Newton-CG", jac=True)

rawDescription: How to minimize one argument of a function using Scipy?

description: Minimize one argument of a function using Scipy


code:
ip_total_len = rp.getlayer(IP).len
ip_header_len = rp.getlayer(IP).ihl * 32 / 8
tcp_header_len = rp.getlayer(TCP).dataofs * 32 / 8
tcp_seg_len = ip_total_len - ip_header_len - tcp_header_len
ans_ack,unans_ack = sr(IP(dst=ip)/TCP(sport=pkt[1].dport, \
                                      dport=pkt[1].sport, \
                                      seq=rp[1].ack, \
                                      ack=rp[1].seq + tcp_seg_len, \
                                      flags="A"), \
                           verbose=0, timeout=1)

rawDescription: Ack number to acknowledge data in scapy

description: Ack number to acknowledge data in scapy


code: storage_url+container_name + '/' + blob_name+'?'+qry_string

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


code:
class Person(object):
    def __init__(self,s):
        self.name = Name(s.get('name',{}))
        self.url = s.get('url','')

rawDescription: Overriding decorated subclass methods

description: Overriding decorated subclass methods


rawDescription: Constructing a waterfall algorithm from multiple columns in a Pandas Data Frame


rawDescription: Pandas convert minute number index (0 to 1440) to datetime


code:
myfile = open("readnwrite.txt", "r").read()
myfile
len(myfile)
len("This should be at the top of the file now.")
len(myfile) - len("This should be at the top of the file now.")

rawDescription: Opening and reading txt files

description: Opening and reading txt files


code:
foo = 7.6
int(foo)

rawDescription: float to integer in python

description: Float to integer in python


code:
from itertools import groupby
from operator import itemgetter

word_dict = dict((letter, set(words))
                 for letter, words in groupby(sorted(word_list),
                                              key=itemgetter(0)))

rawDescription: Assigning lower case alphabet as keys in a dictionary?


rawDescription: How to get s subset sum to print out the integers it used (python)

description: Get s subset sum to print out the integers it used (python)


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "table#MainContent_Table1 > tbody > tr > td:nth-of-type(2)"))
)
print(element.text)

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


code:
def normalize(arr):
    """
    Linear normalization
    http://en.wikipedia.org/wiki/Normalization_%28image_processing%29
    """
    # Do not touch the alpha channel
    for i in range(3):
        minval = arr[...,i].min()
        maxval = arr[...,i].max()
        if minval != maxval:
            arr[...,i] -= minval
            arr[...,i] *= (255.0/(maxval-minval))
    return arr

rawDescription: Convert Image (png) to Matrix,normalizing it, vise versa


code:
def qwer(num):
    return dict([(str(i), i) for i in xrange(num+1)])

rawDescription: What is the name of this dictionary?

description: What is the name of this dictionary


rawDescription: Creating a complex data structure by parsing an output file


code: pd.PeriodIndex(df['date'], freq='Q')

rawDescription: python pandas: get fiscal quarter from fiscal year and month (for UK)

description: Python pandas: get fiscal quarter from fiscal year and month (for UK)


code:
df = df.reset_index() #Make your index into a column
df = pd.melt(df, id_vars = ['index']) #Reshape data
df = df[df['index'] <= df['variable']].sort_values(by = 'value') #Remove duplicates, sort
df ['col'] = df['index'] +','+ df['variable'] #Concatenate strings
df = df[['col','value']] #Remove unnecessary columns
df = df.set_index('col') #Set strings to index
df

rawDescription: Transposing dataframe and sorting

description: Transposing dataframe and sorting


code:
def _check_x12(x12path=None):
    x12path = _find_x12(x12path)
    if not x12path:
        raise X13NotFoundError("x12a and x13as not found on path. Give the "
                               "path, put them on PATH, or set the "
                               "X12PATH or X13PATH environmental variable.")
    return x12path

rawDescription: ARIMA seasonal prediction with Python: x12a and x13as not found on path


code:
print( rep(buildnum) )
# or
print( [buildnum] )

rawDescription: Python write to file causing new line after second variable insertation


code:
word0 | 1
word1 | 1
word2 | 1

rawDescription: Counter in python not showing all words

description: Counter in python not showing all words


code:
from some_model import SomeModel
from some_other_model import SomeOtherModel

__all__ = [
    'SomeModel',
    'SomeOtherModel',
]

rawDescription: Can i divide the models in different files in django

description: Divide the models in different files in django


code:
def __iter__(self):
    for d in self._data:
        yield d

rawDescription: Python, lambda, find minimum

description: Python, lambda, find minimum


code:
import dis
a = Solution()
dis.dis(a.hasCycle)

rawDescription: What makes my python code so slow (Linked List Cycle)?


code:
from utilities import id_number

def show_id(request):
    id = id_number.generate_patient_id_number()
    print(id)
    return render(request, 'index.html', {})

rawDescription: How can I use __init__() in python django

description: Use __init__() in python django


rawDescription: SUDS: Pass Array Parameter in Client.service Method : GAE Python


code:
max_key = {}
for key, values in mydict.iteritems():
    for value in values:
        if key > max_key.get(value, float('-inf')):
            max_key[value] = key

result = {val: max_key[val] for val in myset}

rawDescription: return key under condition

description: Return key under condition


code:
class Canvas_On:
    def __init__(self, master):
        # ... your original code here ...
        self.c.tag_bind('bg', '<Button-1>', self.click)
        self.c.tag_bind('bg', '<B1-Motion>', self.drag)
        self.c.tag_bind('draggable', '<Button-1>', self.click_item)
        self.c.tag_bind('draggable', '<B1-Motion>', self.drag_item)
    # ... etc. ...
    def click_item(self, event):
        x, y = self.c.canvasx(event.x), self.c.canvasy(event.y)
        self.drag_item = self.c.find_closest(x, y)
        self.drag_x, self.drag_y = x, y
        self.tag_raise(item)
    def drag_item(self, event):
        x, y = self.c.canvasx(event.x), self.c.canvasy(event.y)
        self.c.move(self.drag_item, x-self.drag_x, y-self.drag_y)
        self.drag_x, self.drag_y = x, y

class Drawing_Utility:
    # ...
    def drawer(self, canvas):
        self.c.create_rectangle(0, 0, 5000, 5000,
                                fill='black', tags='bg')
        self.c.create_oval(50,50,150,150, fill='orange', tags='draggable')
        self.c.create_oval(1000,1000,1100,1100, fill='orange', tags='draggable')

rawDescription: Moving Around A Python Canvas Without Using Scrollbars


code:
def rmNegatives(L):
    subscript = 0
    for num in L: # here you run over a list which you mutate
        if num < 0:
            L = L[:subscript] + L[subscript:] # here you do not change the list (see comment above)
        subscript += 1 # you have to do this only in the case, when you did not remove an element from the list
    return L

rawDescription: Removing Negative Elements in a List - Python


code:
c = filter(None, [list(set(sublist).intersection(set(b))) for sublist in a])
c

rawDescription: Check if list array contains element in another list


code:
mask = b >= a[..., -1:]
index = np.argmax(mask, axis=-1) - 1

rawDescription: Python/Scipy: Find "bounded" min/max of a matrix


code:
class Serial(object):
    @property
    def baudrate(self):
        """Get or set the current baudrate. Setting the baudrate to a new value
        will reconfigure the serial port automatically.
        """
        return self._baudrate

    @baudrate.setter
    def baudrate(self, value):
        if self._baudrate != value:
            self._baudrate = value
            self._reconfigure_port()

rawDescription: What is the right way to put a docstring on Python property?


code: plt.axis([min(x), max(x), min(y), max(y)])

rawDescription: matplotlib: Incorrect scale of axis

description: Matplotlib: Incorrect scale of axis


code:
import datetime
import mock
from unittest2 import TestCase

from django.core.exceptions import ValidationError

from .. import validators

class ValidationTests(TestCase):
    @mock.patch('utils.date.today')
    def test_validate_future_date(self, today_mock):
        # Pin python's today to returning the same date
        # always so we can actually keep on unit testing in the future :)
        today_mock.return_value = datetime.date(2010, 1, 1)

        # A future date should work
        validators.validate_future_date(datetime.date(2010, 1, 2))

        # The mocked today's date should fail
        with self.assertRaises(ValidationError) as e:
            validators.validate_future_date(datetime.date(2010, 1, 1))
        self.assertEquals([u'Date should be in the future.'], e.exception.messages)

        # Date in the past should also fail
        with self.assertRaises(ValidationError) as e:
            validators.validate_future_date(datetime.date(2009, 12, 31))
        self.assertEquals([u'Date should be in the future.'], e.exception.messages)

rawDescription: Django unit testing with date/time-based objects


code: t4['Population Age 0 - 14'] = t3['Population Age 0 - 14']

rawDescription: Do I want to join/merge, concat, or append these two Pandas DataFrames?


code: result = a[result]

rawDescription: options for applying conditions to numpy arrays

description: Options for applying conditions to numpy arrays


code:
scipy.interpolate.griddata(points, values, xi, method='linear', fill_value=nan)
# 'points' has to contain what you named  x and y
# 'values' has to contain what you named z
# 'xi' has to contain what you named xi,yi

rawDescription: converting map coordinates to lat/long

description: Converting map coordinates to lat/long


code:
class TestA2(TestCaseA):
    def setUp(self):
        self.thing = A2()

rawDescription: Test subclass behaviour?

description: Test subclass behaviour


code:
previous_15 = df['SMA_15'].shift(1)
previous_45 = df['SMA_45'].shift(1)
crossing = (((df['SMA_15'] <= df['SMA_45']) & (previous_15 >= previous_45))
            | ((df['SMA_15'] >= df['SMA_45']) & (previous_15 <= previous_45)))

rawDescription: Python and Pandas - Moving Average Crossover


code:
def on_focus_username(self, event):
    if self.user_text.GetForegroundColour() != wx.BLACK:
        self.user_text.SetForegroundColour(wx.BLACK)
        # Clear text when clicked/focused
        self.user_text.Clear()

def on_deselect_username(self, event):
    if self.user_text.GetLineLength(0) is 0:
        self.user_text.SetForegroundColour(wx.Colour(192, 192, 192))
        # Put a default message when unclicked/focused away
        self.user_text.SetValue("Enter Username")

rawDescription: Global event handlers in wxPython (Pheonix)


code: parser.add_argument('multi', nargs='+')

rawDescription: Why does argparse give me a list-in-a-list?


code:
image_file = StringIO('image from email')
image_file.seek(0, 2)  # Seek to the end
bytes = image_file.tell()  # Get no. of bytes
image_file.seek(0)  # Seek to the start
im = Image.open(image_file)

rawDescription: How to get bytes of image in StringIO container

description: Get bytes of image in StringIO container


code: from PIL import Image

rawDescription: Python on Mac: Image module cannot be installed


code: plot.setData(x, y_new)

rawDescription: How to clear a plot in a `while` loop when using PyQtGraph?

description: Clear a plot in a `while` loop when using PyQtGraph


code:
string = "antpieiw"
checkfor = "iwantpie"
checkOccurence(string, checkfor)
checkfor = "iwantpie234"
checkOccurenct(string, checkfor)

rawDescription: check a string for a substring where the end of the string loops around to the start

description: Check a string for a substring where the end of the string loops around to the start


code:
import hashlib

digests = []
for filename in ['canvas.png', 'img5.png']:
    hasher = hashlib.md5()
    with open(filename, 'rb') as f:
        buf = f.read()
        hasher.update(buf)
        a = hasher.hexdigest()
        digests.append(a)
        print(a)

print(digests[0] == digests[1])

rawDescription: Compare md5 hashes of two files in python


code:
new_func = partial(my_function, d=1, e=2, f=3)
new_func('a', 'b', 'c')
new_func = lambda a,b,c: my_function(a, b, c, 1, 2, 3)
new_func('a', 'b', 'c')

rawDescription: Passing default arguments to functions in Python


code: TEMPLATE_DIRS = ( "home/kevin/first/tutorial/temps", )

rawDescription: Django Tutorial - TemplateDoesNotExist at /polls/


code:
from collections import defaultdict

def list_sub_ddi(list1, list2):
    dd = defaultdict(int)
    for i in list1:
        dd[i] += 1

    for i in list2:
        dd[i] -= 1

    return (x for l in ([k]*n for k,n in dd.iteritems() if n>0) for x in l)

rawDescription: Can I perform minus or join operations on lists in python including duplicate entries

description: Perform minus or join operations on lists in python including duplicate entries


code:
class Product(models.Model):
    # ...
    @property
    def tags(self):
        return self.review_set.values_list('tag_set__name', flat=True).distinct()

def home(request):
    if request.user.is_authenticated():
        products = Product.objects.prefetch_related('review_set__tag_set')
        return render(request, 'home.html', {
            'products': products,
        })

rawDescription: Loop through tuple inside template returns null values


code:
A = np.genfromtxt('file.txt')
B = np.diff(A)
gap = B.max()

rawDescription: Python - Find width of bifurcation in x-y data


code:
def changeText(self):
    self.text = 'different text'
    self.label = QtGui.QLabel(self.text)
    self.initUI()

rawDescription: PyQt: Recreating widgets

description: PyQt: Recreating widgets


code:
import html.parser as htmlparser
parser = htmlparser.HTMLParser()
parser.unescape(text)

rawDescription: Change &#39 into normal character

description: Change &#39 into normal character


code:
postBody = self.request.get('body')
postBody = postBody.encode('iso-8859-1')
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
if DEBUG:
    r.body = postBody
else:
    postBody += "=" * ((4 - len(postBody) % 4) % 4)
    b64 = base64.urlsafe_b64decode(postBody)

rawDescription: How to properly decode Quoted Printable encoding in Django HTML Template

description: Properly decode Quoted Printable encoding in Django HTML Template


code:
x = 8
y = x
x = 4   # <-- Re-definition of x

rawDescription: Data-Binding in Python?

description: Data-Binding in Python


code:
unq
unq_idx
unq_cnt

rawDescription: Checking for and indexing non-unique/duplicate values in a numpy array


rawDescription: Get python decorator arguments at run time


code:
x = [[] for _ in range(n)]
x[0].append(1)
x

rawDescription: A sequence of empty lists of length n in Python?


code:
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

rawDescription: How do I apply a style to the whole row using XLWT Python Excel?

description: Apply a style to the whole row using XLWT Python Excel


rawDescription: Combine many similar regex in one in Python


code:
req = urllib2.Request("web_url/public/api.php?path_info=/projects/add&token=####################", params)
resp = urllib2.urlopen(req)
resp_data = f.read()
if not resp.code == 200 and resp.headers.get('content-type') == 'text/xml':
  # Do your error handling.
  raise Exception('Unexpected response',req,resp)
data = etree.XML(resp_data)
api_id = int(data.xpath('/project/id/text()')[0])
project.API_id = api_id
project.save()

rawDescription: Assigning variables from XML returned from an API call


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--add", help="Add prefix to string")
args = parser.parse_args()

rawDescription: How to make sys.argv arguments optional? (Python)

description: Make sys.argv arguments optional? (Python)


rawDescription: Time series normalization by event

description: Time series normalization by event


code:
import os
os.system("notepad.exe file.txt")

rawDescription: Open a text file window using Python

description: Open a text file window using Python


rawDescription: using functions: print vs return

description: Using functions: print vs return


code: valid_words = [valid for valid in replaces if lookup(valid)]

rawDescription: The Alphabet and Recursion

description: The Alphabet and Recursion


code:
parensnumber = re.compile(r'\s*\((\d+)\)')

count = int(parensnumber.search(line).group(1))
for i in range(count):
    print(parensnumber.sub('-{0}'.format(i + 1), line))

rawDescription: How to parse a number from line

description: Parse a number from line


code:
funcType = type( foo.__cmp__ )
# Alternatively:
import new
cmp2 = new.instancemethod( func, a, foo )

a.__cmp__ = funcType( cmp2, a, foo )
b.__cmp__ = funcType( cmp2, b, foo )

rawDescription: How can i change the __cmp__ function of an instance (not in class)?

description: Change the __cmp__ function of an instance (not in class)


code:
results = soup.find_all(...) # function as before
scraped_paragraphs = map(lambda element: element.string, results)

rawDescription: Python scraping with BeautifulSoup, Only scrape paragraphs with certain word in it


rawDescription: Max similarity of two character dictionaries?


rawDescription: How does Python interpreter look for types?


code:
import test
c = test.TestClass()
c.greetings('Superman')

rawDescription: Passing an argument to a function in a different script?


code:
f, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, sharex='col',
                                           sharey='row', figsize=(5,5))

rawDescription: Matplotlib: Gridspec and aspect='auto' not compatible?


code:
def tree_widget_list(self, show_list):
    """
    Creates a list for updating tree widget
    :param show_list:
    :return:
    """
    items = []
    for item in show_list:
        item_parts = item.split('\\')

        entry = QtGui.QTreeWidgetItem(None, [item_parts[0]])
        items_text = [i.text(0) for i in items]
        if entry.text(0) not in items_text:
            parent_item = entry
        else:
            parent_index = items_text.index(entry.text(0))
            parent_item = items[parent_index]

        if len(item_parts) > 1:
            for i in item_parts[1:]:
                child_item = QtGui.QTreeWidgetItem(None, [i])
                child_list_text = [parent_item.child(i).text(0) for i in xrange(parent_item.childCount())]
                if child_item.text(0) in child_list_text:
                    child_index = child_list_text.index(child_item.text(0))
                    parent_item = parent_item.child(child_index)
                else:
                    parent_item.addChild(child_item)
                    parent_item = child_item
        items.append(entry) if entry.text(0) not in items_text else None
    return items

rawDescription: Duplicates in QTreeWidget

description: Duplicates in QTreeWidget


rawDescription: Is this calculation executed in Python?

description: Is this calculation executed in Python


code:
class Countries:  # pseudo-enum
    NEW_ZEALAND = 1
    UNITED_STATES = 2

rawDescription: Python style: lowercase class names for "namespaces"?


code:
def cut_out_emphasis(str1):
    list1 = ["b", "i", "ul"]
    str2 = ""
    for x in list1:
        str2 = r'%s|%s|\/%s' % (str2, x, x)
    str2 = r'<(%s)[^>]*>' % (str2, )
    re_compiled = re.compile(str2, re.IGNORECASE)
    str1 = re_compiled.sub(', ', str1)
    return str1

rawDescription: python regex sub compile with flags

description: Python regex sub compile with flags


code:
mm  = Person('Grandma', 'F')
mf  = Person('Grandpa', 'M')
m   = Person('Mom', 'F', [mm, mf])
fm  = Person('Nana', 'F')
ff  = Person('Papi', 'M')
f   = Person('Dad', 'M', [fm, ff])
me  = Person('Me', 'M', [m, f])
s   = Person('Sis', 'F', [m, f])
joe = Person('Brother-in-law', 'M')
s1  = Person('Andy', 'M', [s, joe])
s2  = Person('Betty', 'F', [s, joe])
s3  = Person('Carl', 'M', [s, joe])

me.print_relation("grandmother")    # returns 'Nana, Grandma'
me.print_relation("nephew")         # returns 'Andy, Carl'

rawDescription: How do I init a class, Class.__init__(self), from inside this recursive function?

description: Init a class, Class.__init__(self), from inside this recursive function


rawDescription: Port MATLAB bounding ellipsoid code to Python


code:
for obj in all_objects:
    if hasattr(obj, 'gravity'):
        obj.gravity()

rawDescription: Call the same method in all objects in Python?


code:
class QtCapture(QtGui.QWidget):
    def __init__(self, *args):
        super(QtGui.QWidget, self).__init__()

        self.fps = 24
        self.cap = cv2.VideoCapture(*args)

        self.video_frame = QtGui.QLabel()
        lay = QtGui.QVBoxLayout()
        lay.setMargin(0)
        lay.addWidget(self.video_frame)
        self.setLayout(lay)

    def setFPS(self, fps):
        self.fps = fps

    def nextFrameSlot(self):
        ret, frame = self.cap.read()
        # My webcam yields frames in BGR format
        frame = cv2.cvtColor(frame, cv2.cv.CV_BGR2RGB)
        img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)
        pix = QtGui.QPixmap.fromImage(img)
        self.video_frame.setPixmap(pix)

    def start(self):
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.nextFrameSlot)
        self.timer.start(1000./self.fps)

    def stop(self):
        self.timer.stop()

    def deleteLater(self):
        self.cap.release()
        super(QtGui.QWidget, self).deleteLater()

rawDescription: Display OpenCv window on top of PyQt's main window


code:
import numpy as np

N = 1000
P = np.repeat(np.array([1, 2, 3, 4, 5]),N)
T = np.repeat(np.array([0, 0, 1, 1, 1]),N)

def using_bincount():
    U,inverse = np.unique(T,return_inverse=True)
    Q = np.bincount(inverse,weights=P)
    return Q,U
    # (array([  3.,  12.]), array([0, 1]))

def using_lc():
    U = list(set(T))
    Q = [sum([p for (p,t) in zip(P,T) if t == u]) for u in U]
    return Q,U

def using_slice():
    U = np.unique(T)
    Q = np.array([P[T == u].sum() for u in U])
    return Q,U

rawDescription: Numpy vectorization algorithms to sum up numbers with the same time stamps


code:
a = LI()
a.append(1,2,3,4)
a.append(5)

rawDescription: Overriding list method

description: Overriding list method


code:
from __future__ import print_function
from numpy.random import rand
from IPython.parallel import Client
from mkl import set_num_threads
from timeit import default_timer as clock
from scipy.linalg import eig
from functools import partial
from itertools import product

eig = partial(eig, right=False)  # desired keyword arg as standard

class Bench(object):
    def __init__(self, m_size, n_mat, repeat=3):
        self.n_mat = n_mat
        self.matrix = rand(n_mat, m_size, m_size)
        self.repeat = repeat
        self.rc = Client()

    def map(self):
        results = map(eig, self.matrix)

    def ip_map(self):
        results = self.view.map_sync(eig, self.matrix)

    def parfor(self):
        results = {}
        for i in range(self.n_mat):
            results[i] = self.view.apply_async(eig, self.matrix[i,:,:])
        for i in range(self.n_mat):
            results[i] = results[i].get()

    def timer(self, func):
        t = clock()
        func()
        return clock() - t

    def run(self, func, n_engines, n_mkl, view_method):
        self.view = view_method(range(n_engines))
        self.view.apply_sync(set_num_threads, n_mkl)
        set_num_threads(n_mkl)
        return min(self.timer(func) for _ in range(self.repeat))

    def run_all(self):
        funcs = self.ip_map, self.parfor
        n_engines = 2, 4
        n_mkls = 1, 2
        views = self.rc.direct_view, self.rc.load_balanced_view
        times = []
        for n_mkl in n_mkls:
            args = self.map, 0, n_mkl, views[0]
            times.append(self.run(*args))
        for args in product(funcs, n_engines, n_mkls, views):
            times.append(self.run(*args))
        return times

rawDescription: Is it worth using IPython parallel with scipy's eig?


code:
t = df.groupby(["license","month"]).apply(len)
t.unstack(level=0).reindex(index=range(1,13), fill_value=0).T.fillna(0)

rawDescription: statistics with "group by" or "uniq"

description: Statistics with "group by" or "uniq"


rawDescription: Turning an existing array into a multidimensional


code:
from subprocess import Popen, PIPE

input = "some input"
cproc = Popen("c_prog", stdin=PIPE, stdout=PIPE)
out, err = cproc.communicate(input)

rawDescription: Pass many pieces of data from Python to C program


code:
lst1 = random.sample(range(20), 10)
lst2 = random.sample(range(20), 10)
zip(lst1, lst2)

rawDescription: Generating random vertices that don't repeat


rawDescription: Trying to create an array of x and y values after reading file in Python


rawDescription: semantics of generating symmetric matrices in numpy

description: Semantics of generating symmetric matrices in numpy


code: from matplotlib.rcsetup import defaultParams

rawDescription: .matplotlibrc and default options

description: .matplotlibrc and default options


rawDescription: replace only first occurrence of field/word on a file

description: Replace only first occurrence of field/word on a file


code:
mappings = [
    # (regex, action_name)
    (r'Hi ([a-z]+)!', greet),
    (r'Bye', bye),
]

def greet(msg):
    return 'Hello'

def bye(msg):
    return 'Bye'

rawDescription: Python: Loading data from a file into an IRC bot


code:
p = playerPrefs()
p.createNew()

rawDescription: Importing functions from classes outside original file


rawDescription: Python: obtain multidimensional matrix as results from a function


code:
e <- d[1, ]
o <- d[2, ]
chisq.test(o, p = e / sum(e), correct = FALSE)

rawDescription: Different P values for chi square test in Python and R


code: [''.join(j for j in i if j not in forbiddenList) for i in tempList]

rawDescription: how to remove characters from items in a list, using another list as reference

description: Remove characters from items in a list, using another list as reference


code:
g = df_city.groupby('moveyear')
df_city['moveyearemp'] = 0
for year, ind in g.indices.iteritems():
    year_abbr = str(year)[2:]
    df_city.loc[ind, 'moveyearemp'] = df_city.loc[ind, 'jobs%s' % year_abbr]

rawDescription: pandas: grabbing value of column based on value of other variable

description: Pandas: grabbing value of column based on value of other variable


rawDescription: Python - Why doesn't this instance method need parentheses when called inside another instance method?


code:
script = r"C:/Users/dell/byteyears.py"
head, tail = os.path.split(script)
os.path.join(head, 'Python27', tail)

rawDescription: adding string in others

description: Adding string in others


code:
import numpy as np
class Foo():
    def foo(self):
        return np.random.random()

a = np.empty((10,10), dtype=object)
for ind,v in np.ndenumerate(a):
    a[ind] = Foo()

def evaluate_and_reshape(a, shape):
    it = np.nditer( op    = [a.reshape(shape),None],
                    flags = ['multi_index','refs_ok'],
                    op_flags = [['readonly'],
                                ['writeonly','allocate']],
                    op_dtypes = [object, float],
                    itershape = (shape)
                  )
    while not it.finished:
        ind = it.multi_index
        it.operands[1][ind] = it.operands[0][ind].foo()
        it.iternext()
    return it.operands[1]

def sol1():
    return evaluate_and_reshape(a,(20,5))

def sol2():
    return np.reshape( [o.foo() for o in a.flat], (20,5) )

rawDescription: Get array which is the result of invoking a function on each element of an object array


code: df2.columns = df.unique()

rawDescription: Sorting through list and storing distinct values


code:
import time
def key(item):
    return time.strptime(item[0][-16:], "%d/%m/%y à %H:%M")

rawDescription: python - sorting a list of lists by a key that's substring of each element

description: Python - sorting a list of lists by a key that's substring of each element


rawDescription: Replace the contents of a list rather than appending to it


code:
class MyPage:
    def POST(self):
        data = web.input()
        eval(data.code)

rawDescription: Running Python code from an HTML form

description: Running Python code from an HTML form


code:
import json
import re

json_string = """{
  "prop_1": {
    "prop_1_1": ["some <html> data", 17, "more <html> data"],
    "prop_1_2": "here some <html>, too"
  },
  "prop_2": "and more <html>"
}"""

def unhtml(string):
    # replace <tag>...</tag>, possibly more than once
    done = False
    while not done:
        temp = re.sub(r'<([^/]\S*)[^>]*>[\s\S]*?</\1>', '', string)
        done = temp == string
        string = temp
    # replace remaining standalone tags, if any
    string = re.sub(r'<[^>]*>', '', string)
    string = re.sub(r'\s{2,}', ' ', string)
    return string.strip()

def cleanup(element):
    if isinstance(element, list):
        for i, item in enumerate(element):
            element[i] = cleanup(item)
    elif isinstance(element, dict):
        for key in element.keys():
            element[key] = cleanup(element[key])
    elif isinstance(element, basestring):
        element = unhtml(element)

    return element

rawDescription: How can I strip all the HTML content from a JSON file?

description: Strip all the HTML content from a JSON file


code:
def sorted(s, num):
    tmp = s.order(ascending=False)[:num]
    tmp.index = range(num)
    return tmp

rawDescription: Get top biggest values from each column of the pandas.DataFrame


rawDescription: python get substring from regex

description: Python get substring from regex


code:
# in __init__.py
from model.foo import Foo
from model.bar import Bar

rawDescription: How can I split a module into multiple files, without breaking a backwards compatibly?

description: Split a module into multiple files, without breaking a backwards compatibly


rawDescription: creating and referencing separate matplotlib plots

description: Creating and referencing separate matplotlib plots


code:
import os
original_user = os.environ.get('SUDO_USER')
original_uid = os.environ.get('SUDO_UID')
original_gid = os.environ.get('SUDO_GID')

rawDescription: python subprocess as normal user

description: Python subprocess as normal user


code:
import sys
sys.stdout.encoding
u'\xf4'.encode('cp852')

rawDescription: Python's string.format() and Unicode

description: Python's string.format() and Unicode


rawDescription: How to close program in python opened by os.system()?

description: Close program in python opened by os.system()


rawDescription: How to start a file that has a period in front of it?

description: Start a file that has a period in front of it


rawDescription: how to insert two lists as values to a dictionary to the same key

description: Insert two lists as values to a dictionary to the same key


code:
#ipython_notebook::before{content:"Welcome to my notebook"}
#ipython_notebook img{display:none;}

rawDescription: Customize welcome page of ipython notebook


rawDescription: Parsing code with python

description: Parsing code with python


code:
entry_points = """
[distutils.commands]
compile_catalog = babel.messages.frontend:compile_catalog
extract_messages = babel.messages.frontend:extract_messages
init_catalog = babel.messages.frontend:init_catalog
update_catalog = babel.messages.frontend:update_catalog
"""

rawDescription: Distribute, epydoc, and setup.py

description: Distribute, epydoc, and setup.py


code:
reverse_mapping = {}

class A(object):
    _internal_attribute = 'A attribute'

reverse_mapping[A._internal_attribute] = A

rawDescription: Reverse mapping class attributes to classes in Python


code:
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'path.to.MyRenderer',
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}

rawDescription: Django doesn't parse a custom http accept header


code:
def nonlocals():
    import inspect
    stack = inspect.stack()
    if len(stack) < 3: return {}
    f = stack[2][0]
    res = {}
    while f.f_back:
        res.update({k:v for k,v in f.f_locals.items() if k not in res})
        f = f.f_back
    return res

rawDescription: Is there a way to get a dict object with nonlocal variables?


code: '\r\n\r\nYour order was delivered\r\non\r\n6/4\r\n@\r\n4:44 PM\r\n'

rawDescription: Parsing HTML tree in lxml : how can I retrieve the text inside the element?


code:
Counter({'act art': 2, 'act pho': 1, 'act act': 1, 'act pro': 1, 'act evt': 1,
'act pos': 1})

rawDescription: Python to group elements in specified column


code: print("T\u00fcrk K\u0131z\u0131lay\u0131 Genel Ba\u015fkan\u0131m\u0131z Sn. @AhmetLutfiAkar yar\u0131n sabah 08:00'e TV8'de canl\u0131 yay\u0131n konu\u011fu olacak... @TurkKizilayi".decode('raw_unicode_escape'))

rawDescription: Somali encoding

description: Somali encoding


code:
def list(self, request):
    queryset = SomeObject.objects.filter(owner=request.user)

rawDescription: Get Authenticated user from token in Django Rest Framework


code:
import struct
from collections import namedtuple
data = "1"*23
fmt = "20c3B"
Rec = namedtuple('Rec', 'text index')
r = Rec._make([struct.unpack_from(fmt, data)[0:20], struct.unpack_from(fmt, data)[20:]])
r

rawDescription: Is there an elegant way to use struct and namedtuple instead of this?


code:
def memoize(func):
    memo = dict()
    def decorated(n):
        if n not in memo:
            memo[n] = func(n)
        return memo[n]

    return decorated

@memoize
def fib(n):
    #added for demonstration purposes only - not really needed
    global call_count
    call_count = call_count + 1
    #end demonstration purposes

    if n<=1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

call_count = 0 #added for demonstration purposes only - not really needed
for i in range(100):
    print(fib(i))
print(call_count) #prints 100

rawDescription: How do I print a fibonacci sequence to the nth number in Python?

description: Print a fibonacci sequence to the nth number in Python


rawDescription: How to avoid brackets in SQL around Django custom database function call?

description: Avoid brackets in SQL around Django custom database function call


rawDescription: python changing string to date

description: Python changing string to date


code: from functools import partial

rawDescription: enable or disable a field in maya ui with python

description: Enable or disable a field in maya ui with python


code:
...
canvas.pack()
name = '' # initialize a 'name' variable

rawDescription: How to use other variables from other definitions using buttons?

description: Use other variables from other definitions using buttons


rawDescription: Python - Tuple generation from list

description: Python - Tuple generation from list


code:
line.strip(' \n' '\r')
line = line.split(',')
line = [int(num) for num in line]
Network.append(line)

rawDescription: Class and Array Problems

description: Class and Array Problems


rawDescription: Check if characters after delimiter exist in Python


code:
r = "the"
"".join(x*2 for x in r)

rawDescription: How to make a program that doubles letters (input = hello, returns = hheelllloo)

description: Make a program that doubles letters (input = hello, returns = hheelllloo)


code:
num_words = len(corpus)
fvs = [[0]*num_words for _ in docs]

rawDescription: Python: implementing feature vectors efficiently


code:
import random, numpy
numpy.nextafter(0,1)
random.uniform(0, numpy.nextafter(0,1))
random.uniform(0, numpy.nextafter(0,1))
random.uniform(0, numpy.nextafter(0,1))

rawDescription: How do I clip a floating-point number to just below a limit?

description: Clip a floating-point number to just below a limit


code:
math.radians(90)
math.radians(180)

rawDescription: Using PI in python 2.7

description: Using PI in python 2.7


rawDescription: Editing a list to add strings in in different positions to output a formatted string


code: min(example, key=lambda element: (element[0] / element[1]) + element[1])

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code:
def register(*decorators):
    def register_wrapper(func):
        for deco in decorators[::-1]:
            func=deco(func)
        func._decorators=decorators
        return func
    return register_wrapper

rawDescription: Introspection to get decorator names on a method?


code:
def get_from_m(m, i, numc=2):
    a = m[i,:].toarray().flatten()
    argsa = a.argsort()
    return dict( zip( argsa[-numc:], a[ argsa[-numc:] ] ) )

rawDescription: Dictionaries containing the biggest values


code:
class SomePipeline(object):

  ...

  def process_item(self, item, spider):
      with open('file.txt', 'w') as f:

          # format your item into a line here

          f.write(line)

rawDescription: Export scrapy objects into one file per item


code:
#! /usr/bin/env python
import sys

def main():
    #
    # Do something ... Whatever processing you need to do, make it happen here.
    # Don't shove everything into main, break it up into testable functions!
    #
    # Whatever this function returns, is what the exit code of the interpreter,
    # i.e. your script, will be.  Because main is called by sys.exit(), it will
    # behave differently depending on what you return.
    #
    # So, if you return None, 0 is returned.  If you return integer, that
    # return code is used.  Anything else is printed to the console and 1 (error)
    # is returned.
    #
    if an_error_occurred:
        return 'I\'m returning a string, it will be printed and 1 returned'

    # Otherwise 0, success is returned.
    return 0

# This is true if the script is run by the interpreter, not imported by another
# module.
if __name__ == '__main__':
    # main should return 0 for success, something else (usually 1) for error.
    sys.exit(main())

rawDescription: How to make an executable to use in a shell - Python

description: Make an executable to use in a shell - Python


code:
import os

def freopen(filename, mode, fobj):
    new = open(filename, mode)
    newfd = new.fileno()
    targetfd = fobj.fileno()
    os.close(targetfd)
    os.dup2(newfd, targetfd)

rawDescription: How do I change that which is inherited by stdout=None in subrocess.Popen(stdout=None)?

description: Change that which is inherited by stdout=None in subrocess.Popen(stdout=None)


code:
# or

category = request.GET.get('category')
something = request.GET.get('something')
from_price = request.GET.get('from_price')
to_price = request.GET.get('to_price')

q = Q()
if category:
    q |= Q(category=category)
if something:
    q |= Q(something=something)
if from_price:
    q |= Q(price__gt=from_price)
if to_price:
    q |= Q(price__lt=to_price)

d = Data.objects.filter(q)

rawDescription: How to filter data If I filled (for example) only to_price?

description: Filter data If I filled (for example) only to_price


code:
import pandas as pd
import numpy as np
import pandas.io.data as web

def infer_freq(ts):
    med  = np.median(np.diff(ts.index.values))
    seconds = int(med.astype('timedelta64[s]').item().total_seconds())
    if seconds < 60:
        freq = '{}s'.format(seconds)
    elif seconds < 3600:
        freq = '{}T'.format(seconds//60)
    elif seconds < 86400:
        freq = '{}H'.format(seconds//3600)
    elif seconds < 604800:
        freq = '{}D'.format(seconds//86400)
    elif seconds < 2678400:
        freq = '{}W'.format(seconds//604800)
    elif seconds < 7948800:
        freq = '{}M'.format(seconds//2678400)
    else:
        freq = '{}Q'.format(seconds//7948800)
    return ts.asfreq(freq, method='ffill')

aapl = web.get_data_yahoo("AAPL")
print(infer_freq(aapl))

rawDescription: How can I approximate the periodicity of a panda time Series

description: Approximate the periodicity of a panda time Series


code:
from django.conf.urls import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'commonApp.views.get_homepage', name='home'),
    url(r'^login$', 'django.contrib.auth.views.login', name="login"),
    url(r'^logout$', 'django.contrib.auth.views.logout',
        {"next_page": "/"}, name="logout"),
# Admin
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

# Auto-add the applications.
for app in settings.LOCAL_APPS:
    urlpatterns += patterns('',
        url(r'^{0}/'.format(app), include(app + '.urls', namespace=app)),
    )

rawDescription: Django serving each app separately in each its port


code:
number = 523.60000001
rounded = round(number, 3)
rounded

rawDescription: How can I stop printing a float 3 spaces after decimal?

description: Stop printing a float 3 spaces after decimal


code:
g = meshgrid2(x, y, z)
positions = np.vstack(map(np.ravel, g))

rawDescription: Numpy meshgrid points

description: Numpy meshgrid points


code:
import pyglet

def foo(value):
    print("I'm in a loop...")

def main():
    w = pyglet.window.Window()
    @w.event
    def on_draw():
        foo(None)
    pyglet.clock.schedule_interval(foo, 1.0)
    pyglet.app.run()

main()

rawDescription: Where's Pyglet mainloop?

description: Where's Pyglet mainloop


code:
class Part(...):
    product = relationship('products', back_populates='parts')

class Product(...):
    parts = relationship('products', back_populates='product')
    pass

rawDescription: SQLAlchemy relationship introspection

description: SQLAlchemy relationship introspection


code:
df['one'] = 1
df['rolling_count'] = grouped.one.apply(f1)
df = df.drop('one', axis=1)

rawDescription: Python and Pandas - column that "count direction" and show "avarage until now"


code:
def cpu_process_util(pid):
    """
    Returns the process usage of CPU

    Source: http://www.philosophicalgeek.com/2009/01/03/determine-cpu-usage-of-current-process-c-and-c/
    :return: Process CPU usage (int)
    """

    # Creates a process handle
    proc = win32api.OpenProcess(ALL_PROCESS_ACCESS, False, pid)

    FirstProcessTimes = win32process.GetProcessTimes(proc)
    time.sleep(SLEEP_TIME_1_5)
    SecProcessTimes = win32process.GetProcessTimes(proc)

    """
     Process CPU usage is calculated by getting the total amount of time
     the system has operated since the last measurement
     made up of kernel + user) and the total
     amount of time the process has run (kernel + user).
    """

    proc_time_user_prev = FirstProcessTimes['UserTime']
    proc_time_kernel_prev = FirstProcessTimes['KernelTime']

    proc_time_user = SecProcessTimes['UserTime']
    proc_time_kernel = SecProcessTimes['KernelTime']

    proc_usr = proc_time_user - proc_time_user_prev
    proc_ker = proc_time_kernel - proc_time_kernel_prev

    proc_total_time = proc_usr + proc_ker

    return (100 * proc_total_time) / get_sys()

rawDescription: Calculating process cpu usage by Python

description: Calculating process cpu usage by Python


code:
def some_view(request):
     form = TransactionForm(user=request.user)

rawDescription: Django: Filter ModelChoiceField by user

description: Django: Filter ModelChoiceField by user


code: fieldnames = {None: c1.fieldnames[None] + c2.fieldnames[None]}

rawDescription: Python: Concatenate two dictReader strings for header row


code:
class ContributionAdmin(admin.ModelAdmin):
    raw_id_fields = ('subscriber', )

rawDescription: Django admin site : Help needed

description: Django admin site : Help needed


code: 1 in l

rawDescription: Test if value exists in several lists

description: Test if value exists in several lists


code: func = lambda h: h+2

rawDescription: translating matlab code to python: optmizing numerical functions

description: Translating matlab code to python: optmizing numerical functions


rawDescription: Extract items of integers from a regularly spaced list in Python


rawDescription: Python query: iterating through log file


rawDescription: press Javascript generated button with Selenium?

description: Press Javascript generated button with Selenium


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

theta, phi = np.linspace(0, 2 * np.pi, 40), np.linspace(0, np.pi, 40)
THETA, PHI = np.meshgrid(theta, phi)
R = np.cos(PHI**2)
X = R * np.sin(PHI) * np.cos(THETA)
Y = R * np.sin(PHI) * np.sin(THETA)
Z = R * np.cos(PHI)
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
plot = ax.plot_surface(
    X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('jet'),
    linewidth=0, antialiased=False, alpha=0.5)

plt.show()

rawDescription: Spherical coordinates plot in matplotlib


rawDescription: stripping the zeros in csv with python

description: Stripping the zeros in csv with python


code: prime = True

rawDescription: Failing to change bool var state in loop


code:
with open("sample.txt", "rb") as f:
    from itertools import islice
    print(np.genfromtxt(islice(f, start, end+1), delimiter=",", usecols=cols))

rawDescription: load a certain number of rows from csv with numpy

description: Load a certain number of rows from csv with numpy


code:
try:
    # Python 2
    from string import maketrans
except ImportError:
    # Python 3 made maketrans a static method
    maketrans = str.maketrans

vowels = 'aeiouy'
upper_map = maketrans(vowels, vowels.upper())
mystring = "hello world"
mystring.translate(upper_map)

rawDescription: python how to uppercase some characters in string

description: Python how to uppercase some characters in string


rawDescription: How can I make Selenium use my firefox (not create a fresh one)

description: Make Selenium use my firefox (not create a fresh one)


code:
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC

class wait_for_text_to_match(object):
    def __init__(self, locator, pattern):
        self.locator = locator
        self.pattern = pattern

    def __call__(self, driver):
        try:
            element_text = EC._find_element(driver, self.locator).text
            return self.pattern.search(element_text)
        except StaleElementReferenceException:
            return False

rawDescription: How can I get Selenium WebDriver to wait until <dd> element contains data before proceeding?

description: Get Selenium WebDriver to wait until <dd> element contains data before proceeding


rawDescription: Create multi-level index pandas dataframe from delimited string column


code:
from operator import itemgetter

score_list = score()
score_list.sort(key=itemgetter(2), reversed=True) # sort list descending by third element
for i, values in enumerate(score_list):
    print(values, i+1) # print values and rank

rawDescription: sorting a list in python

description: Sorting a list in python


code: ['example1', 'example2', 'example3']

rawDescription: Python - Trouble Parsing XML

description: Python - Trouble Parsing XML


code:
from django import conf, contrib, db, http, shortcuts, template, utils
from django.core import urlresolvers, paginator

rawDescription: django/python imports perfomance

description: Django/python imports perfomance


code: a=[zip(*i) for i in [list(g) for _,g in groupby(t,lambda x : x[0])]]

rawDescription: Reorganise list in list python

description: Reorganise list in list python


rawDescription: NumPy genfromtxt - skipping rows that start with specific number