code:
date_times = pd.date_range(datetime.datetime(2011, 4, 1, 9, 30),
                           datetime.datetime(2011, 4, 16, 0, 0),
                           freq='10s')
VOL = np.random.sample(date_times.size) * 10000.0

df = pd.DataFrame(data={'VOL': VOL}, index=date_times)
df.resample('5Min', how={'VOL': np.mean})

rawDescription: Pandas: De-seasonalizing time-series data


rawDescription: Listing all values from tuple key in dict


code:
df['groupno'] = (df['count'] == 0).cumsum()
df

rawDescription: group data ranges by column value not zero

description: Group data ranges by column value not zero


rawDescription: Python regex for matching bb code

description: Python regex for matching bb code


code:
for i in range(0, ace_count):
    dacl.DeleteAce(0)

rawDescription: How to authorize/deny write access to a directory on Windows using Python?

description: Authorize/deny write access to a directory on Windows using Python


code: from django.db.models import Max

rawDescription: Getting the latest distinct object in Django


code: plt.xticks(range(len(xaxis)), xaxis)

rawDescription: Plotting ticks on the x axis with positive and negative values, in strange order -Python


code:
from itertools import izip

changed_value = random.randint(0,flag_option,len(num_entries))
chromosome = [c if c <= flag_option else v
                for c, v in izip(chromosome, changed_value)]

rawDescription: Replace item in list with corresponding item in another list (Python)


rawDescription: Not able to parse a json post from javascript in Python


code:
yourlist = [{'name' : 'Bob', 'Salary2014' : 2000}, {'name': 'Alice', 'Salary2014' : 1000}, {'name':'Bob', 'Salary2013' : 1500}]
combined = {}
for d in yourlist:
    combined.setdefault(d['name'], {}).update(d)

combined.values()

rawDescription: Combine Dictionarys in a list based on a value


code: extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'numpydoc']

rawDescription: How does NumPy process docstrings into sphinx documentation for Parameters?


code:
with open('myfile.txt', 'rb+') as f:
    f.seek(FIXED_LINE_LENGTH * line_number)
    f.write(new_line)

rawDescription: python replace random line in large file

description: Python replace random line in large file


code:
def wrapper_targetFunc(f, q, somearg):
    while True:
        try:
            work = q.get(timeout=3)  # or whatever
        except queue.Empty:
            return
        f(work, somearg)
        q.task_done()

q = queue.Queue()
for ptf in b:
    q.put_nowait(ptf)
for _ in range(20):
    threading.Thread(target=wrapper_targetFunc,
                     args=(targetFunction, q, otherarg)).start()
q.join()

rawDescription: Threading queue working example

description: Threading queue working example


code:
from collections import defaultdict

def load(fileIn, fileOut):
    with open(fileIn+'.txt') as fin:
        frame_rects = defaultdict(list)

        for row in (map(int, line.split()) for line in fin):
            frame, rect = row[2], [row[3],row[4],row[5],row[6]]
            frame_rects[frame].append(rect)
        fin.close()
        with open(fileOut+'.txt', 'w') as fout:
            for frame, rects in sorted(frame_rects.iteritems()):
                fout.write('{{{}:{}}}\n'.format(frame, rects))

load('filein', 'fileout')

rawDescription: Group values under certain key

description: Group values under certain key


rawDescription: Logic of triangle inequality as python conditionals?


rawDescription: numpy get values in array of arrays of arrays for array of indices

description: Numpy get values in array of arrays of arrays for array of indices


code:
from os.path import expanduser
folder = expanduser('~/Pictures')

rawDescription: platform-independent way to fetch pictures folder?

description: Platform-independent way to fetch pictures folder


code: index = self.widget_dict[some_widget]

rawDescription: wxPython: access sizer of GUI generated by wxFormBuilder and replace child

description: WxPython: access sizer of GUI generated by wxFormBuilder and replace child


code:
from bokeh.plotting import figure, output_file, show

output_file("circle.html")
p= figure(title = 'title',x_axis_label='x',y_axis_label='y')
p.circle(-25,25, radius=5, color="black", alpha=0.8)
show(p)

rawDescription: Bokeh package in Python: How to use rgb to color option


rawDescription: Python: Compare 2 lists of tuples of different size


code: print(len([line for line in a.splitlines() if line.strip()]))

rawDescription: How can I count the number of numbers in this line-separated string literal in python?

description: Count the number of numbers in this line-separated string literal in python


code:
def combine(df_left, df_right, cols=None, on=None):
    def check(r):
        updated = []
        for c in cols:
            xc = '%s_x' % c
            yc = '%s_y' % c
            if math.isnan(r[xc]):
                r[xc] = r[yc]
                updated.append(c)
        r['updated'] = ','.join(updated)
        return r
    left_expanded = df_left.merge(df_right, on=on, how='left')
    left_expanded = left_expanded.apply(check, axis=1)
    columns = [('%s' % c, c.replace('_x', ''))
                for c in left_expanded.columns]
    left_expanded.rename(columns=dict(columns), inplace=True)
    return left_expanded[list(df_left.columns) + ['updated']]

rawDescription: Merging dataframes based on Time

description: Merging dataframes based on Time


code:
score = [1, 2]
df[df.isin(score).any(axis=1)]

rawDescription: What is the best way to create new pandas dataframe consisting of specific rows of an existing dataframe that match criteria?


code:
setenv('PYSPARK_PYTHON', '/path/to/anaconda/bin/python', overwrite=False)
setenv('PYSPARK_DRIVER_PYTHON', '/path/to/anaconda/bin/ipython')

rawDescription: Running Scipy using sparkmooc Vagrant box


code:
data = {"item" : None}
keys = ["a","b","c"]
d2 = dict()

for i in range(len(keys)):
    d2[keys[i]] =  copy.deepcopy(data)

rawDescription: Values assigned differently in seemingly identical dictionaries


rawDescription: Numpy/Python performing terribly vs. Matlab


code:
from datetime import datetime

...

datetime.strptime(td['date'].strip('*'), '%Y-%m-%d')

rawDescription: Navigating an HTML tree in Python

description: Navigating an HTML tree in Python


code:
def foo(arg1, arg2, src, dst=None):
    dst = dst or src

rawDescription: Python - how to set default parameter equal to another parameter


code:
from django.utils import timezone

class ClassName(models.Model):
    ...
    deadline = models.DateTimeField('Deadline')
    status = models.CharField(max_length=10, choices=STATUS)

    def save(self, *args, **kwargs):
        if self.deadline < timezone.now():
            self.status = 'Inactive'
        super(ClassName, self).save(*args, **kwargs)

rawDescription: Adjust Choice in Django CharField using Current Date


code:
from string import Template

class DeltaTemplate(Template):
    delimiter = "%"

def strfdelta(tdelta, fmt):
    d = {"D": tdelta.days}
    d["H"], rem = divmod(tdelta.seconds, 3600)
    d["M"], d["S"] = divmod(rem, 60)
    t = DeltaTemplate(fmt)
    return t.substitute(**d)

rawDescription: formatting python timedelta objects

description: Formatting python timedelta objects


rawDescription: How would I make a dictionary from a list of tuples?


code:
import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequense(unittest.TestCase):
    pass

def test_generator(a, b):
    def test(self):
        self.assertEqual(a,b)
    return test

if __name__ == '__main__':
    for t in l:
        test_name = 'test_%s' % t[0]
        test = test_generator(t[1], t[2])
        setattr(TestSequense, test_name, test)
    unittest.main()

rawDescription: How to generate dynamic (parametrized) unit tests in python?

description: Generate dynamic (parametrized) unit tests in python


code:
a = np.array([
        [1, np.nan, np.nan, np.nan],
        [np.nan, 1, np.nan, 2],
        [np.nan, np.nan, np.nan, np.nan]
    ])
get_nans_blocks_length(a)
array([3, 1, 1, 4], dtype=int64)

rawDescription: Finding start and stops of consecutive values block in Python/Numpy/Pandas


code:
with open("file1") as infile:
    with open("file2","w") as outfile:
        for i,line in enumerate(infile):
            if i==2:
                # 3rd line
                outfile.write("new line1\n")
                outfile.write("new line2\n")
                outfile.write("new line3\n")
            elif i==3:
                # 4th line
                pass
            else:
                outfile.write(line)

rawDescription: Remove and insert lines in a text file

description: Remove and insert lines in a text file


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize

data = np.genfromtxt('data.txt')
def gaussian(x, height, center, width, offset):
    return height*np.exp(-(x - center)**2/(2*width**2)) + offset
def three_gaussians(x, h1, c1, w1, h2, c2, w2, h3, c3, w3, offset):
    return (gaussian(x, h1, c1, w1, offset=0) +
        gaussian(x, h2, c2, w2, offset=0) +
        gaussian(x, h3, c3, w3, offset=0) + offset)

def two_gaussians(x, h1, c1, w1, h2, c2, w2, offset):
    return three_gaussians(x, h1, c1, w1, h2, c2, w2, 0,0,1, offset)

errfunc3 = lambda p, x, y: (three_gaussians(x, *p) - y)**2
errfunc2 = lambda p, x, y: (two_gaussians(x, *p) - y)**2

guess3 = [0.49, 0.55, 0.01, 0.6, 0.61, 0.01, 1, 0.64, 0.01, 0]  # I guess there are 3 peaks, 2 are clear, but between them there seems to be another one, based on the change in slope smoothness there
guess2 = [0.49, 0.55, 0.01, 1, 0.64, 0.01, 0]  # I removed the peak I'm not too sure about
optim3, success = optimize.leastsq(errfunc3, guess3[:], args=(data[:,0], data[:,1]))
optim2, success = optimize.leastsq(errfunc2, guess2[:], args=(data[:,0], data[:,1]))
optim3

plt.plot(data[:,0], data[:,1], lw=5, c='g', label='measurement')
plt.plot(data[:,0], three_gaussians(data[:,0], *optim3),
    lw=3, c='b', label='fit of 3 Gaussians')
plt.plot(data[:,0], two_gaussians(data[:,0], *optim2),
    lw=1, c='r', ls='--', label='fit of 2 Gaussians')
plt.legend(loc='best')
plt.savefig('result.png')

rawDescription: Python-load data and do multi Gaussian fit


code:
import pickle

class Data(object):
    def __init__(self):
        self.x = 12

data = Data()

for p in [0, 1, 2]:
    with open('data.{}'.format(p), 'wb') as fh:
        pickle.dump(data, fh, protocol=p)

# Python 3 only.
with open('data.3', 'wb') as fh:
    pickle.dump(data, fh, protocol=3)

rawDescription: Read python pickle data stream in Android


code:
import cookielib
import json
import mechanize
import sys
import urllib
import urlparse

MAX_PAGE = 6
TERM = 'drug'
DEBUG = False

base_url = 'http://www.ncbi.nlm.nih.gov/images?term=' + TERM
browser = mechanize.Browser()
browser.set_handle_robots(False)
browser.set_handle_referer(True)
browser.set_debug_http(DEBUG)
browser.set_debug_responses(DEBUG)
cjar = cookielib.CookieJar()
browser.set_cookiejar(cjar)

# make first GET request. this will populate the cookie
res = browser.open(base_url)

def write(num, data):
    with open('file_%06d.html' % num, 'wb') as out:
        out.write(data)

def encode(kvs):
    res = []
    for key, vals in kvs.iteritems():
        if isinstance(vals, list):
            for v in vals:
                res.append('%s=%s' % (key, urllib.quote(v)))
        else:
            res.append('%s=%s' % (key, urllib.quote(vals)))
    return '&'.join(res)

write(1, res.read())

# set this var equal to the contents of this: http://pastebin.com/UfejW3G0
POSTDATA = '''<post data>'''

# parse the embedded json vars into POST parameters
PREFIX1 = 'EntrezSystem2.PEntrez.ImagesDb.'
PREFIX2 = 'EntrezSystem2.PEntrez.DbConnector.'
params = dict((k, v[0]) for k, v in urlparse.parse_qs(POSTDATA).iteritems())

base_url = 'http://www.ncbi.nlm.nih.gov/images'
for page in range(2, MAX_PAGE):
    params[PREFIX1 + 'Images_ResultsPanel.Entrez_Pager.CurrPage'] = str(page)
    params[PREFIX1 + 'Images_ResultsPanel.Entrez_Pager.cPage'] = [str(page-1)]*2

    data = encode(params)
    req = mechanize.Request(base_url, data)
    cjar.add_cookie_header(req)
    req.add_header('Content-Type', 'application/x-www-form-urlencoded')
    req.add_header('Referer', base_url)
    res = browser.open(req)

    write(page, res.read())

rawDescription: python mechanize follow_link fails

description: Python mechanize follow_link fails


rawDescription: How to iterate two successive elements of the lists of lists in python ?

description: Iterate two successive elements of the lists of lists in python


code:
class PluralDict(dict):
    def __missing__(self, key):
        if '(' in key and key.endswith(')'):
            key, rest = key.split('(', 1)
            value = super().__getitem__(key)
            suffix = rest.rstrip(')').split(',')
            if len(suffix) == 1:
                suffix.insert(0, '')
            return suffix[0] if value <= 1 else suffix[1]
        raise KeyError(key)

data = PluralDict({'tree': 1, 'bush': 2, 'flower': 3, 'cactus': 0})
fmt = "{tree} tree{tree(s)}, {bush} bush{bush(es)}, {flower} flower{flower(s)}, {cactus} cact{cactus(i,us)}"
print(fmt.format_map(data))

rawDescription: Plural String Formatting

description: Plural String Formatting


code:
for i in range(703):
      for j in range(1247):
         averaged[i][j] = averaged[i][j] + image[i][j]
         averaged[i][j] /= 2

rawDescription: Averaged array calculation using numpy in Python


rawDescription: Iterate through a Namespace

description: Iterate through a Namespace


code:
def my_find(str1,str2):
    start = 0
    end = len(str1)
    all_finds = []
    while str1.find(str2,start,end) != -1 :
        x = str1.find(str2,start,end)
        all_finds.append(x)
        start = x+1

    return all_finds

rawDescription: DNA find all matching items from a list in a string (python 2.7)


rawDescription: python multidimensional list.. how to grab one dimension?

description: Python multidimensional list.. how to grab one dimension


rawDescription: Xpath extract dates between certain characters AND use as dates


code:
iiiiii
nnnnnn
aaaaa
sss
ttt
ee
hh
ll
pp
yy
m
r

rawDescription: Character Distributions

description: Character Distributions


rawDescription: Transform a 3 columns (x, y, result) Python Pandas DataFrame to a DataFrame of result values with x (unique) as row and y (unique) as column


code:
def calculate(request):
    if request.method == "POST":
        os.chdir(settings.PROJECT_PATH + '/calc/')

        f = open('calc_log.txt', 'w')   # Could change to 'a' for user activity log

        f.write("hehehehe")

        for key in request.POST:
            f.write(str(key) + " " + str(request.POST[key]) + '\n')

        f.write('\n\n')
        f.write("test")

        f.close()

    #...

rawDescription: Submit form is empty -- Django

description: Submit form is empty -- Django


code:
start = 0
stop = start

rawDescription: How Python's a, b = b, a works?

description: How Python's a, b = b, a works


code:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from doctors.items import DoctorsItem
from scrapy.http import Request
from urlparse import urljoin

class DoctorsSpiderSpider(BaseSpider):
    name = "doctors_spider"
    allowed_domains = ["coimbatore.com"]
    start_urls = [
        'http://www.coimbatore.com/doctors/home.htm'
    ]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)

        for row in hxs.select('/html/body/center[1]/table[@cellpadding = 0]'):
            i = DoctorsItem()
            i['doctor_name'] = '|'.join(row.select('./tr[1]/td[2]//font[@size = -1]/text()').extract()).replace('\n', ' ')
            i['qualification'] ='|'.join( row.select('./tr[2]/td[2]//font[@size = -1]/text()').extract()).replace('\n', ' ')
            i['membership'] = '|'.join(row.select('./tr[3]/td[2]//font[@size = -1]/text()').extract()).replace('\n', ' ')
            i['visiting_hospitals'] = '|'.join(row.select('./tr[4]/td[2]//font[@size = -1]/text()').extract()).replace('\n', ' ')
            i['phone'] = '|'.join(row.select('./tr[5]/td[2]//font[@size = -1]/text()').extract()).replace('\n', ' ')
            i['consulting_hours'] = '|'.join(row.select('./tr[6]/td[2]//font[@size = -1]/text()').extract()).replace('\n', ' ')
            i['specialist_in'] = '|'.join(row.select('./tr[7]/td[2]//font[@size = -1]/text()').extract()).replace('\n', ' ')
            yield i

        for url in hxs.select('/html/body/center[3]//a/@href').extract():
            yield Request(urljoin(response.url, url), callback=self.parse)

        for url in hxs.select('/html/body//a/@href').extract():
            yield Request(urljoin(response.url, url), callback=self.parse)

rawDescription: Webscraping from directory of HTML files using BS4 and python


code: [0 if not v.strip() else int(v.strip().split()[-1]) for v in inputlist]

rawDescription: extracting integer data from a string in list

description: Extracting integer data from a string in list


code: set(item.split(':')[0] for item in l)

rawDescription: How can I split the strings and get only the first part of it?

description: Split the strings and get only the first part of it


code:
def __hash__(self):
    return 0

rawDescription: Hashing uncertain objects

description: Hashing uncertain objects


code:
days_no_rain = print("Number of days without rain: " + str(len(day)) + count)
days_as_num = len(days.split())
days_with_rain = 7 - days_as_num
print(days_with_rain)

rawDescription: How do I subtract from an array and an user input?

description: Subtract from an array and an user input


code:
import dis
dis.dis(compile('{k: v for k, v in kv_pairs}', '', 'exec'))
dis.dis(compile('{k: v for k, v in kv_pairs}', '', 'exec').co_consts[0])
dis.dis(compile('dict(kv_pairs)', '', 'exec'))

rawDescription: Dictionary comprehensions in python are too comprehensive


code:
from itertools import combinations, product

def all_subs(seq):
    for i in range(1, len(seq)+1):
        for c in combinations(seq, i):
            yield c

rawDescription: Python all combinations for multiple lists with variable k


code:
class BarManager(models.Manager):
    use_for_related_fields = True

    def bar(self, foo=None):
        if foo == None:
            qs = Foo.objects.all()
            for field_name, field_val in self.core_filters.items():
                field_name = field_name.split('__')[1]
                qs = qs.filter(**{ field_name: field_val })
            foo = qs.get()
        # do k00l stuff with foo

rawDescription: Django: How to access originating instance from a RelatedManager?


code:
import asyncio
import sys
from asyncio.subprocess import PIPE

@asyncio.coroutine
def read_and_display(*cmd):
    """Read cmd's stdout, stderr while displaying them as they arrive."""
    # start process
    process = yield from asyncio.create_subprocess_exec(*cmd,
            stdout=PIPE, stderr=PIPE)

    # read child's stdout/stderr concurrently
    stdout, stderr = [], [] # stderr, stdout buffers
    tasks = {
        asyncio.Task(process.stdout.readline()): (
            stdout, process.stdout, sys.stdout.buffer),
        asyncio.Task(process.stderr.readline()): (
            stderr, process.stderr, sys.stderr.buffer)}
    while tasks:
        done, pending = yield from asyncio.wait(tasks,
                return_when=asyncio.FIRST_COMPLETED)
        assert done
        for future in done:
            buf, stream, display = tasks.pop(future)
            line = future.result()
            if line: # not EOF
                buf.append(line)    # save for later
                display.write(line) # display in terminal
                # schedule to read the next line
                tasks[asyncio.Task(stream.readline())] = buf, stream, display

    # wait for the process to exit
    rc = yield from process.wait()
    return rc, b''.join(stdout), b''.join(stderr)

rawDescription: Displaying subprocess output to stdout and redirecting it


code:
results = (session.query(PlayerModel)
                  .join(PlayerModel.messages)
                  .values(PlayerModel.username,
                          MessageModel.message,
                          MessageModel.time))
# results will be a generator object

# This seems a bit convoluted, but here you go.
resultlist = []
for username, message, time in results:
    resultlist.append({'message': message,
                       'username': username,
                       'time': time})

rawDescription: How to achieve inner join using SQLAlchemy?

description: Achieve inner join using SQLAlchemy


code:
import csv

with open(r'C:\path_to_script\filename_Brief.csv') as infh, \
     open('new_file.txt', 'wt') as outfh:
    reader = csv.DictReader(infh)
    for row in reader:
        if row['ALIAS'] == 'Y4K':
             outfh.write('Full_Name = {Full_Name}\n'
                         'PHONE_NO = {PHONE_NO}\n'
                         'ALIAS = {ALIAS}\n'.format(**row))

rawDescription: read in one row of csv file (based on input if i can) with DictReader, then format and write to new file

description: Read in one row of csv file (based on input if i can) with DictReader, then format and write to new file


code:
ymin, ymax = ylim()   # return the current ylim
ylim( (ymin, ymax) )  # set the ylim to ymin, ymax
ylim( ymin, ymax )    # set the ylim to ymin, ymax

rawDescription: How can I stretch my pyplot to make markers more discernible?

description: Stretch my pyplot to make markers more discernible


code: df >> select('one') >> rename(one='first')

rawDescription: "Piping" output from one function to another using Python infix syntax


code:
d = {'album': 'Lonerism', 'song': 'Led Zeppelin (Bonus Track)', 'datetime': '2014-12-10 08:03:00', 'artist': 'Tame Impala'}
d['artist'].lower
d['artist'].lower == 'tame impala'
d['artist'].lower()
d['artist'].lower() == 'tame impala'

rawDescription: Put dict into new list based on a key value in Python


rawDescription: Numpy search for elements of an array in a subset


rawDescription: Producing all groups of fixed-length combinations


O(n) + O(n) = O(n)


code: dict(zip(keys, vals))

rawDescription: array_combine() from PHP equivalent in Python?

description: Array_combine() from PHP equivalent in Python


rawDescription: how do I create dictionary keys from a list

description: Create dictionary keys from a list


code:
import io
f = io.StringIO()
print('my data', file=f)

# to get the value back
a = f.getvalue()
print(a)
f.close()

rawDescription: Python 3 print() to a variable

description: Python 3 print() to a variable


rawDescription: How to re-order a series of sublists?

description: Re-order a series of sublists


rawDescription: How can I 'close' poll in Django

description: 'close' poll in Django


code:
if args is not None:
    if isinstance(args, tuple):
        args = tuple(get_codec(a, self.encoders)(db, a) for a in args)
    elif isinstance(args, dict):
        args = {k: get_codec(a, self.encoders)(db, a) for a in args}
    query = query % args

rawDescription: change paramstyle on python MySQLdb module

description: Change paramstyle on python MySQLdb module


code:
f = open("myfile", "rb")
try:
    byte = f.read(1)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)
finally:
    f.close()

rawDescription: Reading binary file in Python and looping over each byte


code:
from collections import defaultdict
counts = defaultdict(int)
for word, tag in tagged:
 counts[tag] += 1
counts

rawDescription: Count verbs, nouns, and other parts of speech with python's NLTK


code:
def post(self):

    name = self.request.get('name')

    person = DatastoreWrite.Person()

    if name and not name.isspace():
        person.do_insert(name)

    self.redirect('/')

rawDescription: App won't display results inserted by api, will for ones inserted by site


code:
x[:] = np.where(mask, np.nan, np.log(r) * np.cos(t))
y[:] = np.where(mask, np.nan, np.log(r) * np.sin(t))

rawDescription: Log scale on radial contour plot with matplotlib


code:
from string import ascii_letters, digits
allowed = set("-_" + ascii_letters + digits)
s = "app-_l#e"
disallowed = [ch for ch in s if ch not in allowed]

rawDescription: How to address/check whether a character in a string isn't a disallowed character?

description: Address/check whether a character in a string isn't a disallowed character


code: import numpy as np

rawDescription: appending to a pandas dataframe

description: Appending to a pandas dataframe


code: newList = map( str, myList )

rawDescription: django , list of models to list of string

description: Django , list of models to list of string


code: {{ taggeddoc|safe }}

rawDescription: django render_to_response how to send special characters

description: Django render_to_response how to send special characters


rawDescription: Convert row to column header for Pandas DataFrame,


code:
"   ".isspace()
" x  ".isspace()

rawDescription: check if a string has only white characters in python

description: Check if a string has only white characters in python


code:
A = dict()
A.setdefault(1, []).append(3)
A
A.setdefault(1, []).append(5)
A

rawDescription: Add more values to same key

description: Add more values to same key


rawDescription: Binary I/O in Python

description: Binary I/O in Python


code: df.groupby('Facility Type').filter(lambda x: len(x) > 50)

rawDescription: Selecting data based on number of occurences using Python / Pandas


code:
with open("scores.txt") as f:
    scores = {'score{}'.format(i) : line.strip() for i,line in enumerate(f,1)}

rawDescription: Splitting up a string from a file and assigning variables


rawDescription: How to find the path of a changing directory name?

description: Find the path of a changing directory name


code: return [e.lower() for e in temp]

rawDescription: Parsing text with regular expression into list with empty string in result


code:
givenURL = 'http://site.com/?year=2011&month=10&day=5&hour=11'
pattern = "http://site.com/?year=%Y&month=%m&day=%d"
theDate = datetime.strptime(givenURL.split('&hour=')[0], pattern)

rawDescription: Retrieving a date from a complex string in Python


code:
import hotels

def main():
    hotels.load_cache()
    start_server()

rawDescription: web.py shared variables

description: Web.py shared variables


code:
from nltk.corpus import wordnet as wn

def penn_to_wn(tag):
    if tag.startswith('J'):
        return wn.ADJ
    elif tag.startswith('N'):
        return wn.NOUN
    elif tag.startswith('R'):
        return wn.ADV
    elif tag.startswith('V'):
        return wn.VERB
    return None

rawDescription: NLTK convert tokenized sentence to synset format


code:
result = []
for j in range(len(xs[0])):
    for i in range(len(xs)):
        result.append(xs[i][j])

rawDescription: List Comprehension Running Sequence

description: List Comprehension Running Sequence


code: answer

rawDescription: combine list of dictionaries with same key

description: Combine list of dictionaries with same key


code:
flowTcp = ("in_port" + LBRACE + in_port("in_port") + RBRACE + COMMA +
            "eth" + LBRACE + "src" + EQUAL + macAddress("src") + COMMA +
            "dst" + EQUAL + macAddress("dst") + RBRACE + COMMA +
            "eth_type" + LBRACE + eth_type("eth_type") + RBRACE + COMMA +
            "ipv4" + LBRACE + "src" + EQUAL + ipAddress("src") + COMMA +
                "dst" + EQUAL + ipAddress("dst") + COMMA +
                "proto" + EQUAL + proto("proto") + COMMA +
                "tos" + EQUAL + tos("tos") + COMMA +
                "ttl" + EQUAL + ttl("ttl") + COMMA +
                "frag" + EQUAL + frag("frag") + RBRACE + COMMA +
            "tcp" + LBRACE +
                "src" + EQUAL + src("srcPkt") + COMMA +
                "dst" + EQUAL + dst("dstPkt") +
                RBRACE +
            "packets" + COLON + packets("packets"))

rawDescription: extract data from ovs dump-flow using pyparsing

description: Extract data from ovs dump-flow using pyparsing


rawDescription: Writing a function to convert hex to decimal


code:
msg = MIMEText("The nightly build status was a SUCCESS\n\n"
"Build File: http://www.python.org\n\n"
"Build Results File: http://10.51.54.57/sandboxes/"
, project, "\n")

rawDescription: String manipulation in Python

description: String manipulation in Python


code: some_list[::-len(some_list) + 1]

rawDescription: Python slicing from last to first element?


code:
bad
ugly

rawDescription: How to find total number of positive and negative words from a text?

description: Find total number of positive and negative words from a text


code:
# For demonstration purposes, I'm assuming points like the center
# and the corners are simple tuples of integer coordinates
b1 = Block((10, 50), 5, 7)
b2 = Block.from_corners((20, 30), (40, 70))

rawDescription: Groups of optional arguments for a function - python


code: df1.sub(df2.reset_index([0, 1], drop=True), level=2)

rawDescription: Subtract values in a data frame ignoring specific keys


code:
import pandas as pd
import datetime
events = [datetime.datetime(2014, 12, 16, 0, 18, 12),
  datetime.datetime(2014, 12, 16, 0, 18, 27),
  datetime.datetime(2014, 12, 16, 0, 18, 27),
  datetime.datetime(2014, 12, 16, 0, 19, 9),
  datetime.datetime(2014, 12, 16, 0, 19, 39),
  datetime.datetime(2014, 12, 16, 0, 19, 49),
  datetime.datetime(2014, 12, 16, 0, 20, 2),
  datetime.datetime(2014, 12, 16, 0, 20, 19),
  datetime.datetime(2014, 12, 16, 0, 20, 47),
  datetime.datetime(2014, 12, 16, 6, 23, 43),
  datetime.datetime(2014, 12, 16, 6, 25, 45)]
df = pd.DataFrame ({'ts' : events})
df2 = df.ts.value_counts()
df2 = df2.resample('s').fillna(0)
print (df2.head(30))

rawDescription: Pandas - plot events with unequal interval


code:
datetimes = []
for date, time in zip(dates, times):
    datetimes.append(datetime.datetime.combine(date, time))

rawDescription: matplotlib time vs date

description: Matplotlib time vs date


code:
import types
types.BuiltinFunctionType

rawDescription: Python - test whether object is a builtin function


code:
from pprint import pprint
dic1={"720155": ["CAT", "Software"], "356d05": ["ESF", "Software"], "3b3758": ["DBA", "Software"], "9649db": ["Fun", "Software"], "96493f": ["Eagle", "Software"], "99701d": ["Pas", "Software"], "964971": ["Debug", "Software"], "b6f315": ["Bap", "Software"], "a0a824": ["Server", "Software"], "1e00sa": ["Adobe", "Software"], "8c8dd2": ["EXIT", "Software"], "cc1dfg": ["email", "Software"]}
pprint(sorted(dic1.iteritems(), key=lambda i: i[1][0].lower()))

rawDescription: Sorting python dictionary based on value index and in alphabetical order


rawDescription: Read 2 lines of a file into a dataframe with two columns using pandas read_csv()


rawDescription: Fast way to find the mean of a function?

description: Fast way to find the mean of a function


rawDescription: Expanding a numpy array of matrices with zeros


code:
from scipy.ndimage.interpolation import shift
import numpy as np

arrayToShift = np.reshape([i for i in range(27)],(3,3,3))

print('Before shift')
print(arrayToShift)

shiftVector = (1,2,3)
shiftedarray = shift(arrayToShift,shift=shiftVector,mode='wrap')

print('After shift')
print(shiftedarray)

rawDescription: Numpy roll in several dimensions

description: Numpy roll in several dimensions


code:
arr[dest]=v
arr[I]=0
arr

rawDescription: How to randomly change positions of non-zero entries of an array where certain rows are excluded

description: Randomly change positions of non-zero entries of an array where certain rows are excluded


code:
import sympy

def sech(x):
    return sympy.cosh(x)**(-1)
# sympy.sech = sech

def csch(x):
    return sympy.sinh(x)**(-1)
# sympy.csch = csch

arccos = sympy.acos

rawDescription: Sympy custom function

description: Sympy custom function


code:
class Product(models.Model):
    ...

    def add_all_attributes(self):
        for attribute in Attribute.objects.all():
            self.attributes.add(attribute)

rawDescription: Embed product-variance logic into Django models


code:
# Image type (IplImage)
IPL_DEPTH_SIGN = 0x80000000

IPL_DEPTH_1U = 1
IPL_DEPTH_8U = 8
IPL_DEPTH_16U = 16
IPL_DEPTH_32F = 32
IPL_DEPTH_64F = 64

IPL_DEPTH_8S = IPL_DEPTH_SIGN + IPL_DEPTH_8U
IPL_DEPTH_16S = IPL_DEPTH_SIGN + IPL_DEPTH_16U
IPL_DEPTH_32S = IPL_DEPTH_SIGN + 32

# subclassing the ctypes.Structure class to add new features
class _Structure(Structure):
    def __repr__(self):
        """
        Print the fields
        """
        res = []

        for field in self._fields_:
            res.append('%s=%s' % (field[0], repr(getattr(self, field[0]))))

        return self.__class__.__name__ + '(' + ','.join(res) + ')'

class IplTileInfo(_Structure):
    _fields_ = []

class IplROI(_Structure):
    _fields_ = \
    [
        # 0 - no COI (all channels are selected)
        # 1 - 0th channel is selected ...
        ('coi', c_int),
        ('xOffset', c_int),
        ('yOffset', c_int),
        ('width', c_int),
        ('height', c_int),
    ]

# ipl image header
class IplImage(_Structure):
    def __repr__(self):
        """
        Print the fields
        """
        res = []

        for field in self._fields_:
            if field[0] in ['imageData', 'imageDataOrigin']:
                continue

            res.append('%s=%s' % (field[0], repr(getattr(self, field[0]))))

        return self.__class__.__name__ + '(' + ','.join(res) + ')'

IplImage._fields_ = [
    ("nSize", c_int),
    ("ID", c_int),
    ("nChannels", c_int),
    ("alphaChannel", c_int),
    ("depth", c_int),
    ("colorModel", c_char * 4),
    ("channelSeq", c_char * 4),
    ("dataOrder", c_int),
    ("origin", c_int),
    ("align", c_int),
    ("width", c_int),
    ("height", c_int),
    ("roi", POINTER(IplROI)),
    ("maskROI", POINTER(IplImage)),
    ("imageID", c_void_p),
    ("tileInfo", POINTER(IplTileInfo)),
    ("imageSize", c_int),
    ("imageData", c_byte_p),
    ("widthStep", c_int),
    ("BorderMode", c_int * 4),
    ("BorderConst", c_int * 4),
    ("imageDataOrigin", c_char_p)]

class iplimage_t(_Structure):
    _fields_ = \
    [
        ('ob_refcnt', c_ssize_t),
        ('ob_type',  py_object),
        ('ipl_ptr', POINTER(IplImage)),
        ('data', py_object),
        ('offset', c_size_t)
    ]

# gets the dimensions of a numpy ndarray
def get_ndarray_dimensions(img):
    # getting image shape information
    img_shape = img.shape
    img_shape_length = len(img_shape)

    # validating parameters
    if img_shape_length <= 1 or img_shape_length > 3:
        raise ArgumentError('Invalid image information. We support images with 1, 2 or 3 channels only.')

    # getting the amount of channels
    nc = 1 if img_shape_length == 2 else img_shape[2]

    # building the processed image
    h, w = img_shape[0], img_shape[1]

    # returning the height, width and nChannels
    return h, w, nc

def build_ndarray_from_data(iplimage_ptr, img_shape):
    # getting image dimensions
    height, width, n_channels = img_shape

    # getting the IplImage*
    iplimage = iplimage_ptr.contents

    # creating the image header
    cv_img = cv2.cv.CreateImageHeader((width, height), IPL_DEPTH_8U, n_channels)

    # getting the char* from byte data
    str_data = string_at(iplimage.imageData, iplimage.imageSize)

    # setting the image data
    cv2.cv.SetData(cv_img, str_data, iplimage.widthStep)

    # building a CvMat image
    cv_mat = cv_img[:, :]

    # building the ndarray from the CvMat image
    ndarray = np.asarray(cv_mat)

    # returing the built ndarray
    return ndarray

# python wrapper function to the c++ function
def do_something(img):
    # getting the IplImage*
    iplimage_ptr = get_iplimage_ptr(img)

    # calling the c++ function
    ipl_ptr = __c_do_something(iplimage_ptr)

    # getting the image dimensions
    img_shape = get_ndarray_dimensions(img)

    # building the processed image
    proc_img = build_ndarray_from_data(ipl_ptr, img_shape)

    # returning the processed image
    return proc_img

# does something ('pointer' to the c function)
__c_do_something = c_func(
    'do_something', _cdll, POINTER(IplImage),
    ('img', POINTER(IplImage), 1),      # IplImage *img
)

rawDescription: Convert OpenCV IplImage* data to numpy array


code:
lis = [1, 2, 3, 4, 5]
n = 1
lis[-n]
lis[len(lis) - n] # equivalent to lis[-n]

rawDescription: Keep last word on each line of text file, delete rest


code:
import urllib2
fp = urllib2.urlopen('http://bit.ly/rgCbf')
fp.geturl()

rawDescription: Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS


code: temp_dataframe.groupby(level=0,axis=0).apply(lambda x: foo(x.name, x))

rawDescription: Including the group name in the apply function pandas python


code:
# calculate dimensions of axes 1 in figure units
x0, y0, dx, dy = ax1.get_position().bounds
maxd = max(dx, dy)
width = 6 * maxd / dx
height = 6 * maxd / dy

fig.set_size_inches((width, height))

fig.savefig('perfectCircle2.png')

rawDescription: Why is matplotlib plotting my circles as ovals?


rawDescription: How to create lists from csv files and cast columns to ints and floats

description: Create lists from csv files and cast columns to ints and floats


code:
user = User()
manager.add_document(user)

rawDescription: python-couchdb add ViewField to Model after instantiation

description: Python-couchdb add ViewField to Model after instantiation


code:
def get_abs_pos(lVals, word):
    return [i for i,x in enumerate([x for w in l for x in w.split()]) if x == word]

rawDescription: Absolute position from relative

description: Absolute position from relative


code:
import csv
Col1 = "ColumnName1"
Col2 = "ColumnName2"
Col3 = "ColumnName3"
mydictionary={Col1:[], Col2:[], Col3:[]}
csvFile = csv.reader(open("myfile.csv", "rb"))
for row in csvFile:
  mydictionary[Col1].append(row[0])
  mydictionary[Col2].append(row[1])
  mydictionary[Col3].append(row[2])

rawDescription: reading a CSV files columns directly into variables names with python

description: Reading a CSV files columns directly into variables names with python


code:
result = variable['result']
pprint(result)

rawDescription: Python: Retrieve result from inner dictionary


code:
from pathlib import Path
script = Path('/home/kristina/desire-directory/scripts/script.py')
script.parent
script.parent.parent

rawDescription: Get parent of current directory from Python script


code:
def MonteCarlo(starter, x):
    result = dict(w=0,l=0,n=0)
    for i in range(0, x):
        w,l,n = starterTrans3(starter)
        result['w']+=w
        result['l']+=l
        result['n']+=n
    return result

rawDescription: Summing result of Monte Carlo Sim; python


code:
def fast_triu_indices(dim,k=0):

    tmp_range = np.arange(dim-k)
    rows = np.repeat(tmp_range,(tmp_range+1)[::-1])

    cols = np.ones(rows.shape[0],dtype=np.int)
    inds = np.cumsum(tmp_range[1:][::-1]+1)

    np.put(cols,inds,np.arange(dim*-1+2+k,1))
    cols[0] = k
    np.cumsum(cols,out=cols)
    return (rows,cols)

rawDescription: Efficient way to find the index of the max upper triangular entry in a numpy array?


rawDescription: Iterator Object for Removing Duplicates in Python


code: im = array(Image.open(path + "\\" + fname).convert('L'))

rawDescription: Convert a color image to input vector for libsvm


code:
if largest==None:
    largest=numI
if smallest==None:
    smallest=numI

rawDescription: Returns unexpected value

description: Returns unexpected value


code:
myset = set()
myset.add(item)

rawDescription: check if a number already exist in a list in python

description: Check if a number already exist in a list in python


code:
# Suppose the 2D array is pop_density
coarseness = 5
temp = pop_density.reshape((pop_density.shape[0] // coarseness, coarseness,
                            pop_density[1] // coarseness, coarseness))
coarse_pop_density = np.sum(temp, axis=(1,3))

rawDescription: How to coarser the 2-d array data resolution

description: Coarser the 2-d array data resolution


code:
dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file
## once you're at the directory level you want, with the desired directory as the final path node:
dirname1 = os.path.basename(dir)
dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does.

rawDescription: Extract a part of the filepath (a directory) in Python


rawDescription: Runtime Optimization of sympy code using numpy or scipy


rawDescription: Libraries for manipulating multivariate polynomials


rawDescription: How to find url through regex in python?

description: Find url through regex in python


rawDescription: Finding and deleting repeated data entries with two identical features identified by a third unique feature


code: quiet = '-d' in argv and (argv.remove('-d') or True)

rawDescription: How can I do really cheap command line parsing in Python?

description: Do really cheap command line parsing in Python


code:
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QThread
from time import sleep

class LoadingProgressDialog(QtGui.QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Loading files...')

    def show_progress(self, p):
        self.setWindowTitle('Loading files... {}%'.format(p))

class LoadingWorker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    ready = QtCore.pyqtSignal()
    report_progress = QtCore.pyqtSignal(object)

    def process(self):
        print('Worker thread ID: %s' % int(QThread.currentThreadId()))
        print("Worker started")
        self.ready.emit()

        for p in range(0, 100, 10):
            self.report_progress.emit(p)
            sleep(0.2)

        print("Worker terminates...")
        self.finished.emit()

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication([])

    print('Main thread ID: %s' % int(QThread.currentThreadId()))

    workingThread = QThread()
    loadingWorker = LoadingWorker()
    loading_progress_dialog = LoadingProgressDialog()

    loadingWorker.ready.connect(loading_progress_dialog.exec)
    loadingWorker.report_progress.connect(loading_progress_dialog.show_progress)
    loadingWorker.finished.connect(workingThread.quit)
    loadingWorker.finished.connect(loading_progress_dialog.close)

    loadingWorker.moveToThread(workingThread)

    workingThread.started.connect(loadingWorker.process)
    workingThread.start()

    sys.exit(app.exec_())

rawDescription: PyQt Dialog not responsible while thread running


code: my_text = re.split(r"[^\w-',]+",text)

rawDescription: Regex to ignore specific characters

description: Regex to ignore specific characters


code:
DS = pkt.FCfield & 0x3
to_DS = DS & 0x1 != 0
from_DS = DS & 0x2 != 0

rawDescription: SCAPY PYTHON - Get 802.11 DS Status

description: SCAPY PYTHON - Get 802.11 DS Status


rawDescription: Python: How to store mutable variables like sets?


code:
from gensim import corpora
dictionary = corpora.Dictionary(df["review_text"])

rawDescription: How to map the word in data frame to integer ID with python-pandas and gensim?

description: Map the word in data frame to integer ID with python-pandas and gensim


code: sorted(ItemList, key=lambda item: (-item[0], item[1]))

rawDescription: Difficulty Sorting Tuples with itemgetter


rawDescription: How to convert pandas timezone aware timestamps to UNIX epoche?

description: Convert pandas timezone aware timestamps to UNIX epoche


code: os.system("yourScript.py -yourargs")

rawDescription: Restart a python script from backround_thread


code:
beast
lemon
ape
apple
sea
pea
orange
bat

rawDescription: tkinter and scrabble solver problems

description: Tkinter and scrabble solver problems


code:
purchase_dict
purchase_dict[2]

rawDescription: Is there a more time-wise efficient way to populate a dictionary


code:
with open('text.txt') as f:
    data = [list(line.strip()) for line in f if line.strip()]

rawDescription: Using File IO to create matrix

description: Using File IO to create matrix


code:
abc
ghi

rawDescription: How to delete a line from a file using python

description: Delete a line from a file using python


code:
def glob(pathname):
    """Return a list of paths matching a pathname pattern.

    The pattern may contain simple shell-style wildcards a la
    fnmatch. However, unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns.

    """
    return list(iglob(pathname))

rawDescription: Renaming multiple files in a folder by adding Prefix using python


code:
def allbut(*names):
    names = set(names)
    return [item for item in levels if item not in names]

rawDescription: Grouping by everything except for one index column in pandas


rawDescription: how to take date value from string in python?

description: Take date value from string in python


code:
for col in ['A', 'C', 'D']:
    df[col] = list(map(lambda xs, i: xs[i], df[col], k))

df

rawDescription: Python Pandas - Split different entries into separate rows allowing only certain combinations


code:
from itertools import groupby

with open('somefile') as fin:
    lines = ((line.split(None, 2)[:2], line) for line in fin if line.strip())
    for k, g in groupby(lines, lambda L: L[0]):
        lines = [el[1] for el in g]

rawDescription: Python- group lines by first two words

description: Python- group lines by first two words


code: set((type(dog) for dog in df.dog_name))

rawDescription: How do I subset a pandas data frame based on a list of string values?

description: Subset a pandas data frame based on a list of string values


code:
g = "abcdeÿÿaaaabbbÿÿcccdddÿÿeeeÿÿ"
import re
g.find(re.search(r'[^\x20-\x7E]',g).group(0))

rawDescription: how can i finding the index of non-ASCII character in python string?

description: Finding the index of non-ASCII character in python string


code:
lnz = lattice.nonzero()
lnz

rawDescription: index of a random choice from numpy array

description: Index of a random choice from numpy array


code:
nn.activate([0,0])
nn.activate([1,0])
nn.activate([0,1])
nn.activate([1,1])

rawDescription: How to train a neural network to supervised data set using pybrain black-box optimization?

description: Train a neural network to supervised data set using pybrain black-box optimization


code:
class MyProgressBar(QtGui.QProgressBar):
    def setValue(self, value):
        QtGui.QProgressBar.setValue(self, value)
        if value == self.maximum():
            palette = QtGui.QPalette(self.palette())
            palette.setColor(QtGui.QPalette.Highlight,
                             QtGui.QColor(QtCore.Qt.red))
            self.setPalette(palette)

rawDescription: Changing the color of a QProgressbar()

description: Changing the color of a QProgressbar()


code:
a = [1,2,3]
b = a
id(a), id(b)
del a[:]
a.append(4)
b

rawDescription: Assigning Variables in While loops

description: Assigning Variables in While loops


code:
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(12, 10))
for i in range(1, 26):
    fig.add_subplot(5, 5, i)
plt.show()

rawDescription: How do I set the matplotlib window size for the MacOSX backend?

description: Set the matplotlib window size for the MacOSX backend


code:
myzipfile = zipfile.Zipfile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
    [ ... ]

rawDescription: Python: downloading and unzipping a .zip file without writing to disk


code:
def condfunc(myvar):
    return "This" if myvar == "single" else "That"

rawDescription: Passing strings to functions

description: Passing strings to functions


rawDescription: setting up iterative item query in python

description: Setting up iterative item query in python


code:
t = pd.Timestamp.now()
(t - t.normalize()).total_seconds()

rawDescription: Given a timestamp, get total N. of seconds in the hour


code:
from Tkinter import Tk, Frame, Button

def translate(button):
    if button["text"] in monthdict.keys():
        button.config(bg="Red", text=monthdict[button["text"]])
    else:
        for key, val in monthdict.iteritems():
           if val in button["text"]:
               button.config(bg="Blue", text=key)

root = Tk()
mainframe = Frame(root)
mainframe.pack()
monthdict = {"January": "Enero", "February": "Febrero", "March": "Marzo"}

janbutton = Button(mainframe, text="January", bg="Blue", command= lambda: translate(janbutton))
janbutton.pack()
febbutton = Button(mainframe, text="February", bg="Blue", command= lambda: translate(febbutton))
febbutton.pack()
marchbutton = Button(mainframe, text="March", bg="Blue", command= lambda: translate(marchbutton))
marchbutton.pack()
root.mainloop()

rawDescription: How can I optimize my code for my Spanish Translation Program?

description: Optimize my code for my Spanish Translation Program


code: {k: min(i for i in (h1.get(k), h2.get(k)) if i) for k in h1.viewkeys() | h2}

rawDescription: Merge dictionaries with minimum value of common keys


code:
dict1 = dict(emp1={"Name": "McKay", "Job": "Developer"}, emp2={"Name": "Mandy", "Job": "Nurse"})
for emp, info in sorted(dict1.items(), key=lambda kv: kv[1]['Name']):
    print('{0}: {1[Name]} - {1[Job]}'.format(emp, info))
for emp, info in sorted(dict1.items(), key=lambda kv: kv[1]['Job']):
    print('{0}: {1[Name]} - {1[Job]}'.format(emp, info))

rawDescription: Worth using sorted( ,key=) on a nested dictionary?


code:
def query_by_month(request):
    if request.method == 'POST':
        form = PickDateForm(request.POST)
        if form.is_valid():
            selected_date= form.cleaned_data['date']    # 'selected_date' is a datetime.date object
            photos = Photo.objects.filter(uploaded_time__year=selected_date.year,
                                          uploaded_time__month=selected_date.month)
            return HttpResponse('Photos: ' + repr(photos))
        else:
            return HttpResponse('Invalid form')
    else:
        form = PickDateForm()
    return render(request, 'pickdate.html', {'form': form})

rawDescription: Django Dynamically search item by month using datepicker


code:
liste_usager = input(":")
liste_usager = [int(n) for n in liste_usager.split(' ')]
print(liste_usager)
print(type(liste_usager[0]))

rawDescription: Convert this string to int list

description: Convert this string to int list


code:
A
B
out
np.corrcoef(A[0],B), np.corrcoef(A[1],B), np.corrcoef(A[2],B)

rawDescription: Correlate a single time series with a large number of time series


code:
import re
re.match(r'^results/', 'results/3')  # no end of string $
re.match(r'^results/$', 'results/3')

rawDescription: Django: url dispatcher

description: Django: url dispatcher


code:
Local._get_collection().aggregate([
    # Match the documents that have the required user
    { "$match": {
         "points.user": user
    }},

    # unwind the embedded array to de-normalize
    { "$unwind": "$points" },

    # Matching now filters the elements
    { "$match": {
         "points.user": user
    }},

    # Group back as an array
    { "$group": {
        "_id": "$_id",
        "token": { "$first": "$token" },
        "points": { "$push": "$points" }
    }}
 ])

rawDescription: get filtered embeded elements from all class on mongoengine

description: Get filtered embeded elements from all class on mongoengine


code: ['road', 'pill', 'pillow', 'ball', 'work', 'box', 'foot', 'basket']

rawDescription: Separating compound nouns from basic nouns part 2


rawDescription: How to change pixel color in Python

description: Change pixel color in Python


code:
def names(teacher):
    direct = {c['name'] for c in teacher['colleagues']}
    return direct.union(*(names(c) for c in teacher['colleagues']))

rawDescription: Extract set of values from nested dictionaries/lists Python


rawDescription: How to remove a string with varying numbers at the end

description: Remove a string with varying numbers at the end


rawDescription: How to apply a decorator to subroutines in python

description: Apply a decorator to subroutines in python


rawDescription: javascript comparison operators

description: Javascript comparison operators


code:
A = np.arange(10)
B = np.random.random((10,3,5))
C0 = np.array([A[i]*B[i,:,:] for i in range(len(A))])
C1 = A[:,None,None] * B
np.allclose(C0, C1)

rawDescription: numpy array multiplication with arrays of arbitrary dimensions

description: Numpy array multiplication with arrays of arbitrary dimensions


code:
progress, total = 1000, 4000
"Getting anagrams and saving them... {}/{} or: {:.0%} done.".format(progress, total, progress / total)

rawDescription: Displaying a floor division

description: Displaying a floor division


rawDescription: Python Prevent readline from converting hex value


code:
g = networkx.DiGraph()
x = 'some string'
g.add_edge(1, 2, {x:2})
g[1][2]

rawDescription: Passing variables as arguments to networkx.add_edge() attributes


code:
def make_trie(*words):
     root = {}
     for word in words:
         current = root
         for letter in word:
             current = current.setdefault(letter, {})
         # insert sentinel at the end
         current[None] = None
     return root

def find_first(s, trie):
    for i in range(len(s)):
        pos, current, found = i, trie, []
        while pos < len(s) and s[pos] in current:
            found.append(s[pos])
            current = current[s[pos]]
            if None in current:  # whole substring detected
                return ''.join(found)
            pos += 1

leftmost = find_first(s, make_trie(s1, s2, s3))

rawDescription: Python: Is there a shortcut to finding which substring(from a set of substrings) comes first in a string?


rawDescription: How to find the most frequent words before and after a given word in a given text in python?

description: Find the most frequent words before and after a given word in a given text in python


code:
import csv

print('Column 1, Column 2, Column 3, Column 4, Column 5')
with open('data1', 'r') as f:
    reader=csv.reader(f)
    next(reader)
    for row in reader:
        print(row[0], row[1], row[2], row[3], row[1][-5:], sep=', ')

rawDescription: Python 3.5 Extract Digits from Column into New Column


rawDescription: Correct layout for dictionary literals

description: Correct layout for dictionary literals


code: [w for w in words if 'I=' in w]

rawDescription: Searching a string and returning only things I specify


code:
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}

for i in xrange(1000000):
    the_thing = options.get(something, 4)

rawDescription: Most efficient way of making an if-elif-elif-else statement when the else is done the most?


code:
from pprint import pprint
import nose
from nosetimer import plugin

plugin = plugin.TimerPlugin()
plugin.enabled = True
plugin.timer_ok = 1000
plugin.timer_warning = 2000
plugin.timer_no_color = False

nose.run(plugins=[plugin])
result = plugin._timed_tests
pprint(result)

rawDescription: How to benchmark unit tests in Python without adding any code

description: Benchmark unit tests in Python without adding any code


code:
for filename in word_count_dict["Britain"]:
    if filename == 'total': continue
    print("Britain appears in {} {} times".format(filename, word_count_dict["Britain"][filename]))

rawDescription: how to iterate over all keys in dictionary python?

description: Iterate over all keys in dictionary python


rawDescription: Python Regex capture multiple sections within string


code:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

rawDescription: How to open sqlite3 installed by Python 3?

description: Open sqlite3 installed by Python 3


rawDescription: remove extension in list python

description: Remove extension in list python


code:
happy_array = np.random.randn(28, 28)
im = plt.imshow(happy_array, cmap='seismic', interpolation='none')
cbar = plt.colorbar(im)
plt.show()

rawDescription: Given a 2D numpy array of real numbers, how to generate an image depicting the intensity of each number?


code:
import fileinput
...

# Read pairs as lines of input from STDIN
for line in fileinput.input():
    ...

rawDescription: How to get filename from stdin

description: Get filename from stdin


rawDescription: Select two random rows from numpy array

description: Select two random rows from numpy array


rawDescription: Python- How to convert stringed operator back to its special meaning?


rawDescription: Populating a sparse list with random 1's


code: perms = Permission.objects.filter(**{user_groups_query: user_obj})

rawDescription: Error while logging in when primary key of Django `User` is a `CharField`


code:
df['C'] = df.C.fillna(999)
df['D'] = df.D.replace('', np.NaN)

rawDescription: Dealing with missing data in Pandas and Numpy


rawDescription: Different class variables and usage

description: Different class variables and usage


code:
address = 1234567890
h = iter(hex(address)[2:].zfill(12))
":".join(i + next(h) for i in h)

rawDescription: Python - Get mac address

description: Python - Get mac address


code:
from models import MyModel, SomeOtherModel
m = MyModel
m.put()

rawDescription: GAE, Python: How to define db object classes in only one place?


code:
outFile.writelines("process.control.timeout=900\n"
                      if "process.control.timeout" in line else line
                         for line in process)

rawDescription: Search for a line that contains some text, replace complete line python


code:
import math
N = 600851475141
divisors = []
for i in xrange(1, int(math.sqrt(N))+1):
    if N % i == 0:
        divisors.extend(set((i, N//i)))
for d in sorted(divisors):
    print(d)

rawDescription: how to make this script a little bit faster?

description: Make this script a little bit faster


code:
@inlineCallbacks
def do_redis(self):
    foo = yield self.db.get('somekey')
    bar = yield self.db.hget(foo, 'bar') # Get 'bar' field of hash foo

rawDescription: Twisted: Advise on using txredisapi library required


code:
fig, ax = plt.subplots()
df = pd.Series([1, 2, 3])
df.plot(ax=ax)
plt.show(block=False)
time.sleep(5)
plt.close(fig)

rawDescription: how to close pandas dataframe plot

description: Close pandas dataframe plot


code:
from ast import literal_eval
df['col2'] = df['col2'].apply(literal_eval)

rawDescription: In pandas/python, reading array stored as string


code: {state: count.most_common(3) for state, count in courses.items()}

rawDescription: Checking for Values in a Dictionary

description: Checking for Values in a Dictionary


code:
class c:
    def m(self):
        pass
c.m

rawDescription: Why does setattr fail on a bound method

description: Why does setattr fail on a bound method


code:
colored = ColoredComic.create_from_Inked(pk=ink_id)
colored.colored = True
colored.save()

rawDescription: Populating Models from other Models in Django?


code: Mat[ Mat<0 ] = 0

rawDescription: python array conditional change on elements check numpy

description: Python array conditional change on elements check numpy


rawDescription: python code to get the files outside the current working directory

description: Python code to get the files outside the current working directory


code:
def double_preceding(v):
    values = v[:] # Make a copy of the list passed as argument

    if (values != []): # If list is not empty, store the first value in 'temp'
        temp = values[0]
    else:
        return

    v[0] = 0 # Set the first value of the list as '0' (as the problem says it)

    for i in range(1, len(values)): # Iterate 'n - 1' times, where n is the length of the list
        v[i] = 2 * temp # Set the corresponding value to twice the precedent (the precedent is stored in 'temp')
        temp = values[i]

rawDescription: A double preceding function with bug

description: A double preceding function with bug


code:
from itertools import combinations
[comb for i in range(1, 20) for comb in combinations(vals, i) if sum(comb) == target]

rawDescription: Finding Combinations to the provided Sum value


code:
from contextlib import closing

with closing(fileinput.input(['file1.txt', 'file2.txt'])) as infiles:
    for line in infiles:
        pass # stuff

rawDescription: Iterate across lines in two files in sequence


code: ['Zara', 'Nike', 'Alfani', 'Banana_Republic']

rawDescription: Return Shared Values using Python Dictionary


code:
listOne = list(map('!'.join, listOne))
listOne

rawDescription: Put a symbol between every letter in a list of strings


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

class Main(object):
    def clear(self):
        plt.clf()
    def redraw(self):
        self.clear()
        plt.plot(self.data)
        plt.title('100')
        plt.text(50,0.85,'100')
        plt.draw()
    def on_click(self,event):
        self.data=np.random.random(100)
        self.redraw()
    def run(self):
        plt.figure()
        plt.connect('button_press_event', self.on_click)
        plt.show()

    def __init__(self):
        self.data=np.random.random(100)

if __name__=='__main__':
    m=Main()
    m.run()
    print(m.data)

rawDescription: python matplotlib -- regenerate graph?

description: Python matplotlib -- regenerate graph


code:
def getNumeric(prompt):
    while True:
        try:
            res = int(input('Enter: '))
            break
        except (ValueError, NameError):
            print("Numbers only please!")
    return res

rawDescription: Getting safe user input in python

description: Getting safe user input in python


code:
# log and compile the statement up front
try:
  logging.info('Compiling and evaluating:\n%s' % statement)
  compiled = compile(statement, '<string>', 'single')
except:
  self.response.out.write(traceback.format_exc())
  return

rawDescription: How is http://shell.appspot.com/ executing code online?


code: numpy.add.at(A, C, B)

rawDescription: Assembly numpy vector

description: Assembly numpy vector


code:
def Base64Encode(ndarray):
    return json.dumps([str(ndarray.dtype),base64.b64encode(ndarray),ndarray.shape])
def Base64Decode(jsonDump):
    loaded = json.loads(jsonDump)
    dtype = np.dtype(loaded[0])
    arr = np.frombuffer(base64.decodestring(loaded[1]),dtype)
    if len(loaded) > 2:
        return arr.reshape(loaded[2])
    return arr

''' just to compare '''
def SimpleEncode(ndarray):
    return json.dumps(ndarray.tolist())
def SimpleDecode(jsonDump):
    return np.array(json.loads(jsonDump))

rawDescription: Dumping 2D Python array with Json

description: Dumping 2D Python array with Json


code:
import numpy as np
import numexpr as ne

a = np.arange(10)
b = np.arange(10, 20)
c = np.arange(20, 30)

rawDescription: Numexpr: How to use "local_dict" and "global_dict"?


code:
def engine(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None

        def handle_exception(typ, value, tb):
            if runner is not None:
                return runner.handle_exception(typ, value, tb)
            return False
        with ExceptionStackContext(handle_exception) as deactivate:
            try:
                result = func(*args, **kwargs)
            except (Return, StopIteration) as e:
                result = getattr(e, 'value', None)
            else:
                if isinstance(result, types.GeneratorType):
                    def final_callback(value):
                        if value is not None:
                            raise ReturnValueIgnoredError(
                                "@gen.engine functions cannot return values: "
                                "%r" % (value,))
                        assert value is None
                        deactivate()
                    runner = Runner(result, final_callback)
                    runner.run()
                    return
            if result is not None:
                raise ReturnValueIgnoredError(
                    "@gen.engine functions cannot return values: %r" %
                    (result,))
            deactivate()
            # no yield, so we're done
    return wrapper

rawDescription: Difference in tornado.gen.engine v/s tornado.gen.coroutine


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

column_labels = list('ABCDEFGH')
row_labels = list('WXYZ')
fig, ax = plt.subplots()
data = np.array([[ 0.96753494,  0.52349944,  0.0254628 ,  0.5104103 ],
         [ 0.07320069,  0.91278731,  0.97094436,  0.70533351],
         [ 0.30162006,  0.49068337,  0.41837729,  0.71139215],
         [ 0.19786101,  0.15882713,  0.59028841,  0.06242765],
         [ 0.51505872,  0.07798389,  0.58790067,  0.44782683],
         [ 0.68975694,  0.53535385,  0.15696023,  0.35641951],
         [ 0.66481995,  0.03576846,  0.9623601 ,  0.96006395],
         [ 0.45865404,  0.50433582,  0.18182575,  0.35126449],])

data[3,:] = np.nan
heatmap = ax.pcolor(data, cmap=plt.cm.seismic,
                    vmin=np.nanmin(data), vmax=np.nanmax(data))
heatmap.cmap.set_under('black')

bar = fig.colorbar(heatmap, extend='both')

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

rawDescription: Python: Leave Numpy NaN values from matplotlib heatmap and its legend


code:
foo is bar
foo is other

rawDescription: Comparing lists by reference vs value in Python


rawDescription: How can I find the missing value more concisely?

description: Find the missing value more concisely


rawDescription: Extra newline character for children of Beautiful Soup


rawDescription: Adding numbers within object

description: Adding numbers within object


code:
def delUnknownChar1(s):
    good = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-'")
    clean = ""
    for ele in s:
        if ele in good:
            clean += ele
    return clean.lstrip("-'").rstrip("-")

rawDescription: Python: Suggestion needed to optimise runtime of filter character method


code:
def xy(x, y):
#Gives the remainder of the division of x by y. Outputs as r.
   while x >= y:
       x -= y
   return x

rawDescription: Python - Trying to use the value of a name from one module in a different module


code:
m_key, m_value = 'p', 1
a = {m_key: m_value, 'r': 2}
b = {m_key: m_value, 'r': 3}

rawDescription: Defined dict entries Python

description: Defined dict entries Python


code:
def select(lst, subselect, select):
    return [sublst[slice(*subselect)] for sublst in lst[slice(*select)]]

rawDescription: python select range from list of list

description: Python select range from list of list


code:
from Tkinter import *

#------------------------------------

def my_bind(event): # bind send 1 argument to my_bind
    # different type of event can have different atributes
    #print event, event.widget, event.char, event.keysym, event.keycode

    new_text = e1.get() + e2.get()
    t.config(text=new_text)

#------------------------------------

top = Tk()

#---

t = Label(top)
t.pack()

#---

e1 = Entry(top)
e1.pack()

e1.bind('<Key>', my_bind)

#---

e2 = Entry(top)
e2.pack()

e2.bind('<Key>', my_bind)

#---

top.mainloop()

#------------------------------------

rawDescription: Constantly Update Label Widgets From Entry Widgets TKinter


code: all(v == 0 for v in values)

rawDescription: Check if all values of iterable are zero


code:
def find(path, pattern):
    for root, dirs, files in os.walk(path):
        for match in fnmatch.filter(files, pattern):
            yield os.path.join(root, match)

paths = list(find(".", "foobar.ext"))

rawDescription: Translate standard output memory file to string of English text as if a print command were being used


code:
cli = "./binary %s" % (argument)
cli_parts = shlex.split(cli)
mp = Popen(cli_parts, stdin=PIPE, stderr=PIPE, stdout=PIPE)
mp.communicate()[0]

rawDescription: Hadoop Streaming: Mapper 'wrapping' a binary executable


code:
file_path = '/tmp/dict_test.txt'
import json
data = [
    {"score": "10", "grade": "E", "music": "song5", "maxcombo": "1", "perfect": "20", "great": "1", "good": "20", "miss": "1"},
    {"score": "20", "grade": "D", "music": "song4", "maxcombo": "2", "perfect": "20", "great": "2", "good": "20", "miss": "2"},
    {"score": "30", "grade": "C", "music": "song3", "maxcombo": "3", "perfect": "20", "great": "3", "good": "20", "miss": "3"},
    {"score": "40", "grade": "B", "music": "song2", "maxcombo": "4", "perfect": "20", "great": "4", "good": "20", "miss": "4"},
    {"score": "50", "grade": "A", "music": "song1", "maxcombo": "5", "perfect": "20", "great": "5", "good": "20", "miss": "5"},
]

# dump the dict contents using json
with open(file_path, 'w') as outfile:
    json.dump(data, outfile, indent=4, separators=(',', ':'))

# Let's read the data back again from the file
file_text = ''
with open(file_path, 'rt') as file_placeholder:
    lines = file_placeholder.readlines()
    file_text = ''.join(lines)  # This provides the whole file data as string

print('file_text = {}'.format(file_text))
# Load as json
json_text = json.loads(file_text)
print('json = {}'.format(json_text))
print('file_text type = {}; json_text type = {}'.format(type(file_text), type(json_text)))

rawDescription: Exporting and Importing a array from python


rawDescription: determine a class attribute is Property?

description: Determine a class attribute is Property


code: matrix[X,Y] = Z

rawDescription: Filling matrix with array of coordinates in python


rawDescription: Is there a function that gives me a file name without path?


rawDescription: why is that str.count('') ≠ (from str.count('A') + str.count('B') + ... + str.count('Z'))

description: Why is that str.count('') ≠ (from str.count('A') + str.count('B') + ... + str.count('Z'))


rawDescription: Do python's variable length arguments (*args) expand a generator at function call time?


code:
def tolist(x):
    g = re.match(r"(WK\d{2})(Q\d)(\d{4})", str(x))
    return [g.group(3), g.group(2), g.group(1)]

rawDescription: Sorting by Date string in pandas - Python 2.7


rawDescription: Making time bins bigger in a large dataset with python


code:
import os.path
file_name = row['file_root_name']+'.smil'
full_path = os.path.join(path, file_name)
output = open(full_path, 'w')

rawDescription: Write file to directory based on variable in Python


code:
sort_order = self.request.get('sort_order', None)
self.response.out.write(self.rendered_games_list(sort_order))

rawDescription: Update Jinja2 template variables

description: Update Jinja2 template variables


code:
def skipIfTrue(flag):
    def deco(f):
        def wrapper(self, *args, **kwargs):
            if getattr(self, flag):
                self.skipTest()
            else:
                f(self, *args, **kwargs)
        return wrapper
    return deco

rawDescription: How can I decorate a Python unittest method to skip if a property I've previously evaluated isn't True?

description: Decorate a Python unittest method to skip if a property I've previously evaluated isn't True


code:
import sqlite3
class Point(object):
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return "Point(%f, %f)" % (self.x, self.y)
def adapt_point(point):
    return "%f;%f" % (point.x, point.y)
def convert_point(s):
    return Point(*(float(c) for c in s.split(";")))
sqlite3.register_adapter(Point, adapt_point)
sqlite3.register_converter("point", convert_point)
p = Point(4.0, -3.2)
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test").fetchone()[0]
cur.execute("select cast(p as text) from test").fetchone()[0]

rawDescription: Selectively bypass data type converter

description: Selectively bypass data type converter


code:
l=num_str.split(',')
[l[i:i+2] for i in range(0,len(l),2)]
[l[i:i+7] for i in range(0,len(l),7)]

description: Python: convert "5,4,2,4,1,0" into [[5, 4], [2, 4], [1, 0]]


code:
import requests
from bs4 import BeautifulSoup

url = "http://www.indiabix.com/computer-science/operating-systems-concepts/013001"
data = requests.get(url, headers={
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36"
}).content
soup = BeautifulSoup(data, "html.parser")

answers_string = soup.findAll("input", {"id":"hdnAjaxImageCacheKey"})[0]["value"]
answers = answers_string[::-1][17:22].upper()

# iterate over questions
for num, question_block in enumerate(soup.select(".bix-div-container")):
    question = question_block.select(".bix-td-qtxt")[0].get_text(strip=True)
    print(question + "\n")

    # iterate over answers
    for answer_block in question_block.select(".bix-tbl-options tr"):
        number, answer = answer_block.select(".bix-td-option")

        print(number.get_text(), answer.get_text())

    print("\nANSWER: " + answers[num])
    print("----")

rawDescription: Python BeautifulSoup: Text from the html (web) page not shown while soup.find_all(..)


code:
from tempfile import TemporaryFile
with open("out.txt") as f, TemporaryFile("w+") as t:
    h, ln = next(f), len(next(f).split(","))
    header = h.strip().split(",")
    f.seek(0), next(f)
    header += range(ln)
    print(pd.read_csv(f, names=header))

rawDescription: read_csv with missing/incomplete header or irregular number of columns

description: Read_csv with missing/incomplete header or irregular number of columns


rawDescription: Removing elements from pandas series in python


code:
class Server:
    thread = ClientThread

    #(some code)
    def run( self ):
       self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
       self.sock.bind( ( '127.0.0.1', 5050 ) )
       new_thread = thread( client )
       print('Incoming Connection. Started thread ', end=' ')
       self.thread_list.append( new_thread )
       new_thread.start()

rawDescription: Python3 - import and override method

description: Python3 - import and override method


code:
results = np.zeros((e.shape[0],2),nodes.dtype)
results[J] = nodes[I,1:]
results

rawDescription: Python - Replace data of an array by 2 values of a second array


rawDescription: Using a for loop to concatenate columns in Pandas


code:
import numpy as np
import pandas as pd
from patsy import dmatrices
from sklearn.linear_model import LogisticRegression

X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25,
3.5,4.0,4.25,4.5,4.75,5.0,5.5]
y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]

zipped = list(zip(X,y))
df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f'])

y, X = dmatrices('p_or_f ~ study_hrs',
                  df, return_type="dataframe")

y = np.ravel(y)

model = LogisticRegression(C=100000, fit_intercept=False)
model = model.fit(X,y)
print(pd.DataFrame(np.transpose(model.coef_),X.columns))

rawDescription: python logistic regression (beginner)

description: Python logistic regression (beginner)


code: list(b for i in a if len(i) == 1 for b in i)

rawDescription: Find the indices of subarrays of single element


code:
for tup in ( x for x in l if x[1] == 1 ):
    ...

rawDescription: python - iterating over a subset of a list of tuples

description: Python - iterating over a subset of a list of tuples


code:
#python 2.7.6

for i in range(1, 101):
    print(i),
    if i%10==0:
        print

rawDescription: Ten numbers per row using a pair of nested while loops


rawDescription: Get HTML Source of WebElement in Selenium WebDriver using Python


code:
import glob
glob.glob('*ITunes*.XLS')

rawDescription: How to move a file with a complicated filename in python

description: Move a file with a complicated filename in python


rawDescription: Get Data from JSON Python?

description: Get Data from JSON Python


rawDescription: Screenshot of a window using python

description: Screenshot of a window using python


code:
idx1, idx2 = min(combinations(range(len(_list)), 2),
                 key=lambda pair: sum(w * (x - y) ** 2
                                      for w, x, y in zip(weights_list, as_list[pair[0]], as_list[pair[1]])))
aux1, aux2 = _lists[idx1], _lists[idx2]

rawDescription: Compress dict sum statement with Python

description: Compress dict sum statement with Python


code:
from natural import number
number.ordinal(3)
number.ordinal(1234567)

rawDescription: giving numbers ordinal suffixes in python

description: Giving numbers ordinal suffixes in python


code:
def index_slice(arr1, arr2):
    lens = np.abs(arr1 - arr2)
    if not all((lens == max(lens)) | (lens == 0)):
        raise ValueError('The number of indices in some dimensions were inconsistent. Array lengths were %r' % lens)

    max_len = lens.max()
    result = np.empty((len(lens), max_len), dtype=np.int32)

    for dim, (a, b) in enumerate(zip(arr1, arr2)):
        if a == b:
            result[dim, :] = a
        elif a > b:
            result[dim, :] = np.arange(a, b, -1)
        else:
            result[dim, :] = np.arange(a, b)

    return result

rawDescription: Function to slice indices in Numpy

description: Function to slice indices in Numpy


code:
# arr1_weights[i] is the sum of all terms arr1[i] gets multiplied by in the
# original version
arr1_weights = arr2[::-1].cumsum()[::-1] - arr2

sum_prods = arr1.dot(arr1_weights)

rawDescription: Efficient Double Sum of Products

description: Efficient Double Sum of Products


code:
grouped = df.groupby((df.salary.diff() <= 0).cumsum())
parts = [g.reset_index(drop=True) for k, g in grouped]
for p in parts:
    print(p)

rawDescription: How to split DataFrame using some constraint?

description: Split DataFrame using some constraint


rawDescription: Pandas multiIndex DataFrame sort

description: Pandas multiIndex DataFrame sort


rawDescription: A way to pass milions of items in python to C program many times in rapid succesion


code:
custom_style = {'axes.labelcolor': 'white',
                'xtick.color': 'white',
                'ytick.color': 'white'}
sns.set_style("darkgrid", rc=custom_style)

rawDescription: Best way to display Seaborn/Matplotlib plots with a dark iPython Notebook profile

description: Display Seaborn/Matplotlib plots with a dark iPython Notebook profile


code:
mylist = []
mylist.append(('key', 'value'))
mylist.insert(0, ('foo', 'bar'))

rawDescription: Is it possible to add <key, value> pair at the end of the dictionary in python


code: random.choice([s for s in list_of_strings if len(s) > x])

rawDescription: Extract random values from list that fulfil criteria? Python


code:
forest.train(...)
forest.predict(...)

rawDescription: Random Trees in OpenCV from python

description: Random Trees in OpenCV from python


code: from mymod import mymod

rawDescription: Import object from module of same name using __import__


rawDescription: fmin with really poor performance. fmin_bfgs with precision loss. Minimization does not fit well

description: Fmin with really poor performance. fmin_bfgs with precision loss. Minimization does not fit well


code:
@cachedProperty(name='test')
def my_func(self):
    return 'ok'

rawDescription: python decorator arguments with @ syntax

description: Python decorator arguments with @ syntax


code:
# combine the lists
zipped = zip(alist, blist)

# write to a file (in append mode)
file = open("filename", 'a')
for item in zipped:
    file.write("%d, %d\n" % item)
file.close()

rawDescription: Combining 2 lists in python

description: Combining 2 lists in python


code:
def my_func(lst):
    return ', '.join(lst[:-1])+' and '+lst[-1]

rawDescription: Using .join() in Python

description: Using .join() in Python


code:
a = [1, 2, 2, 3, 4, 5]
condition = lambda x: x > 2
b = [x for x in a if condition(x)]      # b == [3, 4, 5]
a = [x for x in a if not condition(x)]  # a == [1, 2, 2]

rawDescription: Python list comprehension- "pop" result from original list?


code: db.execute("UPDATE MyTable SET url = finalURL(url) WHERE ...")

rawDescription: How to update the value of a specific column of every row in DB with the output of a function that was passed in the original value.

description: Update the value of a specific column of every row in DB with the output of a function that was passed in the original value.


code: [x for x in product(range(100),range(100),range(100)) if sum(x)<=100]

rawDescription: Python: Generate matrix of Nx4 integers who sum is a constant


rawDescription: How to get a common integer in python from a float list?

description: Get a common integer in python from a float list


code:
output_final = []
for i in range(5):  # we have 5 processes
    output_final.append(output.get())

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


rawDescription: In Appcelerator Titanium, how can I get Django's CSRF token?


code:
mydata = "クラ"
print(mydata)

rawDescription: How to read oslo config value in unicode

description: Read oslo config value in unicode


rawDescription: Creating my own string functions

description: Creating my own string functions


code:
def core(x):
    y = input("choose a number: ")
    if y == x:
        print("You gussed the right number!")
        return y
    elif y > x:
        print("The number is lower, try again")
        return y
    else:
        print("The number is higher, try again")
        return y

rawDescription: Return a value from a function called in while loop


code:
import numpy as np
cols = range(0,5) + range(6,35)
data = np.loadtxt("data.txt", delimiter=",", usecols=cols, dtype=np.float)
data

rawDescription: Read in csv file with one column of strings in the middle


code:
import argparse
parser = argparse.ArgumentParser(description="Hello")
group = parser.add_mutually_exclusive_group()
group.add_argument('--period', action='store')
group.add_argument('--df_dt', nargs='+')
args = parser.parse_args()

rawDescription: Python argparse mutually exclusive group with 1 vs 2 arguments


code:
a = 0
f = open('test.txt')
while a < 50:
    a = a + 1
    print(f.readline(), end='')
else:
    f.close()

rawDescription: Python - Loadtext for specific number of lines


code: f /= np.sqrt(np.sum(f**2, axis=1))[...,np.newaxis]

rawDescription: Parallel array manipulations in numpy

description: Parallel array manipulations in numpy


code:
import numpy as np
a = np.array(a)
a.mean(axis=1)

rawDescription: Using the reduce function on a multidimensional array


code: squence = Sequence(lastsequence, start, end)

rawDescription: Don't create the object if a condition isn't verfied


rawDescription: Supporting subtasks in Taskpaper script

description: Supporting subtasks in Taskpaper script


code:
import numpy as np
x=np.random.random(10)
x
np.set_printoptions(precision=3)
print(x)

rawDescription: How do I get wider numpy array print output?

description: Get wider numpy array print output


rawDescription: Sublime Text 2 shortcut for show/hide tabs


rawDescription: Convert jsonString to something parseable in Python?


code:
class Block(Sprite):
    def __init__ (self):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.rect = self.image.get_rect()

rawDescription: Am I using the constructor __init__ wrong?


code: len(net.layers[1].blobs)    # >> 2

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


code:
from collections import Iterable

def flatten(collection):
    for element in collection:
        if isinstance(element, Iterable) and not isinstance(element, str):
            for x in flatten(element):
                yield x
        else:
            yield element

rawDescription: Flatten an iterable of iterables

description: Flatten an iterable of iterables


rawDescription: Sorting cells of big numpy matrices

description: Sorting cells of big numpy matrices


code:
class SomeModel(models.Model):
   name = models.CharField(max_length=300)
   # etc, etc.

   def __unicode__(self):
       return unicode(self.name)

   def something_else(self):
       return self.another_field

rawDescription: make model __unicode__ method return to multiple colums

description: Make model __unicode__ method return to multiple colums


rawDescription: Loop for each item in a list

description: Loop for each item in a list


code:
def activeHostsQuery():
    args = ['curl', '-s', '-k', '-H', 'X-Requested-With: curl demoapp', '-u','username:password', 'https://qualysapi.qualys.com/api/2.0/fo/scan/?action=fetch&scan_ref=scan/1111111.22222&mode=brief&output_format=csv', '|', 'cut', '-d', '-f1', '|', 'sort', '|', 'uniq', '|', 'grep', '-E', '"\"[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\""', '|', 'wc', '-l']

    activeHostsNumber = subprocess.Popen(" ".join("'%s'" % a for a in args), shell=True, stdout=subprocess.PIPE).communicate()[0]
    return activeHostsNumber

rawDescription: Subprocess Python.. Stringing together commands


code:
# this will set the schema and table dynamically based on the input.
fill = {'schema_name': 'test_schema', 'stage_table': 'test_table'}
# need to replace the schemaname and stagetable from the input dict
output = [{id:100, 'query':'SELECT DISTINCT column FROM ${schema_name}.${stage_table}'}]

rawDescription: Replace multiple values in dictionary in Python 3


rawDescription: copy 2D array into 3rd dimension, N times (Python)

description: Copy 2D array into 3rd dimension, N times (Python)


rawDescription: Python dict values to list of integers

description: Python dict values to list of integers


code:
def unique_second_element(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x[1] in seen or seen_add(x[1]))]

rawDescription: delete duplicates from list of tuples

description: Delete duplicates from list of tuples


code: del audio['tag_to_delete']

rawDescription: Delete Music File Metadata Tag

description: Delete Music File Metadata Tag


rawDescription: How do I return the matched portion of a string in a Pandas Series?

description: Return the matched portion of a string in a Pandas Series


code:
configuration.update(
    timeout=60,
    host='example.com',
)

rawDescription: python dict.update vs. subscript to add a single key/value pair

description: Python dict.update vs. subscript to add a single key/value pair


rawDescription: Django - how to override form template tag in html


rawDescription: Construct DatetimeIndex if you only have year


code: re.search("[a-zA-Z]\d{2}", "S07E01 - Meet the New Boss.avi").group()

rawDescription: Find 1 letter and 2 numbers using RegEx

description: Find 1 letter and 2 numbers using RegEx


rawDescription: python list tree indexing

description: Python list tree indexing


code:
numTrees2 <- array(0, dim=c(length(farms), length(crops)), dimnames=tree_dimList);
numTrees2['Farm A','apple'] = 200;
# etc

rawDescription: How to structure an easily extensible Monte Carlo model in R

description: Structure an easily extensible Monte Carlo model in R


rawDescription: How do I convert a DataFrame from long to wide format, aggregating a column's values by counts

description: Convert a DataFrame from long to wide format, aggregating a column's values by counts


code:
def patch_request_class(app, size=64 * 1024 * 1024):
    """
    By default, Flask will accept uploads to an arbitrary size. While Werkzeug
    switches uploads from memory to a temporary file when they hit 500 KiB,
    it's still possible for someone to overload your disk space with a
    gigantic file.

    This patches the app's request class's
    `~werkzeug.BaseRequest.max_content_length` attribute so that any upload
    larger than the given size is rejected with an HTTP error.

    .. note::

       In Flask 0.6, you can do this by setting the `MAX_CONTENT_LENGTH`
       setting, without patching the request class. To emulate this behavior,
       you can pass `None` as the size (you must pass it explicitly). That is
       the best way to call this function, as it won't break the Flask 0.6
       functionality if it exists.

    .. versionchanged:: 0.1.1

    :param app: The app to patch the request class of.
    :param size: The maximum size to accept, in bytes. The default is 64 MiB.
                 If it is `None`, the app's `MAX_CONTENT_LENGTH` configuration
                 setting will be used to patch.
    """
    if size is None:
        if isinstance(app.request_class.__dict__['max_content_length'],
                      property):
            return
        size = app.config.get('MAX_CONTENT_LENGTH')
    reqclass = app.request_class
    patched = type(reqclass.__name__, (reqclass,),
                   {'max_content_length': size})
    app.request_class = patched

rawDescription: Rejecting files greater than a certain amount with Flask-Uploads?


code:
from collection import defaultdict
my_dict = defaultdict(dict)
my_dict['foo']['bar'] = some_var

rawDescription: Correct way to edit dictionary value python


code:
import Tkinter

class main:
        def __init__(self,root):
                # make a label with some space around the text
                self.lbl1 = Tkinter.Label(root,
                                          width = 16, height = 4,
                                          text = "Foobar")
                self.lbl1.pack()

                # Call a function when lbl1 is clicked
                # <Button-1> means a left mouse button click
                self.lbl1.bind("<Button-1>", self.yadda)
                self.lbl1.bind("<Enter>", self.green)
                self.lbl1.bind("<Leave>", self.red)

        def yadda(self, event):
                self.lbl1.config(text="Clicked!")

        def green(self, event):
                self.lbl1.config(bg="green")

        def red(self,event):
                self.lbl1.config(bg="red")

if __name__ == "__main__":
    root = Tkinter.Tk()
    main(root)
    root.mainloop()

rawDescription: How to disable text shaking when I click a button?

description: Disable text shaking when I click a button


rawDescription: Getting matrix from data using pandas or python


code:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
things_to_find = ['abc', 'def']
[i for i, x in enumerate(my_list) if any(thing in x for thing in things_to_find)]

rawDescription: Find list index of list items within other list items


code:
mask = df['arrival_time'] > '07:35:00'
# then work on df[mask]

rawDescription: Get nearest time value and convert format


code: re.split(r'(\d+\.?\d+)', entry)

rawDescription: trying to split a string on the space after a floatingpoint number - python positive lookbehind assertion

description: Trying to split a string on the space after a floatingpoint number - python positive lookbehind assertion


code:
class Ui_Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Ui_Form, self).__init__(parent)
        self.setObjectName(_fromUtf8("Form"))
        self.resize(761, 637)
        self.pushButton = QtGui.QPushButton()
        self.pushButton.setGeometry(QtCore.QRect(0, 550, 201, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.connect(self.pushButton, QtCore.SIGNAL("released()"), self.get_output1_statement)

        self.tableWidget = QtGui.QTableWidget()
        self.tableWidget.setGeometry(QtCore.QRect(0, 0, 741, 551))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,     QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(5)
        sizePolicy.setVerticalStretch(5)
        sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
        self.tableWidget.setSizePolicy(sizePolicy)
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(50)
        self.tableWidget.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("name"))
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.tableWidget)
        layout.addWidget(self.pushButton)
        self.setLayout(layout)
        for i in range(1, 5):
            self.tableWidget.setHorizontalHeaderItem(i,     QtGui.QTableWidgetItem("column_{0}".format(i)))
        self.retranslateUi()

    def retranslateUi(self):
        self.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "button1", None))

    def get_output1_statement(self):
        self.tableWidget.clearContents()
        self.tableWidget.setItem(0,0,QtGui.QTableWidgetItem("add some data"))

app = QtGui.QApplication(sys.argv)
form = Ui_Form()
form.show()
app.exec_()

rawDescription: pyqt and table widget clear contents

description: Pyqt and table widget clear contents


code:
from timeit import timeit

def foo():
    return 123456789 + 987654321

n = 10000000
time = timeit(foo, number=n)
print(time)

rawDescription: Python loop speed sources

description: Python loop speed sources


rawDescription: Python splitting string to find specific content


code:
def generate_paths(depth, x=0, y=0):
    if x == depth:
        yield ((x, y),)
    else:
        for path in generate_paths(depth, x+1, y):
            yield ((x, y),) + path
        for path in generate_paths(depth, x+1, y+1):
            yield ((x, y),) + path

rawDescription: Modifying a recursive function that counts no. of paths, to get sequence of all paths


code:
results = []
for i, j in itertools.product(params_list1, params_list2):
    results.append(myfunction(i, j))

rawDescription: Iterate over parameters without a loop

description: Iterate over parameters without a loop


code:
from pprint import pprint as pp
pp(ZODB.interfaces.IStorage.__iro__)
pp(Products.Archetypes.interfaces.storage.IStorage.__iro__)

rawDescription: Plone/Zope/ZODB: how to override storage method on a File field


code:
class ValidationRule(models.Model):
    other = models.ForeignKey(OtherModel)
    other_field = models.CharField(max_length=256)

rawDescription: Django Model set foreign key to a field of another Model


code:
class Porsche(object):
    def __init__(self, color):
        self.color = color

class PorscheCreator(object):
    def __init__(self):
        self._cars = []
    def create(self, *args, **kwargs):
        porsche = Porsche(*args, **kwargs)
        self._cars.append(porsche)
        return porsche
    def _get_cars(self):
        for each in self._cars:
            yield each
    cars = property(_get_cars)

creator = PorscheCreator()
myPorsche = creator.create('blue')
myPorsche2 = creator.create('red')

rawDescription: Create and retrieve object list in Python enhanced


code:
li = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
s = "a tag [[Media:]] - I want to replace all [[Media:]] tags with a names of pictures stored in a list. For example in a converted document there will be 5 [[Media:]] tags d by a tag [[Media:]] - I want to replace all [[Media:]] tags"
for item in li:
   s = s.replace("[[Media:]]", item, 1)  # max. 1 replace per call
s

rawDescription: How to change a string in a file to strings froma a list

description: Change a string in a file to strings froma a list


code:
string = ''
for element in list:
    string += element
string # return string as result

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
sql = 'SELECT neighborhoods from aprtable where risk_factor > ?'
args = [8]
cursor.execute(sql, args)
neighborhoods = cur.fetchall()

rawDescription: Dynamically fill a python dictionary

description: Dynamically fill a python dictionary


code:
def get_range(dictionary, begin, end):
  return {k: v for k, v in dictionary.items() if begin <= k <= end}

rawDescription: python: how to get a subset of dict

description: Python: how to get a subset of dict


code:
from itertools import islice
n=4
np.array(zip(*[islice(A,i,None) for i in range(n)]))

rawDescription: Consecutive, Overlapping Subsets of Array (NumPy, Python)


code: df.foo.map( clean ).astype( float )

rawDescription: Pandas clean column and apply optional multiplier


code:
from operator import itemgetter
my_getter = itemgetter("type","id")
seen_items = set()
filtered_values = [x for x in dict_list if my_getter(x) not in seen_items and not seen_items.add(my_getter(x))]
sorted(filtered_dictlist,key=my_getter,reverse=True)

rawDescription: How to sort dict list with multiple key attributes - python

description: Sort dict list with multiple key attributes - python


rawDescription: Return index of dictionary values, when dict values are a list


code:
class PersonalDataForm(forms.ModelForm):
    status = forms.ChoiceField(
        widget=forms.Select,
        choices=Status.get_status_list(),
        label='Статус',
        required=False
    )

    def __init__(self, *args, **kwargs):
        super(PersonalDataForm, self).__init__(*args, **kwargs)
        self.fields["status"].initial = self.instance.status.id # this line sets the value

    class Meta:
        model = UserProfile
        fields = ('name1', 'name2', )

rawDescription: how to fill out the form initial data?

description: Fill out the form initial data


rawDescription: Why isn't my solution to Project Euler 9 working?


code:
user = User.query(...).get()
projectKeys = user.projectKeys # you can retrieve these as required

rawDescription: Relationships in the Datastore (One-to-Many)


code:
msg ="What is your favorite flavor?"
title = "Ice Cream Survey"
choices = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"]
choice = choicebox(msg, title, choices)

rawDescription: EasyGUI- Integerbox Output

description: EasyGUI- Integerbox Output


code:
from xml.etree import ElementTree as et
t1 = et.parse('test1.xml')
t2 = et.parse('test2.xml')
t2.find('your/element').append(t1.getroot())
t2.write('test3.xml')

rawDescription: Parent the root of an etree to the element of another etree


rawDescription: Dividing in Python

description: Dividing in Python


code:
class JSONEncodedDict(TypeDecorator):
    "Represents an immutable structure as a json-encoded string."

    impl = VARCHAR

    def process_bind_param(self, value, dialect):
        if value is not None:
            value = json.dumps(value)
        return value

    def process_result_value(self, value, dialect):
        if value is not None:
            value = json.loads(value)
        return value

rawDescription: What kind of database schema would I use to store users' transaction histories?


code: soup.find(text=lambda x: x and x.startswith('Coupon Code')).next_element.text

rawDescription: Scrap Data from Website using css style Using Beautifull soup


code:
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

rawDescription: subprocess.Popen in Threads

description: Subprocess.Popen in Threads