code:
import random
import operator

ops = {
    '+':operator.add,
    '-':operator.sub
}
def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion(a):
    # you get the user input, it will be a string. eg: "5"
    guess = input("")
    # now you need to get the integer
    # the user can input everything but we cant convert everything to an integer so we use a try/except
    try:
        integer_input = int(guess)
    except ValueError:
        # if the user input was "this is a text" it would not be a valid number so the exception part is executed
        print('Please enter a valid number')
        # if the code in a function comes to a return it will end the function
        return
    if integer_input == a:
        print("Correct!")
    else:
        print("Wrong, the answer is",a)

askQuestion(generateQuestion())

rawDescription: How does my input not equal the answer?

description: How does my input not equal the answer


code:
for opt, arg in opt_list:
    if opt == '-r':
        process(arg)

rawDescription: Modify python script to run on every file in a directory


code:
class RewindableFile(file):
    def __init__(self, *args, **kwargs):
        nb_backup = kwargs.pop('nb_backup', 1)
        super(RewindableFile, self).__init__(*args, **kwargs)
        self._nb_backup = nb_backup
        self._backups = []
        self._time_anchor = 0

    def next(self):
        if self._time_anchor >= 0:
            item = super(RewindableFile, self).next()
            self._backup(item)
            return item
        else:
            item = self._forward()
            return item

    def rewind(self):
        self._time_anchor = self._time_anchor - 1
        time_bound = min(self._nb_backup, len(self._backups))
        if self._time_anchor < -time_bound:
            raise Exception('You have gone too far in history...')

    def __iter__(self):
        return self

    def _backup(self, row):
        self._backups.append(row)
        extra_items = len(self._backups) - self._nb_backup
        if extra_items > 0:
            del self._backups[0:extra_items]

    def _forward(self):
        item = self._backups[self._time_anchor]
        self._time_anchor = self._time_anchor + 1
        return item

rawDescription: Iterator using itertools is skipping a line


code:
def unique_perms(iterable):
    perm_set = set()
    permutations = [i for i in itertools.permutations(iterable) if i not in perm_set and not perm_set.add(i)]
    return [''.join(p) for p in (map(str, perm) for perm in permutations)]

rawDescription: Sorted number permutations list from numeric variables or numeric list with no duplicates


code:
subq = sess.query(Score.user_id, func.sum(Score.amount).label('score_increase')).\
                  filter(Score.created_at > someday).\
                  group_by(Score.user_id).subquery()
sess.query(User).join((subq, subq.c.user_id==User.user_id)).order_by(subq.c.score_increase)

rawDescription: SQLAlchemy filter query by related object


rawDescription: Pandas Melt on Multi-index Columns Without Manually Specifying Levels (Python 3.5.1)


code:
def MonteCarlo(T, S, x):
    for i in range(0, x):
        starterTrans(T[:], S)

rawDescription: Trouble with zip when running for loop monte carlo sim; python


code: int(s)

rawDescription: Removing decimal place from int or string in Python


rawDescription: Accessing an additional profile from templates


code:
# Last-modified: 21 Oct 2013 05:35:16 PM

import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import csv, os, scipy
import pandas
from PIL import *

data = np.loadtxt('louisianastormb.csv',dtype=np.str,delimiter=',',skiprows=1)
'''print data'''
fig = plt.figure(figsize=(12,12))

ax = fig.add_axes([0.1,0.1,0.8,0.8])

m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57.,
            projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,
            resolution ='l',area_thresh=1000.)

m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=0.5)
m.drawstates(linewidth=0.5)
# m.bluemarble(ax=ax)

# Creates parallels and meridians
m.drawparallels(np.arange(10.,35.,5.),labels=[1,0,0,1])
m.drawmeridians(np.arange(-120.,-80.,5.),labels=[1,0,0,1])
m.drawmapboundary(fill_color='aqua')
color_dict = {'AUDREY': 'red', 'ETHEL': 'white', 'BETSY': 'yellow','CAMILLE': 'blue', 'CARMEN': 'green','BABE': 'purple', }

colnames = ['Year','Name','Type','Latitude','Longitude']
data = pandas.read_csv('louisianastormb.csv', names=colnames)
names = list(data.Name)
lat = list(data.Latitude)
long = list(data.Longitude)
colorNames = list(data.Name)
#print lat
#print long
lat.pop(0)
long.pop(0)
colorNames.pop(0)
latitude= map(float, lat)
longitude = map(float, long)
# added by nye17
longitude = [-i for i in longitude]
# x, y = m(latitude,longitude)
x, y = m(longitude,latitude)
# convert to numpy arrays
x = np.atleast_1d(x)
y = np.atleast_1d(y)
colorNames = np.atleast_1d(colorNames)
#Plots points on map
for colorName in color_dict.keys():
    plt.plot(x[colorName == colorNames],y[colorName == colorNames],linestyle ='-',label=colorName,color=color_dict[colorName], linewidth=5 )
    lg = plt.legend()
    lg.get_frame().set_facecolor('grey')
plt.show()

rawDescription: Lines not plotting on graph using Python/Basemap


code:
def xy_wrapper(x, y):
    return ",".join(spreadout(['x'] * x, ['y'] * y))

rawDescription: Python - "properly" organise (spread out) x and y data


rawDescription: Converting a unicode string to see unicode code points


code:
fig, ax = plt.subplots(subplot_kw=dict(aspect='equal'))
col = plot_polygon_collection(ax, s.geometry)

rawDescription: GeoPandas plotting - any way to speed things up?


code:
def student_data(name, age, number, enrolled):
    return '[' + ','.join([name, str(age), number, str(enrolled)]) + ']'

rawDescription: Putting biographical data in order from 4 parameters using python 3.3


code: reduce(lambda x,y: x+y, [i+'='+dic[i]+'&' for i in dic])[:-1]

rawDescription: Convert Dictionary to String

description: Convert Dictionary to String


code: gb['date'].max() - gb['date'].min()

rawDescription: Calculate date variance based on common id


code:
class grid(object):

    def __init__(self, width=0, height=0):
        self._data = [None] * width * height;
        self.width = width
        self.height = height

    def __getitem__(self, pos):
        if type(pos) != tuple or len(pos) != 2:
            raise IndexError('Index must be a tuple of length 2')
        x, y = pos
        if 0 <= x < self.width and 0 <= y < self.height:
            return self._data[x + self.width * y]
        else:
            raise IndexError('Grid index out of range')

    def __setitem__(self, pos, value):
        if type(pos) != tuple or len(pos) != 2:
            raise IndexError('Index must be a tuple of length 2')
        x, y = pos
        if 0 <= x < self.width and 0 <= y < self.height:
            self._data[x + self.width * y] = value
        else:
            raise IndexError('Grid index out of range')

    @property
    def columns(self):
        return [
            [self[x, y] for x in xrange(self.width)]
            for y in xrange(self.height)
        ]

    @property
    def rows(self):
        return [
            [self[x, y] for y in xrange(self.height)]
            for x in xrange(self.width)
        ]

rawDescription: python: how to have a property and with a setter function that detects all changes that happen to the value

description: Python: how to have a property and with a setter function that detects all changes that happen to the value


code: arr = cellArray[i*ncols+j]

rawDescription: Faster way than concatenate of combining multiple cv2 images (numpy arrays) in python?


code:
new = MIMEText("This is the placeholder draft message text.")
new["Subject"] = "Example Mail"
new["To"] = "emtholin@gmail.com"
new["From"] = "emtholin@gmail.com"

raw = base64.urlsafe_b64encode(new.as_string())
message = {'message': {'raw': raw, 'threadId': "14ec598be7f25362"}}
draft = service.users().drafts().create(userId="me", body=message).execute()

rawDescription: MIME Headers Not Making it Through Gmail API


rawDescription: why is my code not writing to a new text file

description: Why is my code not writing to a new text file


code:
value = '01'
needed = 8 - len(value)
value = '0' * needed + value

rawDescription: Add leading 0's to value until length is 8 characters long


code:
class B(object):
  def __getattr__(self, method):
    return getattr(self.get_connection(key), method)

rawDescription: Python class interface design

description: Python class interface design


code:
def analyseImage(self, imPath):

    img = Image.open(imPath)
    grey = img.convert('L')

    #Switches black (0) and white (255) for label to be effective
    bw = np.asarray([255 if x < 128 else 0 for x in grey])

    lbl, nlbls = label(bw)
    labels = range(1, nlbls + 1)
    coords = [np.column_stack(np.where(lbl == k)) for k in labels]

    imfile = Image.fromarray(bw)

rawDescription: Convert a black or white only rgb array into a 1 or 0 array in Python


rawDescription: print sum of strings as float

description: Print sum of strings as float


code:
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty
from kivy.app import App
from kivy.lang import Builder

from random import random

kv = '''
<ColoredLabel>:
    background_color:
    canvas.before:
        Color:
            rgba: self.background_color
        Rectangle:
            pos: self.pos
            size: self.size
'''

Builder.load_string(kv)

class ColoredLabel(Label):
    background_color = ListProperty((0, 0, 0, 1))

class TestApp(App):
    def build(self):
        layout = BoxLayout(size_hint=(1, None), height=50)
        for label in ('a', 'b', 'c', 'd'):
            label = ColoredLabel(text=label, background_color=(random(), random(), random(), 1))
            layout.add_widget(label)

        return layout

if __name__ == '__main__':
    TestApp().run()

rawDescription: python kivy add text inside rectangle

description: Python kivy add text inside rectangle


code:
from inspect import iscode

for x in func.__code__.co_consts:
    if iscode(x):
        # Skip <setcomp>, <dictcomp>, <listcomp> or <genexp>
        if x.co_name.startswith('<') and x.co_name != '<lambda>':
            continue
        firstconst = x.co_consts[0]
        # Compute the qualified name for the current code object
        # Note that we don't know it's "type" yet
        qualname = '{func_name}.<locals>.{code_name}'.format(
                        func_name=func.__name__, code_name=x.co_name)
        if firstconst is None or firstconst != qualname:
            print(x, 'represents a function {!r}'.format(x.co_name))
        else:
            print(x, 'represents a class {!r}'.format(x.co_name))

rawDescription: Is it possible to access inner functions and classes via code objects?


code:
from StringIO import StringIO
import pandas as pd
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

f = StringIO(
"""931,Oxfordshire,9314125,123255,Larkmead School,Abingdon,125,124,20,SUPP,8
931,Oxfordshire,9314126,123256,John Mason School,Abingdon,164,164,25,6,16
931,Oxfordshire,9314127,123257,Fitzharrys School,Abingdon,150,149,9,0,11
931,Oxfordshire,9316076,123298,Our Lady's Abingdon,Abingdon,57,57,SUPP,SUPP,16
""")
df = pd.read_csv(f, names=['A','B','C','D','E','F','G', 'H','I','J', 'K'],
                 header=None)
df.replace('SUPP', 3.0, inplace=True)
df = df.convert_objects(convert_numeric=True)
df['KG'] = df['K']*1.0/df['G']
plt.plot(df['KG'], marker='o')

l, = plt.plot(df['KG'], marker='o', linestyle='', visible=False)
datacursor(l, hover=True, point_labels=df['E'], bbox=dict(fc='white'),
           formatter=lambda **kwargs: kwargs['point_label'][0], xytext=(0, 25))

plt.show()

rawDescription: How to show data labels when you mouse over data

description: Show data labels when you mouse over data


code:
# The following mimics PCA::operator() implementation from OpenCV's
# matmul.cpp() which is wrapped by Python cv2.PCACompute(). We can't
# use PCACompute() though as it discards the eigenvalues.

# Scrambled is faster for nVariables >> nObservations. Bitmask is 0 and
# therefore default / redundant, but included to abide by online docs.
covar, mean = cv2.calcCovarMatrix(PCAInput, cv2.cv.CV_COVAR_SCALE |
                                            cv2.cv.CV_COVAR_ROWS  |
                                            cv2.cv.CV_COVAR_SCRAMBLED)

eVal, eVec = cv2.eigen(covar, computeEigenvectors=True)[1:]

# Conversion + normalisation required due to 'scrambled' mode
eVec = cv2.gemm(eVec, PCAInput - mean, 1, None, 0)
# apply_along_axis() slices 1D rows, but normalize() returns 4x1 vectors
eVec = numpy.apply_along_axis(lambda n: cv2.normalize(n).flat, 1, eVec)

rawDescription: Python OpenCV PCACompute Eigenvalue

description: Python OpenCV PCACompute Eigenvalue


code:
from django.db.models.signals import post_save
from blog.models import Entry

def invalidate_blog_index(sender, **kwargs):
    expire_view_cache("blog")

post_save.connect(invalidate_portfolio_index, sender=Entry)

rawDescription: Expire a view-cache in Django?

description: Expire a view-cache in Django


rawDescription: Encrypt a string in Python. Restrict the characters used to only alphanumeric


code:
#select a parent node
mc = document.getElementsByTagName("mcdata")[0]
#append the new node as child of the parent
mc.appendChild(element)

rawDescription: Minidom element insertion into xml

description: Minidom element insertion into xml


code:
def msrange(start, stop, step=0.000001):
    while start <= stop:
        yield round(start, 6)
        if start + step > stop:
            yield stop
        start += step

rawDescription: Make a counter in Python

description: Make a counter in Python


code:
import rule
rule_list = []
for name in dir(rule):
    value = getattr(rule, name)
    if isinstance(value, type) and issubclass(value, Rule):
        rule_list.append(value())

rawDescription: Initialize all the classes in a module into nameless objects in a list


rawDescription: Python - Flatten lists of lists of two different types in one function


rawDescription: Python: Parse elapsed time (minutes : seconds) to seconds


code:
def append(self, *items):
    self.list.extend(items)

rawDescription: Python - Neaten this append/extend conditional


rawDescription: Conversion of a specific character in a string to Upper Case


code:
from itertools import groupby
y = groupby(x, itemgetter(1))

rawDescription: Sorting and Grouping Nested Lists in Python


code:
for row in world_map:
    for i, column in enumerate(row):
        if column == "i":
            if i > 0 and row[i - 1] == ' ':
                row[i - 1] = 'i'
                row[i] = ' '

rawDescription: Multidimensional array for a text based game


rawDescription: pandas: how to aggregate a subset of groupby rows into a single row?

description: Pandas: how to aggregate a subset of groupby rows into a single row


rawDescription: How to save a Data Frame column as a list? [Pandas]

description: Save a Data Frame column as a list? [Pandas]


code:
from __future__ import print_function, division
import pandas as pd
import numpy as np

# Create first dictionary
n = 5
s = np.random.randint(1,101,n)
r = np.random.rand(n)
d = {"r":r,"s":s}
df = pd.DataFrame(d)
print(df)

# Create second dictionary
n = 2
s = np.random.randint(1,101,n)
r = np.random.rand(n)
t = np.array(["a","b"])
d2 = {"r":r,"s":s,"t":t}
df2 = pd.DataFrame(d2)
print(df2)

print(pd.concat([df, df2]))

rawDescription: Concatenating dictionaries of numpy arrays (avoiding manual loops if possible)


code:
def temp_file_name(l):
    id0, id1 = l.split()[:2]
    return "tile_%s_%s.tmp" % (id0, id1)

def split_file(name):
    ofiles = {}
    try:
        with open(name) as f:
            for l in f:
                if l:
                    fn = temp_file_name(l)
                    if fn not in ofiles:
                        ofiles[fn] = open(fn, 'w')
                    ofiles[fn].write(l)
    finally:
        for of in ofiles.itervalues():
            of.close()

split_file('srcdata1.txt')

rawDescription: Efficent way to split a large text file in python


code:
schema = df1.schema
df2 = sqlContext.createDataFrame(rdd, schema=schema)

rawDescription: saving a list of rows to a Hive table in pyspark

description: Saving a list of rows to a Hive table in pyspark


code:
import numpy as np
from numpy import newaxis

def explicit(a):
    n = a.shape[0]
    m = np.zeros_like(a)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k]
    return m

def implicit(a):
    n = a.shape[0]
    m = np.zeros_like(a)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k]
    return m

a = np.random.randn(10,10)
assert np.allclose(explicit(a), implicit(a), atol=1e-10, rtol=0.)

rawDescription: Numpy matrix operations

description: Numpy matrix operations


code:
hash(list())
hash(tuple())

rawDescription: Cases where use of tuple is a must

description: Cases where use of tuple is a must


code:
locFillSemiDown = extract('img' + str(num) + '.png', 'filledsemidown.png')

for loc in locSemiDown:
   for y in range(loc[0], loc[0] + 11):
      for x in range(loc[1], loc[1] + 6):
         if(img.item(x,y,0) == 0 and img.item(x,y,1) == 0 and img.item(x,y,2) == 0):
            img.itemset((x - 5, y,0),0)
            img.itemset((x - 5, y,1),0)
            img.itemset((x - 5, y,2),0)
            img.itemset((x, y,0),0)
            img.itemset((x, y,1),255)
            img.itemset((x, y,2),255)

rawDescription: How to translate a small section of an image using OpenCV in Python

description: Translate a small section of an image using OpenCV in Python


rawDescription: How do I extract emails from dictionary in python as key value pair?

description: Extract emails from dictionary in python as key value pair


rawDescription: Get main domain url without hardcoding

description: Get main domain url without hardcoding


code:
rooms = [Room1, Room2]

# I assume you want to assign your rooms a number from 1 to ...
def get_room(id):
    return rooms[id - 1]

rawDescription: How do I define a function in python to choose a list.

description: Define a function in python to choose a list.


code:
for j in xrange(i - 1, i - 5, -1):
    l = searchlines[j]
    # see if the line is what you want

rawDescription: Searching from Bottom to Top in Python

description: Searching from Bottom to Top in Python


code: soup = BeautifulSoup(data, "lxml")

rawDescription: Finding all links matching specific URL template in an HTML page


code:
'test' or 'again'
False or 'again'
False or 0
1 or 0

rawDescription: Python operator that mimic javascript || operator


code:
from __future__ import division
from moviepy.editor import *
from moviepy.video.tools.segmenting import findObjects

def clip_typewriter(text, duration_clip, duration_effect):
    # `duration_effect` is effectively the time where the last letter appears.
    clip_text = TextClip(
                    text,
                    color='white',
                    font='Consolas',
                    fontsize=80,
                    kerning=3,
                    )
    letters = findObjects(clip_text, preview=False)
    # Select the start time in seconds for each letter found:
    n = len(letters)
    times_start = [duration_effect*i/(n-1) for i in range(n)]
    clips_letters = []
    for i, letter in enumerate(letters):
        clips_letters.append(letter
            .set_position(letter.screenpos)
            .set_start(times_start[i])
            .set_end(duration_clip)
            # Here you can add key sounds using `set_audio`.
            )
    return CompositeVideoClip(clips_letters, size=clip_text.size)

if __name__ == '__main__':
    screensize = (320, 180)
    fps = 12
    clip_1 = clip_typewriter('hello', 2, 1).set_start(1).set_position('center')
    clip_2 = clip_typewriter('world', 2, 1).set_start(4).set_position('center')
    clip_final = CompositeVideoClip([clip_1, clip_2], size=screensize)
    clip_final.write_gif('test_typewriter.gif', fps=fps)

rawDescription: Moviepy zooming effects need tweaking

description: Moviepy zooming effects need tweaking


code: plt.plot(x, A.T + np.array([[0,1,2]]), marker="o")

rawDescription: plot a curve from an array with variable x axis

description: Plot a curve from an array with variable x axis


code: sum(1 for i in range(len(L)) if L[i:i+len(s)]==s)

rawDescription: Counting sublists in a list

description: Counting sublists in a list


rawDescription: Recursively dir() a python object to find values of a certain type or with a certain value


code:
class A:
    @classmethod
    def GetMembers(cls):
        return dict(vars(cls))

class B(A):
    FOO = 'foobar'
    BAR = 'barfoo'

rawDescription: Access child's __dict__ from parent in Python?


rawDescription: iterating through a list with an if statement

description: Iterating through a list with an if statement


code:
def check(s):
    buffer = s[:5]
    i = 5
    count0, count1 = 0, 0
    while i < len(s):
        if len(buffer) == 5:
            first = buffer[0]
            if first == '0':
                count0 -= 1
            else:
                count1 -= 1
            buffer = buffer[1:]
        buffer += s[i]
        if buffer[-1] == '0':
            count0 += 1
        else:
            count1 += 1
        if count0 < 2:
            return "REJECT"
        i += 1
    if buffer.count('0') >= 2:
        return "ACCEPT"
    else:
        return "REJECT"

rawDescription: Deterministic Finite Automata for {0,1} Every5-Two0


rawDescription: Re-order three lists and maintain relation between indices?


code:
import tkinter as tk

# --- functions ---

def nxt():
    global count

    count += 1

    print("Forward:", count)

def bck():
    global count

    count -= 1

    print("Back:", count)

def run():
    global count

    count += 0.1

    print(count)

    if count < 100:
        # run again after 100ms
        root.after(100, run)

# --- main ---

root = tk.Tk()
root.geometry("100x100-0+0")
count = 0

# ntxt/bck without arguments because you need `global`
tk.Button(root, text="Next", command=nxt).pack()
tk.Button(root, text="Previous", command=bck).pack()

run() # without arguments because you need `global`

root.mainloop()

rawDescription: Is it possible to run a while loop and check for tkinter input in python 3


code:
import json
if plan:
    investments = Investment.objects.all().filter(plan = plan).order_by('maturity_date').filter(maturity_date__gte = now)
    fi_list = {}
    for i in investments:
        financial_institution = i.financial_institution
        amount = i.get_current_value(date)
        fi_list[financial_institution] = amount
    context['jsonString'] = json.dumps(fi_list)

rawDescription: loop through django list in javascript

description: Loop through django list in javascript


code:
class Matrix(object):
    def __init__(self, rows, columns, default=0):
        self.m = []
        for i in range(rows):
            self.m.append([default for j in range(columns)])

    def __getitem__(self, index):
        return self.m[index]

rawDescription: Multidimensional array in Python

description: Multidimensional array in Python


code:
import re
from urllib.request import urlopen

def get_page(url, encoding='utf-8'):
    return urlopen(url).read().decode(encoding, errors='ignore')

def get_title(txt, reg=re.compile('<title>(.*)</title>', re.IGNORECASE | re.DOTALL)):
    match = reg.search(txt)
    if match is None:
        return ''
    else:
        return match.group(1).strip()

def main():
    with open('websites.txt') as inf:
        urls = [line.strip() for line in inf]
    titles = [get_title(get_page(url)) for url in urls if url]
    print(titles)

if __name__=="__main__":
    main()

rawDescription: Crawler only loads one title

description: Crawler only loads one title


rawDescription: python - how to apply backspaces to a string

description: Python - how to apply backspaces to a string


rawDescription: I am stuck at the process of retrieving a value from a matrix


code:
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

rawDescription: Sort a list of Class Instances Python

description: Sort a list of Class Instances Python


code:
response = execute_low_level(
        'HGET', 'redis:key', 'hash:key', host='localhost', port=6379)

rawDescription: Redis in python, how do you close the connection?


code:
reobj = re.compile("(?:auto|allow-|iface)(?:(?!(?:auto|allow-|iface)).)*(?<!\s)", re.DOTALL)
result = reobj.findall(subject)
result

rawDescription: Divide string containing some keywords into list using Python


code: [[x[0] for x in y] for y in dataset]

rawDescription: Python - Merge lists in a row from a list


code:
class MySpider(scrapy.Spider):
    name = 'test'

    def start_requests(self):
        data = read_csv()
        for d in data:
            yield scrapy.Request(d.url, meta={'name': d.name})

rawDescription: give names to start_urls in scrapy

description: Give names to start_urls in scrapy


rawDescription: Python Django - Accessing foreignkey data


rawDescription: Adding Multiple Widgets to QTableWidget Cell in PyQt


code:
labels = ('', 'UARFCN', 'DL/UL', 'RSSI')
lwidth = max(len(l) for l in labels)
table = []

channel_numbers = [int(cname[7:]) if cname.startswith('channel') else None for cname in band3]
if None in channel_numbers:
    raise ValueError("channel name doesn't follow pattern")
channel_numbers.sort()

cwidth = 0
for channel_number in channel_numbers:
    channel_data = band2['channel{}'.format(channel_number)]
    entry = dict(zip(labels, (
        'Channel {}'.format(channel_number),
        channel_data[0],
        '{}/{}'.format(*channel_data[1:3]),
        channel_data[3]
    )))
    cwidth = max(cwidth, max(len(str(v)) for v in entry.values()))
    table.append(entry)

rawDescription: Formatting output python

description: Formatting output python


code: set(filter(bool, [getattr(obj, field) for field in ['field1', 'field2', 'field3']]))

rawDescription: What's the most pythonic way to write this filtered list comprehension?


rawDescription: How can I interleave or create unique permutations of two stings (without recursion)

description: Interleave or create unique permutations of two stings (without recursion)


rawDescription: How can I format a decimal to always show 2 decimal places?

description: Format a decimal to always show 2 decimal places


code:
def is_reverse(a,b):
    # copy b -- Not strictly necessary if you don't care about changing the inputs...
    c = b[:]
    c.reverse()
    for i in range(len(a)):
        if a[i] != c[i]:
            return False
    return True

rawDescription: Python reverse function

description: Python reverse function


code: sleep(uniform(0, 0.3))  # random sleep from 0 to 0.3 seconds

rawDescription: Create a typewriter-effect animation for strings in Python


code:
plt.ion()  # if you don't have this, you probably don't get anything until you don't call a blocking `plt.show`
fig, ax = plt.subplots() # create an empty plot
ax.plot([1,2,3])  # create the line
plt.draw()  # draw it (you can also use `draw_if_interactive`)
ax.set_xlim([-1,4])  #set the limits
plt.draw()  # updata the plot

rawDescription: Why do pyplot methods apply instantly and subplot axes methods do not?


code:
import time
import sys

def _print(string):
    sys.stdout.write(string)
    sys.stdout.flush()

_print('hello ')
time.sleep(2)
_print('world')

rawDescription: Printing on the same line with time.sleep()


code:
curs.execute("CREATE TABLE my_table (a_column text);")
conn.commit()

rawDescription: How to create tables in sqlite 3?

description: Create tables in sqlite 3


code:
def index(request):
    top_category_list = Category.objects.order_by('-likes')[:5]
    for category in top_category_list:
        category.url = encode_url(category.name)

    page_list = Page.objects.order_by('-views')[:5]
    cat_list = get_category_list()

    context_dict = {'categories': top_category_list,
                    'pages': page_list,
                    'cat_list': cat_list}

    context = RequestContext(request, context_dict)
    return render_to_response('rango/index.html', context=context)

rawDescription: What is the difference between context_dict and context in django, python?


code:
def wind(direction, strength):
    def _wind(particle):
        if random.randint(0,100) < strength:
            particle.x += direction
    return _wind

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
def foo(): pass

foo
lambda: None

rawDescription: Python 'Functions are objects'

description: Python 'Functions are objects'


code:
np.percentile([0, 100], 75, interpolation='linear')
np.percentile([0, 100], 75, interpolation='midpoint')

rawDescription: NumPy percentile function different from MATLAB's percentile function


code:
row = ['222','7']

struct.unpack('H', bytearray(map(int,row)))
Out[24]: (2014,)

rawDescription: (Python) Formatting strings for struct.unpack?


code: df['weekend'] = [d.weekday() >= 5 for d in df.ts]

rawDescription: Pandas group by several values in a single column


code:
import os

# make a list of all .py files in the same dir that dont start with _
__all__ = installed = [ name for (name,ext) in ( os.path.splitext(fn) for fn in os.listdir(os.path.dirname(__file__))) if ext=='.py' and not name.startswith('_') ]
for name in installed:
    # import them all
    __import__( name, globals(), locals())

rawDescription: Python: importing through function to main namespace


code:
...
for i in range(3):
    plt.scatter(x[:,i], y[:,i], c=t, cmap=colmaps[i], label=i, s=200, alpha=0.7)
plt.legend(markerscale=0.7, scatterpoints=1)
ax = plt.gca()
legend = ax.get_legend()
legend.legendHandles[0].set_color(plt.cm.Blues(.8))
legend.legendHandles[1].set_color(plt.cm.Greys(.8))
legend.legendHandles[2].set_color(plt.cm.Reds(.8))
legend.get_frame().set_alpha(0.5)
...

rawDescription: Python Scatter Plot with Colorbar and Legend Issues


code:
code = compile(stmt, '<string>', 'exec')
f_no_opt = types.FunctionType(code, globals())
t_no_opt = min(timeit.repeat(f_no_opt, repeat=10, number=10))
t_opt = min(timeit.repeat(f_opt, repeat=10, number=10))
t_opt / t_no_opt

rawDescription: Is it REALLY true that Python code runs faster in a function?


code:
try:
    from itertools import izip
except ImportError:
    izip = zip  # Python 3

origincoords = ['51.41833327,0.115963078',
                '51.34666046,-0.210947524',
                '51.39574919,-0.045778021']

for route, origincoord in izip(results, origincoords):
    route['origincoord'] = origincoord

rawDescription: Adding Labeled Values to JSON

description: Adding Labeled Values to JSON


code:
app.route('/<major>/')
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.encode('utf8', 'ignore').upper() }))
    return flask.jsonify(**course_list)

rawDescription: Flask Display Json in a Neat Way

description: Flask Display Json in a Neat Way


code: vars[:len(paths)] = paths[:len(paths)]

rawDescription: For loop variable increment (Python 2.7)


code:
form1 = {"energy_category": "electricity",
         "location": "home",
         "location-home": "shift",
         "distributor": "7",
         "postcode": "3000",
         "energy_concession": "0",
         "solar": "0",
         "disclaimer_chkbox": "disclaimer_selected",
         }

form2 = {"person-count":"1",
"room-count":"4",
"refrigerator-count":"0",
"gas-type":"3",
"pool-heating":"0",
"spaceheating[]":"none",
"spacecooling[]":"none",
"cloth-dryer":"0",
"waterheating[]":"other"}

sub_url = "https://compare.switchon.vic.gov.au/submit"

with requests.Session() as s:
    s.post(sub_url, data=form1)
    r = (s.get("https://compare.switchon.vic.gov.au/energy_questionnaire"))
    s.post("https://compare.switchon.vic.gov.au/energy_questionnaire/submit",
           data=form2)
    r = s.get("https://compare.switchon.vic.gov.au/offers")
    print(r.content)

rawDescription: Multi POST query (session mode)

description: Multi POST query (session mode)


code:
class A:
    def methodA(self):
        return 5

class B:
    def methodB(self):
        return 10

class X():
    @classmethod
    def new(cls, baseclass):
        if baseclass == A:
            return AX()
        elif baseclass == B:
            return BX()
        else: raise Exception("Not supported baseclass %s!" % str(baseclass))

    def methodX(self):
        return 42

class AX(A, X):
    pass

class BX(B, X):
    pass

rawDescription: Decide baseclass at runtime

description: Decide baseclass at runtime


code:
def indexing(A, p):
    m,n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    P = np.random.randint(0, p, (m,n))
    M, N = np.indices(A.shape)
    B[M,N,P] = A
    return B

rawDescription: Copy numpy array from one (2-D) to another (3-D)


code:
import requests
from bs4 import BeautifulSoup

s = requests.session()
r = s.get('http://bac.menara.ma/ministere/')    # go to form page, get cookies and "hidden" form field

soup = BeautifulSoup(r.content)
texte2 = soup.find('input', attrs={'name': 'texte2'})['value']

data = {'txt1': '12345678', 'texte2': texte2}
r = s.post('http://bac.menara.ma/ministere/resultat.jsp', data=data)
html = r.content
assert 'Nom ; ELOUARDI ASSIA' in html

rawDescription: Sending Post method manually using Python


code:
['Total message length is 76 bytes', 'Tue Apr 23 05:00:43 2013', 10, 1, 255, 104, 'NGIN', 'MAIN', 'Product XX finished reprocessing cdc XXXXX at jesadr 0']
['Total message length is 99 bytes', 'Tue Apr 23 05:00:43 2013', 10, 1, 255, 70, 'CSSPRD', 'liab_checker', 'Checkpointed to XXXXXXXXXXXXXXXX:XXXXXXX.XXX at jesadr 0 (serial 0)']
['Total message length is 91 bytes', 'Tue Apr 23 05:00:44 2013', 10, 0, 255, 1, 'MLIFE', 'dayend', 'dayend 1 Copyright XXXX XXXXXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXX.']

rawDescription: Python unpacking binary stream from tcp socket


code:
def isEveryNumberPositiveIn(numberList):
    foundCounterexampleYet = False
    for number in numberList:
        if number <= 0:
            foundCounterexampleYet = True
            break
    return not foundCounterexampleYet

rawDescription: Python-Recursion-New To Programming

description: Python-Recursion-New To Programming


code:
def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in range(0, len(l), n): # Use xrange if you're using Python 2 - it won't create the range list.
        yield l[i:i+n]

rawDescription: How to chunk any type of file in python and convert that file into string

description: Chunk any type of file in python and convert that file into string


rawDescription: Pass an array in python odeint

description: Pass an array in python odeint


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

from matplotlib.table import Table

def main():
    data = pandas.DataFrame(np.random.random((12,8)),
                columns=['A','B','C','D','E','F','G','H'])
    checkerboard_table(data)
    plt.show()

def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['yellow', 'white']):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    # Add cells
    for (i,j), val in np.ndenumerate(data):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]

        tb.add_cell(i, j, width, height, text=fmt.format(val),
                    loc='center', facecolor=color)

    # Row Labels...
    for i, label in enumerate(data.index):
        tb.add_cell(i, -1, width, height, text=label, loc='right',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height/2, text=label, loc='center',
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    return fig

if __name__ == '__main__':
    main()

rawDescription: custom matplotlib plot : chess board like table with colored cells

description: Custom matplotlib plot : chess board like table with colored cells


code:
request1
app/data/mydata_a.csv
request2
app/data/mydata_b.csv

rawDescription: how to loop list to pass string to function name in python

description: Loop list to pass string to function name in python


rawDescription: Can't get python to read/display my variable


code: cb = fig.colorbar(im, ticks=mticker.MultipleLocator(25))

rawDescription: How to get colorbar ticks at multiples of 1, 2, 5, 10, 20 in Matplotlib

description: Get colorbar ticks at multiples of 1, 2, 5, 10, 20 in Matplotlib


rawDescription: Python: Comparing all elements of two arrays and modifying 2nd array


code:
def run(self):
   jobs = [gevent.spawn(self.server),gevent.spawn(self.job)]
   gevent.joinall(jobs)

rawDescription: Gevent,http/cgi non blocking server

description: Gevent,http/cgi non blocking server


code:
a,b,c,d = (int(input()) for _ in range(4))
a,b,c,d

rawDescription: Entering few integers in one line

description: Entering few integers in one line


code:
v = a.view(np.float64).reshape(len(a), -1)
v.shape
v[0]
v[0, -1]

rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


code:
def lcs(a, b):
    tbl = [[0 for _ in range(len(b) + 1)] for _ in range(len(a) + 1)]
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            tbl[i + 1][j + 1] = tbl[i][j] + 1 if x == y else max(
                tbl[i + 1][j], tbl[i][j + 1])
    res = []
    i, j = len(a), len(b)
    while i and j:
        if tbl[i][j] == tbl[i - 1][j]:
            i -= 1
        elif tbl[i][j] == tbl[i][j - 1]:
            j -= 1
        else:
            res.append(a[i - 1])
            i -= 1
            j -= 1
    return res[::-1]

rawDescription: Find overlap of two lists, preserving sequence order


code:
import random

names = "Balo", "Bandugl", "Baroro", "Cag", "Charoth", "Duglinglabat", "Dulko", "Fangot"

rand_name = random.choice(names)

c1 = open("character_one.txt", "w")

c1.write(rand_name)

c1.close()

rawDescription: Cannot write random choice from list into text file


code:
l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']

output = [' '.join(w for w in a.split() if w.isupper())  for a in l]
# or:
output = [' '.join(filter(str.isupper, a.split())) for a in l]

rawDescription: how to delete lowercase words from a string in python

description: Delete lowercase words from a string in python


code:
COMPETITION_TYPE_CHOICES = [
     (1, 'Olympic Games'),
     (2, 'ISU Championships'),
     (3, 'Grand Prix Series'),
]

COMP_TYPE_CHOICES_AND_EMPTY = [('','All')] + COMPETITION_TYPE_CHOICES

rawDescription: ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong?


code:
import re
# this will match 01:23, 11:34, 12:00, etc.
timex = re.compile('(\d{2}:\d{2})[ ]?pm NST')

match = timex.search(text)
if match:
    variable = match.groups(0)

rawDescription: Python: getting finding a variable in a string


rawDescription: python list literal / initialization with dynamic number of elements

description: Python list literal / initialization with dynamic number of elements


code: {k: {i for i, j in enumerate(strlist) if j == k} for k in set(strlist)}

rawDescription: Generating an inverse index

description: Generating an inverse index


rawDescription: Python: Assigning function along with parameters to a variable


code:
data1, data2 = read_csv_file()
calculate_min(data1)

rawDescription: Creating table and calculation of min from txt file


code:
from lmfit import minimize, Parameters, Parameter, report_fit
import numpy as np

xdata = np.array([177.,180.,183.,187.,189.,190.,196.,197.,201.,202.,203.,204.,206.,218.,225.,231.,234.,
      252.,262.,266.,267.,268.,277.,286.,303.])

ydata = np.array([0.81,0.74,0.78,0.75,0.77,0.81,0.73,0.76,0.71,0.74,0.81,0.71,0.74,0.71,
      0.72,0.69,0.75,0.59,0.61,0.63,0.64,0.63,0.35,0.27,0.26])

def fit_fc(params, x, data):

    n1 = params['n1'].value
    n2 = params['n2'].value
    n3 = params['n3'].value
    n4 = params['n4'].value
    n5 = params['n5'].value

    model = n1 + (n2 * x + n3) * 1./ (1. + np.exp(n4 * (n5 - x)))

    return model - data #that's what you want to minimize

# create a set of Parameters
# 'value' is the initial condition
# 'min' and 'max' define your boundaries
params = Parameters()
params.add('n1', value= 0.2, min=0.2, max=0.8)
params.add('n2', value= -0.005, min=-0.3, max=10**(-10))
params.add('n3', value= 1.0766, min=-1000., max=1000.)
params.add('n4', value= -0.36379, min=-1000., max=1000.)
params.add('n5', value= 274.0, min=0., max=1000.)

# do fit, here with leastsq model
result = minimize(fit_fc, params, args=(xdata, ydata))

# write error report
report_fit(params)

xplot = np.linspace(min(xdata), max(xdata), 1000)
yplot = result.values['n1'] + (result.values['n2'] * xplot + result.values['n3']) * \
                              1./ (1. + np.exp(result.values['n4'] * (result.values['n5'] - xplot)))
#plot results
try:
    import pylab
    pylab.plot(xdata, ydata, 'k+')
    pylab.plot(xplot, yplot, 'r')
    pylab.show()
except:
    pass

rawDescription: Scipy's Optimize Curve Fit Limits

description: Scipy's Optimize Curve Fit Limits


code:
from Tkinter import *

master=Tk()
w = Scale(master, from_=1, to=10)
w.config(state=DISABLED,takefocus=0)
w.pack()

master.mainloop()

rawDescription: Tkinter Scale Widget State

description: Tkinter Scale Widget State


rawDescription: Average inter signout time in pandas dataframe


code:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]

ratio = float(len(a)) / float(len(a) + len(b))
c = [(not a and b.pop(0)) or (not b and a.pop(0)) or
     (random.random() < ratio and b.pop(0)) or a.pop(0)
     for _ in range(len(a) + len(b))]

rawDescription: Randomly Interleave 2 Arrays In Python

description: Randomly Interleave 2 Arrays In Python


code:
def read_images(start, end):
    for i in range(start, end):
        img = skimage.data.imread("./test/MINtruc%s.tiff" % i)
        ...

rawDescription: Python - read great number of pictures in loop


code:
class Test(object):
    def __init__(self, f):
        self.f = f

def myfunc(s):
    return 'myfunc ' + s

s = 'hello'
a = Test(lambda: myfunc(s))
s = 'bye'
print(a.f())

s = 'hello'
a = Test(lambda s=s: myfunc(s))
s = 'bye'
print(a.f())

rawDescription: python - pass a argument expecting function object

description: Python - pass a argument expecting function object


code:
from itertools import groupby
from operator import itemgetter
[(k , sum(e for _,e in v)) for k,v in groupby(zip(EmpID, TotDur), itemgetter(0))]
[(u'1046', 4.5), (u'8008', 2.7), (u'8011', 1.2)]

rawDescription: Python:List Addition

description: Python:List Addition


code:
class LabEquipmentView(BrowserView):

    def aparatus_backrefs(self):
        return back_references(self.context, 'apparatus')

rawDescription: Reverse reference RelationList in Dexterity type


code:
import os
import fnmatch
out_files = [os.path.join(root, filename)
             for root, dirs, filenames in os.walk('.')
             for filename in fnmatch.filter(filenames,
                                            '???[0-9][0-9][0-9][0-9]????*.txt')
             if 1 <= int(filename[3:7]) <= 146]

rawDescription: File name matching with fnmatch

description: File name matching with fnmatch


code:
from ast import literal_eval
modified_s = s.replace("false", "False").replace("true", "True")
modified_s = '{' + s.replace("false", "False").replace("true", "True") + '}'
literal_eval(modified_s)

rawDescription: Reading comma separated string values as dictionary elements in python


rawDescription: Trouble with a simple query PyODBC

description: Trouble with a simple query PyODBC


code:
class TooMuchBits(Exception):
    pass

def encode_str(data):
    buf = bytearray()
    for char in data:
        num = ord(char)

        # Lower case latin letters
        if num >= 97 and num <= 122:
            buf.append(num - 96)

        # Space
        elif num == 32:
            buf.append(27)

        else:
            raise TooMuchBits(char)

    return buf

def decode_str(data):
    buf = bytearray()
    for num in data:
        if num == 27:
            buf.append(' ')
        else:
            buf.append(chr(num+96))

    return bytes(buf)

rawDescription: How to encode English plain-text (consisting only of letters a-z and whitespace) using a 5-bit character encoding in Python?

description: Encode English plain-text (consisting only of letters a-z and whitespace) using a 5-bit character encoding in Python


code:
from os import listdir
from os.path import isfile, isdir, join

def walk(p):
  for item in listdir(p):
    item = join(p, item)
    if isfile(item):
      print("File: " + item)
    elif isdir(item):
      print("Dir: " + item)
      walk(item)
    else:
      print("Unknown: " + item)

path = raw_input('Enter path to search')
walk(path)

rawDescription: printing number of files per directory python

description: Printing number of files per directory python


code: datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam)

rawDescription: Get hours difference from UTC to given timezone with Python


code: re_ips = r'Failed password for (?:root|invalid user\s?.*) from ((?:\d{1,3}\.){3}\d{1,3}) '

rawDescription: Python - splitting a list then loop through to find an ip address


code: values = interpolate.griddata((Y, X), Z, (grid_x, grid_y), method='linear')

rawDescription: Plot (x, y, z) triples on 2d plane with a colormap


code: scipy.stats.chi2.ppf(0.05, 5)

rawDescription: Is there a python equivalent of R's qchisq function?


code:
import numpy as np
import datetime as dt
dates=[dt.date(2010,1,1)+dt.timedelta(days=i) for i in range(365)]
values=range(365)
data=np.array(zip(dates,values),dtype=[('dates','object'),('value','<f8')])

rawDescription: How to reference numpy array objects?

description: Reference numpy array objects


code:
image_component1 = image[:, :, 0]
image_component2 = image[:, :, 1]

result = (np.abs(image_component1) > 1.) | (np.abs(image_component2) > 1.)

rawDescription: Fast way to add calculated value element to multidimensional numpy array


rawDescription: Django activity stream filter Actions by foreignkey in target model


code:
class Cell(object):
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt

rawDescription: Python copy and concatenate linked lists, preserve order


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

driver = webdriver.Chrome()
driver.get("https://www.google.com/search?q=a1%20plumbing%20boise&gws_rd=ssl#gws_rd=ssl&lrd=0x54aeff4cb0b24461:0x23720b81e2bed658,1")

# wait for reviews to appear
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.review-snippet")))

while True:
    reviews = driver.find_elements_by_css_selector("div._ju")
    driver.execute_script("arguments[0].scrollIntoView();", reviews[-1])

rawDescription: How to scroll a div when ajax is used to load data in python selenium

description: Scroll a div when ajax is used to load data in python selenium


code:
import numpy   # there's an np variable in the code
def attempt_reshape(self, newdims, is_f_order):
    newnd = len(newdims)
    newstrides = numpy.zeros(newnd+1).tolist()  # +1 is a fudge

    self = numpy.squeeze(self)
    olddims = self.shape
    oldnd = self.ndim
    oldstrides = self.strides

    #/* oi to oj and ni to nj give the axis ranges currently worked with */

    oi,oj = 0,1
    ni,nj = 0,1
    while (ni < newnd) and (oi < oldnd):
        print(oi, ni)
        np = newdims[ni];
        op = olddims[oi];

        while (np != op):
            if (np < op):
                # /* Misses trailing 1s, these are handled later */
                np *= newdims[nj];
                nj += 1
            else:
                op *= olddims[oj];
                oj += 1

        print(ni,oi,np,op,nj,oj)

        #/* Check whether the original axes can be combined */
        for ok in range(oi, oj-1):
            if (is_f_order) :
                if (oldstrides[ok+1] != olddims[ok]*oldstrides[ok]):
                    # /* not contiguous enough */
                    return 0;
            else:
                #/* C order */
                if (oldstrides[ok] != olddims[ok+1]*oldstrides[ok+1]) :
                    #/* not contiguous enough */
                    return 0;

        # /* Calculate new strides for all axes currently worked with */
        if (is_f_order) :
            newstrides[ni] = oldstrides[oi];
            for nk in range(ni+1,nj):
                newstrides[nk] = newstrides[nk - 1]*newdims[nk - 1];
        else:
            #/* C order */
            newstrides[nj - 1] = oldstrides[oj - 1];
            #for (nk = nj - 1; nk > ni; nk--) {
            for nk in range(nj-1, ni, -1):
                newstrides[nk - 1] = newstrides[nk]*newdims[nk];
        nj += 1; ni = nj
        oj += 1; oi = oj
        print(olddims, newdims)
        print(oldstrides, newstrides)

    # * Set strides corresponding to trailing 1s of the new shape.
    if (ni >= 1) :
        print(newstrides, ni)
        last_stride = newstrides[ni - 1];
    else :
        last_stride = self.itemsize # PyArray_ITEMSIZE(self);

    if (is_f_order) :
        last_stride *= newdims[ni - 1];

    for nk in range(ni, newnd):
        newstrides[nk] = last_stride;
    return newstrides

rawDescription: When will numpy copy the array when using reshape()


rawDescription: Kivy: Update to ListView data with ListAdapter or DictAdapter does not change button text


rawDescription: One Way to Grab both text and percentages regex python distinguish numbers from letters within parantheses


code:
from py2neo import neo4j
graph = neo4j.GraphDatabaseService('http://localhost:7474/db/data/')

movies = graph.find('Movie', 'title', 'The Matrix')

rawDescription: py2neo (1.6) how to get an existing node by node property without CypherQuery

description: Py2neo (1.6) how to get an existing node by node property without CypherQuery


code:
from operator import itemgetter

fields = itemgetter(0, 1)    # zero-based field numbers of the fields of interest
with open('sample_categories.csv') as csvfile:
    next(csvfile)     # skip over header line
    for line in csvfile:
        filename, category = fields(line.split())
        with open(filename) as infile, open(category, 'a') as outfile:
            outfile.write(infile.read())

rawDescription: Joining files by corresponding columns in outside table


code:
def pick_Q(N, M, Q):
    """
    Given a deck of N cards, where M are marked,
    and Q cards are taken randomly without replacement,
    return the probability that at least one marked card is taken.
    """
    return 1. - scipy.stats.hypergeom.pmf(0, N, M, Q)

rawDescription: Drawing cards from a deck in SciPy with scipy.stats.hypergeom


code:
from collections import defaultdict
dic = defaultdict(list)
dic[1].append(1)
dic[2].append(2)
dic
dic[3]

rawDescription: python: Why listA.append('a') affects listB?

description: Python: Why listA.append('a') affects listB


code:
Process.py
import xml.etree.ElementTree as ElementTree

pythonAppConfXmlTree = ElementTree.parse('pythonAppConf.xml')
matchString = pythonAppConfXmlTree.find('./matchString').text.strip()

def match(key):
    return key == matchString

rawDescription: MapReduce how to allow Mapper to read an xml file for lookup


rawDescription: recursive way to go through a nested list and remove all of a select value

description: Recursive way to go through a nested list and remove all of a select value


code:
for value in globals().values():
    if inspect.isclass(value) and value.__module__.startswith('a.'):
        value.__module__= 'a'

rawDescription: Masquerading real module of a class

description: Masquerading real module of a class


rawDescription: python 2.7 username with minimum and max

description: Python 2.7 username with minimum and max


rawDescription: index and column for the max value in pandas dataframe

description: Index and column for the max value in pandas dataframe


code:
query1 = ("Select * from table_name WHERE id= %d;" % localid)
cursor.execute(query1)

rawDescription: format specifier for bigint of mysql-python

description: Format specifier for bigint of mysql-python


code:
from matplotlib.widgets import Cursor
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, axisbg='#FFFFCC')

x, y = 4*(np.random.rand(2, 100)-.5)
ax.plot(x, y, 'o')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)

# set useblit = True on gtkagg for enhanced performance
cursor = Cursor(ax, useblit=True, color='red', linewidth=2 )

plt.show()

rawDescription: cross hairs in python animation

description: Cross hairs in python animation


code:
class staticorinstancemethod(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner):
        return functools.partial(self.func, instance)

rawDescription: Python: avoid defining both a classmethod and an instancemethod


code: {{ review.get_index_display }}

rawDescription: Accessing list item in django template

description: Accessing list item in django template


code: df.index = df.index + 1

rawDescription: In Python pandas, start row index from 1 instead of zero without creating additional column


code: # soup = soup.find("li", {"class", "review-rating"})

rawDescription: Print all elements in <li> - BeautifulSoap


code:
import re
tuple_pattern = re.compile("\(([^,)]+),\s*([^)]+)\)")

with open(filename) as f:
    for line in f.readlines():
        print(tuple_pattern.findall(line))

rawDescription: Python: Read line by line, performing an operation at each end line


code:
b
b['image']
b['someval']
b[1]
b[b['image']=='viola.jpg']

rawDescription: Calculate mean of elements in array with same "identifier"


code:
np.random.choice(a, size=n, replace=False, p=w)
np.random.choice(a, size=n, replace=True, p=w)

rawDescription: Probabilistic selection from a numpy array


code:
mb.menu.add_command(label="Argonian", command=lambda: changename(0))
mb.menu.add_command(label="Khajiit", command=lambda: changename(1))

rawDescription: Creating a drop down menu item selection Python


code:
index = pd.MultiIndex.from_product([dates, zlevel, lat, lng])
index.names = ['dates', 'zlevel', 'lat', 'long']
df = pd.DataFrame(SM.ravel(), index=index)

rawDescription: Python Pandas Panel4D resample

description: Python Pandas Panel4D resample


code: d = dict(key1=val1, key2=val2)

rawDescription: Generate Dictionary in Python at run time


code:
from ATTEngine import ATTSpeech
a = ATTSpeech()
a.text_from_file('/Users/issackelly/Desktop/here.wav')

rawDescription: Using the AT&T Speech to Text API With Python


code:
def kurt3(X, w):
    n, m = X.shape
    K = np.zeros_like(X)
    W = 2*w + 1
    N = W*W

    Xp = np.zeros((4, W, W), dtype=X.dtype)
    xp = np.zeros((4, W), dtype=X.dtype)

    for j in xrange(m-W+1):
        # reinitialize every time we reach row 0
        Xp[0] = x1 = X[:W,j:j+W]
        Xp[1] = x2 = x1*x1
        Xp[2] = x3 = x2*x1
        Xp[3] = x4 = x2*x2

        s = Xp.sum(axis=2)       # make sure we sum along the fastest index
        S = s.sum(axis=1)        # the running sums
        s = s.T.copy()           # circular buffer of row sums

        M = S / N
        M12 = M[0]*M[0]
        V = M[1] - M12;

        # kurtosis at row 0
        K[w,w+j] = (M[3] - 4*M[0]*M[2] + 3*M12*(M12 + 2*V)) / (V*V) - 3

        for i in xrange(n-W):
            xp[0] = x1 = X[i+W,j:j+W]   # the next row
            xp[1] = x2 = x1*x1
            xp[2] = x3 = x2*x1
            xp[3] = x4 = x2*x2

            k = i % W                   # index in circular buffer
            S -= s[k]                   # remove cached contribution of old row
            s[k] = xp.sum(axis=1)       # cache new row
            S += s[k]                   # add contributions of new row

            M = S / N
            M12 = M[0]*M[0]
            V = M[1] - M12;

            # kurtosis at row != 0
            K[w+1+i,w+j] = (M[3] - 4*M[0]*M[2] + 3*M12*(M12 + 2*V)) / (V*V) - 3
    return K

rawDescription: Implementing a "Kurtosis filter" using scipys generic_filter


code:
import settings.databases as dbs_list

def post_save_function(UserModel):
     for db in dbs_list:
          UserModel.save(using=db,force_insert=True)

rawDescription: Django multidb: write to multiple databases


code:
from astropy.io import fits
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator

minorLocator = AutoMinorLocator()

def radial_profile(data, center):
    x, y = np.indices((data.shape))
    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)
    r = r.astype(np.int)

    tbin = np.bincount(r.ravel(), data.ravel())
    nr = np.bincount(r.ravel())
    radialprofile = tbin / nr
    return radialprofile

fitsFile = fits.open('testfig.fits')
img = fitsFile[0].data[0]
img[np.isnan(img)] = 0

#center = np.unravel_index(img.argmax(), img.shape)
center = (-fitsFile[0].header['LBOUND2']+1, -fitsFile[0].header['LBOUND1']+1)
rad_profile = radial_profile(img, center)

fig, ax = plt.subplots()
plt.plot(rad_profile[0:22], 'x-')

ax.xaxis.set_minor_locator(minorLocator)

plt.tick_params(which='both', width=2)
plt.tick_params(which='major', length=7)
plt.tick_params(which='minor', length=4, color='r')
plt.grid()
ax.set_ylabel(fitsFile[0].header['Label'] + " (" + fitsFile[0].header['BUNIT'] + ")")
ax.set_xlabel("Pixels")
plt.grid(which="minor")
plt.show()

rawDescription: Radial Profile from a .fits image

description: Radial Profile from a .fits image


code:
timeit.Timer(lambda: sorted(ll1+ll2)).repeat()
timeit.Timer(lambda: list(heapq.merge(ll1,ll2)) ).repeat()

rawDescription: Merge two lists with labels

description: Merge two lists with labels


code:
import ConfigParser
class MyConfigParser(ConfigParser.ConfigParser):
    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s : %s\n" % (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")
        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key != "__name__":
                    fp.write("%s : %s\n" %
                             (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")

filename='/tmp/testconfig'
with open(filename,'w') as f:
    parser=MyConfigParser()
    parser.add_section('test')
    parser.set('test','option','Spam spam spam!')
    parser.set('test','more options',"Really? I can't believe it's not butter!")
    parser.write(f)

rawDescription: Using colons in ConfigParser Python

description: Using colons in ConfigParser Python


code:
import collections
def maxIntersection(sets,n,trials = 100000):
    k = guessSize(sets,n,trials)
    filteredSets = [s for s in sets if len(s) >= k]
    counts = collections.Counter()
    for s in filteredSets:
        for x in s:
            counts[x] +=1
    t = {x for x,c in counts.items() if c >= k}
    filteredSets = [s & t for s in filteredSets if len(s & t) >= k]
    return largestIntersection(filteredSets,n)

rawDescription: Find all subsets from list of sets that appears in at least N different sets


rawDescription: Numpy matrix row stacking

description: Numpy matrix row stacking


rawDescription: Plot nodes values in Networkx (Python)?

description: Plot nodes values in Networkx (Python)


code:
def check_n(request, elements, kw):
    if not is_valid(kw['n']):
        raise ValueError('invalid url parameter')
    return elements, kw

config.add_route('numbers', 'numbers/{n:[1-9]\d*}/', pregenerator=check_n)

rawDescription: How to ensure URLs generated by Pyramid's route_url and route_path are valid?

description: Ensure URLs generated by Pyramid's route_url and route_path are valid


rawDescription: Handle 1 to n elements

description: Handle 1 to n elements


code:
import lxml.objectify as objectify
import io

content='''\
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dd="http://example.com/ns/1.0" xml:lang="en-US">
<entry>
    <content type="html">Hello World!</content>
    <dd:country_code>USA</dd:country_code>
</entry>
</feed>'''

doc=objectify.parse(io.BytesIO(content))
tree=doc.getroot()

rawDescription: Using objectify to get items with a different namespace prefix


code:
d['anotherVarName'] = 123
d.keys()

rawDescription: Equivalent of "genvarname" in Python

description: Equivalent of "genvarname" in Python


code: args = parser.parse_args(argv)

rawDescription: Python: how can I ingest arguments from JSON file?


code:
for item in itertools.islice(items, 0, stop):
    print(item)

rawDescription: How can I limit iterations of a loop in Python?

description: Limit iterations of a loop in Python


code: np.array([y[i] * id for i, id in zip(y.argmax(axis=0), idcodes)]).sum(axis=0)

rawDescription: Cascading numpy logical_and leads to memory error


code:
AAAA
AAAB
AAAC
AAAD
AAAE
AAAF
AAAG
AAAH
AAAI
AAAJ
AAAK
...
AAAX
AAAY
AAAZ

rawDescription: Iterate and match in large files in python


code: df = df.set_index('mm_id', drop=True).transpose()

rawDescription: Group by pandas

description: Group by pandas


code:
foo(bar, baz, quux1=quux1, quux2=quux2)
foo(*(bar, baz), quux1=quux1, quux2=quux2)
foo(**{'bar': bar, 'baz': baz, 'quux1': quux1, 'quux2':quux2})

rawDescription: Passing as kwargs, reading as args - a special or temporary feature?


code:
@_refactorMe
def fooB(param1, param2):
    fooB_code  #uses only param1

@_refactorMe
def fooB(param1, param2):
    fooB_code  #uses only param1

rawDescription: Code refactoring with python decorators?

description: Code refactoring with python decorators


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-y', action='store_true')
parser.parse_args('-y'.split())
parser.parse_args(''.split())

rawDescription: Python CLI - Answer yes to all user questions


code: alpha_1, alpha_2, ..., alpha_k

rawDescription: How to Normalize similarity measures from Wordnet


code:
import numpy as np # Import NumPy module

Nx = 5;
Ny = 7;

# Use np.arange that is a colon counterpart in NumPy/Python
xm_row = np.arange(-(Nx-1)/2.0+0.5,(Nx-1)/2.0-0.5+1)
ym_col = np.arange(-(Ny-1)/2.0+0.5,(Ny-1)/2.0-0.5+1)

# Use meshgrid just like in MATLAB
xm,ym = np.meshgrid(xm_row,ym_col)

rawDescription: MATLAB to Python Conversion Arrays

description: MATLAB to Python Conversion Arrays


code:
plt.triplot(points[:,0], points[:,1], 'k-', linewidth=1, alpha=0.5)

plt.imshow(new_colors, extent=(0, width, 0, height), origin='lower')
plt.show()

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


code:
row = df_result.irow(0) # an example row to pass to get_col_name
row
row.name # use to get rows of df
df.ix[row.name]
b = (df.ix[row.name] == row['value'])
b
b.argmax() # index of a True value
b.index[b.argmax()] # the index value (column name)

rawDescription: Get column name where value is something in pandas dataframe


code: [list(tup) for tup in itertools.izip_longest(*l, fillvalue="")]

rawDescription: Python: transposing uneven rows into columns


code:
xmlreplace=re.compile("((?i)[^\w\_\-\.])", re.UNICODE)
print(re.sub(xmlreplace, "-" , "regex test"))

rawDescription: Replacing a single character by a substring in python 3


code:
from pyteomics import mgf
import sys
import numpy as np

def process(mgf_file, pep_files):
    ann_arrays = {}
    for ann_spectra in pep_files:
        a = np.genfromtxt(ann_spectra, invalid_raise=False,
                          filling_values=0.0, usecols=(0,))
        b = np.delete(a, 0)
        ann_arrays[ann_spectra] = b

    with mgf.read(mgf_file) as reader:
        for spectrum in reader:
            for ann_spectra, array in ann_arrays.iteritems():
                if np.allclose(array, spectrum['m/z array']):
                # allclose may be better for floats than array_equal
                    file_name = 'DeNovo/good_training_seq/{}.mgf'.format(
                                                      ann_spectra[:-4])
                    spectrum['params']['seq'] = ann_spectra[
                                                      :ann_spectra.find('-') - 1]
                    mgf.write((spectrum,), file_name)

if __name__ == '__main__':
     pep_files = sys.argv[1:]
     mgf_file = '/DeNovo/QE_2706_229_sequest_high_conf.mgf'
     process(mgf_file, pep_files)

rawDescription: Faster way to parse file to array, compare to array in second file


code:
from ast import literal_eval

s = '(63, 166) - (576, 366)'
(x1, y1), (x2, y2) = literal_eval(s.replace('-', ','))

rawDescription: extracting data from formatted string (python)

description: Extracting data from formatted string (python)


rawDescription: urls.py and redirecting urls

description: Urls.py and redirecting urls


code: c = b.flat

rawDescription: Repeat NumPy array without replicating data?


code:
s = pd.Series(np.random.randint(2, size=2000), pd.date_range('2010-01-01', periods=2000))
counts = s.groupby([s.index.year, s.index.month]).sum()
counts

rawDescription: Trouble plotting Pandas Series

description: Trouble plotting Pandas Series


code:
1
Dominic
2
Eric
3
Joe
4
Sasha
5
Olivia
6
Callum
7
Dominic
8
Eric
9
Joe
10
Sasha
11
Olivia
12
Callum
13
Dominic
14
Eric
15
Joe
16
Sasha
17
Olivia
18
Callum

rawDescription: Read two consecutive lines from a file into a dictionary as value, key pairs


code:
import ConfigParser
configParser = ConfigParser.ConfigParser()
config.read('config.ini')

format = config.get('formatter_simple', 'format')
fileHandler.setFormatter(format)

rawDescription: Logging in Python with Config File - Using handlers defined in file through code


code:
layout = GridLayout(cols=3, spacing=10, size_hint_y=None, row_force_default=True)
layout.bind(width=lambda *_: setattr(layout, 'row_default_height',
        (layout.width - (layout.spacing[0] * (layout.cols - 1))) / layout.cols))
layout.bind(minimum_height=layout.setter('height'))

rawDescription: Making a gridview inside of an scrollview, that is the size of the screen


code: from config.settings import LOG_LEVEL

rawDescription: Toggle between production and development


code:
entry = '363898,Catullus,84-11-1 BC'.split(',')
numbers = entry[-1].split('-')
numbers = '-'.join([numbers[0].zfill(4)] + numbers[1:])
entry = entry = ','.join(entry[:-1] + [numbers])
entry

rawDescription: How to replace years without leading zeros, with leading zeros using Python re?

description: Replace years without leading zeros, with leading zeros using Python re


code:
from itertools import groupby

max_count = {}

for val, grp in groupby(test_list):
    count = sum(1 for _ in grp)
    if count > max_count.get(val, 0):
        max_count[val] = count

rawDescription: Python, work with list, find max sequnce length


code:
from __future__ import division
from math import ceil

def make_combos(max_val,target_sum,n_cells):
    combos = []
    # The highest possible value of the next cell is whatever is
    # largest of the max_val, or the target_sum minus the number
    # of remaining cells (as you can't enter 0).
    highest = min(max_val, target_sum - n_cells + 1)
    # The lowest is the lowest number you can have that will add upp to
    # target_sum if you multiply it with n_cells.
    lowest = int(ceil(target_sum/n_cells))
    for x in range(highest, lowest-1, -1):
        if n_cells == 1: # This is the last cell, no more recursion.
            combos.append((x,))
            break
        # Recurse to get the next cell:
        # Set the max to x (or we'll get duplicates like
        # (6,3,2,1) and (6,2,3,1), which is pointless.
        # Reduce the target_sum with x to keep the sum correct.
        # Reduce the number of cells with 1.
        for combo in make_combos(x, target_sum-x, n_cells-1):
            combos.append((x,)+combo)
    return combos

if __name__ == '__main__':
    import pprint
    # And by using pprint the output gets easier to read
    pprint.pprint(make_combos( 6,12,4))

rawDescription: KenKen puzzle addends: REDUX A (corrected) non-recursive algorithm


code:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

rawDescription: Plot 2-dimensional NumPy array using specific columns


code:
for z in zip_handler.infolist():
    zip_handler.extract(z, dir_name)

rawDescription: Extract files from a zip folder with sub folders into a single folder


code:
import urlparse

...

o = urlparse.urlparse(self.request.url)

rawDescription: How can I get the base URI in AppEngine?

description: Get the base URI in AppEngine


code:
next_call = time.clock() - 1  # init to a little before now
while not exit_condition:
    if test:
        otherFunction()
    if test:
        anotherFunction()
    if test and (time.clock() > next_call):
        next_call = time.clock() + MIN_TIME_DELTA
        myFunction()

rawDescription: Python - looking for a way to stop a function being called temporarily in a infinte while loop


code:
def close_database():
    proceed_to_close()

import atexit
atexit.register(close_database)

rawDescription: Method that gets called on module deletion in Python


code: ar = map(int, input().split())

rawDescription: How do i take formatted input in python?

description: Take formatted input in python


code:
M._fields
M.body
# doc would be in the first slot
M.body[0]._fields
M.body[0].value
# it contains a string object, so maybe it's the doc string
M.body[0].value._fields
M.body[0].value.s

rawDescription: Parsing Python Module Docstrings

description: Parsing Python Module Docstrings


code:
1
1 and 2
1, 2 and 3
first, second, third and forth

rawDescription: Printing a list with a grammatically correct "and"


code:
df_3
df_3['NEXT_FAILED'] = df_3.sort_values(by='DATETIME').groupby('ID')['ORDER_FAILED'].shift(-1)
df_3['SECONDS_TO_NEXT_ORDER'] = -df_3.sort_values(by='DATETIME').groupby('ID')['DATETIME'].diff(-1).dt.total_seconds()
condition = (df_3.NEXT_FAILED == True) & (df_3.ORDER_FAILED == True) & (df_3.SECONDS_TO_NEXT_ORDER <= 300)
df_3[~condition].drop(['NEXT_FAILED','SECONDS_TO_NEXT_ORDER'], axis=1)

rawDescription: GroupBy - Datetime diff() combining additional criteria


code:
chart.Parent.Height = new_height
chart.Parent.Width = new_width
chart.Parent.Top = v_position
chart.Parent.Left = h_position

rawDescription: Delete legend in an Excel plot with Python and win32com


code:
# models.py
from django.db import models

class Play(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateTimeField()

rawDescription: Passing data from Django to D3

description: Passing data from Django to D3


code: np.arange(0, 2*math.pi, math.pi/100)

rawDescription: How to Do Trigonometric Range of Floats in Python?


code:
from django.conf import urls

urlpatterns = patterns('',
    url(r'^tags_input/', include('tags_input.urls', namespace='tags_input')),
    # ... other urls ...
)

rawDescription: Using `raw_id_fields` to select related objects in the admin


code:
import json

return HttpResponse(json.dumps(option), content_type="application/json")

rawDescription: jQuery str.split does not works

description: JQuery str.split does not works


code:
class Dog(object):
    __implements__ = (IWalk, IRun, IMakeASound)

rawDescription: Why pylint keeps saying my class is R0923 - 'interface not implemented'


code: number = int(raw_input('enter a number: '))

rawDescription: Choose largest odd number python

description: Choose largest odd number python


rawDescription: Missing data, insert rows in Pandas and fill with NAN


code:
def __build_board(self):
    """ Creates tic-tac-toe board of 9 blank buttons. """
    for row_num in range(3):
        for col_num in range(3):
            def mkbutton():
                b = Button(self, text = "    ",
                           command = lambda: self.__change_button(b))
                return b
            bttn = mkbutton()
            bttn.grid(row = row_num + 1, column = col_num, sticky = W)

rawDescription: How do you use the same function as the command for multiple buttons created in a loop?

description: Use the same function as the command for multiple buttons created in a loop


code:
import numpy as np

ints32 = np.array([0, 0, 0, 0], dtype="<i4") # dtype string means little endian 4 byte ints
assert len(ints32) == 4
ints16 = ints32.view(dtype="<i2")
assert len(ints16) == 8 # 32-bit ints need half as much space as a 32-bit int
ints32[0] = 0x11223344
assert ints16[0] == 0x3344
print(ints16) # prints [13124 4386 0 0 0 0 0 0]
# Thus, showing ints16 is backed by the same memory as ints32

rawDescription: Define Ctypes array that overlaps in memory for numpy array and multiprocessing


code:
for entries in myDictionary.values():
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

rawDescription: Python 3 - Print Specific List Item from Dictionary


rawDescription: Create users on Microsoft Active Directory using a Scripting Language


code:
file_to_change = 'testingthecodexlconverter.csv'

file1 = open(file_to_change, 'r+')

with file1  as f:
    for line in f:
        line = line[2:-12]

        tokens = line.split(',')

        # if column index 3 is empty then print without formatting for
        # unnecessary space.
        if not tokens[3]:
            print(tokens[0] + ", " + tokens[2].strip(" ") + ", " + tokens[1] + ",,,")
        else:
            print(tokens[0] + "," + tokens[3] +  ", " + tokens[2].strip(" ") + ", " + tokens[1] + ",,,")

rawDescription: Rearranging sections of lines of a file using regular expressions python


code: range(1, p + 1)

rawDescription: Python; Updating several positions in a list with "for x in range"


code:
fd = os.open("filename", os.O_CREAT | os.O_WRONLY | os.O_NONBLOCK)
os.write(fd, "data")
os.close(fd)

rawDescription: How to write to a file using non blocking IO?

description: Write to a file using non blocking IO


code:
from itertools import repeat
[x for item in l for x in repeat(item, 2)]

rawDescription: Duplicate element in python list

description: Duplicate element in python list


rawDescription: Move last two episodes from directory in Python?


code: 'What is your rating for?: Bob'.split(': ')

rawDescription: Extracting multiple string values of variable length before and after a delimiter in a list


code: '[110308] Asia and India'.lstrip(" []" + string.digits)

rawDescription: Split string by regular expression

description: Split string by regular expression


code:
from datetime import date, datetime
today = date.today()
DATE_TO_COMPARE = 'May 10'
parsed = datetime.strptime(DATE_TO_COMPARE, '%b %d').date().replace(year=today.year)
parsed
parsed > today
DATE_TO_COMPARE = 'May 20'
parsed = datetime.strptime(DATE_TO_COMPARE, '%b %d').date().replace(year=today.year)
parsed
parsed > today

rawDescription: Is it possible to compare day + month(not year) against current day + month in python?


code: [x + y for x, y in zip(a_list, b_list)]

rawDescription: Remove elements from the array

description: Remove elements from the array


code:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

ab = zip(a, b)
aabb = list(ab)

print(list(aabb))

rawDescription: python list(zipobject) returns empty (list) container

description: Python list(zipobject) returns empty (list) container


code:
from itertools import chain

infiles = [open('{}_example.txt'.format(i+1), 'r') for i in xrange(100)]
with open('example.txt', 'w') as fout:
    for infile in infiles:
        fout.write(infile.read())
        fout.write('\n')

rawDescription: join plenty of files in python

description: Join plenty of files in python


rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


code:
#schema1.py
from base import LoadTender

PublicBase = declarative_base(metadata=MetaData(schema='public'))

class LoadTender(PublicBase, LoadTender):
    __tablename__ = 'load_tenders'

rawDescription: Using a different schema for the same declarative Base in sqlalchemy


code:
class App(Frame):
    def __init__(self, master, queue1):
        Frame.__init__(self, master)
        self.root = master
        self.root.title("Please, bear with me, for a moment : )")
        self.queue = queue1
        self.listbox = tk.Listbox(self.root, width=50, height=20)
        self.listbox.pack(padx=10, pady=10)
        self.running = 1
        self.periodiccall()

    def periodiccall(self):
        self.check_queue()
        if self.running:
            self._job = self.after(100, self.periodiccall)

    def check_queue(self):
        while self.queue.qsize():
            try:
                msg = self.queue.get(0)
                self.listbox.insert('end', msg)
                self.listbox.yview(END)
            except queue.Empty:
                # killing thread
                self.running = 0
                self.root.destroy()

rawDescription: Tkinter, show user new window with information about what program is doing while main window is not responding


code:
import scipy as sc
import matplotlib.pyplot as plt

plegma=1000
his_pos=[]  # list which holds the position of the particle in the grid
means=[]    #list which holds the means

for p in range(10000):
    #-------Initialize problem--------
    in_pos = int(sc.random.randint(0,len(grid),1)) #initial position of particle
    grid=sc.ones(plegma)   # grid full of available positions(ones)
    his_pos.append([])

rawDescription: python,scipy- homework -- how to keep history of the particle position in the grid

description: Python,scipy- homework -- how to keep history of the particle position in the grid


code:
class Foo(object): pass

prop.__get__(Foo(), Foo)
prop.__set__(Foo(), 'bar')
prop.__delete__(Foo())

rawDescription: How does the @property decorator work?

description: How does the @property decorator work


code: new_date_list, flipkart_sale_list, paytm_sale_list = [[x[i] for x in sorted_lists] for i in range(3)]

rawDescription: python sort lists from 1 list based on date elements

description: Python sort lists from 1 list based on date elements


rawDescription: delete items from a set while iterating over it

description: Delete items from a set while iterating over it


code:
class Car(object):
   def __init__(self):
       self.name = input("What name do you want")

first_car = Car()

rawDescription: python oop get argument from user's input

description: Python oop get argument from user's input


code:
g = resamp.groupby(level='date').apply(lambda x: x / x.sum())
g.head()

rawDescription: Grouping daily data by month in python/pandas and then normalising


rawDescription: Run multiple scrapy spiders at once using scrapyd


code:
class BaseHandler(webapp2.RequestHandler):
    ...
    def render_jinja(self, name, **data):
        data['logout_url']=users.create_logout_url(self.request.uri)
        template = jinja_environment.get_template('templates/'+name+'.html')
        self.response.out.write(template.render(data))

rawDescription: Tipfy & Jinja: Creating a logout URL for every page


code:
from collections import Counter
c = Counter(i.extension for i in file_list)
print(c)

rawDescription: Counting entries with Python dictionary datatype


code:
if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: How to perform bilinear interpolation in Python

description: Perform bilinear interpolation in Python


code: [s.strip() for s in string.splitlines() if s.strip()]

rawDescription: How to clean up this string in python with strip?

description: Clean up this string in python with strip


code: result = [item for sublist in zip(a,b) for item in sublist]

rawDescription: Pythonic way to mix two lists

description: Pythonic way to mix two lists


code: from module import function

rawDescription: How to import a single function to my main.py in python from another module?

description: Import a single function to my main.py in python from another module


code: a = Dimarray(values, [('lat', lat), ('lon', lon)])

rawDescription: How to retrieve the original order of key-word arguments passed to a function call?

description: Retrieve the original order of key-word arguments passed to a function call


code:
import ctypes
from ctypes import wintypes

netapi32 = ctypes.WinDLL('netapi32')

STYPE_DISKTREE  = 0x00000000
STYPE_PRINTQ    = 0x00000001
STYPE_DEVICE    = 0x00000002
STYPE_IPC       = 0x00000003
STYPE_MASK      = 0x000000FF
STYPE_TEMPORARY = 0x40000000
STYPE_SPECIAL   = 0x80000000

MAX_PREFERRED_LENGTH = 0xFFFFFFFF
ERROR_MORE_DATA = 0x00EA

class NET_API_BUFFER(ctypes.Structure):
    pass

class SHARE_INFO(NET_API_BUFFER):
    pass

class SHARE_INFO_1(SHARE_INFO):
    _fields_ = (('shi1_netname', wintypes.LPWSTR),
                ('shi1_type',    wintypes.DWORD),
                ('shi1_remark',  wintypes.LPWSTR))

LPNET_API_BUFFER = ctypes.POINTER(NET_API_BUFFER)

class LPSHARE_INFO(LPNET_API_BUFFER):
    _type_ = SHARE_INFO

class LPSHARE_INFO_1(LPSHARE_INFO):
    _type_ = SHARE_INFO_1

LPLPSHARE_INFO = ctypes.POINTER(LPSHARE_INFO)

if not hasattr(wintypes, 'LPBYTE'): # 2.x
    wintypes.LPBYTE = ctypes.POINTER(wintypes.BYTE)

if not hasattr(wintypes, 'LPDWORD'): # 2.x
    wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)

netapi32.NetShareEnum.argtypes = (
    wintypes.LPWSTR,  # _In_    servername
    wintypes.DWORD,   # _In_    level
    LPLPSHARE_INFO,   # _Out_   bufptr
    wintypes.DWORD,   # _In_    prefmaxlen
    wintypes.LPDWORD, # _Out_   entriesread
    wintypes.LPDWORD, # _Out_   totalentries
    wintypes.LPDWORD) # _Inout_ resume_handle

netapi32.NetApiBufferFree.argtypes = (
  LPNET_API_BUFFER,) # _In_ Buffer

def list_shares(server_name):
    pshare_info = LPSHARE_INFO_1()
    entries_read = wintypes.DWORD()
    total_entries = wintypes.DWORD()
    resume_handle = wintypes.DWORD()
    shares = []
    while True:
        result = netapi32.NetShareEnum(server_name,
                                       1,
                                       ctypes.byref(pshare_info),
                                       MAX_PREFERRED_LENGTH,
                                       ctypes.byref(entries_read),
                                       ctypes.byref(total_entries),
                                       ctypes.byref(resume_handle))
        if result and result != ERROR_MORE_DATA:
            raise ctypes.WinError(result)
        try:
            for i in range(entries_read.value):
                info = pshare_info[i]
                if info.shi1_type & STYPE_MASK == STYPE_DISKTREE:
                    shares.append(info.shi1_netname)
        finally:
            free_result = netapi32.NetApiBufferFree(pshare_info)
            if free_result:
                raise ctypes.WinError(free_result)
        if result != ERROR_MORE_DATA:
            break
    return shares

rawDescription: How to list remote windows host shared directories in Python?

description: List remote windows host shared directories in Python


code:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

rawDescription: Basic plotting of wavelet analysis output in matplotlib


rawDescription: Extracting tokens where some are optional


code:
with open('original.txt', 'r') as f, open('new.txt', 'w') as o:
    for line in f:
       if line.lstrip().split(' ')[0].isalpha() and len(line.split(' ')) > 2:
           o.write(line)

rawDescription: How to delete lines in a file in Python?

description: Delete lines in a file in Python


code:
row = "{:20}{:10}{:10}"  # build formatter string

with open('path/to/file.txt') as inf:
    lines = [line.split() for line in inf]

for fname, mname, lname, id, num in lines:
    col1 = ' '.join([fname, mname, lname])
    col2 = id
    col3 = num
    print(row.format(col1, col2, col3))

rawDescription: python-making strings line up in a column exactly n spaces from left

description: Python-making strings line up in a column exactly n spaces from left


code:
sub = Sub()
sub.load()
sup = Super()
sup.load()

rawDescription: Calling load functions in correct order from constructors


code:
from flask.ext.wtf import Form

class OrganizationForm(Form):
    organization = TextField('Organization name:')

rawDescription: pre-populate wtforms text field with values

description: Pre-populate wtforms text field with values


code:
delta = 0.001
t = np.arange(1000) * delta
a = t
b = t**2
c = np.convolve(a, b) * delta
d = t**4 / 12
plt.plot(np.arange(len(c)) * delta, c)
plt.plot(t[::50], d[::50], 'o')
plt.show()

rawDescription: python numpy.convolve to solve convolution integral with limits from 0 to t instead -t to t

description: Python numpy.convolve to solve convolution integral with limits from 0 to t instead -t to t


code:
def truncate(it, n):
    cache = [next(it) for i in range(n)]
    index = 0
    for val in it:
        yield cache[index]
        cache[index] = val
        index = (index + 1) % n

rawDescription: All but the last N elements of iterator in Python


code: httppost.addHeader("Referer", referer);

rawDescription: html form submission in python and php is simple, can a novice do it in java?

description: Html form submission in python and php is simple, can a novice do it in java


rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code:
from django.shortcuts import render

def index(request):
    if request.user.is_anonymous():
        tld_set = []
    else:
        tld_set = request.user.tld_set.all()
    context = {'tld_set': tld_set}
    return render(request, 'index.html', context)

rawDescription: Join records between two tables with Django ORM


code:
def len(obj):
    return obj.__len__()

rawDescription: Proper way to make functions extensible by the user


rawDescription: Python 2.7 - Conditional passing empty k,v pairs to dict instead of moving to next iterator


code: allHref = soup.findAll('a', { "class" : "nametessera" })

rawDescription: How to retrieve these elements from a webpage?

description: Retrieve these elements from a webpage


rawDescription: Creating time series DataFrame from event data


code:
x_copy = x[:]
removed = 0
for i, a in enumerate(x):
    if any(a.compare(b) for b in x_copy[:i-removed]):
        del x_copy[i-removed]
        removed += 1
        # a is a duplicate of an already seen item, so do something

rawDescription: Comparing list of unique objects with custom function


code:
class Photo(models.Model):
    photo = StdImageField(upload_to='photos', verbose_name=_("photo"),
                  variations={'large': (600, 600), 'thumbnail': (100, 100)},
                  render_variations=preprocess)

rawDescription: Django modify image before it's handled by stdimage


code:
timeit.timeit('all(x)','x = numpy.arange(1,100000)',number=1)
#~.0175
timeit.timeit('numpy.all(x)','x = numpy.arange(1,100000)',number=1)
#~.00043

rawDescription: Why is numpy.all much slower than python standard all?


code: subprocess.call(['cmd', 'pybot', 'AdminTests', '-v', 'LOGIN URL:_mylink', '-d', r'.\results'])

rawDescription: Using the subprocess module of Python to run a program with arguments from the command line


code:
class MyModulesHolder(dict):
    pass

modules = MyModulesHolder()
modules.__dict__ = modules
modules.update({string: getattr(MainModule, string) for string in arr})

rawDescription: How to use from import if I would like to import the module as a String?

description: Use from import if I would like to import the module as a String


rawDescription: How to shorten this if and elif code in Python

description: Shorten this if and elif code in Python


code:
# Plot scatter with mayavi
figure = mlab.figure('DensityPlot')
figure.scene.disable_render = True

pts = mlab.points3d(x, y, z, density, scale_mode='none', scale_factor=0.07)
mask = pts.glyph.mask_points
mask.maximum_number_of_points = x.size
mask.on_ratio = 1
pts.glyph.mask_input_points = True

figure.scene.disable_render = False
mlab.axes()
mlab.show()

rawDescription: How to plot a 3D density map in python with matplotlib

description: Plot a 3D density map in python with matplotlib


code:
class ModelNameAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        # Your code will follow ...

rawDescription: django admin hook run code from super

description: Django admin hook run code from super


rawDescription: Wxpython closing windows

description: Wxpython closing windows


code: import matplotlib.pyplot as plt

rawDescription: Drawing log-linear plot on a square plot area in matplotlib


code: short_sha = repo.git.rev_parse(sha, short=4)

rawDescription: get short sha of commit with gitpython

description: Get short sha of commit with gitpython


code:
lines = ['Adam Smith, Age: 24, Male, Favorite Thing: Reading page: 16',
         'Adam Smith, Age: 16, Male, Favorite Thing: Being a regex example']
# two Adams, but we only want the one who is 16 years old.
repattern = re.compile(r'''Adam \w+, Age: 16, (?:Male|Female), Favorite Thing: [^,]*?''')
for line in lines:
    if repattern.match(line):
        print(line)
        # Adam Smith, Age: 16, Male, Favorite Thing: Being a regex example
# note if we'd used re.search for Age: 16, it would have found both lines!

rawDescription: What Regex to use in this example

description: What Regex to use in this example


code:
first = True
print("[ ", end="")
for i in executor.map(fct, v1, v2):
    if first:
        first = False
    else:
        print(" , ", end="")

    print(str(i), end="")
print("]", end="")

rawDescription: How to print results of Python ThreadPoolExecutor.map immediately?

description: Print results of Python ThreadPoolExecutor.map immediately


code:
gen = (i for i,x in enumerate(stuff) if x == "baz")
list(gen)

rawDescription: Emulate index method with generator

description: Emulate index method with generator


code: import module_2

rawDescription: Clone a module and make changes to the copy


code:
with open('.tmp', 'w+') as tempf,  open('.tmp2', 'w+') as tempf2:
    proc  = subprocess.check_call(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
    tempf.seek(0)
    gitoutput = tempf.read()
print(gitoutput)

rawDescription: Python Parsing subprocess Output

description: Python Parsing subprocess Output


code:
for col in ['A', 'C', 'D']:
    df[col] = df[col].str.split(',')

df

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


rawDescription: How to strip unicode "punctuation" from Python string

description: Strip unicode "punctuation" from Python string


code: itertools.product(files, files)

rawDescription: Performing statistical test on every possible file combination in a folder


code:
import re

allStocks = ['SLTD +14% NRX +14%L MEIP -68% YU -345% RXII -13%RESN -10% LBIO -10% WHLR-10% HSIDD -339%','ENZ -17% NSLP -17% SCON -15% PKOH -15% PFIE -14% PRTS -14% NES -14% HELI']
stocksWithStuff = []

for messyDayOfStocks in allStocks:
    # Get each match
    for match in re.finditer(r"([A-Z]{2,5})\s*([-+]?\d{2,3}%)", messyDayOfStocks):
        # Format it
        stocksWithStuff.append("{0} {1}".format(match.group(1), match.group(2)))

print(stocksWithStuff)

rawDescription: Combining REs that can match multiple messy stock entries


code:
from myapp import app
app.run(debug=True)

rawDescription: Flask application logfile is not written under Apache deployment


code:
from datetime import datetime

# get depart date
depart_date = datetime.strptime(" ".join([next_available_date.text, month, year]), "%d %b %Y")
initial_return_date = depart_date.strftime("%d-%m-%Y")

return_date_input = driver.find_element_by_id("ctl00_centralDynamicContent_OutDateTextBox")
# remove readonly attribute
driver.execute_script("arguments[0].removeAttribute('readonly','readonly');", return_date_input)
return_date_input.send_keys(initial_return_date)

# open datepicker

rawDescription: Store a date selected from one datepicker into the next datepicker


rawDescription: How to check elements in two different lists in python with condition?

description: Check elements in two different lists in python with condition


code:
from collections import deque
fname = "source.txt"
last_lines = deque(maxlen = 4)
with open(fname) as f:
  text = f.read()
  for line in text.splitlines(True):
    last_lines.append(line)
#f is closed when we leave the block

outfname = fname
with open(outfname, "w") as of:
  for line in last_lines:
    of.write(line)

rawDescription: Python: splitlines() from text file then write them back to text file


code:
import datetime
d=datetime.datetime.strptime("2014-04-04 22:35:00.207", "%Y-%m-%d %H:%M:%S.%f")
print ("Date: %s" % (d.date()))
print ("Time: %s" %(d.time()))
print ("Time: %s" %(d.time().strftime("%I:%M:%S %p")))

rawDescription: django - convert mssql datetime to separate date and time

description: Django - convert mssql datetime to separate date and time


code: dict(key_value.findall('       P=0.9626;IPU=.$.+1T.+1T.+;IRF=ncRNA;IUC=UTR3;IGN=NCRNA00115;IGI=NCRNA00115,RP11-206L10.16-001;IET=0;IEO=0;IEN=.;IHT=0;IHVC=0;IHD=.;IHI=.;IHN=.;IDI=.;IDN=.;ITMAF=.;ITAMR=.;ITASN=.;ITAFR=.;ITEUR=.;ITNRB=+A;ISF=.;ISD=.;ISM=.;ISX=.;\n'))

rawDescription: Python - Extract and reformat field names from rows of data


code: host = socket.gethostbyaddr(ip)

rawDescription: How to split the return of socket,gethostbyaddr and write to file?

description: Split the return of socket,gethostbyaddr and write to file


code:
@Inspector
def exampleFunc(value=0, otherValue=3):
    pass

exampleFunc()  # 0,3
exampleFunc('foo')  # foo,3
exampleFunc(otherValue='foo', value=555) # 555,foo

rawDescription: generate a list of arguments in correct order from args and kwargs?

description: Generate a list of arguments in correct order from args and kwargs


code:
pyscaldamage =['Casing','casing','Screen','screen','water','wet','Water','Wet','bad','Bad','Speakers','speakers,','Charger','charger','Buttons','buttons']
OSissue = ['crashed','Crashed','Slow','Slow','Freezing','freezing','Rebooting','rebooting','Loading','loading','fails','Fails']
phonesetup = ['Setup','setup','Email','email','WIFI','wifi','Bluetooth','bluetooth','Contacts','contacts','Icloud','icloud']
lol = input('What is the issue? ')
# Examine all the words in the splitted string
# if you lowercase them, the user's case (ScReeN) doesn't matter
# You can also make your searchlist only lowercase with this
if any(issue.lower() in pyscaldamage for issue in lol.split()):
    print('k')
    # This is a better way to open files because you dont have to remember
    # to close them
    with open('pyscaldamage.txt', 'w') as fix:
        # do stuff
        pass # get rid of this once you have stuff in the with statement

rawDescription: Using the split function

description: Using the split function


code:
path = path.encode('ascii')
path = bytes(path, 'ascii')

rawDescription: pass a path from python 2 and 3 to c++ using ctypes

description: Pass a path from python 2 and 3 to c++ using ctypes


rawDescription: List comprehension with nested lists (sublists)


code:
rrss3 = pd.merge(jj1a, jjra, on='driver_trip', how='right').fillna(0.0)
rrss3['prob'] = np.where((rrss3['prob_x'] == 1) & (rrss3['prob_y'] == 1), 1, 0)
rrss3[['driver_trip', 'prob']].sort('driver_trip')

rawDescription: pandas merge not using sql

description: Pandas merge not using sql


rawDescription: Python: Rabin-Karp algorithm hashing

description: Python: Rabin-Karp algorithm hashing


rawDescription: How can I add textures to my bars and wedges?

description: Add textures to my bars and wedges


code:
import logging
from flask import Flask
app = Flask(__name__)  # or instead of __name__ provide the name of the module
app.logger.setLevel(logging.ERROR)

rawDescription: Change Flask logs from INFO to DEBUG

description: Change Flask logs from INFO to DEBUG


code:
def get_field_value(driver, field):
    field = field.capitalize() + ":"
    return driver.find_element_by_xpath("//div[@class = 'dc_label' and . = '%s']/following-sibling::div[@class = 'dc_value']" % field).text

rawDescription: How to use Selenium to get the housing data

description: Use Selenium to get the housing data


code: j2 = sorted(i for i in j if i >= 5)

rawDescription: Return list of items in list greater than some value


code: ['lower' if x < 3 else 'higher' for x in lst]

rawDescription: using a conditional and lambda in map

description: Using a conditional and lambda in map


code:
falls_into_a_region_of_interest = False
for x, y in ListOfRegionsOfInterest:
    if i >= x and i <= y:
        falls_into_a_region_of_interest = True
        break

rawDescription: if statement depending on list len

description: If statement depending on list len


code: dict3 = dict((dict1[key], dict2[key]) for key in dict1 if key in dict2)

rawDescription: Merge 2 dictionaries in Python

description: Merge 2 dictionaries in Python


code:
def Hello(a=None, b=None, c=None):
    return ' and '.join([n for n in ('a', 'b', 'c') if locals()[n]])

rawDescription: method overloading python

description: Method overloading python


rawDescription: Time complexity of a huge list in python 2.7