code:
import re # to be able to use regular expressions
count = 0
found_one_at_least = False
result = ""
with open("read_file", "r") as f:
    for line in f:
        if re.search(regexp, line) is not None: # single line re to know when to start recording; returns None if there is no match, help(re.search) will tell you
            break # stop this loop and go on to the actual recording
    for line in f: # this will continue reading from where the last loop stopped, because it is an f is an iterator
        # to make it not do that you can use f.seek(0), but we do not need that
        result += line # append the line to the result
        count += line.count("[")-line.count("]") # compute the number of open/close brackets
        if count >= 1: # this is just so it does not stop at the first line if there is no [ in it
            found_one_at_least = True
        if count == 0 and found_one_at_least:
            break # stop recording when we are back at the "root" level
with open("write_file", "w") as f: # open the file, and let python handle closing and cleaning up...
    f.write(result) # write the result

rawDescription: Stripping custom methods using python

description: Stripping custom methods using python


rawDescription: Running a program from its Directory Using Cron


code:
import cv2
import cPickle

im=cv2.imread("/home/bikz05/Desktop/dataset/checkered-3.jpg")
gr=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
d=cv2.FeatureDetector_create("SIFT")
kp=d.detect(gr)

index = []
for point in kp:
    temp = (point.pt, point.size, point.angle, point.response, point.octave,
        point.class_id)
    index.append(temp)

# Dump the keypoints
f = open("/home/bikz05/Desktop/dataset/keypoints.txt", "w")
f.write(cPickle.dumps(index))
f.close()

rawDescription: OpenCV-Python : Find a code for writing keypoins to a file


code:
class Subthing(models.Model):
    ...
    thing = models.ForeignKey(Thing, related_name='subthings')
    ...

rawDescription: A puzzle concerning Q objects and Foreign Keys


code:
from werkzeug.routing import SubPath

app = Flask(__name__)

# register blueprints and extensions
# load config, etc.

app.url_map._rules = SubPath(app.config['APPLICATION_ROOT'], app.url_map._rules)

rawDescription: Add route prefix to Flask application running behing Gunicorn


code:
hex_string = '\x70f=l\x26hl=en\x26geocode=\x26q\x3c'
ascii_string = reformat_content(hex_string)
hex_string == ascii_string

rawDescription: How to convert hex string "\x89PNG" to plain text in python

description: Convert hex string "\x89PNG" to plain text in python


code:
from collections import OrderedDict

class EnumMeta(type):

    def __new__(mcls, cls, bases, d):
        print(d)
        return type.__new__(mcls, cls, bases, d)

    @classmethod
    def __prepare__(mcls, cls, bases):
        return OrderedDict()

class Color(metaclass=EnumMeta):
    red = 1
    green = 2
    blue = 3

rawDescription: How to get attributes in the order they are declared in a Python class?

description: Get attributes in the order they are declared in a Python class


code:
l.check(
    ('root', 'INFO', 'a message'),
    ('root', 'ERROR', 'another error'),
    )

rawDescription: Writing a unit test for Python logger formatted output


code:
from django.conf import settings

def interceptor(request):
    return {'interceptor': settings.HTTP_AJAX_INTERCEPTOR}

rawDescription: Sending a value in context to all template renderd in Django without sending in context in every view


rawDescription: pandas - parsing column containing strings and column containing int into datetime

description: Pandas - parsing column containing strings and column containing int into datetime


code:
class Model(object):
 pass
class View(object):
 pass
class Controller(object):
 model = Model()
 view = View()

rawDescription: Laying out MVC classes in Python

description: Laying out MVC classes in Python


code:
lis=[('Knightriders',), ('The Black Knight',), ('Fly by Knight',), ('An Arabian Knight',), ('A Bold, Bad Knight',)]
[x[0] for x in lis]

rawDescription: Convert list of single element tuples to list of elements


rawDescription: wx.lib.pubsub: How to change the value in a timer

description: Wx.lib.pubsub: How to change the value in a timer


rawDescription: Partial replacement with re.sub()

description: Partial replacement with re.sub()


code:
class Foo(object):
    __initialized = False
    def __init__(self, a, b):
        try:
            self.a = a
            self.b = b
            # ...
        finally:
            self.__initialized = True

    def __setattr__(self, attr, value):
        if self.__initialzed:
            print(self.b)
        super(Foo, self).__setattr__(attr, value)

rawDescription: Overriding __setattr__ at runtime

description: Overriding __setattr__ at runtime


code:
def difference_np(array, subset_length):
    assert subset_length > 2, "subset_length must be larger than 2"
    length = array.size
    total_diff = array.max()-array.min()

    current_min = array[:subset_length].min()
    current_max = array[:subset_length].max()
    max_diff = current_max - current_min
    max_diff_index = 0
    index = subset_length
    while index < length:
        i_new = index
        i_old = index-number
        index += 1
        new = array[i_new]
        old = array[i_old]

        # the idea here is to avoid calculating the
        #   min/max over the entire subset as much as possible,
        #   so we treat every edge case separately.
        if new < current_min:
            current_min = new
            if old == current_max:
                current_max = array[i_old+1:i_new-1].max()
        elif new > current_max:
            current_max = new
            if old == current_min:
                current_min = array[i_old+1:i_new-1].min()
        elif old == current_min:
            current_min = array[i_old+1:i_new].min()
        elif old == current_max:
            current_max = array[i_old+1:i_new].max()
        else:
            continue

        current_diff = current_max-current_min
        if current_diff > max_diff:
            max_diff = current_diff
            max_diff_index = i_old

        # shortcut-condition
        if max_diff == total_diff:
            print('shortcut at', (index-1)/(length-subset_length), '%' )
            break

    return max_diff, max_diff_index

rawDescription: Efficient way to iterate over sublists of a huge list in python


code: zip(*ix)

rawDescription: advanced numpy/pandas indexing

description: Advanced numpy/pandas indexing


code: {{ object|has_voted:user }}

rawDescription: Is it possible to perform model methods in a template?


code:
df = pd.read_csv("2013indiv_unit_reported_data.txt", delim_whitespace=True,
                 names=["rowcol", "data"])
df["row"] = df["rowcol"].str[:14]
df["col"] = df["rowcol"].str[14:]
df_new = df.pivot(index="row", columns="col", values="data")
df_new = df_new.fillna("")
df_new.to_csv("table.dat", index=False)

rawDescription: Transpose Census Flat Files in Python

description: Transpose Census Flat Files in Python


code:
import sys
import liball
sys.modules['foo'] = liball
sys.modules['bar'] = liball

rawDescription: fake python modules via symlinks: on windows?

description: Fake python modules via symlinks: on windows


rawDescription: python pandas: computing argmax of column in matrix subset

description: Python pandas: computing argmax of column in matrix subset


code:
def plot_with_zoom(*args, **kwargs):
    im = ax.imshow(*args, **kwargs)
    imcopy = copy.copy(im)
    axins.add_artist(imcopy)

rawDescription: Zoomed inset in matplotlib without re-plotting data


code: response = json.dumps(response.text, sort_keys = False, indent = 2)

rawDescription: Pretty Display JSON data from with Flask


rawDescription: Compare dictionary key, values with nested list elements - Python


rawDescription: Writing Calculated Info to the front of a text file in Python


code: MakeNewEntry(date=datetime.datetime.now(), id=123, **{column_name: data})

rawDescription: Can I use the value of a variable as a parameter name for a function?

description: Use the value of a variable as a parameter name for a function


code:
class Seeker(object):
    def __init__(self, *a, **k):
        self.l = list(*a, **k)
        self.d = {}

    def find(self, value):
        where = self.d.get(value)
        if where is None:
            self.d[value] = where = self.l.find(value)
        return where

    def __setitem__(self, index, value):
        if value in self.d: del self.d[value]
        self.l[index] = value

    # and so on for other mutators that invalidate self.d; then,

    def __getattr__(self, name):
        # delegate everything else to the list
        return getattr(self.l, name)

rawDescription: Efficient list manipulation in python

description: Efficient list manipulation in python


code:
for item in values:
   if item + " " not in keys:
       print(item)

rawDescription: Checking if an item in a list is in another list


code:
s = pd.Series(np.arange(55))
s
s.index = pd.MultiIndex.from_tuples(s.index.map(lambda x: (x/10, x%10)))
s.unstack(0)

rawDescription: Splitting pandas series into multiple columns


code:
class dgReplaceLibCommand(sublime_plugin.TextCommand):
    def run(self, edit, **args):
        if (args['replaceSet'] == "CFML to cfScript"):
            self.cfml_to_cfscript(edit)

rawDescription: How to pass args to an instance of sublime_plugin.WindowCommand?

description: Pass args to an instance of sublime_plugin.WindowCommand


code: getResponse()

rawDescription: Python array behaving weirdly

description: Python array behaving weirdly


code:
def module_method():
    return "I am a module method"

class ModClass:
     @staticmethod
     def static_method():
         # the static method gets passed nothing
         return "I am a static method"
     @classmethod
     def class_method(cls):
         # the class method gets passed the class (in this case ModCLass)
         return "I am a class method"
     def instance_method(self):
         # An instance method gets passed the instance of ModClass
         return "I am an instance method"

rawDescription: In Python how do I use a class method without passing an instance to it?


code:
...
url(r'URL/^(?P<url_param>[a-zA-Z0-9_]*)/$', 'views.view_for_all_pages', name='view_for_all_pages')
...

rawDescription: How can I get Django to create a unique URL view and page for each URLField entered

description: Get Django to create a unique URL view and page for each URLField entered


code: {{ data|pretty }}

rawDescription: jinja 2 nested dictionaries to yaml

description: Jinja 2 nested dictionaries to yaml


code:
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 = bottomright = prior = None
    n=0
    while n!=1:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONUP:
                if not topleft:
                    topleft = event.pos
                else:
                    bottomright = event.pos
                    n=1
        if topleft:
            prior = displayImage(screen, px, topleft, prior)
    return ( topleft + bottomright )

if __name__ == "__main__":
    input_loc = 'stack.png'
    output_loc = 'out.png'
    screen, px = setup(input_loc)
    left, upper, right, lower = mainLoop(screen, px)

    # ensure output rect always has positive width, height
    if right < left:
        left, right = right, left
    if lower < upper:
        lower, upper = upper, lower
    im = Image.open(input_loc)
    im = im.crop(( left, upper, right, lower))
    pygame.display.quit()
    im.save(output_loc)

rawDescription: Image Cropping using Python

description: Image Cropping using Python


code: original_query = list(query)

rawDescription: Python list is behaving weird

description: Python list is behaving weird


code:
history = ' '.join(list[-4:-1])
history

rawDescription: What is the most efficient method to parse this line of text?


code:
def parse_file(open_file):
    result = []

    for line in open_file:
        indent_level = len(line) - len(line.lstrip())
        if indent_level == 0:
            levels = ['','','']
        item = line.lstrip().split('(', 1)[0]
        levels[indent_level - 1] = item
        if indent_level == 3:
            result.append('.'.join(levels))
    return result

data1 = set(parse_file(file1))
data2 = set(parse_file(file2))

differences = [
    ('common elements', data1 & data2),
    ('missing from file2', data1 - data2),
    ('missing from file1', data2 - data1) ]

rawDescription: How to compare clusters?

description: Compare clusters


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

fig, ax = plt.subplots()
im = ax.imshow(np.random.random((10, 10)), cmap='gist_earth')
cbar = fig.colorbar(im)
cbar.set_label('Test', y=0, ha='right', rotation=-90, va='bottom')
plt.show()

rawDescription: How to move a colorbar label downward?

description: Move a colorbar label downward


code:
import itertools
myCombinedIterable = itertools.chain.from_iterable(mylistOfLists)
myCombinedList = list(myCombinedIterable)

rawDescription: Python: Combining a list of lists

description: Python: Combining a list of lists


rawDescription: Convert a list to dictionary in Python based on first index of list value


code:
class Rule( object ):
    def __init__( self, text ):
        self.text= text
    def test( self, A, B, C, D, E, F, G ):
        return eval( self.text )

r1= Rule( "A==B" )
r2= Rule( "A==B and B==C" )
r3= Rule( "A in {listname!s}".format( listname=someList ) )

rawDescription: How to write small DSL parser with operator module in python

description: Write small DSL parser with operator module in python


code:
def create_subgraph(G,sub_G,start_node):
    for n in G.successors_iter(start_node):
        sub_G.add_path([start_node,n])
        create_subgraph(G,sub_G,n)

rawDescription: NetworkX DiGraph create subgraph (DiGraph) by node


code:
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))

...

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'templates/'),
)

rawDescription: Django Userena - Correctly override default django app templates?


code:
from scrapy import log
from scrapy.contrib.spiders import XMLFeedSpider
from myproject.items import TestItem

class MySpider(XMLFeedSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com/feed.xml']
    iterator = 'iternodes' # This is actually unnecesary, since it's the default value
    itertag = 'item'

    def parse_node(self, response, node):
        log.msg('Hi, this is a <%s> node!: %s' % (self.itertag, ''.join(node.extract())))

        item = Item()
        item['id'] = node.select('@id').extract()
        item['name'] = node.select('name').extract()
        item['description'] = node.select('description').extract()
        return item

rawDescription: How to scrape xml urls with scrapy

description: Scrape xml urls with scrapy


code:
query_single_sql
[]

rawDescription: Python MySQLdb doesn't wait for the result


code:
fields = {'a': 'A', 'b': '', 'c': 'C'}
[key for key, value in fields.iteritems() if not value]

rawDescription: Doing validation across a large number of items using all()


rawDescription: How do you perform basic joins of two RDD tables in Spark using Python?

description: Perform basic joins of two RDD tables in Spark using Python


code:
from twisted.internet import defer, task
from twisted.web.client import getPage

BATCH_SIZE = 5

def main_task(reactor):
    def fetch_urls():
        for url in get_urls():
            yield getPage(url).addCallback(parse)

    coop = task.Cooperator()
    urls = fetch_urls()

    return (defer.DeferredList([coop.coiterate(urls)
                               for _ in xrange(BATCH_SIZE)])
            .addCallback(task_finished))

task.react(main_task)

rawDescription: Twisted: Waiting for subtasks to finish

description: Twisted: Waiting for subtasks to finish


code:
def deleteUser(self):
  self.__user = getInput('Enter the username you want to delete records for: ', 1)
  if self.__user == 'QUIT0x0':
    return
  # ...

rawDescription: In python, how do you stop code in a function being executed?


code:
from itertools import zip_longest # or izip_longest in Python 2.x
from pymongo import MongoClient, UpdateOne

client = MongoClient()
db = client.db
collection = db.collection
requests = []
fields = ['name', '_id']
for document in collection.find():
    unset_op = dict(zip_longest(set(document.keys()).difference(fields), [''], fill_value=''))
    requests.append(UpdateOne({'_id': document['_id']}, {'$unset': unset_op}))
    # Execute per 1000 operations and re-init.
    if len(requests) == 1000:
        collection.bulk_write(requests)
        requests = []

# clean up the queues
if requests:
    collection.bulk_write(requests)

rawDescription: How to unset all fields except some known fields?

description: Unset all fields except some known fields


code:
x = array([1, 1, 2, 3, 4, 4, 5, 6, 2, 1])
unique_x, unique_indexes = np.unique(x, return_index=True)
unique_x
unique_indexes

rawDescription: Numpy: fast/easy way to get indices of array whose value is equal to another array?


code:
rects = [pygame.Rect(0,0,100,100), pygame.Rect(30,30,30,30)]
next((i for (i, r) in enumerate(rects) if r.collidepoint(10, 10)), -1)
next((i for (i, r) in enumerate(rects) if r.collidepoint(100, 200)), -1)

rawDescription: Looking for a concise way to check for point collision in a list of Rects


code:
userservice = build(GOOGLE_PLUS_SERVICE_NAME, GOOGLE_PLUS_VERSION, http=http)
userpeople = userservice.people()
me = userpeople.get(userId="me").execute()

print(me)

rawDescription: Get user info from YouTube Google API in Python (API v3)


code:
class Foo(object):
    def __init__(self, name):
        setattr(self, name, 42)
f = Foo('bar')
f.bar
f.bar = 'hello'
f.bar

rawDescription: Python class members with dynamic names

description: Python class members with dynamic names


rawDescription: For Base64 encode, prefer str.encode('base64_codec') or base64.b64encode(str)?


rawDescription: python list average over bin sizes

description: Python list average over bin sizes


code:
loading.cache.loaded = False
management.call_command('syncdb', interactive=False)

rawDescription: dynamically loading django apps at runtime

description: Dynamically loading django apps at runtime


code:
float(0) == int(0)
float == int

rawDescription: pyasn1 and strange mismatch when setting component

description: Pyasn1 and strange mismatch when setting component


code:
import re
if matches:
    extracted = re.findall( matches[0],  postal_addr)[0]

rawDescription: Python - match a word in a string with a list of strings


code: follow = driver._find_element_by_xpath('//button[@class="_jvpff _k2yal _csba8 _i46jh _nv5lf"]').text

rawDescription: Python with Seleneium Webdriver, reading a button and saving its text


code: b = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)

rawDescription: Returning multiple values from function in python 3.5


code: {an_object.name : an_object for an_object in object_list}

rawDescription: Best way to turn a list into a dict, where the keys are a value of each object?

description: Turn a list into a dict, where the keys are a value of each object


code:
def test():
    if True:
        print("Yup")
    else:
        slartibartfast()

test()

rawDescription: Changing python to read code differently?


code:
#Start with a base case of 0 = "0" and fill in the results as they are computed
def n(x, m={0:'0'}):
    if x not in m:
        #Didn't have the answer, lets compute it.
        m[x] = '{0}{1}{0}'.format(n(x-1), x)

    #Look up what the answer is because we already computed it
    return m[x]

for x in range(5):
    print(n(x))

rawDescription: Recursive pattern to take input integer and return palindrome


code: repeat(4, foo, "test")

rawDescription: Python, how to pass an argument to a function pointer parameter?


code:
m = (mat - mat.T)
np.fill_diagonal(m, mat.diagonal())
m

rawDescription: Subtract transpose from a matrix but keep the original diagonal


code:
import struct
struct.pack("!f",3.14159)

rawDescription: Python Float to Ord values

description: Python Float to Ord values


code: data.columns = [x.lower() for x in data.columns]

rawDescription: python: make pandas dataframe column headers all lowercase

description: Python: make pandas dataframe column headers all lowercase


rawDescription: convert list of tuples to multiple lists in Python

description: Convert list of tuples to multiple lists in Python


rawDescription: python preserving order in set after removing duplicate

description: Python preserving order in set after removing duplicate


code:
from collections import defaultdict
summary = defaultdict( int )
for issue in Issues.objects.all():
    summary[issue.queue, issue.status] += 1

rawDescription: Pivoting data and complex annotations in Django ORM


rawDescription: Issues ith loop is django

description: Issues ith loop is django


code:
count=0
array3=[]
while count < 20:
    temp=[]
    count_inner=0
    count+=1
    while count_inner< 10:
            temp.append(0)
            count_inner+=1
    array3.append(temp)
array3

rawDescription: Creating arrays with for and while loops - Python 2


code: u, counts = np.unique(x, return_counts=True)

rawDescription: Finding the difference between two numpy structured arrays


code:
input(term.red("Question: ") + term.bold)
print(term.normal + term.move_up + term.green("Correct!") + term.clear_eol)

rawDescription: How to print over raw_input's line in Python?

description: Print over raw_input's line in Python


code: mylist = [2*math.pi*radius*math.cos(phi[i]) for i in range(num)]

rawDescription: Aesthetic way of appending to a list in Python?


code:
arr = myIter / (N + 1)
X = numpy.repeat(arr, N)
Y = numpy.tile(arr, N)

rawDescription: Python NumPy Arrays

description: Python NumPy Arrays


code:
while threading.active_count() > 1:
    try:
        main_thread = threading.current_thread()
        for t in threading.enumerate(): # enumerate all alive threads
            if t is not main_thread:
               t.join(.1)
    except KeyboardInterrupt:
        break

rawDescription: Persistence of urllib.request connections to a HTTP server


code:
def SetWindowShape(self, evt=None):
    r = wx.RegionFromBitmap(self.bmp)
    self.hasShape = self.SetShape(r)

def OnPaint(self, evt):
    dc = wx.PaintDC(self)
    dc.DrawBitmap(self.bmp, 0,0, True)

rawDescription: What is the simplest way to create a shaped window in wxPython?


rawDescription: Add vertex attributes to a weighted igraph Graph in python


rawDescription: Python: Center array image

description: Python: Center array image


rawDescription: Django ORM Query to limit for the specific key instance


code:
# define a "power ON api endpoint"
@app.route("/API/v1.0/power-on/<deviceId>",methods=['POST'])
def powerOnDevice(deviceID):
    payload = {}
    #get the device by id somehow
    device = devices.get(deviceId)
    # get some extra parameters
    # let's say how long to stay on
    params = request.get_json()
    try:

      device.turn_on(params['durationinminutes'])
      payload['success'] = True
      return payload
    except:
      payload['success'] = False
      # add an exception description here
      return payload

# define a "power OFF api endpoint"
@app.route("/API/v1.0/power-off/<deviceId>",methods=['POST'])
def powerOffDevice(deviceID):
    payload = {}
    #get the device by id somehow
    device = devices.get(deviceId)
    try:
      device.turn_off()
      payload['success'] = True
      return payload
    except:
      payload['success'] = False
      # add an exception description here
      return payload

rawDescription: How to receive and process JSON in Flask?

description: Receive and process JSON in Flask


code:
import numpy as np
from scipy.ndimage import convolve

length_l = 10
time_l = 10
u = np.zeros((length_l, length_l))# (x,y)
u[:,  0] = 1
u[:, -1] = 1

alpha = .1
weights = np.array([[ 0,  1,  0],
                    [ 1, -4,  1],
                    [ 0,  1,  0]])

for i in range(5):
    u += alpha * convolve(u, weights)
    print(u)

rawDescription: Weighted sum of adjacent values in numpy array


code:
df.loc[mask_fill,'C'] = df['A']
df.loc[mask_fill,'B'] = df['A']

rawDescription: Fill NaN in candlestick OHLCV data

description: Fill NaN in candlestick OHLCV data


code:
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)

rawDescription: Truncating ints without rounding?

description: Truncating ints without rounding


rawDescription: Continuous Fourier Transform with Python / Sympy (Analytical Solution)


code:
grid = {'max_depth':10}

clf = XGBClassifier()
clf.max_depth
clf.set_params(**grid)
clf.max_depth

rawDescription: XGBoost XGBClassifier Defaults in Python


code:
from collections import Counter
common = Counter(yourList).items()
average = [(a, float(b) / len(common)) for (a,b) in common]

rawDescription: Trying to take the average of strings in a list and compare there counts in list to input file


code:
df.index = idx
df
df.unstack(0)[0]

rawDescription: pandas: convert a CSV series into a data frame

description: Pandas: convert a CSV series into a data frame


code:
#!python3

import json

with open('sessionstore.js', encoding='utf-8') as f:
    content = json.load(f)

# The loaded content is a dictionary. List the keys first (console).
for k in content:
    print(k)

# Now list the content bound to the keys. As the console may not be capable
# to display all characters, write it to the file.
with open('out.txt', 'w', encoding='utf-8') as f:

    # Write the overview of the content.
    for k, v in content.items():
        # Write the key and the type of the value.
        f.write('\n\n{}:  {}\n'.format(k, type(v)))

        # The value could be of a list type, or just one item.
        if isinstance(v, list):
            for e in v:
                f.write('\t{}\n'.format(e))
        else:
            f.write('\t{}\n'.format(v))

    # Write the content of the tabs in each windows.
    f.write('\n\n=======================================================\n\n')
    windows = content['windows']
    for n, w in enumerate(windows, 1):  # the enumerate is used just for numbering the windows
        f.write('\n\tWindow {}:\n'.format(n))
        tabs = w['tabs']
        for tab in tabs:
            # The tab is a dictionary. Display only 'title' and 'url' from
            # 'entries' subdictionary.
            e = tab['entries'][0]
            f.write('\t\t{}\n\t\t{}\n\n'.format(e['url'], e['title']))

rawDescription: How to keep track of webpages opened in web-browser using Python?

description: Keep track of webpages opened in web-browser using Python


rawDescription: Insert data from one sorted array into another sorted array


rawDescription: Python sorted list [a1, a2 ... b1, b2]

description: Python sorted list [a1, a2 ... b1, b2]


code:
match = re.search(r'>(\w+)\s+(\w+)', line)
if match:
    tag, gene = match.groups()
    myDict[tag] = gene

rawDescription: Using regex to transform data into a dictionary in Python


code:
tree = html.fromstring(someString)
table_tops = set(tree.xpath('//table'))-set(tree.xpath('//table//table'))

rawDescription: When using LXML why is the body element not the parent of the table element in this snippet of html


code:
def clean_email(self):
    data = self.cleaned_data['email']
    if User.objects.filter(email=data).exists():
        raise forms.ValidationError("This email already used")
    return data

rawDescription: Django auth.user with unique email

description: Django auth.user with unique email


code: dates_filtered = [d for d in dates if d != 'Date']

rawDescription: How do I perform math operations on dates and sort them in Python?

description: Perform math operations on dates and sort them in Python


code:
import re
s = 'Z Miramar      Wellington  Nz'
re.sub(r'\s+', ' ', s)

rawDescription: How to remove extra spaces in a string?

description: Remove extra spaces in a string


code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

rawDescription: Can I use Flask-SQLAlchemy and SQLAlchemy at the same time?

description: Use Flask-SQLAlchemy and SQLAlchemy at the same time


rawDescription: Python: PyQt QTreeview example - selection


code: result = MyModel.objects.filter(reduce(operator.or_, [Q(slug=s) for s in slug])) if hasattr(slug, "__iter__") else MyModel.objects.filter(slug=slug)

rawDescription: Best practices method of implementing a django OR query from an iterable?


code:
import itertools
marker = itertools.cycle((',', '+', '.', 'o', '*'))
for n in y:
    plt.plot(x,n, marker = marker.next(), linestyle='')

rawDescription: unique plot marker for each plot in matplotlib

description: Unique plot marker for each plot in matplotlib


code:
sorter = np.argsort(Shop_Products)
sorter[np.searchsorted(Shop_Products, Shop_Query, sorter=sorter)]
Shop_Inventory[sorter[np.searchsorted(Shop_Products, Shop_Query, sorter=sorter)]]

rawDescription: How to find in a parent string list, the indexes corresponding to a child string list

description: Find in a parent string list, the indexes corresponding to a child string list


rawDescription: Something in python similar to index method for multiple ocurrences


code:
def bla(value, rep):
   if type(rep) is int:
       print (value*rep)
   else:
       print ("Bad parameter type")

rawDescription: How to get python to not print something

description: Get python to not print something


code:
def dfs(graph, start, target, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)

    for n in (set( graph[start] ) - visited):
        if n == target:
            return True
        return dfs(graph, n, target, visited)
    return False

rawDescription: How to stop depth-first search when the target vertex of the graph is found?

description: Stop depth-first search when the target vertex of the graph is found


code:
calc_agi = round((AGI + float(self.rules.all_rules['dmg_AGI_add'])) * float(self.rules.all_rules['dmg_AGI_mult']))
calc_int = round((INT + float(self.rules.all_rules['dmg_INT_add'])) * float(self.rules.all_rules['dmg_INT_mult']))
calc_str = round((STR + float(self.rules.all_rules['dmg_STR_add'])) * float(self.rules.all_rules['dmg_STR_mult']))
dmg_max = round((calc_agi + calc_int + calc_str) * float(self.rules.all_rules['dmg_overall_mult']) + float(self.rules.all_rules['dmg_overall_add']))

rawDescription: Safely parsing user defined equations in Python 3 without eval


code:
from collections import defaultdict
values = defaultdict(list)
_ = map(lambda person: values[person.last_name].append(person), Person.objects.all())

rawDescription: Split queryset or get multiple querysets by field instead of just ordering by field


code:
@app.route('/<lang_code>/<any(about,sobre):about>')
def about(about):
    pass

rawDescription: Format canonical URL structure correctly with URL Processors


code:
first_name = 'Foo'
last_name = 'Bar'

print("Your name and numeric value is:")
fullname = first_name + ' ' + last_name
print(' '.join(fullname))

fullname = str.lower(fullname)
output = ''
for letter in fullname:
    if letter == ' ':
        output += '  '
    else:
        number = (ord(letter) - 97)%9 + 1
        output += str(number) + ' '
print(output)

rawDescription: align columns of letters?

description: Align columns of letters


rawDescription: How can I write this query in Django? (datetime)

description: Write this query in Django? (datetime)


code:
store = pd.HDFStore('test.h5',mode='w')
store.append('df',mi)

rawDescription: Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes


rawDescription: Create ipaddr-py IPv6Address from byte string


code:
if __name__ == "__main__":
    entries = [ImD.ImageData(width, height) for _ in range(images)]
    seeds = numpy.random.poisson(100, images) # array of values

    pool = multiprocessing.Pool()
    for i, e in enumerate(pool.starmap_async(do_voroni, zip(entries, seeds))):
        e.generate_heat_map_image("ImagesOutput/Entries/Entry{:02d}".format(i))

rawDescription: Parallel Processing - Pool - Python

description: Parallel Processing - Pool - Python


code:
timeit.timeit('[]', number=10**7)
timeit.timeit('{}', number=10**7)
timeit.timeit('list()', number=10**7)
timeit.timeit('dict()', number=10**7)

rawDescription: Why is [] faster than list()?

description: Why is [] faster than list()


code:
from fileinput import FileInput

with FileInput(args.infile) as file:
    process(file)
# sys.stdin is still open here

rawDescription: Context manager for optionally redirected I/O


code:
import json
json.loads(ipa)
print(json.loads(ipa))

rawDescription: Python: print unicode string stored as a variable


rawDescription: How to find median using Spark

description: Find median using Spark


code: 'Ad ad'

rawDescription: Search for string in file while ignoring id and replacing only a substring


code:
import numpy as np
import scipy as sy
import scipy.fftpack as syfp
import pylab as pyl

dt = 0.02071
t = dt*np.arange(100000)             ## time at the same spacing of your data
u = np.sin(2*np.pi*t*.01)            ## Note freq=0.01 Hz

# Do FFT analysis of array
FFT = sy.fft(u)

# Getting the related frequencies
freqs = syfp.fftfreq(len(u), dt)     ## added dt, so x-axis is in meaningful units

# Create subplot windows and show plot
pyl.subplot(211)
pyl.plot(t, u)
pyl.xlabel('Time')
pyl.ylabel('Amplitude')
pyl.subplot(212)
pyl.plot(freqs, sy.log10(abs(FFT)), '.')  ## it's important to have the abs here
pyl.xlim(-.05, .05)                       ## zoom into see what's going on at the peak
pyl.show()

rawDescription: How to calculate frequency of a give wave and time

description: Calculate frequency of a give wave and time


code:
import numpy as np
from scipy.sparse import coo_matrix

input = np.loadtxt( 'info.txt', delimiter=',' , dtype=str)
rows,cols,data = input.T
map_rows = { val:ind for ind,val in enumerate( np.unique(rows) ) }
map_cols = { val:ind for ind,val in enumerate( np.unique(cols) ) }
result   = coo_matrix( (data.astype(float),( [map_rows[x] for x in rows], [map_cols[x] for x in cols]) ) )

rawDescription: What's the most pythonic way to load a matrix in ijv/coo/triplet format?


code:
class MainPageHandler(Handler):
    def get(self):
        current_user = self.current_user
        graph = facebook.GraphAPI(self.current_user['access_token'])

rawDescription: Integrate facebook login in google app engine with python


code: Element('A', 1) in heap

rawDescription: Check if heapq contains value

description: Check if heapq contains value


code:
import os
import glob
import pandas as pd

def get_merged_csv(flist, **kwargs):
    return pd.concat([pd.read_csv(f, **kwargs).set_index('X') for f in flist], axis=1).reset_index()

path = 'C:/Users/csvfiles'
fmask = os.path.join(path, '*mask*.csv')

df = get_merged_csv(glob.glob(fmask))

rawDescription: Use pandas (and glob?) to merge numerous (csv) data text files from a directory.


code:
super_list = [
    'E:\\a2001.jpg',
    'E:\\a2008.jpg',
    'E:\\a2007.jpg',
    'E:\\a2002.jpg',
    'E:\\a2009.jpg',
    'E:\\a2009.jpg'
]
my_list = ['2001','2002','2009']
result_list = [x for x in super_list if any(y in x for y in my_list)]
result_list

rawDescription: Extract the elements from a super list using the textual information available in sub list


code: [key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]

rawDescription: python: How to get column names from pandas dataframe - but only for continuous data type?

description: Python: How to get column names from pandas dataframe - but only for continuous data type


code: dayOfYears = [x.strftime("%j") for x in dates]

rawDescription: getting day of years for each month in python

description: Getting day of years for each month in python


code:
# -*- coding: utf-8 -*-
import os
import pypyodbc

workingFolder = "C:\\Users\\Gord\\Desktop\\"
pipeFileName = "stuff.txt"
commaFileName = "stuff.csv"

with open (workingFolder + pipeFileName, "r") as pipeFile:
    data = pipeFile.read()
with open (workingFolder + commaFileName, "w") as commaFile:
    commaFile.write(data.replace("|",","))

connStr = (
    r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' +
    r'DBQ=C:\Users\Public\Database1.accdb'
    )
db = pypyodbc.connect(connStr)

qry = """INSERT INTO text_file_data ([Letter], [Number], [Batch], [Year], [Parcel], [Amount])
    SELECT F1, F2, F3, F4, F5, F6
    FROM [Text;FMT=Delimited;HDR=NO;IMEX=2;CharacterSet=437;Database="""
qry += workingFolder + "].[" + commaFileName.replace(".","#") + "]"

crsr = db.cursor()
crsr.execute(qry)
db.commit()
db.close()

os.remove(workingFolder + commaFileName)

rawDescription: import text file to Access 2003 database using Python

description: Import text file to Access 2003 database using Python


rawDescription: Python-saving while loop results

description: Python-saving while loop results


code:
dateList = list()
for user in users:
    for record in user.records:
        dateList.append(record.datetime)

rawDescription: Accessing all class variables in a container without a loop


rawDescription: "exists" keyword in Python?

description: "exists" keyword in Python


code:
numbers[0], numbers[0]
numbers[0] + 1, numbers[1]
numbers[0] + 2, numbers[2]
...

rawDescription: Determine if numbers are in ascending order using 'all'


code:
from bisect import insort

l = ['a',"b", 'c', 'e']

insort(l, "d")
print(l)
insort(l, "f")
print(l)

['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']

rawDescription: Python - efficiently find where something would land in a sorted list?


code:
table = [[u'a1',u'b2',u'c3'],[u'd4',u'e5',u'f6'],...]
lines = "\n".join(sum(table, [])) + "\n" # if you want a trailing newline

rawDescription: Creating multi line text string from list of lists


code:
import numpy as np
import datetime as dt
import csv

def mkdate(text):
    return dt.datetime.strptime(text, '%Y-%m-%d%H:%M:%S:%f')

def using_csv(fname):
    desc=([('data', '|S4'), ('num', '<i4'), ('date', '|O4')]+
          [('col{i}'.format(i=i), '<f8') for i in range(19)])
    with open(fname,'r') as f:
        reader=csv.reader(f,delimiter='\t')
        data=np.array([tuple(row[:2]+[mkdate(''.join(row[2:4]))]+row[4:])
                       for row in reader],
                      dtype=desc)
    # print(mc.report_memory())
    return data

rawDescription: Python array of datetime objects from numpy ndarray


code:
love
lol
loki
loki
ki
loutre
poutre

rawDescription: Converting a sed regular expression to python code


code:
class EBoolean(CEnumeration):
    FALSE = 0
    TRUE = 1

rawDescription: How to define C-Enumeration types in python

description: Define C-Enumeration types in python


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)


code:
def print_csv_data(data):
  with open('my_output', 'w') as f:
     f.write('Program,Version,Count')
     for k, v in data.iteritems():
        for id, count in v.iteritems():
           f.write(k+','+id+','+count)

rawDescription: Printing nested dicts to CSV in Python

description: Printing nested dicts to CSV in Python


code:
circles[0]  # 5.0, the value of circle 1 (stored at index 0)
circles[1]  # 7.0, the value of circle 2 (stored at index 1)

rawDescription: How can you store user input within a loop without overwriting?

description: Store user input within a loop without overwriting


code:
height, width = size_as_tuple[0], size_as_tuple[1]
image.thumbnail((height, width), Image.ANTIALIAS)

rawDescription: Resizing an image in PIL

description: Resizing an image in PIL


code:
import pygame, sys
from pygame.locals import *

try:
    import Android
except ImportError:
    Android = None

pygame.init()

if Android:
    android.init()
    android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

size = width, height = 1276,650
screen = pygame.display.set_mode(size)

r = 0
bif = pygame.image.load("map.png")
pygame.display.set_caption("Pygame 2D RPG !")
x,y=0,0
movex, movey=0,0
character="boy.png"
player=pygame.image.load(character).convert_alpha()

PAUSED = False
font = pygame.font.SysFont("serif", 72)
text_paused = font.render("PAUSED", True, (255, 0, 0))

while True:

    # --- events ---

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            elif event.key==K_q:
                PAUSED = not PAUSED

        if not PAUSED:
            if event.type==KEYDOWN:
                if event.key==K_a:
                    movex=-1
                elif event.key==K_d:
                    movex=+1
                elif event.key==K_w:
                    movey=-1
                elif event.key==K_s:
                    movey=+1
            if event.type==KEYUP:
                if event.key==K_a:
                    movex=0
                elif event.key==K_d:
                    movex=0
                elif event.key==K_w:
                    movey=0
                elif event.key==K_s:
                    movey=0

    # --- changing values ---

    if not PAUSED:
        x+=movex
        y+=movey

    # --- drawing ---

    screen.fill((r,0,0))
    screen.blit(bif,(0,0))
    screen.blit(player,(x,y))

    if PAUSED:
        screen.blit(text_paused, (100, 100))

    pygame.display.update()

rawDescription: Pygame pause key

description: Pygame pause key


rawDescription: Simple python regex groups can't parse date


rawDescription: Pandas dataframe get first row of each group


code:
dataDefault = ['<Correct Parameters>', 'Bird: Bird = 3', 'Cat: Cat = 40', 'Dog: Dog = 10', 'Bat: Bat = 10', 'Tiger: Tiger = 19', 'Fish: Fish = 234']
setData = [{'Bat': 'Bat = 10', 'Fish': 'Fish = 16', 'Dog': 'Dog = 5', 'Cat': 'Cat = 4', 'Tiger': 'Tiger = 11', 'Bird': 'Bird = 3'}, {'Bat': 'Bat = Null', 'Fish': 'Fish = 24', 'Dog': 'Dog = 10', 'Cat': 'Cat = 40', 'Tiger': 'Tiger = 19', 'Bird': 'Bird = 4'}]

rawDescription: Compare Entries in a dictionary with a list and print the results


code:
from itertools import tee
with open("somefile.txt", "r") as fh:
    fh1, fh2, fh3 = tee(fh, 3)

rawDescription: Is there a way to shallow copy an existing file-object?


code:
#Import necessary libraries
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

#Coordinates that are to be transformed
long = -112.367
lat = 41.013

#Create a basemap for your projection. Which one you use is up to you.
#Some examples can be found at http://matplotlib.org/basemap/users/mapsetup.html
m = Basemap(projection='sinu',lon_0=0,resolution='c')

#Project the coordinates:
projected_coordinates = m(long,lat)

rawDescription: Python / shapely: Calculate Polygon area in planar units (e.g. square-meters)


code:
for i in range(len(oldlist)):

    #Make it empty
    newlist = []

    for j in range(len(xlist)):
        if (xlist[i][0] <= oldlist[j][0] and  oldlist[j][0] <= xlist[i][1]):
            newlist.append(oldlist[j][0])
    print(repr(newlist))
    mean = sum(newlist)/float(len(newlist))
    print(mean)

rawDescription: Averaging values in a nested loop in python


code:
row = soup.find('big', text=re.compile('Current\s*Weather')).find_parent('tr')
while True:
    row = row.find_next_sibling('tr')
    cells = row.find_all('td')
    if len(cells) != 2:
        break
    label, value = (cell.get_text().strip() for cell in cells)
    print(label, value, sep=': ')

rawDescription: Trying to get data with BeautifulSoup

description: Trying to get data with BeautifulSoup


code:
#!/usr/bin/python3
import time
from multiprocessing import Pool, Manager
from threading import Thread

NUM_PROCESSES = 4

def consumer(q):
    out = []
    while True:
        val = q.get()
        if val is None:
            #poison pill
            break
        #doing some work here
        time.sleep(0.01)
        out.append(val)
    return out

def producer(queue):
    flip = True
    val = 5

    def flipper():
        nonlocal flip
        input('enter to flip it!')
        while True:
            flip = not flip
            txt = 'up' if flip else 'down'
            input('val is {}, now counting {}'.format(val, txt))

    t = Thread(target=flipper, args=(), daemon=True)
    t.start()

    while val > 0:
        for _ in range(NUM_PROCESSES):
            queue.put(val)
        val = val + (1 if flip else -1)
        time.sleep(0.2)

    print()
    print('hit zero, shutting down.')

    for _ in range(NUM_PROCESSES):
        #poison pills
        queue.put(None)

if __name__ == '__main__':
    pool = Pool(processes=NUM_PROCESSES)
    m = Manager() # N.B.: multiprocessing.Queue doesn't work with Pool.apply_async
    q = m.Queue()

    results = pool.apply_async(consumer, args=(q,))
    producer(q) # running in main thread because I'm lazy

    print(results.get())

rawDescription: Python: Using Multiprocess to switch functions


code:
l.extend([None, 0, {}])
l
len(l)
bool(l)

rawDescription: Python, how to implement a list subclass that evaluates as False if its items evaluate False?


rawDescription: Matplotlib: combine different lines into a single object to be plotted many times


code:
import csv

out_file = 'output.csv'
header_names = ["Test Number", "result", "output_value","duration_of_test"]

data = [[1, 5, 10, 20], [2, 6, 20, 25], [3, 7, 8, 15]]
data.insert(0, header_names)

with open(out_file, 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerows(zip(*data))

rawDescription: Is there any way to create column header in csv file instead of row headers using python


code:
def process_email(infile):
    fp = open(infile)
    msg = email.message_from_file(fp)
    subject = msg.get('subject')

infolder = "C:\\emlfiles\\"
for infile in os.listdir(infolder):
    process_email(os.path.join(infolder, infile))

rawDescription: Python code applying to multiple files or folder


code:
import logging

class AppFilter(logging.Filter):
    def filter(self, record):
        record.app_name = 'Super App'
        return True

logger = logging.getLogger(__name__)
logger.addFilter(AppFilter())
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(syslog)

logger.info('The sky is so blue')

rawDescription: How do I add custom field to Python log format string?

description: Add custom field to Python log format string


code:
content = []
with open("myFile.bed")as f:
    for line in f:
        content.append(line.strip().split())

rawDescription: Working with "bed" files in python

description: Working with "bed" files in python


rawDescription: Creating a weighted score column from Pandas pivot table


code:
parser.add_argument('--range', default=[4,3,2],
                    nargs=3, metavar=('start', 'end', 'step'),
                    type=int, help='specify a range')

rawDescription: argparse set default to multiple args

description: Argparse set default to multiple args


code:
if last_key != key:
    if(tot_cnt > 1):
        sys.stdout.write("%s\t%s\n" % (last_key, tot_cnt))

rawDescription: How to get the Reducer to emit only duplicates

description: Get the Reducer to emit only duplicates


code: [my_functionb(y) for y in (my_functiona(x) for x in a) if y<10]

rawDescription: python "multiple" combine/chain list comprehension

description: Python "multiple" combine/chain list comprehension


code:
x = [1, 2, 3]
(ctypes.c_int * len(x))(*x)
list((ctypes.c_int * len(x))(*x))
(ctypes.c_int * len(x))(*x)[1]

rawDescription: What does (ctypes.c_int * len(x))(*x) do?


code:
from bokeh.plotting import *

output_file("foo.html")

inds = [2, 5, 6, 8, 9]
colors = ["red", "orange", "blue", "green", "#4488aa"]

rect(inds, inds, 1.0, 1.0, color=colors)

show()

rawDescription: Plot topics with bokeh or matplotlib

description: Plot topics with bokeh or matplotlib


code:
def match(k, v, pat):
    try:
      if fnmatch.fnmatch(k, pat):
        return isinstance(v, dict)
    except TypeError:
        return False

for k, v in myiter.items():
  if match(k, v, '*'):
    for sk, sv in v.items():
      if match(sk, sv, '*.txt'):
        sv['name'] = 'Woot'

rawDescription: How to glob for iterable element

description: Glob for iterable element


rawDescription: Python/Regex - Match .#,#. in String

description: Python/Regex - Match .#,#. in String


code:
import unittest

class TestFoo(unittest.TestCase):
    def test_ok(self):
        self.assertEqual(1+2, 3)
    def test_fail(self):
        self.assertEqual(1+2, 4)
    def test_error(self):
        1/0
    @unittest.skip('blah')
    def test_skip(self):
        self.assertEqual(42, 42)

class MyResult(unittest.TextTestResult):
    def addError(self, test, err):
        self.call_web_api(test, err)
        return super(MyResult, self).addError(test, err)
    def addFailure(self, test, err):
        self.call_web_api(test, err)
        return super(MyResult, self).addFailure(test, err)
    def call_web_api(self, test, err):
        print('***', test, err)

if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestFoo))

    runner = unittest.TextTestRunner(resultclass=MyResult)
    runner.run(suite)

rawDescription: Accessing test status in pyunit tearDown


rawDescription: Python-How to create a list of N elements from a given list


code:
from datetime import date, timedelta
import luigi

class AggregateArtists(luigi.Task):
    date = luigi.DateParameter(default=date.today() - timedelta(days=1))

    def output(self):
        return luigi.LocalTarget("/tmp/foobar.txt")

    def run(self):
        with self.output().open('w') as out_file:
            out_file.write(self.date.strftime("%Y%m%d") + "\n")

if __name__ == "__main__":
    luigi.run()

rawDescription: use luigi.DateParameter in a run function of a Luigi Orchestrator Task

description: Use luigi.DateParameter in a run function of a Luigi Orchestrator Task


code:
print([cls for cls in vars()['Foo'].__subclasses__()])
# [<class '__main__.Bar'>, <class '__main__.Baz'>]

rawDescription: How can I find all subclasses of a given class in Python?

description: Find all subclasses of a given class in Python


code:
#worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot

class Worker(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(list)
    def __init__(self):
        QObject.__init__(self)

    @pyqtSlot()
    def _search_cast_(self):
        self.cc = casting()
        self.cc.initialize_cast()
        availablecc = self.cc.availablecc
        self.intReady.emit(availablecc)
        self.finished.emit()

rawDescription: PyQt5 QObject: Cannot create children for a parent that is in a different thread


code:
def connection(pairs, item):
    return ''.join([p[1-p.index(item)] for p in pairs if item in p])

rawDescription: For element in list of tuples, return other element in tuple


code: name = str(self.nameLe.text())

rawDescription: How do I get the input from a PyQt linedit object?

description: Get the input from a PyQt linedit object


code:
import os
for filename in os.listdir("/mydirectory"):
    if filename.endswith(".mp3"):
        file = filename

rawDescription: How to play multiple mp3 files one after the other using pygame?

description: Play multiple mp3 files one after the other using pygame


rawDescription: how to correctly split the following string ? - Python

description: Correctly split the following string ? - Python


rawDescription: Python 3, Converting a string storing binary data to Int


rawDescription: SQLAlchemy querying function

description: SQLAlchemy querying function


code:
def csr_add_sparse_vec(sps_mat, sps_vec) :
    """Adds a sparse vector to every row of a sparse matrix"""
    # No checks done, but both arguments should be sparse matrices in CSR
    # format, both should have the same number of columns, and the vector
    # should be a vector and have only one row.

    rows, cols = sps_mat.shape

    new_data = sps_mat.data
    new_pointer = sps_mat.indptr.copy()
    new_cols = sps_mat.indices

    aux_idx = np.arange(rows + 1)

    for value, col in itertools.izip(sps_vec.data, sps_vec.indices) :
        new_data = np.insert(new_data, new_pointer[1:], [value] * rows)
        new_cols = np.insert(new_cols, new_pointer[1:], [col] * rows)
        new_pointer += aux_idx

    return sps.csr_matrix((new_data, new_cols, new_pointer),
                          shape=sps_mat.shape)

rawDescription: Adding a very repetitive matrix to a sparse one in numpy/scipy?


code:
def extract_choices(text):
    choices = []

    def callback(match):
        variants = match.group().strip('{}')
        choices.append(dict(
            (v.lstrip('+'), v.startswith('+'))
            for v in variants.split('|')
        ))
        return '___'

    text = re.sub('{.*?}', callback, text)

    return text, choices

rawDescription: Python - Multiple choice markup parsing

description: Python - Multiple choice markup parsing


code:
@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
    # updated: get value for key "html", encode correctly
    data = request.form.get("html").encode("utf-8")
    # do whatever with the data
    return "Data retrieved"

rawDescription: Save current html state to file via jQuery $.ajax POST to Flask view


code: model = sm.Logit(y, x.astype(float)).fit()

rawDescription: splitting data into test and train, making a logistic regression model in pandas

description: Splitting data into test and train, making a logistic regression model in pandas


rawDescription: python finding mac os build number

description: Python finding mac os build number


code:
lot = [('hello', 25), ('hell', 4), ('bell', 4)]
sorted(sorted(lot, key=lambda r: r[0]), key=lambda r: r[1], reverse=True)

rawDescription: How to sort a python list bidirectionally, by numbers in descending order and by alphabets in ascending order?

description: Sort a python list bidirectionally, by numbers in descending order and by alphabets in ascending order


code:
t = torch.Tensor()
type(t)       == 'userdata' # Because the class was written in C
torch.type(t) == 'torch.DoubleTensor'
# or
t:type()      == 'torch.DoubleTensor'

rawDescription: how to get the class type in lua / translation from python

description: Get the class type in lua / translation from python


code:
from string import ascii_lowercase
alphabets = dict(zip(ascii_lowercase, range(1,27)))

rawDescription: Iterating over a list while incrementing another variable at the same time


code:
if path.startswith(r'//'):
    return False

rawDescription: pytest (py.test) very slow startup in cygwin

description: Pytest (py.test) very slow startup in cygwin


code:
from copy import deepcopy
for ind, ele in enumerate(deepcopy(List1)):
    for sub_ele in ele:
        List1[ind].extend(deepcopy(sub_ele) for _ in range(c[sub_ele]))

print(List1)

rawDescription: How to compare two unequal lists and append matching elements value back to the first List

description: Compare two unequal lists and append matching elements value back to the first List


rawDescription: Python:How can I get screenshot data in PIL.ImageGrab?


code:
save()
activate(block='true')

rawDescription: Anyone tried Cluster automation with WLST?


code:
from subprocess import Popen, PIPE, STDOUT

wget = Popen(['/usr/bin/wget', theurl], stdout=PIPE, stderr=STDOUT)
stdout, nothing = wget.communicate()

with open('wget.log', 'w') as wgetlog:
    wgetlog.write(stdout)

rawDescription: Python: How to suppress the output of os.system


code:
def download_content(self):
    self.ids["download_button"].disabled = True
    req = UrlRequest(ZIP_URL, on_progress=self.update_progress,
                     chunk_size=1024, on_success=self.unzip_content,
                     file_path=ZIP_FILENAME)

def update_progress(self, request, current_size, total_size):
    self.ids['download_progress_bar'].value = current_size / total_size

rawDescription: Download file with Kivy app without locking event loop


rawDescription: Create a url with an article's title

description: Create a url with an article's title


code:
dic = {name: {'location': value[0], 'population': value[1], 'president': value[2]}
       for name, value in dic.items()}

rawDescription: python, how to update the dictionaries by mutating its format?

description: Python, how to update the dictionaries by mutating its format


code: os.write(w, '{}\n'.format(child))

rawDescription: How to to get the pid of a daemon created by a double fork?

description: To get the pid of a daemon created by a double fork


code:
import pandas as pd
data = [[2, 4, "Focus"],
        [3, 4, "Fiesta",],
        [1, 4, "300"],
        [7, 3, "Pinto"]]

# This dataframe is exactly as intended
df = pd.DataFrame(data=data)

# Slice a subset of the `values` numpy object array
raw_slice = df.values[1:,:]

newdf = pd.DataFrame(data=raw_slice)
for col, dtype in zip(newdf, df.dtypes):
    newdf[col] = newdf[col].astype(dtype)
print(newdf.dtypes)
print(newdf)

rawDescription: Can't set appropriate dtypes reading from a Numpy array


code:
def __init__(self, parentFrame):
    wx.Frame.__init__(self, None, title="New Frame")
    self.parentFrame = parentFrame

rawDescription: wxPython SetLabel outside frame's class?

description: WxPython SetLabel outside frame's class


code:
from __future__ import print_function  # we need print as function to use within lamdba
d3 = [[[0 for col in range(3)]for row in range(3)] for x in range(3)]

d3[0][2][2] = 1
d3[1][2][2] = 2

d3 = reduce(list.__add__, reduce(list.__add__, d3))  # get flatten matrix

map(lambda x: print(x[0]/9, (x[0] - (x[0]/9)*9)/3, x[0] % 3, '=', x[1]), [(i, e) for i, e in enumerate(d3) if e != 0])

#print x / 9             # i
#print (x - (x/9)*9) / 3 # j
#print x % 3             # k

rawDescription: finding non zero entries in 3D matrix using only maps, lambda and reduce

description: Finding non zero entries in 3D matrix using only maps, lambda and reduce


code:
def main():
    print('Radius\tArea\tCircumference')
    print('----------------------------')
    print()
    for radius in range(1, 11):
        for area in range(1, 11):
            for circumference in range(1, 11):
                pi = 3.14
                diameter = radius * 2
                radius = diameter / 2
                area = pi * radius**2
                circumference = (2 * pi) * radius

        #print(radius, '\t', area, '\t' , format(circumference, ".2f"))
        radius_str        = "%0.2f" % radius
        area_str          = "%0.2f" % area
        circumference_str = "%0.2f" % circumference
        print("%6s\t%6s\t%6s" % (radius_str, area_str, circumference_str))

main()

rawDescription: Python programming indentation issue

description: Python programming indentation issue


code:
#-- Get the region not covered by individual squares.
uncovered_region = Polygon(bigsquare).difference(union)

# In some cases, the result will be a single polygon...
if not isinstance(uncovered_region, MultiPolygon):
    uncovered_region = [uncovered_region]

for poly in polygonize(uncovered_region):
    patch = PolygonPatch(poly, fc='purple', alpha=0.5, zorder=2)
    ax.add_patch(patch)

rawDescription: Find holes in a union of rectangles?

description: Find holes in a union of rectangles


code: cursor.execute('UPDATE people SET address = %s WHERE id = %s', ('Columbia, MD', 2));

rawDescription: Update specific cell in mySQL using python


code:
'3' number 1 with key: 1
'3' number 2 with key: 2
'3' number 3 with key: 3

rawDescription: Dictionary Iteration Python

description: Dictionary Iteration Python


code: AA = 'Foo'

rawDescription: I want to refer to a variable in another python script


code: temp =  [x[:-1]+[int(x[-1])] for x in sorted(data,key=lambda x:int(x[-1]))]

rawDescription: Python - Indexing, comparing and appending


code:
config = Configurator()
config.add_route('item_options', '/item/{item}/some_options',
                 # tell pyramid where in the resource tree to go for this url
                 traverse='/foos/{item}')

rawDescription: Pyramid authorization for stored items

description: Pyramid authorization for stored items


rawDescription: python regular expressions in find and replace

description: Python regular expressions in find and replace


code:
collect_of_docs = sc.parallelize([
    (1, "Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
    (2, "Mauris magna sem, vehicula sed dictum finibus, posuere id ipsum."),
    (3, "Duis eleifend molestie dolor, quis fringilla eros facilisis ac.")])

rawDescription: spark, small issue about reduceByKey

description: Spark, small issue about reduceByKey


rawDescription: XOR on two lists in Python

description: XOR on two lists in Python


code:
phrases = df_multigram['multigram'].tolist()
freq_dict = freq.to_dict()

rawDescription: Break pandas DataFrame column into multiple pieces and combine with other DataFrame


code:
#Build StdLib.DLL
gb = glob.glob(r".\Lib\*.py")
gb.append("/out:StdLib")

rawDescription: Compiling IronPython into an exe that uses standard library packages


code:
with open('file_name') as f:
     re.findall(r'\S+|\n',f.read())

rawDescription: Python splitting text file keeping newlines


code:
def intersecting_sets(sets):
    import networkx as nx
    G = nx.Graph()
    # Nodes of the graph should be hashable
    sets = map(frozenset, sets)
    for to_node in sets:
        for from_node in sets:
            # off-course you don't want a self loop
            # and only interested in intersecting nodes
            if to_node != from_node and to_node & from_node:
                G.add_edge(to_node, from_node)
    # and remember to convert the frozen sets to sets
    return [map(set, lst) for lst in nx.connected_components(G)]

rawDescription: Get a list of lists of the sets which intersect each other in python


rawDescription: Manipulating indices to 2d numpy array

description: Manipulating indices to 2d numpy array


code:
@add_tests([(mode.SILENT,), (mode.NOISY,)], [{}, {}], build_name_mode, "test_mode_flow")
@add_tests([(1,), ()], [{"speed":33}, {"speed":22, "gear":4}], # can mix args and kwargs
           build_gear_mode, "test_gear_flow")
class TestRestart(unittest.TestCase):
    ...

rawDescription: Dynamically adding tests to my Test Cases


code: start_timestamp = datetime.datetime(2014, 1, 14)

rawDescription: Converting Twitter time zone and performing searches


code:
blocks = (ty1 != ty1.shift()).cumsum()
blocks

rawDescription: distinct contiguous blocks in pandas dataframe

description: Distinct contiguous blocks in pandas dataframe


rawDescription: Using the split function

description: Using the split function


rawDescription: removing pairs of elements from numpy arrays that are NaN (or another value) in Python

description: Removing pairs of elements from numpy arrays that are NaN (or another value) in Python


code:
with fits.open("example.fits") as hdulist:
    events = hdulist[1].data   # since hdu 0 should be an ImageHDU type, the events are probably in the first extension
    midx = np.int((np.max(events['x'])+np.min(events['x']))/2)
    midy = np.int((np.max(events['y'])+np.min(events['y']))/2)
    midist = events['z'][(events['x'] == midx) & (events['y'] == midy)]

rawDescription: Efficiently get midpoint of image in Python with astropy


rawDescription: Sum of elements stored inside a tuple

description: Sum of elements stored inside a tuple


rawDescription: Doubling the matrix in numpy

description: Doubling the matrix in numpy


rawDescription: module holding variables, mutable vs immutable

description: Module holding variables, mutable vs immutable


code: pd.rolling_sum( data2.AboveUpper, window=X ) >= X

rawDescription: More Efficient way to check values of neighboring rows in pandas dataframe for stock backtesting


code:
import timeit
def re_remove(text): return shortword.sub('', text)

def lc_remove(text): return ' '.join(word for word in text.split() if len(word)>3)

timeit.timeit('remove(" in the echo chamber from Ontario duo ")', 'from __main__ import re_remove as remove')
timeit.timeit('remove(" in the echo chamber from Ontario duo ")', 'from __main__ import lc_remove as remove')

rawDescription: Remove small words using Python

description: Remove small words using Python


code:
def savePict(pict, name):
  filehandle=getMediaPath(name)
  writePictureTo(pict,filehandle)

rawDescription: Saving a picture in Python

description: Saving a picture in Python


code:
# Wait 3 seconds
time.sleep(3)
# Set the icon to idle
self.statusIcon.set_from_file("img/lin_idle.png")

rawDescription: Pygtk StatusIcon not loading?

description: Pygtk StatusIcon not loading


rawDescription: How to manually create a sparse matrix in Python

description: Manually create a sparse matrix in Python


code: x == np.arange(len(x))[:,None]

rawDescription: Set values in matrix to 1 where index matches value


code:
models = dict()
for field, cache in self.env.cache.iteritems():
    for id_, value in cache.iteritems():
        models.setdefault(field.model_name, list())
        models[field.model_name].append(id_)

for name, ids in models.iteritems():
    for record in self.env[name].browse(ids):
        record.write(record._convert_to_write(record._cache))

rawDescription: How to write to database all cache in Odoo environment?

description: Write to database all cache in Odoo environment


code:
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('foobar306@gmail.com', 'testing123testing')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
mail.dir()
dir(mail)
dir(mail).sort()
d=dir(mail)
d.sort()
d
mail.list()
mail.select("INBOX") # connect to inbox.
mail.list()
mail.list("INBOX")
mail.open("INBOX")
mail.recent()
mail.create("sarnoldwashere")
mail.list()
mail.logout()

rawDescription: Problems with IMAP in Gmail with Python

description: Problems with IMAP in Gmail with Python


rawDescription: Pandas better way to aggregate over multiple series


rawDescription: How to use django-contact-form (third-party app)?

description: Use django-contact-form (third-party app)


code:
def a_normal_decorator(function):
    def wrapper():
        return function()
    return wrapper

rawDescription: A more elegant way for this python decorator


code:
from django.db.models import Count

class Model(models.Model):
    score = models.IntegerField()
    ...

    def ranking(self):
        aggregate = Model.objects.filter(score__lt=self.score).aggregate(ranking=Count('score'))
        return aggregate['ranking'] + 1

rawDescription: How do I get the position of a result in the list after an order_by?

description: Get the position of a result in the list after an order_by


code:
H, W, b = masked_img.shape
for i in range(0,H,1):
   for j in range(0,W,1):
    if masked_img[i,j,0] > 1 or masked_img[i,j,1] > 1 or masked_img[i,j,2] > 1:
        meanblue = meanblue + masked_img[i,j,0]
        meangreen = meangreen + masked_img[i,j,1]
        meanred = meanred + masked_img[i,j,2]
        count = count+1

rawDescription: Python nested for loop in RGB average

description: Python nested for loop in RGB average


rawDescription: Is a Python function stored as an object?


code:
import win32com.client
app = win32com.client.Dispatch("Excel.Application")
sheet = app.ActiveSheet

rang = sheet.Range("A1","A3")
names = rang.Value
nameLst = [name[0] for name in names]

#Iterate over the rows ic ColB. Remember Excel uses base 1 not 0 for inexing
for rowI in range(1,3):
    cellNames = sheet.Cells(rowI,2).Value

    #split cellNames by "," and add all of the names to a list.
    cellNamesLst = [cellName.strip() for cellName in cellNames.split(",")]

    #Now we want a list of all names that are in cellNamesLst and in nameLst
    matchLst = [matchName for matchName in cellNamesLst if matchName in nameLst]

    #Create a string of all matches to go in Col C
    allMatches = ", ".join(matchLst)

    #Lastly put all matches in in Col C
    sheet.Cells(rowI,3).Value = allMatches

rawDescription: In excel with python, how do you find words, from an entire column, in a cell containing multiple words?


rawDescription: How to divide a list in python?

description: Divide a list in python


code:
[elem**2 for elem in a]
[elem**2 for elem in b]

rawDescription: for loop returning unexpected values when squaring values

description: For loop returning unexpected values when squaring values


code: X[:, indices[:n]] # n most important features

rawDescription: Python Slicing Numpy Array according to feature_importances_


code:
with open("commentsfordjango.txt", "wb") as f:
    f.write(fullcomment.encode('utf8'))

rawDescription: Unicode in a Django-powered site

description: Unicode in a Django-powered site


rawDescription: Adding cell values from multiple sheets in Excel workbook via Python


code:
file_out = lasfile.File("outPut",mode='w',header= h)

for group in samples.itervalues():
    for p in group:
        file_out.write(p)

file_out.close()

rawDescription: Python increase performance of random.sample


code:
class GeoRSS(webapp2.RequestHandler):

    def get(self):
        start = datetime.datetime.now() - timedelta(days=60)
        count = (int(self.request.get('count'
                 )) if not self.request.get('count') == '' else 1000)
        try:
            entities = memcache.get('entities')
        except KeyError:
            entity = Entity.all().filter('modified >',
                                  start).filter('published =',
                    True).order('-modified').fetch(count)
        memcache.set('entities', entities)
        template_values = {'entities': entities, 'request': self.request,
                           'host': os.environ.get('HTTP_HOST',
                           os.environ['SERVER_NAME'])}
        dispatch = 'templates/georss.html'
        path = os.path.join(os.path.dirname(__file__), dispatch)
        output = template.render(path, template_values)
        self.response.headers['Cache-Control'] = 'public,max-age=%s' \
            % 86400
        self.response.headers['Content-Type'] = 'application/rss+xml'
        self.response.out.write(output)

rawDescription: Generating RSS feed under Google App Engine


code:
button = browser.find_by_xpath("//button[jsl = 'Newest']")
button[0].click()

rawDescription: Splinter browser automation select option


code: np.all(res1[np.lexsort(res1.T), :] == res2[np.lexsort(res2.T), :])

rawDescription: Possible to add numpy arrays to python sets?


code:
h = """
A weak handicap that looked wide open.

 LADY MAKFI showed vastly improved form to shed her maiden tag on this seasonal debut for a new yard. The filly offered little for Tony Martin last year, but did show some ability on her debut and is evidently capable when fresh. She saw it out well and it´ll be interesting to see how she copes with a rise.

 Weardiditallgorong went down fighting over this longer trip and probably improved again on her last-time-out second at Bath. This was her best effort yet on the AW.

 Chauvelin, in second-time blinkers, turned in his most encouraging effort for some time and is certainly well treated on his best form.

 Happy Jack not for the first time travelled easily until making heavy weather of it when asked for his effort. [David Orton]

"""

from lxml import html

x = html.fromstring(h)

div = x.xpath("//*[@id='ANALYSIS']")[0]

# find bold tags by class name
for b in div.xpath(".//b[@class='black']"):
    # get bold text
    print(b.text)
    # get text between current bold up to next br tag.
    print(b.xpath("./following::text()[1]"))

rawDescription: Python: pulling bold text and the text that follows


code:
#!/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
import sys
sys.argv[0] = sys.argv[0].replace('-2.6', '')
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c9','console_scripts','easy_install'
__requires__ = 'setuptools==0.6c9'
import sys
from pkg_resources import load_entry_point

sys.exit(
   load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()
)

rawDescription: Choose Python version for egg installation or install parallel versions of site-package


code: max_values = data[n1:n2, :].max(axis=0)

rawDescription: How to find the maximum value of a numpy array between given indicies?

description: Find the maximum value of a numpy array between given indicies


code: itertools.product(list_of_aa, repeat=3)

rawDescription: Create list with combinations of 3 elements of other list with repetitions


code:
a="1.MATCHES$$TEXT$$STRING"
a.split("$$TEXT$$")
a="2.MATCHES $$TEXT$$ STRING"
a.split("$$TEXT$$")

rawDescription: Split a string by a delimiter in python

description: Split a string by a delimiter in python


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

data = np.random.random((10,10))
labels = 'abcdefghij'

fig, ax = plt.subplots()
im = ax.pcolor(data, cmap='gray', edgecolor='black', linestyle=':', lw=1)
fig.colorbar(im)

# Shift ticks to be at 0.5, 1.5, etc
for axis in [ax.xaxis, ax.yaxis]:
    axis.set(ticks=np.arange(0.5, len(labels)), ticklabels=labels)

plt.show()

rawDescription: Matplotlib: Move ticklabels between ticks


code:
import requests
requests.Request('GET',
    'https://oauth-api.beatport.com/catalog/3/tracks',
    params={'facets': 'artistName:Axwell /\\ Ingrosso',
            'perPage': 150}).prepare().url
requests.Request('GET',
    'https://oauth-api.beatport.com/catalog/3/tracks',
    params={'facets': 'artistName:Axwell /\\\\ Ingrosso',
            'perPage': 150}).prepare().url
requests.Request('GET',
    'https://oauth-api.beatport.com/catalog/3/tracks',
    params={'facets': r'artistName:Axwell /\\ Ingrosso',
            'perPage': 150}).prepare().url

rawDescription: Escaping backslash in Python requests

description: Escaping backslash in Python requests


code:
def setdictvalto(d, value):
    for k in d:
        if isinstance(d[k], dict):
            setdictvalto(d[k], value)
        else:
            d[k] = value

rawDescription: How to set all values of a complex dict to the same one?

description: Set all values of a complex dict to the same one


code:
int('a16',16)  #builtin function
toInt('a16',16)

rawDescription: Python int method

description: Python int method


code: {'Language': {248: 'German', 246: 'English', 247: 'French'}, 'Primary purpose': {226: 'Learn how to use', 227: 'Technical Support', 292: 'Purchase', 62: 'Other'}, 'Device': {104: 'Mobile', 102: 'Desktop', 103: 'Tablet'}}

rawDescription: How to create dictionary of dictionaries from a dataframe using python's pandas

description: Create dictionary of dictionaries from a dataframe using python's pandas


code:
from operator import itemgetter
getter = itemgetter("someKey")
hits = [ ( getter(first_dic), filter(lambda dic: getter(dic) == getter(first_dic), set_of_pk_values[idx:-1]) ) for idx, first_dic in enumerate(set_of_pk_values[:-1])]

rawDescription: Python Nested For Loop Array Comparison - Possibility of Optimization?


rawDescription: summing the number of occurrences per day pandas

description: Summing the number of occurrences per day pandas


code:
region = (session
    .query(Region)
    .filter(Region.region_code.op('div')(region_prefix))
    .one()
)

rawDescription: MySQL and SQLAlchemy integer diversion in WHERE clause


code:
import logging
import math

import cv2
import numpy as np

# ============================================================================

CAR_COLOURS = [ (0,0,255), (0,106,255), (0,216,255), (0,255,182), (0,255,76)
    , (144,255,0), (255,255,0), (255,148,0), (255,0,178), (220,0,255) ]

# ============================================================================

class Vehicle(object):
    def __init__(self, id, position):
        self.id = id
        self.positions = [position]
        self.frames_since_seen = 0
        self.counted = False

    @property
    def last_position(self):
        return self.positions[-1]

    def add_position(self, new_position):
        self.positions.append(new_position)
        self.frames_since_seen = 0

    def draw(self, output_image):
        car_colour = CAR_COLOURS[self.id % len(CAR_COLOURS)]
        for point in self.positions:
            cv2.circle(output_image, point, 2, car_colour, -1)
            cv2.polylines(output_image, [np.int32(self.positions)]
                , False, car_colour, 1)

# ============================================================================

class VehicleCounter(object):
    def __init__(self, shape, divider):
        self.log = logging.getLogger("vehicle_counter")

        self.height, self.width = shape
        self.divider = divider

        self.vehicles = []
        self.next_vehicle_id = 0
        self.vehicle_count = 0
        self.max_unseen_frames = 7

    @staticmethod
    def get_vector(a, b):
        """Calculate vector (distance, angle in degrees) from point a to point b.

        Angle ranges from -180 to 180 degrees.
        Vector with angle 0 points straight down on the image.
        Values increase in clockwise direction.
        """
        dx = float(b[0] - a[0])
        dy = float(b[1] - a[1])

        distance = math.sqrt(dx**2 + dy**2)

        if dy > 0:
            angle = math.degrees(math.atan(-dx/dy))
        elif dy == 0:
            if dx < 0:
                angle = 90.0
            elif dx > 0:
                angle = -90.0
            else:
                angle = 0.0
        else:
            if dx < 0:
                angle = 180 - math.degrees(math.atan(dx/dy))
            elif dx > 0:
                angle = -180 - math.degrees(math.atan(dx/dy))
            else:
                angle = 180.0

        return distance, angle

    @staticmethod
    def is_valid_vector(a):
        distance, angle = a
        threshold_distance = max(10.0, -0.008 * angle**2 + 0.4 * angle + 25.0)
        return (distance <= threshold_distance)

    def update_vehicle(self, vehicle, matches):
        # Find if any of the matches fits this vehicle
        for i, match in enumerate(matches):
            contour, centroid = match

            vector = self.get_vector(vehicle.last_position, centroid)
            if self.is_valid_vector(vector):
                vehicle.add_position(centroid)
                self.log.debug("Added match (%d, %d) to vehicle #%d. vector=(%0.2f,%0.2f)"
                    , centroid[0], centroid[1], vehicle.id, vector[0], vector[1])
                return i

        # No matches fit...
        vehicle.frames_since_seen += 1
        self.log.debug("No match for vehicle #%d. frames_since_seen=%d"
            , vehicle.id, vehicle.frames_since_seen)

        return None

    def update_count(self, matches, output_image = None):
        self.log.debug("Updating count using %d matches...", len(matches))

        # First update all the existing vehicles
        for vehicle in self.vehicles:
            i = self.update_vehicle(vehicle, matches)
            if i is not None:
                del matches[i]

        # Add new vehicles based on the remaining matches
        for match in matches:
            contour, centroid = match
            new_vehicle = Vehicle(self.next_vehicle_id, centroid)
            self.next_vehicle_id += 1
            self.vehicles.append(new_vehicle)
            self.log.debug("Created new vehicle #%d from match (%d, %d)."
                , new_vehicle.id, centroid[0], centroid[1])

        # Count any uncounted vehicles that are past the divider
        for vehicle in self.vehicles:
            if not vehicle.counted and (vehicle.last_position[1] > self.divider):
                self.vehicle_count += 1
                vehicle.counted = True
                self.log.debug("Counted vehicle #%d (total count=%d)."
                    , vehicle.id, self.vehicle_count)

        # Optionally draw the vehicles on an image
        if output_image is not None:
            for vehicle in self.vehicles:
                vehicle.draw(output_image)

            cv2.putText(output_image, ("%02d" % self.vehicle_count), (142, 10)
                , cv2.FONT_HERSHEY_PLAIN, 0.7, (127, 255, 255), 1)

        # Remove vehicles that have not been seen long enough
        removed = [ v.id for v in self.vehicles
            if v.frames_since_seen >= self.max_unseen_frames ]
        self.vehicles[:] = [ v for v in self.vehicles
            if not v.frames_since_seen >= self.max_unseen_frames ]
        for id in removed:
            self.log.debug("Removed vehicle #%d.", id)

        self.log.debug("Count updated, tracking %d vehicles.", len(self.vehicles))

# ============================================================================

rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code:
for s, df in sources.items():

    temp = df.loc[A.index]  # the source data set indexed by A's index
                            # this will contain NaN's where df does not
                            # have corresponding index entries
    temp.dropna(inplace=True) # dropping the NaN values leaves you with
                             # only the values in df matching the index in A
    if len(temp) > 0:
        A.loc[temp.index] = temp  # now assign the data to A

print(A)

rawDescription: Conditional merge of other multiple Pandas DataFrames


code:
def remove_duplication(my_list):
    my_newlist = []
    for x in my_list:
        x = map(str.strip,x.split(';'))
        my_newlist.append(";".join(sorted(set(x),key=lambda y:x.index(y))))
    return my_newlist

remove_duplication(a_list)

rawDescription: Remove duplicated string(s) in strings in a list


rawDescription: Disregarding a line while calculating frequency in python


code:
from lxml import etree
# ...
objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)

rawDescription: Python - How to append the same XML element multiple times with lxml.objectify


code: repost_pid, repost_permalink, _, repost_title, repost_submitter = row

rawDescription: Python: Assign variables from array

description: Python: Assign variables from array


code:
tag|category
bath|9
bath|10

rawDescription: Python: select most frequent using group by


code:
from __future__ import print_function # make it work with Python 2 and 3

df = pd.read_csv('f123_dates.csv', index_col=0, parse_dates=[0, 1],
                 delim_whitespace=True)
print(df.groupby([df.index, df.Time.dt.hour]).agg(['mean','sum']))

rawDescription: How to groupby two fields in pandas?

description: Groupby two fields in pandas


rawDescription: DRY Django querysets

description: DRY Django querysets


code: func = decorate_func(func)

rawDescription: How do you use a python decorator on a function whose definition you cannot access?

description: Use a python decorator on a function whose definition you cannot access


rawDescription: How to partially copy using python an Hdf5 file into a new one keeping the same structure?

description: Partially copy using python an Hdf5 file into a new one keeping the same structure


code:
l = list(grep_index('opt1', enumerate(sys.argv)))   # non-recursive
r = list(grep_index('diff', enumerate_recursive(your_data)))  # recursive

rawDescription: Grep multi-layered iterable for strings that match (Python)


code:
#app/models.py
from django.contrib.postgres.fields import HStoreField
class Something(models.Model):
    name = models.CharField(max_length=32)
    data = models.HStoreField(db_index=True)

rawDescription: Django dynamic model fields

description: Django dynamic model fields


code: pd.pivot_table(df, index='Sequence', columns='Level', values='Count')

rawDescription: Convert categorical data into various columns for plotting in pandas


code:
import asyncio
from contextlib import suppress

class Periodic:
    def __init__(self, func, time):
        self.func = func
        self.time = time
        self.is_started = False
        self._task = None

    async def start(self):
        if not self.is_started:
            self.is_started = True
            # Start task to call func periodically:
            self._task = asyncio.ensure_future(self._run())

    async def stop(self):
        if self.is_started:
            self.is_started = False
            # Stop task and await it stopped:
            self._task.cancel()
            with suppress(asyncio.CancelledError):
                await self._task

    async def _run(self):
        while True:
            await asyncio.sleep(self.time)
            self.func()

rawDescription: How can I periodically execute a function with asyncio?

description: Periodically execute a function with asyncio


code:
a = iter(list(range(10)))
for i in a:
   print('Printing: {}'.format(i))
   next(a)

rawDescription: Python list iterator behavior and next(iterator)


code:
for i,j in data:
    file.write('%-15s %s\n' % (i,j))

rawDescription: Writing white-space delimited text to be human readable in Python


code:
with open("output.xml", "w") as f:
    f.write(doc.toprettyxml(indent="  "))

rawDescription: How to save an xml file to disk?

description: Save an xml file to disk


code:
data = list(conn.escape_string, data)

sql = "INSERT IGNORE INTO users_time_zone (user_id, email, username, gcm_reg_id, time_zone) " \
      "VALUES(%s, '%s', '%s', '%s', '%s') ON DUPLICATE KEY UPDATE gcm_reg_id ='%s', id=LAST_INSERT_ID(id) "\
        % data

rawDescription: Wrong sql syntax because of single or double quote in string


code:
x = 1; y = 1 # corresponds to number 5 in the original array
B[y:y+N, x:x+N]

rawDescription: Slicing outside numpy array

description: Slicing outside numpy array


rawDescription: combining lists inside values in pyspark

description: Combining lists inside values in pyspark


code:
if request.is_ajax():
    cur = connections['data'].cursor()
    SQL = 'SELECT uuid, name FROM abc_abc where parent_id  = %s'
    auto_type = request.POST.get('type','')
    conv = iri_to_uri(auto_type)
    conv2 = (conv,)
    cur.execute(SQL,conv2)
    colors = dictfetchall(cur)
    return render_to_response('abc/add.html', {
            'colors' : colors,
            }, context_instance=RequestContext(request))

rawDescription: Django using AJAX with Forms, Views

description: Django using AJAX with Forms, Views


code:
# deprecated in 1.8:
# urlpatterns = patterns('',
urlpatterns = [
    # Example:
    url(r'^rock_and_feat/$', app.views.rock_and_feat, name='rock_and_feat'),
]
# )

rawDescription: django 1.8 using one view in another

description: Django 1.8 using one view in another


code:
class SVM(StatModel):
    '''wrapper for OpenCV SimpleVectorMachine algorithm'''
    def __init__(self):
        self.model = cv2.SVM()

    def train(self, samples, responses):
        #setting algorithm parameters
        params = dict( kernel_type = cv2.SVM_LINEAR,
                       svm_type = cv2.SVM_C_SVC,
                       C = 1 )
        self.model.train(samples, responses, params = params)

    def predict(self, samples):
        return np.float32( [self.model.predict(s) for s in samples])

rawDescription: Python OpenCV SVM implementation

description: Python OpenCV SVM implementation


code:
dct = {'A': 'C', 'R': 'E', 'D': 'A', 'L': 'R', 'C': 'D'}
wanted = "A"
get_key_or_val_itms(dct, wanted)

rawDescription: Python - using dictionary to count keys and values


code:
length = 0
for char in myString:
    length += 1
print(length)

rawDescription: Reading the length of a string without using a built-in function?


rawDescription: How to write a recursion function for all the possible parameter combinations in python

description: Write a recursion function for all the possible parameter combinations in python


code:
from itertools import groupby

def read_parag(filename):
    with open(filename) as f:
        for k,g in groupby((line.strip() for line in f), bool):
            if k:
                yield list(g)

rawDescription: itertools.takewhile within a generator function - why is it evaluated once only?

description: Itertools.takewhile within a generator function - why is it evaluated once only


code: stemmedWords

rawDescription: Stem words of complex structure

description: Stem words of complex structure


code:
sensor = {
    'id': 'aaaaa',
    'name': 'temp001',
    'quantity': 'temperature',
    'unit': 'C',
    'charlength': 4,
    'convert': {
        'linear': ("linear", 3, 2, 6),
        'quadratic': ("quadratic", 2, 4, 7, 8)
    }
}

rawDescription: Can I store Python function on a MongoDB collection?

description: Store Python function on a MongoDB collection


rawDescription: better way to convert list element into a list like this one

description: Better way to convert list element into a list like this one


code:
word = input('word: ')
print(file.read().split().count(word))

rawDescription: How to check how many times a word appears in a text file

description: Check how many times a word appears in a text file


code:
import sys
def main(arg):
    print("Hello World"+arg)

if __name__ == "__main__":
    main(sys.argv[1])

rawDescription: return value from one python script to another

description: Return value from one python script to another


code: string.find("\n\n", pos)  # searches for "\n\n" starting from position `pos`, returning the first match

rawDescription: How can I find the boundaries of a paragraph with Python `string.find()`?

description: Find the boundaries of a paragraph with Python `string.find()`


code:
filtered = [i for i in item_list if not any(stop in i for stop in not_allowed)]
filtered

rawDescription: Check if string contains any elements from list


code: DF

rawDescription: Create Pandas Datetime index from 8 digit date and 2,3, and 4 digit time


code:
import numpy as np
from matplotlib import pyplot as plt
import random, sys
from datetime import datetime, timedelta
import time

tWindow=1 #moving window in minutes

timeList=[datetime.now()]
valList=[random.randint(1, 20)]

fig = plt.figure() #Make a figure
ax = fig.add_subplot(111) #Add a subplot

#Create the line with initial data using plot_date to add time to the x axis
line,=plt.plot_date(timeList, valList, linestyle='-')

#Set the x limits to the time window
ax.set_xlim([datetime.now()-timedelta(seconds=tWindow*60),datetime.now()])

#set the y limits
ax.set_ylim(0,20)

#grab the blank background to clear the plot later
background = fig.canvas.copy_from_bbox(ax.bbox)

#show the figure
fig.show()

#loop
for i in range(100):
    #restore the background
    fig.canvas.restore_region(background)

    #add time to time list
    timeList.append(datetime.now())

    #add random value to values
    valList.append(random.randint(1, 20))

    #update the line data
    line.set_data(timeList,valList)

    #update x limits
    ax.set_xlim([datetime.now()-timedelta(seconds=tWindow*60),datetime.now()])

    #redraw widnow
    fig.canvas.draw()

    #pause the loop for .5 seconds
    time.sleep(0.5)

rawDescription: matplotlib axes formatting

description: Matplotlib axes formatting


rawDescription: Python While Not recordset.EOF that wont .MoveNext


code:
from django.http import HttpResponse
from django.template import Context, Template

def my_view(request):
    # some logic

    template = Template(data)
    context = Context({})  # you can provide a context if needed
    return HttpResponse(template.render(context))

rawDescription: Can beautiful soup output be sent to browser?


code:
import numpy as np
listvals = []
for i in range(10):
    listvals.append((xc, yc))
mat_vals = np.vstack(listvals)

rawDescription: Create 2d Array in Python Using For Loop Results


code:
def add_view(self, request, form_url='', extra_context=None):
    return ContractAdminView.as_view()(request)

rawDescription: Django pass TemplateView to ModelAdmin.add_view


code:
a = "hello i am stackoverflow.com user +-"
print(re.sub(r'\\(?=[\s"])', r'', re.escape(a)))

rawDescription: How can I find a match and update it with RegEx?

description: Find a match and update it with RegEx


code:
from selenium.webdriver.support.select import Select

select = Select(driver.find_element_by_name("servers"))
select_by_visible_text(myServerIP)

rawDescription: While statement not evaluating to false for Selenium Webdriver


rawDescription: How do I convert unicode to unicode-escaped text

description: Convert unicode to unicode-escaped text


code:
class CompressedJSONField(JSONField, CompressedField):
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        value = JSONField.to_python(self, value)
        value = CompressedField.to_python(self, value)
        return value

rawDescription: Django custom field with multiple inheritance


code:
a
a1,a2,a3 = np.vsplit(a[np.random.permutation(a.shape[0])],(6,8))
a1
a2
a3

rawDescription: Numpy: split array randomly

description: Numpy: split array randomly


code:
words_no_double_caps = [word for word in words_alnum
                        if sum(ch.isupper() for ch in word) < 2]
words_no_double_caps = list(filter((lambda word: sum(map(
                           lambda ch: ch.upper(), word)) < 2), words_alnum))

rawDescription: python filter rewrite filter

description: Python filter rewrite filter


code:
{'123 Solar': [{'Email': '',
                'Organization': '123 Solar',
                'Phone': '444-444-4444',
                'website': 'www.123solar.com'},
               {'Email': 'joey@123solar.com',
                'Organization': '123 Solar',
                'Phone': '',
                'Website': 'www.123solar.com'}],
 '234 test': [{'Email': 'a@123solar.com',
               'Organization': '234 test',
               'Phone': '111',
               'Website': 'b.123solar.com'},
              {'Email': 'ac@123solar.com',
               'Organization': '234 test',
               'Phone': '222',
               'Website': 'bd.123solar.com'}]}

rawDescription: Sort a list of dictionaries while consolidating duplicates in Python?


code:
johnsmith = student('John', 'Smith', 14, 3.5)
intropython = course('Python 1', 20)
intropython.add_student('John Smith', johnsmith)

rawDescription: assigning objects to another object python

description: Assigning objects to another object python


code:
with open('inputfilename.txt') as menu:
    d = {}
    for line in menu:
        key, value = line.split(None, 1)
        d[key] = value.strip()
    return d

rawDescription: Converting file to dict

description: Converting file to dict


code:
#!python3

import binascii
import os

def processChunk(f, pos, chunk_size):
    f.seek(pos)
    b = f.read(chunk_size)
    b1 = b[:8]                  # first 8 bytes
    b2 = b[8:]                  # the rest
    s1 = ' '.join('{:02x}'.format(x) for x in b1)
    s2 = ' '.join('{:02x}'.format(x) for x in b2)
    print('{:08x}:'.format(pos), s1, '|', s2)

fname = 'a.txt'
sz = os.path.getsize(fname)     # not checking existence for simplicity
chunk = 16

with open(fname, 'rb') as f:

    for pos in range(sz - chunk, 0, -chunk):
        processChunk(f, pos, chunk)

    if pos > 0:
        processChunk(f, 0, pos)

rawDescription: Reading a binary file on backwards using python


rawDescription: Is there a better way to index dataframes?


rawDescription: How to loop backwards in python?

description: Loop backwards in python


code:
def onLeft(self):
    self.splitter.setSizes([1, 0])

def onBoth(self):
    self.splitter.setSizes([1, 1])

def onRight(self):
    self.splitter.setSizes([0, 1])

rawDescription: How to control qsplitter handle using buttons

description: Control qsplitter handle using buttons


code:
from bs4 import BeautifulSoup
BeautifulSoup('

Hello

', 'html.parser')
BeautifulSoup('

Hello

', 'html5lib')

rawDescription: Utilizing BeautifulSoup on a completely flat HTML hierarchy


code:
a
arr = np.array(a)
out

rawDescription: Numpy create matrix with values in specific locations


code:
import threading, Queue #queue in 3.x

my_queue = Queue.Queue()

def go(*args):
    my_thread = threading.Thread(target=function_that_does_stuff)

def function_that_does_stuff():
    my_queue.put("Logging in...")
    do_lots_of_stuff()
    my_queue.put("Doing stuff #1...")
    do_even_more_stuff()
    my_queue.put("Success!")

rawDescription: How do I make a button in my tk UI that makes the program do a whole ton of stuff when it is pressed not freeze the window?

description: Make a button in my tk UI that makes the program do a whole ton of stuff when it is pressed not freeze the window


code:
from numpy import linspace, meshgrid
from matplotlib.mlab import griddata

def grid(x, y, z, resX=100, resY=100):
    "Convert 3 column data to matplotlib grid"
    xi = linspace(min(x), max(x), resX)
    yi = linspace(min(y), max(y), resY)
    Z = griddata(x, y, z, xi, yi)
    X, Y = meshgrid(xi, yi)
    return X, Y, Z

rawDescription: Make contour of scatter

description: Make contour of scatter


code: arr = np.column_stack([nodnr.T, coord])

rawDescription: Formatted output from numpy arrays

description: Formatted output from numpy arrays


code:
if 1<= sel_song <=90:
    s.path.join(directory, "{}.mp3".format(sel_song))

rawDescription: Pythonic way of setting path from list

description: Pythonic way of setting path from list


code: plt.plot(x, y, marker='.', linestyle='None', color="#e0e0e0")

rawDescription: HTML colors in matplotlib

description: HTML colors in matplotlib


code:
while(True):
    user_input = int(input('Please enter a number:'))
    if(user_input == -9999):
        break
    elif(user_input >= 0):
        p.append(user_input)
    elif(user_input <= 0):
        n.append(user_input)
    #always append to a, makes the order the same as input order.
    a.append(user_input)

rawDescription: asking for numbers in python and returning a list

description: Asking for numbers in python and returning a list


code:
import re

def type_and_size(s):
    return re.split('[][]', s+'[1]', 2)[:2]

type_and_size('char')
['char', '1']

type_and_size('char[5]')
['char', '5']

rawDescription: get datatype length in python by parsing a string

description: Get datatype length in python by parsing a string


code:
def findTerm(self, term):
    node = self.tree
    for c in term:
        c = c.lower()
        if re.match("[a-z]",c):
            if c in node[0]:
                node = node[0][c]
            else:
                return False
    return node[1] != None

rawDescription: Accessing a Dynamically Generated Nested Dictionary