code:
session_vals = df['Session'].unique()
d = dict(zip(session_vals, np.arange(1, len(session_vals) + 1)))

df['Session'] = df['Session'].map(d)

rawDescription: reindex (remapping) column's value

description: Reindex (remapping) column's value


code:
def make_b( a, seed ):
    yield seed
    for a,b in zip( a[:-1], a[1:] ):
        seed= someFunction( seed, a, b )
        yield seed

rawDescription: how to rewrite this loop in a more efficient way in python

description: Rewrite this loop in a more efficient way in python


rawDescription: Jinja2 dynamic variable building

description: Jinja2 dynamic variable building


rawDescription: Why do the following codes take different times for execution (What is actually going on inside numpy arrays)?


code: os.system("raspivid -t 20000 /home/pi/test.h264 &")

rawDescription: Synchronize a Linux system command and a while-loop in Python


code: yield old, new

rawDescription: Bigram function using python

description: Bigram function using python


code:
df1 = pd.get_dummies(df, dummy_na=True)
df1
df1.loc[df1.v1_nan == 1, ["v1_A", "v1_B"]] = np.nan
del df1["v1_nan"]
df1

rawDescription: Retaining NaN values after get_dummies in Pandas


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    ...,
    'myapp.menu_context_processor.menu'
)

rawDescription: Site menu using django

description: Site menu using django


code:
import re
text = "This is a text; this is another   text.,."
re.split('([\s.,;()]+)', text)

rawDescription: Split strings on whitespaces, but do not remove them


code:
pos_t=st.find("t")
"".join(e if (e != 'e' or i > pos_t) else 'i' for i,e in enumerate(st))

rawDescription: Replace character in a string conditional on appearance of another character in the string Python


code:
defaults = [2, 5, 9]
np.hstack((np.zeros((x,1)), np.tile(defaults, (x,y))))

rawDescription: How to initialize NumPy array with different default value for each column?

description: Initialize NumPy array with different default value for each column


code: [x for x,y in groupby(L) if len(list(y))<2]

rawDescription: Removing elements that have consecutive dupes


code:
result = []
for tup in zip(a, b):
    for x in tup:
        result.append(x)

rawDescription: Python two list lists shuffle

description: Python two list lists shuffle


rawDescription: Can't figure out this simple recursion with Python


code:
#!/usr/local/opt/python/bin/python2.7

# -*- coding: utf-8 -*-
import re
import sys

from IPython import start_ipython

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(start_ipython())

rawDescription: iPython installed but not found

description: IPython installed but not found


code:
i = '"string"'  # simulated input
t = '"this is a very long string with whitespace"'  # another simulated input
scanner.scan(i)
scanner.scan(t)

rawDescription: Using RE scanner to find material in double quotes?


rawDescription: Python: combine list with lists of list while preserving lists elements


code:
keyword_dictionary = {
    'Animal' : {'animal', 'dog', 'cat'},
    'Art' : {'art', 'sculpture', 'fearns'},
    'Buildings' : {'building', 'architecture', 'gothic', 'skyscraper'},
    'Vehicle' : {'car','formula','f-1','f1','f 1','f one','f-one','moped','mo ped','mo-ped','scooter'},
    'Person' : {'person','dress','shirt','woman','man','attractive','adult','smiling','sleeveless','halter','spectacles','button','bodycon'},
    'People' : {'people','women','men','attractive','adults','smiling','group','two','three','four','five','six','seven','eight','nine','ten','2','3','4','5','6','7','8','9','10'},
    'Food' : {'food','plate','chicken','steak','pizza','pasta','meal','asian','beef','cake','candy','food pyramid','spaghetti','curry','lamb','sushi','meatballs','biscuit','apples','meat','mushroom','jelly', 'sorbet','nacho','burrito','taco','cheese'},
    'Glass' : {'glass','drink','container','glasses','cup'},
    'Bottle' : {'bottle','drink'},
    'Signage' : {'sign','martini','ad','advert','card','bottles','logo','mat','chalkboard','blackboard'},
    'Slogan' : {'Luck is overrated'},
    'DJ' : {'dj','disc','jockey','mixer','instrument','turntable'},
    'Party' : {'party'}
 }

def matcher(keywords, searcher):
    for word in searcher:
        for key, words in keywords.items():
            if word in words:
                print(key)
                break

with open("test.txt") as termsdesk:
    for line in termsdesk:
        matcher(keyword_dictionary, line.split())

rawDescription: Python - reading complex lines of text into dictionary


code:
import timeit

def algorithm():
    x=1.0
    while 1+x/2 != 1.0:
        x/=2.0
    #print x  # disabled so i don't get 100,000 prints

timeit.timeit(algorithm, number=100000) # 100,000 times!

rawDescription: Why an iterative algorithm for finding epsilon in python takes virtually roughly 0 seconds?


code:
for year,r in results:
  if int(year) in valid:
   print('In {0} the name {1} occured the most ({2} times)'.format(year, r[0][0], r[0][1]))

rawDescription: Reading text file and returning most popular name for that year


rawDescription: numpy vstack vs. column_stack

description: Numpy vstack vs. column_stack


rawDescription: expand within notebook does not work as expected

description: Expand within notebook does not work as expected


code: printa(*cord())

rawDescription: Passing functions which have multiple return values as arguments in Python


code: cast(v.vendorName, c_char_p).value[7]

rawDescription: Print a C string in Python

description: Print a C string in Python


code:
df = pd.DataFrame([[1,2,3,4],[1,2,3,4]]).set_index(0)
df
df.index.name=None
df

rawDescription: Pandas adding extra row to DataFrame when assigning index


rawDescription: Python: Determine whether list of lists contains a defined sequence


code:
def prepped_compare2(obj1, obj2, li_field):

    for field in li_field:
        if getattr(obj1, field) != getattr(obj2, field):
            return False
    return True

starttime = time.time()
li_field = [f for f in vars(obj1) if f.startswith('field')]
for i in range(100000):
    prepped_compare2(obj1, obj2, li_field)
print('prepped2 compare runtime: {:.3f} s'.format(time.time() - starttime))

rawDescription: Selective comparison of class objects

description: Selective comparison of class objects


code:
PlayUp = PhotoImage(file=currentdir+r'\Up_image.gif')
PlayDown = PhotoImage(file=currentdir+r'\Down_image.gif')

rawDescription: Python Change Button Image and change it back


code:
def movingAverages(seq, k):
    circle = seq + seq[:k]
    for j in range(len(seq)):
        yield sum(circle[j:j+k])/k

rawDescription: Circular moving average on a tuple in Python


rawDescription: Weird behavior specifying date limits with pandas


code: data2 = data.view('float32')

rawDescription: Making my NumPy array shared across processes


code:
import datetime as dt
import pandas as pd
parse = lambda x: dt.datetime.strptime(x, '%Y%m%d %H%M%S %f')
df = pd.read_csv('test.csv', parse_dates=[['date', 'time', 'milliseconds']],
                 index_col=0, date_parser=parse)

rawDescription: Getting a time index in python for pandas dataframe


code:
Output
Reserved = 2
CPU = 1
Flag = 1
VQI = 12
Group_ID = 16
DI = 2
DE = 1
ACOSS = 5
RGH = 8

rawDescription: How do I get Python XML to stop having wasted Child Nodes

description: Get Python XML to stop having wasted Child Nodes


code:
a=1
while a==1:
    try:
        bass = input('Enter Bass Level: ')
        print('Bass level is at ' + str(bass))
        if bass >=4:
            print("Bass is crisp")
        elif bass < 4:
            print('Bass is not so crisp')
        a=0
    except ValueError:
        print('Invalid Entry')
        a=1

rawDescription: Python 3.4 User Input

description: Python 3.4 User Input


code: [[[i+b[k],j+b[k]] for (i,j) in a[k]] for k in range(len(a))]

rawDescription: Adding value to range of values in a list?


code:
conditions = [ # blink if player is outside screen
              (lambda: not s_r.contains(player), pygame.event.Event(E_OUTSIDE)),
               # if mouse if over player then grow and shrink player
              (lambda: player.collidepoint(pygame.mouse.get_pos()), pygame.event.Event(E_MOUSE))]

while True:
    # generate events from conditions
    map(pygame.event.post, [e for (c, e) in conditions if c()])

    for event in pygame.event.get():
       ...

rawDescription: PyGame Custom Event

description: PyGame Custom Event


code:
zlib.compress("Hello, wørld".encode("utf-16"))
zlib.compress("Hello, wørld".encode("utf-8"))

rawDescription: compress a string in python 3?

description: Compress a string in python 3


code:
if 'VGA' in line:
    return line.split('VGA')[1]

rawDescription: Command output parsing in Python2.7

description: Command output parsing in Python2.7


code: np.diff(image, axis=1)

rawDescription: Python - differentiating an image in the X direction


code:
r = random.choice(secret_encoding)
...
_a = globals()[r](a)

rawDescription: Understanding a custom encryption method in python


code:
setup(
    # Other setup args here...

    data_files = (
                    # Use the function above...
                    generate_data_files(GTK_RUNTIME_DIR, GTK_THEME_DEFAULT) +
                    generate_data_files(GTK_RUNTIME_DIR, GTK_THEME_WINDOWS) +
                    generate_data_files(GTK_RUNTIME_DIR, GTK_ICONS) +

                    # ...or include single files manually
                    [
                        (GTK_GTKRC_DIR, [
                            os.path.join(GTK_RUNTIME_DIR,
                                GTK_GTKRC_DIR,
                                GTK_GTKRC)
                        ]),

                        (GTK_WIMP_DIR, [
                            os.path.join(
                                GTK_RUNTIME_DIR,
                                GTK_WIMP_DIR,
                                GTK_WIMP_DLL)
                        ])
                    ]
                )
)

rawDescription: Bundling GTK resources with py2exe

description: Bundling GTK resources with py2exe


code:
import os
dirs = [d for d in os.listdir('.') if os.path.isdir(d)]
sorted(dirs, key=lambda x: os.path.getctime(x), reverse=True)[:1]

rawDescription: How to get the newest directory in Python

description: Get the newest directory in Python


code:
app = QtGui.QApplication(sys.argv)
browser = Browser(queue_in, queue_out)
app.exec_()

rawDescription: PySide browser in a separate process

description: PySide browser in a separate process


code:
mylist = [1,2,3,4,5]
len(mylist)

rawDescription: Getting the length of an array in Python


code:
CHUNK_SIZE = 50

def fetch_parallel(job_list):
    results = []
    queue = Queue.Queue()
    while job_list:
        threads = [threading.Thread(target=avhash, args=(job, queue))
                      for job in job_list[:CHUNK_SIZE]]
        job_list = job_list[CHUNK_SIZE:]
        for thread in threads:
            thread.daemon = True
            thread.start()
        for thread in threads:
            thread.join()
        results.extend(queue.get() for _ in threads)
    return results

rawDescription: Thread/Queue hanging issue

description: Thread/Queue hanging issue


code: s = d.read()

rawDescription: Tab separated data python

description: Tab separated data python


rawDescription: Handling attributes of a class within a numpy array


code:
[id(e) for e in grid]
grid[0][0]=False
[id(e) for e in grid]
grid

rawDescription: Modify element [0][0] in a Python 2D list


NAME Surname

kind: drive#permission

role: owner

type: user

rawDescription: Google Drive Permissions API – security settings


rawDescription: Numpy dot in a for loop

description: Numpy dot in a for loop


code:
import csv

with open(filename, 'wb') as f:
    writer = csv.writer(f)
    for (k1, k2), (v1, v2) in sorted(some_dict.iteritems(), key=lambda i: i[1][0]):
        writer.writerow([k1, k2, v1, v2])

rawDescription: Sort a dictionary of arrays in python with a tuple as the key


code:
def paw_pattern_problems(paw_labels, dx, dy):
    """Check whether or not the label sequence "paw_labels" conforms to our
    expected spatial pattern of paw impacts. "paw_labels" should be a sequence
    of the strings: "LH", "RH", "LF", "RF" corresponding to the different paws"""
    # Check for problems... (This could be written a _lot_ more cleanly...)
    problems = False
    last = paw_labels[0]
    for paw, dy, dx in zip(paw_labels[1:], dy, dx):
        # Going from a left paw to a right, dy should be negative
        if last.startswith('L') and paw.startswith('R') and (dy > 0):
            problems = True
            break
        # Going from a right paw to a left, dy should be positive
        if last.startswith('R') and paw.startswith('L') and (dy < 0):
            problems = True
            break
        # Going from a front paw to a hind paw, dx should be negative
        if last.endswith('F') and paw.endswith('H') and (dx > 0):
            problems = True
            break
        # Going from a hind paw to a front paw, dx should be positive
        if last.endswith('H') and paw.endswith('F') and (dx < 0):
            problems = True
            break
        last = paw
    return problems

rawDescription: How to sort my paws?

description: Sort my paws


code:
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relation
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('sqlite:///')
Session = sessionmaker(bind=engine)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    addresses = relation("Address", backref="user")

class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    email = Column(String(50))
    user_id = Column(Integer, ForeignKey("users.id"))

Base.metadata.create_all(engine)

rawDescription: SQLAlchemy declarative property from join (single attribute, not whole object)


code:
e = ["2311","1441","31","233122"]
r = ["asasa2311","dadewr1441","app"]
[eelem for relem in r for eelem in e if eelem in relem]

rawDescription: Cross Matching in python

description: Cross Matching in python


code:
language_mapping = {'en': 'en', 'ger': 'de'}
myLang = language_mapping.get(lang, 'fa')

rawDescription: Using conditions in variable assignments in Python


code:
seen = set()
drepr = lambda d: tuple(sorted(d.items()))

output = {}
for el in input:
    if drepr(el) not in seen:
        output.setdefault(el['id'], []).append(el)
        seen.add(drepr(el))

rawDescription: Fastest way to create dict from a large list of Dict


code: subkey = int(hexkey[pos:pos+8], 16)

rawDescription: Refactor this block cipher keying function


code: grouped = [grouped['pid'] for pid in sorted(grouped)]

rawDescription: Group list of dictionaries to list of list of dictionaries with same property value


code:
import cliask

yn = cliask.agree('Yes or no? ',
                  default='y')
animal = cliask.ask('Cow or cat? ',
                    validator=('cow', 'cat'),
                    invalid_response='You must say cow or cat')

print(yn)
print(animal)

rawDescription: Is there a Python equivalent to HighLine?


code:
import random

iPhone = 'Original 3G 3GS 4 4S 5 5C 5S 6 6Plus'.split()

z = 0
while z < 3:
    x = random.randint(0,9)
    print (iPhone[x])
    z += 1  # Remember to increment z so the while loop exits when it should

rawDescription: List index out of range and random number to choose an item in list


rawDescription: Pandas and dataframe: How to transform a ordinal variable in a binary variable?


code:
def first_scalar(foo):
    result = None
    while True:
        try:
            result = next(iter(foo))
        except TypeError:
            return result

rawDescription: Python: Get first element of list potentially containing sublists


code:
import numpy as np

data = np.array([0.2, 6.4, 3.0, 1.6])
bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
cats = np.digitize(data, bins)
cats
# array([1, 4, 3, 2])

rawDescription: Python identify in which interval the numbers are


rawDescription: Removing spaces from astring within a CSV in python


rawDescription: easy way of getting number of bits from a numpy type?

description: Easy way of getting number of bits from a numpy type


rawDescription: Convert data based on multiple dictionaries


code:
class Base(object):
    def __init__(self):
        print("My type is", Base)

class Derived(Base):
    def __init__(self):
        super().__init__()
        print("My type is", Derived)

d = Derived()

rawDescription: Determine the defining class from within a method


rawDescription: Using python to extract a few lines from a data file


code:
from __future__ import division
from sympy import *
x = symbols('x')
w = symbols('w', cls=Function)
a,b,E,J =  symbols('a b E J')
equ = E*J*diff(w(x),x,4) - a*x -b - w(x)
dsolve(equ, w(x))
# This generates a function that is too generic and too big to copy-paste
# Let's make some assumptions
J = Symbol('J', real=True, positive=True)
E = Symbol('E', real=True, positive=True)
equ = E*J*diff(w(x),x,4) - a*x -b - w(x)
dsolve(equ, w(x))

rawDescription: Numeric solve transcendental equation in python or Matlab


code:
line = 'unicode 0, <runtime error >,0'
re.findall(r'<.+?>', line)

rawDescription: How to match this kind of string in Python use re?

description: Match this kind of string in Python use re


rawDescription: Splitting a list of sequences into two lists efficiently


rawDescription: xpath selecting elements and iterating over the tag

description: Xpath selecting elements and iterating over the tag


rawDescription: comparing numpy structured arrays

description: Comparing numpy structured arrays


code: print >> outputfile, value1, "NOMINAL" if type(value1) is str else "NUMERIC"

rawDescription: Pythonic way to make string dependend on type of variable


code: ['dig', '+short', x]

rawDescription: Python- best way to pass variable arguments to subprocess.call


code: drops = [Droplet(*parseFromFile(line)) for line in file]

rawDescription: Dynamic object instantiation in Python

description: Dynamic object instantiation in Python


code:
def qux(self):
    return self.bar() + 3

rawDescription: How can I make a method takes the value(s) from another method from within the same class in Python

description: Make a method takes the value(s) from another method from within the same class in Python


code:
import android

droid = android.Android()

activity = 'com.twofortyfouram.locale.intent.action.FIRE_SETTING'
extras = {}
extras['de.devmil.minimaltext.locale.extras.VAR_NAME'] = 'Your Variable name'
extras['de.devmil.minimaltext.locale.extras.VAR_TEXT'] = 'Your Variable content'

packagename =  'de.devmil.minimaltext'
classname = 'de.devmil.minimaltext.locale.LocaleFireReceiver'

intent = droid.makeIntent(activity, None, None, extras, None, packagename, classname).result

droid.sendBroadcastIntent(intent)

rawDescription: Show data on android desktop with SL4A Python (example)


code:
unq, unq_inv = np.unique(a, return_inverse=True)
f_unq = unq**2
f_a = f_unq[unq_inv]
a
f_a

rawDescription: How to get lists of indices to unique values efficiently?

description: Get lists of indices to unique values efficiently


code:
wordsindict = ['somewhere', 'over', 'rainbow', 'bluebirds', 'fly', 'birds', 'fly', 'over', 'rainbow', 'why', 'why', 'double', 'time', 'population', 'long', 'takes', 'population', 'double', 'size', 'whoa', 'full', 'rainbow', 'way', 'double', 'rainbow', 'double', 'rainbow', 'way']

list2 = [['somewhere', 'over', 'rainbow', 'bluebirds', 'fly', 'birds', 'fly', 'over', 'rainbow', 'why', 'why'], ['double', 'time', 'population', 'long', 'takes', 'population', 'double', 'size'], ['whoa', 'full', 'rainbow', 'way', 'double', 'rainbow', 'double', 'rainbow', 'way']]
d = {}
for word in set(wordsindict):
    d[word] = []
    for i, l in enumerate(list2):
        for wordy_word in l:
            if wordy_word == word:
                d[word].append(i)
print(d)

rawDescription: comparing lists and storing index values if lists match

description: Comparing lists and storing index values if lists match


code:
#
# To activate this environment, use:
# > activate py3k
#

rawDescription: What is the correct syntax for launching ipython qtconsole/notebook for python version=x


rawDescription: Dynamic function docstring

description: Dynamic function docstring


code: re.search(r'#(\d+)', 'This is a generated number #123 which is an integer.').group(1)

rawDescription: Python and Regex - extracting a number from a string


rawDescription: Python: xticks and labels stuck on one side of the subplot


code:
import pandas as pd
from patsy import dmatrices

dat = pd.read_csv('wow.csv')
y, X = dmatrices('levels ~ week + character + guild')

rawDescription: OLS Regression: Scikit vs. Statsmodels?

description: OLS Regression: Scikit vs. Statsmodels


code:
orig_defaults = foo.func_defaults
foo.func_defaults = (10,)
assert foo() == 10
foo.func_defaults = orig_defaults
assert foo() == 5

rawDescription: Change default arguments of function in python


code:
class BuyFilterView(PaginationMixin, ListView):
    template_name = "buy_filter.html"
    paginate_by = 50

    def get_queryset(self):
        return ProductFilter(self.request.GET, queryset=Goods.objects.exclude(price=''))

    def get_context_data(self, **kwargs):
        context = super(BuyFilterView, self).get_context_data(**kwargs)
        context['cart'] = Cart.objects.get(user=self.request.user)
        return context

rawDescription: How to pass queryset with exclude param in django-filter extension

description: Pass queryset with exclude param in django-filter extension


rawDescription: How to find number of users, number of users with a profile object, and monthly logins in Django

description: Find number of users, number of users with a profile object, and monthly logins in Django


code: np.where(np.any(cc, 0), a, c)

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


code:
check_events()
update_snake()
collision_check()
draw_things()
clock.tick(FPS)

rawDescription: Why wont collide_rect work in this scenario? The game keeps printing "Collided!" even when the two sprites aren't touching?


code: collections.Counter(tuple(i) for i in [[1,2], [1,2], [3,4]])

rawDescription: How do I make a list a key value in a dictionary?

description: Make a list a key value in a dictionary


code:
cl = (ser.notnull() & (ser != 0))
labels = ((cl != cl.shift()) & cl).cumsum() * cl + (ser * 0)
labels

rawDescription: Pandas Label Sequences of 1 in a 0-1 valued Series


code:
import select
q = select.poll()
q.register(stdout,select.POLLIN)

rawDescription: Python: How to peek into a pty object to avoid blocking?


code:
kmerlen = 30
kmerstep = 1     # new variable

# ...
for i in xrange(len(seq1) - kmerlen + 1):
    key = seq1[i:i+kmerlen:kmerstep]    # add step to slice
    lookup[key].append(i)

# ...
for i in xrange(len(seq2) - kmerlen + 1):
    key = seq2[i:i+kmerlen:kmerstep]    # here too

rawDescription: Hashing sequences with constraints

description: Hashing sequences with constraints


code:
import timeit
import sys
import re

r = re.compile(b'ABC')
s = b"Can you count to three or sing 'ABC?'" * 1024

PYTHON_3 = sys.version_info >= (3, )
if len(sys.argv) > 1: # standard slicing
    print(timeit.timeit("r.search(s[10:])", setup='from __main__ import r, s'))
elif PYTHON_3: # memoryview in Python 3
    print(timeit.timeit("r.search(s[10:])", setup='from __main__ import r, s; s = memoryview(s)'))
else: # buffer in Python 2
    print(timeit.timeit("r.search(buffer(s, 10))", setup='from __main__ import r, s'))

rawDescription: Is there a way to use a memoryview with regexes in Python 2?


code: pool.map_async(g, range(2), 1) # if specified to have two processes before

rawDescription: Initializing and destorying Python multiprocessing workers


code:
from collections import defaultdict

mylist = [('country', 'NN'), ('shoot', 'NN-DT-PPL'), ... ]
res = defaultdict(list)

for item, tags in mylist:
    res[tags.count('-') + 1].append((item, tags))

rawDescription: Append list items by number of hyphens available


code: dict_compute = {tenants:[{single_ins:ck.reports.get_total(tenant_id=tenants, service='compute', instance_id=single_ins)} for single_ins in instances] for tenants,instances in tenant_id_dict.iteritems()}

rawDescription: Dictionary and list value processing

description: Dictionary and list value processing


code:
import string
_trans = None
def phred64ToStdqual4(qualin):
    global _trans
    if not _trans:
        _trans = string.maketrans(''.join(chr(i) for i in range(31, 127)), ''.join(chr(i) for i in range(127 - 31)))
    return qualin.translate(_trans)

rawDescription: Convert ascii encoding to int and back again in python (quickly)


code:
with open('your_file.txt', 'r') as f:
    s = f.read()

tree = ET.fromstring('<root>' + s + '</root>')
...

rawDescription: Creating a python table from key/counters text file


rawDescription: Print a dictionary of lists vertically

description: Print a dictionary of lists vertically


code:
for r in A:  # r = [1, 2, 3]
    for t in r:  # t = 1 (on first iteration)
        print(t,)
    print

rawDescription: Print a nested list line by line - Python


rawDescription: How do I get the recent json object based on datetime value?

description: Get the recent json object based on datetime value


code:
a = '%he#llo, my website is: http://www.url.com/abcdef123'
re.findall('(http://\S+|\S*[^\w\s]\S*)',a)

rawDescription: Regex. Match words that contain special characters or 'http://'


code:
def get_attrs_dict(self):
    return self.__dict__

rawDescription: returning a list from an objects elements?

description: Returning a list from an objects elements


code:
def single_shot_connect(signal, slot):
    def disconnect(*args, **kwargs):
        signal.disconnect(slot)
        signal.disconnect(disconnect)
    signal.connect(slot)
    signal.connect(disconnect)

rawDescription: How to make generic PySide single shot slot

description: Make generic PySide single shot slot


code:
import pysal
coords = [(0,0), (10,0), (10,10), (0,10), (0,0)]
pts = map(pysal.cg.Point, coords)
polygon = pysal.cg.Polygon(pts)
shp = pysal.open('myPolygon.shp','w')
shp.write(polygon)
shp.close()

rawDescription: Where to begin? Using x,y,z data to display a building lot


rawDescription: Not sure how to XPath to specific website element


code: colormap = np.array(['r', 'g', 'b'])

rawDescription: Using multiple colors in matplotlib plot


code:
from collections import defaultdict

data = defaultdict(dict)

data[year][month] = [day]

rawDescription: Which data structure to use in Python to store data like this?


code:
for i in range(n):
    [x, y, z][i % 3]()

rawDescription: Inside a range how can I internally count up to 3?


code:
def other_function(parent, *args, **kwargs):
    return etree.SubElement(parent, 'thing', attrib=kwargs)

rawDescription: Parsing **kwargs

description: Parsing **kwargs


rawDescription: How do I remove hex values in a python string with regular expressions?

description: Remove hex values in a python string with regular expressions


rawDescription: Pick x (f.e. first) characters from a List entry then pick random entries from the new list


code:
# foo.py
import settings
bar = settings.current_settings.bar
settings.current_settings.foo = True

rawDescription: how to override default values needed by function in module?

description: Override default values needed by function in module


code: result = sum(ar.astype('bool') for ar in list_of_arrays)

rawDescription: Numpy: find occurrences for non-zero values, grouped by index


code:
import re
re.split(r'(\w+)', '(a1 b2 c3)')

rawDescription: How to split a string by multiple characters and keep the split chars in return value?

description: Split a string by multiple characters and keep the split chars in return value


code: my_list[:] = [m for m in my_list if 'blahblah' in m]

rawDescription: Python: Having difficulty filtering out strings containing certain substrings


code:
class MyObject(object):
    @decorator
    def function(self):
         pass

rawDescription: How to retrieve arguments from a "fluid" decorated function

description: Retrieve arguments from a "fluid" decorated function


code:
import numpy as np
import random

# m denotes the number of examples here, not the number of features
def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.transpose()
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        # avg cost per example (the 2 in 2*m doesn't really matter here.
        # But to be consistent with the gradient, I include it)
        cost = np.sum(loss ** 2) / (2 * m)
        print("Iteration %d | Cost: %f" % (i, cost))
        # avg gradient per example
        gradient = np.dot(xTrans, loss) / m
        # update
        theta = theta - alpha * gradient
    return theta

def genData(numPoints, bias, variance):
    x = np.zeros(shape=(numPoints, 2))
    y = np.zeros(shape=numPoints)
    # basically a straight line
    for i in range(0, numPoints):
        # bias feature
        x[i][0] = 1
        x[i][1] = i
        # our target variable
        y[i] = (i + bias) + random.uniform(0, 1) * variance
    return x, y

# gen 100 points with a bias of 25 and 10 variance as a bit of noise
x, y = genData(100, 25, 10)
m, n = np.shape(x)
numIterations= 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)

rawDescription: gradient descent using python and numpy

description: Gradient descent using python and numpy


code:
def remove_starts(lst):
    seen = ()
    for elem in lst:
        if elem.startswith(seen):
            continue
        yield elem
        seen = elem[:4]

rawDescription: remove later strings starting with a certain thing in a list python

description: Remove later strings starting with a certain thing in a list python


code: companies = [item['name'] for item in data["companies"]]

rawDescription: Efficiently find objects satisfying relationship


code:
from dis import dis
dis(nest)

rawDescription: Iterated function in Python

description: Iterated function in Python


code: test()

rawDescription: Cumulative counts in NumPy without iteration


code:
Web_Keywd = 'car loan cheap'

words = set(Web_Keywd.split())
results = set(
    lemma.name
    for word in words
        for synset in wn.synsets(word)
            for lemma in synset.lemmas
)
# results -> {'loanword', 'tatty', 'automobile', 'cheap', 'chinchy',...

rawDescription: Using NTLK properly with python

description: Using NTLK properly with python


code:
spam = "blah"
spamify("I like %s!")
spamify("Do you like %s?")

spam = "other stuff"
spamify("I like %s!")
spamify("Do you like %s?")

rawDescription: How to set the global value of % in python

description: Set the global value of % in python


code:
class foo(object):
    ...
    def bar(self, _counter=[0]):
        _counter[0] += 1
        return _counter[0]

rawDescription: Adding attributes to instance methods in Python


code:
def call_dict(d):
    k, v = list(d.items())[0]  # ('RouteAdd', {route_config: ...})
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = call_dict(v2)
        elif isinstance(v2, list):
            kwargs[k2] = [(call_dict(v3) if isinstance(v3, dict) else v3) for v3 in v2]
        else:
            kwargs[k2] = v2
    return globals()[k](**kwargs)

rawDescription: Read python dict or yaml and call as python function with arguments and objects


code:
from collections import Counter
print([element for element,count in Counter(list1).most_common()])

rawDescription: How to sort a list with duplicate items by the biggest number of duplicate occurrences - Python

description: Sort a list with duplicate items by the biggest number of duplicate occurrences - Python


code:
from bisect import bisect_left
def word_exists(wordlist, word_fragment):
    try:
        return wordlist[bisect_left(wordlist, word_fragment)].startswith(word_fragment)
    except IndexError:
        return False # word_fragment is greater than all entries in wordlist

rawDescription: Fastest way in Python to find a 'startswith' substring in a long sorted list of strings


code: indexes = [i for i, t in enumerate(zip(a, b, c)) if max(t) > max_limit]

rawDescription: Make this simple for/if block more pythonic


code:
df = DataFrame(randn(10,2),index=pd.date_range('20000101',periods=10))
df.iloc[0:3,0] = np.nan
df.iloc[0:2,1] = np.nan
df

rawDescription: Get index where both rows are not NaN

description: Get index where both rows are not NaN


code:
from threading import Event,Thread

class RepeatTimer(Thread):
    def __init__(self, t, callback, event):
        Thread.__init__(self)
        self.stop = event
        self.wait_time = t
        self.callback = callback
        self.daemon = True

    def run(self):
        while not self.stop.wait(self.wait_time):
            self.callback()

rawDescription: Is it possible to execute function every x seconds in python, when it is performing pool.map?


code:
import StringIO
f = StringIO.StringIO()
plt.savefig(f, ...)
size = len(f.getvalue())

rawDescription: Estimate final size of image without writing it to disk with Python


rawDescription: Python split('\n') breaks a row midway instead of after end of line


code:
import sys
import test_wdw
from PySide import QtGui
from PySide import QtCore

class Main_Window(QtGui.QMainWindow):
    def __init__(self):
        super(Main_Window,self).__init__()
        self.initUI()

    def initUI(self):
        self.statusBar()

        self.new_window=QtGui.QAction("&Window alpha",self)
        self.new_window.triggered.connect(self.open_window)

        self.menu_bar=self.menuBar()
        self.menu1=self.menu_bar.addMenu('&Menu 1')
        self.menu1.addAction(self.new_window)

        # Creates a QMdiArea to manage all windows
        self.wmanager=QtGui.QMdiArea()
        self.setCentralWidget(self.wmanager)

        # Shows the main window
        self.showMaximized()

    def open_window(self):
        test_wdw.launch_window()
        test_wdw.window_alpha=self.wmanager.addSubWindow(test_wdw.window)
        # Shows the new window
        test_wdw.window_alpha.show()

def main():
    app=QtGui.QApplication(sys.argv)
    main_wdw=Main_Window()
    sys.exit(app.exec_())

if __name__=="__main__":
    main()

rawDescription: What is the correct way to use QThreads?

description: What is the correct way to use QThreads


code:
def game():
    while True:
        player_hand = ask_player_for_choice()
        machine_hand = determine_machine_choice()
        who_won = determine_winner(player_hand, machine_hand)
        display_winner(player_hand, machine_hand, who_won)
        if not ask_to_play_again():
            return

rawDescription: Accessing variables outside a function in Python


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
    artists = ax.pie(df[col], autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

fig.legend(artists[0], df.index, loc='center')

plt.show()

rawDescription: How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib

description: Make MxN piechart plots with one legend and removed y-axis titles in Matplotlib


code:
from sympy import *
x, y = symbols('x, y')
expr = 2*x - 7*y
solve(expr, y)

rawDescription: SymPy express variable in terms of another


code:
all_genres = pd.unique(movies[['Genre1','Genre2','Genre3']].values.ravel())
dff = pd.DataFrame(columns=['Nb_sales', 'Nb_view'],
                   index=all_genres, data=0)

for col in ['Genre1', 'Genre2', 'Genre3']:
    for genre, value in zip(movies[col].values, movies['sales'].values):
        dff.loc[(genre, 'Nb_sales')] += value
        dff.loc[(genre, 'Nb_view')] += 1

rawDescription: np.mean for rows with specific values across multiple columns

description: Np.mean for rows with specific values across multiple columns


code:
class S(str):
    def reverse(self):
        return self.__str__()[::-1]

s = S('hello')
s.reverse()

rawDescription: Python: How to add a custom function to a pre-existing object?


rawDescription: map pandas Dataframe columns to dictionary values

description: Map pandas Dataframe columns to dictionary values


code: bisect.insort_left(some_list, item)

rawDescription: Efficiency of Python sorted() built-in function vs. list insert() method


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(
    { "c1": np.array(['a','a','b','b','a']) ,
      "c2": np.array([1,2,2,2,2])} )
to_keep = {'a':[1],'b':[2,3]}
to_keep = pd.DataFrame([(key, item) for key, val in to_keep.items() for item in val],
                       columns=['c1', 'c2'])
#   c1  c2
# 0  a   1
# 1  b   2
# 2  b   3

print(pd.merge(df, to_keep, how='inner'))

rawDescription: Indexing on multiple arguments that depend on each other in pandas dataframe


code:
def maybe_replace(word, length=4):
  if len(word) == length:
    return 'something'
  else:
    return word

rawDescription: Python 3.2 Replace all words in a text document that are a certain length?


code:
import Tkinter
import tkMessageBox

rawDescription: Installing tkMessageBox on Python2.7

description: Installing tkMessageBox on Python2.7


code:
from docx import Document

document = Document('..path..')
table = document.tables[0]
cell = table.row[0].cells[0]
paragraph = cell.paragraphs[0]
text = paragraph.text

rawDescription: Extract particular word from docx table using python native library docx


code:
import datetime
year = datetime.date.today().year

rawDescription: Python function that takes an input and spits out a month and how many days it has


rawDescription: Python Comparison of byte literals

description: Python Comparison of byte literals


code: df.loc[df['size'].notnull() & df['value'] == 0, 'value'] = np.nan

rawDescription: Pandas: writing to original data frame. SettingWithCopyWarning


rawDescription: Generate random values based on a variable in Python


code:
def split_to_chunks(wholeFileList):
    s = ssdeep()
    calculated_chunks = []
    for someFileId in wholeFileList:
        for chunk in calculated_chunks:
            if s.compare(chunk[0], someFileId) > threshold:
                chunk.append(someFileId)
                break
        else: # important: this else is on 'for ' level
            # so if there was no 'break' so someFileId is a base for new chunk:
            calculated_chunks.append( [someFileId] )
    return calculated_chunks

rawDescription: Trouble in Grouping similar files using Multi processing and ssdeep Python


code:
def per_word(filename):
    with open(filename) as fh:
        for line in fh:
            for word in line.split():
                yield word

rawDescription: Struggling with python generator function


code:
class Migration(DataMigration):

    def forwards(self, orm):
        for item in queryset_iterator(orm['myapp.myclass'].objects.all()):
            if not item.uuid:
                item.uuid = uuid.uuid1()
                item.save()

    def backwards(self, orm):
        for item in queryset_iterator(orm['myapp.myclass'].objects.all()):
            if item.uuid:
                item.uuid = None
                item.save()

rawDescription: UUID field added after data already in database. Is there any way to populate the UUID field for existing data?


code:
from eyediagram._brescount import bres_segments_count
bres_segments_count(sticks, img)
plt.imshow(img, interpolation='nearest', cmap=cm.hot)

rawDescription: Directly "plot" line segments to numpy array


code:
from method2 import *

# Call the function with the argument:

arg = foo()

with open('input.dat', 'rb') as f:
  arg.data = f.read()

bar(arg)

rawDescription: Store file contents in a buffer and assign it to a pointer in Python


code: eq = TransientTerm() == DiffusionTerm(diffusion_coefficient) - ImplicitSourceTerm(phi)

rawDescription: Space dependent diffusion in fipy

description: Space dependent diffusion in fipy


code:
def save_uploaded_file (form_field, upload_dir):
    """This saves a file uploaded by an HTML form.
       The form_field is the name of the file input field from the form.
       For example, the following form_field would be "file_1":
           <input name="file_1" type="file">
       The upload_dir is the directory where the file will be written.
       If no file was uploaded or if the field does not exist then
       this does nothing.
    """
    form = cgi.FieldStorage()
    if not form.has_key(form_field): return
    fileitem = form[form_field]
    if not fileitem.file: return
    fout = file (os.path.join(upload_dir, fileitem.filename), 'wb')
    while 1:
        chunk = fileitem.file.read(100000)
        if not chunk: break
        fout.write (chunk)
    fout.close()

rawDescription: Upload a File with Python

description: Upload a File with Python


code:
i= 0 #<-- first loop
j= 0 #<-- second loop
j= 1 #<-- second loop
j= 2 #<-- second loop
i= 1 #<-- first loop
j= 0 #<-- second loop
j= 1 #<-- second loop
j= 2 #<-- second loop
j= 3 #<-- second loop
j= 4 #<-- second loop
j= 5 #<-- second loop

rawDescription: How does the nested loop iterates?

description: How does the nested loop iterates


code: test(u'Ã')

rawDescription: Django regex unicode ignores \w tag

description: Django regex unicode ignores \w tag


code: output = cv2.filter2D(image, -1, kernel)[1:-1, 1:-1]

rawDescription: OpenCV - altering the filter2D function

description: OpenCV - altering the filter2D function


code:
mystr
mystr[0]
mystr[-1]
mystr[::-1]
mystr[:-5]

rawDescription: Append a portion of a string to a list

description: Append a portion of a string to a list


code:
g = df.groupby('DateOccurence')
g.Category.apply(pd.value_counts)

rawDescription: Pandas groupby date

description: Pandas groupby date


code: links = soup.findAll('a', href=re.compile('^http://section.website.com/\d{6}$'))

rawDescription: Filtering URLs obtained using BeautifulSoup


code:
from Tkinter import *

def cursor():
    if not root.cget('cursor') == '':
        root.config(cursor='')
    else:
        root.config(cursor='fleur')

root = Tk()
Button(root, text='Change cursor', command=cursor).pack()
root.mainloop()

rawDescription: TkInter: how to display the normal cursor?


rawDescription: Convert an IP string to a number and vice versa


code:
import string, random
lst = [{random.choice(string.printable): random.randrange(100)} for _ in range(1000)]
timeit.timeit('f(lst)', 'from __main__ import lst, d_reduce as f', number=10000)
timeit.timeit('f(lst)', 'from __main__ import lst, d_chain as f', number=10000)
timeit.timeit('f(lst)', 'from __main__ import lst, d_comp as f', number=10000)

rawDescription: Python - Convert list of single key dictionaries into a single dictionary


code: [(key, group) for key, group in groupby(L, key=bool)]

rawDescription: Make a new sublist of preceding characters every time there's a zero in a list, excluding the zero


rawDescription: Recomended way to create a matrix containing strings in python


code: main()

rawDescription: Return len of the longest word in a list


code:
h = np.random.random((3,4))
nodata = 10
h.flat[[2,3,4,7,8,9]] = 10
ibound = np.random.randint(0,2,(3,4))
L1TopOld = np.ones((3,4))*5
h
ibound
L1TopOld
eps = 0.01

rawDescription: Efficient way to do conditional checks on Numpy Arrays


code:
f = [int(element) for element in d]
g = [int(element) for element in e]
f
g

rawDescription: Slicing a python string with intervals?

description: Slicing a python string with intervals


code:
def party_generator(size=1, chars=string.ascii_uppercase):
    parties = []
    seen = set()
    while len(parties) < 2:
        party = ''.join(random.choice(chars) for x in range(size))
        if party in seen:
            continue
        seen.add(party)
        parties.append('Party {}'.format(party))
    return parties

rawDescription: Generate 2 Unique but random Elements in a List


rawDescription: hexadecimal string to byte array in python

description: Hexadecimal string to byte array in python


code:
db.sample3.find().pretty()
{
    "_id" : ObjectId("5339c9ff0bb9bc1b3a5bf7a4"),
    "name" : "Nicholas",
    "friends" : [
        "Amy",
        "Joe",
        "Amanda"
    ]
}
{
    "_id" : ObjectId("5339ca120bb9bc1b3a5bf7a5"),
    "name" : "John",
    "friends" : [
        "Amy",
        "Amanda",
        "Sam",
        "Steve"
    ]
}

rawDescription: How do you do $elemMatch in Mongokit?

description: Do $elemMatch in Mongokit


code:
def keyboardTapCallback(proxy, type_, event, refcon):
    # Convert the Quartz CGEvent into something more useful
    keyEvent = NSEvent.eventWithCGEvent_(event)

rawDescription: system wide shortcut for Mac OS X

description: System wide shortcut for Mac OS X


code:
def step_mask_improved(x, limit=+1):
    b = np.broadcast(x, limit)
    out=np.atleast_1d(np.zeros(b.shape))
    out[np.where(x>0)]=1

    zeroindices=np.where(x==0)
    check=out[zeroindices]

    check=np.where(limit>0,1,check)
    check=np.where(limit==0,.5,check)
    check=np.where(limit<0,0,check)
    out[zeroindices]=check

    return out

rawDescription: Numpy zero rank array indexing/broadcasting


rawDescription: Reading ε using python

description: Reading ε using python


code: combList = list(combObject) # Don't iterate over it before you do this!

rawDescription: working with combinations object in python

description: Working with combinations object in python


code:
class CustomStringIO(StringIO):
    def close(self):
        import pdb; pdb.set_trace()
        super(CustomStringIO, self).close()

rawDescription: "I/O operation on closed file" with StringIO in Django view test


code:
def setCBState(self, wid, statedict):
    """ sets the state of all checkboxes on widget wid"""
    CBs = wid.children()
    for box in CBs:
        if isinstance(box, QtGui.QCheckBox) and statedict[box.objectname()]:
            box.setCheckState(QtCore.Qt.Checked)

rawDescription: Pyside restore checkbox state from dict

description: Pyside restore checkbox state from dict


rawDescription: Calling dll in python 3 with LPSTR

description: Calling dll in python 3 with LPSTR


code:
from itertools import groupby

grouped = [list(g) for k, g in groupby(string)]

rawDescription: Run Length Encoding in Python with List Comprehension


code:
output_list = [list(key) + value for key, value in output_dict.iteritems()]
print(output_list)

rawDescription: Restructuring a list of lists in python

description: Restructuring a list of lists in python


code:
import pandas as pd
import numpy as np
import functools
np.random.seed(2015)

N = 50
dfs = [pd.DataFrame(np.random.randint(5, size=(N,4)),
                    columns=['org', 'name', 'items', 'spend']) for i in range(9)]
for i, df in enumerate(dfs, start=1):
    df.rename(columns={col:'{}_df{}'.format(col, i) for col in ('items', 'spend')},
              inplace=True)
merge = functools.partial(pd.merge, on=['org', 'name'])
result = functools.reduce(merge, dfs)
print(result.head())

rawDescription: Pandas: merge multiple dataframes and control column names?


code: from __future__ import print_function

rawDescription: Display Number of Iterations in Output Window


code: count = len(re.findall(r'(?<!\S)'+ re.escape(word) + r'(?!\S)', line, re.IGNORECASE))

rawDescription: Count the occurrence of a word in a txt file in python


code:
import unicodedata
len(u''.join(ch for ch in u'A\u0332\u0305BC' if unicodedata.combining(ch) == 0))

rawDescription: How do I get the "visible" length of a combining Unicode string in Python?

description: Get the "visible" length of a combining Unicode string in Python


code:
with open('c:/HashFiles/search_engine_primary.sql') as inf, open('c:/HashFiles/hashes.txt','w') as outf:
    for i in xrange(47):
        inf.next()       # skip a line

    for line in inf:
        data = line.split(',')
        if len(data) > 15:      # skip any line without enough data items
            hash = data[15]
            outf.write(hash + '\n')

rawDescription: parsing/extracting data from a text file. Unable to make it work

description: Parsing/extracting data from a text file. Unable to make it work


rawDescription: Django-date incrementation in a list with ManyToManyField


rawDescription: Delete Column in Pandas based on Condition


code:
from collections import Counter
m = ['a', 'b', 'a', 'b', 'c']
Counter(m).most_common()

rawDescription: Python sort strings by count of appearances of the strings in the list


code:
from collections import Counter
l = [1,2,3,4,4]
Counter(l).most_common(1)[0][0]

rawDescription: Easy way to find what item repeated in list


code:
s = s.groupby('grp').apply(lambda x: x.val.tolist())

a    [0, 1]
b    [1, 0]
c    [2, 4]
d       [3]
e       [4]
k       [2]
n       [3]

rawDescription: groupby multiple value columns

description: Groupby multiple value columns


code: catid in catids

rawDescription: How to make "value is in dateframe column" quicker

description: Make "value is in dateframe column" quicker


code:
names = []
labels = []
for c in br.form.controls.__iter__():
    names.append(c.name)
    labels.append(c._label)

rawDescription: Obtaining the label of the control of a form in Mechanize


code:
product_df['month_num'] = product_df.groupby('product_desc').cumcount()
product_df

rawDescription: How to increment a row count in groupby in DataFrame

description: Increment a row count in groupby in DataFrame


code: gb = df.groupby(['officeID','CandidateId'], as_index=False)['total_votes'].sum()

rawDescription: Understanding groupby in pandas

description: Understanding groupby in pandas


code: sorted_data = sorted(data, key=by_veg_sum, reverse=True)

rawDescription: Ordered dictionary Sum and Top 3 of the Ordered dictionary sum


code:
np.column_stack((R_match[1],C_match[1]))  # Second point
np.column_stack((grps_R[1],grps_C[1]))    # Its eight neighbors

rawDescription: Find a nodes 8 neighbors on a 2D grid

description: Find a nodes 8 neighbors on a 2D grid


rawDescription: How do you force only one relationship in django when multiple are possible?

description: Force only one relationship in django when multiple are possible


code:
aa = {"Fruit":[u'Apple',u'Banana',u'lemon'],
      "Student":[ u'pen',u'book',u'chair' ],
      "Family":[u'father',u'mother']}

obj = 'pen'
for key in aa:
    if obj in aa[key]:
        print(obj + ' is in ' + key)

rawDescription: Python how to compare string in a list with dict


code:
def initUI(self):

    pixmapShow = PixmapContainer("image.jpg")
    pixmapShow.setMaximumSize(350, 200)

    grid = QtGui.QGridLayout(self)
    grid.setSpacing(10)
    grid.addWidget(pixmapShow, 0, 1)

    self.setGeometry(400, 400, 400, 400)
    self.setWindowTitle('Review')
    self.show()

rawDescription: How to set maximum widths and heights for pixmaps?

description: Set maximum widths and heights for pixmaps


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('')
html = '
TEST MESSAGE
'
snippet = BeautifulSoup(html).p.extract()
snippet
soup.body.append(snippet)
soup

rawDescription: Building paragraph tag in beautifulsoup

description: Building paragraph tag in beautifulsoup


code:
import re
from pyteomics import fasta

with open('num.txt') as nums:
    lines = re.findall(r'\w+\.txt\s+\d+', nums.read())

numbers = {}
for line in lines:
    line_split = re.split(r'\.txt\s+', line)
    count = line_split[1]
    numbers[line_split[0]] = int(line_split[1])

with fasta.read('data.txt') as data:
    new_data = ((header, seq[:numbers.get(header.rsplit('|', 1)[-1])])
            for header, seq in data)
    fasta.write(new_data, 'new_data.txt')

rawDescription: Length cutting through file handling

description: Length cutting through file handling


code: print ['&\x8cj\xbay\x93\xb9']

rawDescription: Accessing individual elements of an encrypted list in python


code:
[ssp]
a:re.compile(r'')

rawDescription: regular expression Pattern object getting converted to string if fetched from config.cfg file

description: Regular expression Pattern object getting converted to string if fetched from config.cfg file


code:
import importlib
module = importlib.import_module(module_name)

rawDescription: is it possible to import file if the file name is in variable?

description: Is it possible to import file if the file name is in variable


code:
def myrange(start, step, count):
    return range(start, start + (step * count), step)

rawDescription: Python range function: defining the length of sequence instead of the step size


code:
def compare(src, test):
    if len(src) != len(test):
        return # must be the same length
    diffmap = [0]*len(src)
    count = 0
    for i, c in enumerate(src):
        if not c == test[i]:
            count = count+1
            diffmap[i] = 1
    return test, count, diffmap

rawDescription: Comparing string differences to a list of strings


code:
#place the following in a method of a vte instance
env = os.environ.copy()
try:
    po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
        universal_newlines=True, env=env)
    po.wait()
    output, error_output = po.communicate()

    if po.returncode:
        print(error_output)
    else:
        self.feed(output) #here you're printing to your terminal.

except OSError as e:
    print('Execution failed:', e, file=sys.stderr)

rawDescription: Best Way of redirecting output to a VTE terminal


code:
# build a complex array of your cells
z = np.array([complex(c.m_x, c.m_y) for c in cells])

rawDescription: Efficiently Calculating a Euclidean Distance Matrix Using Numpy


rawDescription: best way to index by value of the header in a 2d list

description: Index by value of the header in a 2d list


code: sortedList=sorted(reader, key=lambda t: float( t[1] ))

rawDescription: Sorting a csv file in Python with sorted() returns values in programmer DESC order, not time DESC order


code:
def lcs_length(a, b):
    table = [[0] * (len(b) + 1) for _ in xrange(len(a) + 1)]
    for i, ca in enumerate(a, 1):
        for j, cb in enumerate(b, 1):
            table[i][j] = (
                table[i - 1][j - 1] + 1 if ca == cb else
                max(table[i][j - 1], table[i - 1][j]))
    return table[-1][-1]

rawDescription: Python: Length of longest common subsequence of lists


code:
import random
results = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
for count in range(6000000):
    die = random.randint(1, 6)
    results[die] += 1

print('Here are the results:')
# Loop over the *keys* of the dictionary, which are the die numbers
for die in results:
    # The format(..., ',d') function formats a number with thousands separators
    print(die, '=', format(results[die], ',d'))
# Sum up all the die results and print them out
print('Total rolls equal:', sum(results.values()))

rawDescription: how to format numbers with commas in python

description: Format numbers with commas in python


code:
try:
    g1, g2 = text.rsplit('/', 2)
except ValueError:
    pass # do something appropriate

rawDescription: Extract particular group of a repeating substring with regex


code:
weekly = []
for x in range(0, len(daily), 7):
     weekly.append( sum(visitors[x:x+7]) )

rawDescription: Find the sum of subsets of a list in python


code: from lib.bs4 import BeautifulSoup

rawDescription: Python on Appengine using BeautifulSoup ImportError: No module named bs4


code:
import dis
dis.dis(test1)
dis.dis(test2)

rawDescription: Why is slice assignment faster than `list.insert`?


code:
lessthan, greaterthan = [], []
for v in ab:
    if v < knowndistance:
        lessthan.append(v)
    else:
        greaterthan.append(v)

rawDescription: Comparison of float numbers to a known value python


code:
for i in x:
  print(i, end="")  # substitute the null-string in place of newline

rawDescription: Print statements without new lines in python?


code:
with open("test.txt") as f:
    for line in f:
        if line.rstrip() == "***a":
            print("")
            for line in f:
                if line.rstrip() == "---a":
                    break
                print(line.rstrip())

rawDescription: printing lines between start and end point

description: Printing lines between start and end point


code:
if self.returncode is None:
    if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
        self.returncode = _GetExitCodeProcess(self._handle)
    return self.returncode

rawDescription: Is it necessary to call Popen.wait() to "clean up" after the Popen object?


code: [n[1] for n in s]

rawDescription: Python slicing of list of list

description: Python slicing of list of list


code:
result.index += 1
result.index

rawDescription: Start index at 1 when writing Pandas DataFrame to CSV


code:
form_widget_args = {
    'description': {
        'rows': 100,
        'style': 'font-family: monospace;'
    }
}

rawDescription: Flask Admin: TextArea with monospace font


code: x0 = int(rho*np.sin(theta)*np.cos(phi))

rawDescription: How to rotate a 3D spot with numpy?

description: Rotate a 3D spot with numpy


code:
import struct
x = 173.125
s = struct.pack('>f', x)
''.join('%2.2x' % ord(c) for c in s)

rawDescription: Python: obtain & manipulate (as integers) bit patterns of floats


code:
from functools import partial
from operator import ne
filter(partial(ne, None), (0,1,2,3,4,5,None,None,None,None,None))

rawDescription: Python Optimize Grouper Function to avoid None elements


rawDescription: Sorting names containing numbers

description: Sorting names containing numbers


code:
surf = pygame.Surface((100,200)) # I'm going to use 100x200 in examples
data = pygame.image.tostring(surf, 'RGBA')

rawDescription: How to save pygame Surface as an image to memory (and not to disk)

description: Save pygame Surface as an image to memory (and not to disk)


code: monkeys_punched_yet = True

rawDescription: How to disable/restrict a line of code after it has been run? (Python)

description: Disable/restrict a line of code after it has been run? (Python)


code:
@app.route('/day-lookup', method=['GET'])
def day_lookup():
    year = request.args.get('year', None)
    # error handle here

    calendar_tuple = get_days_for_dates(year)
    # do something with it, return the list, etc.

rawDescription: With Flask and Angular, how do I make $scope variables available to a python function


code:
id_data = df.Identifier.str.strip("[]").str.split(";").tolist()
df_id = pd.DataFrame(id_data, columns=list("abcde"), index=df.index, dtype=int)
df2 = df.join(df_id)

rawDescription: Convert a column in a pandas DataFrame into multiple columns


rawDescription: NLTK "generate" function: How to get back returned text?


code: from itertools import izip, imap

rawDescription: Turn Python list from CSV with multi-value fields into a Python nested list, sort nested list values and export to CSV


code:
for i in range(50):
    data = loadtxt('{0}.txt'.format(i + 1), float)

rawDescription: read multiple files by python

description: Read multiple files by python


code: w["button"].configure(command = lambda : delete(w["url"], widgets))

rawDescription: Dynamicaly deleting widgets in Tkinter in Python


code:
Y = np.arange(20, dtype=np.float)
Ynan = np.insert(Y, (5,)*3, (np.nan,)*3)
X = np.rec.fromarrays([Ynan, Ynan+100], names='g,h')
X

rawDescription: reassigning expanded recarray field

description: Reassigning expanded recarray field


code: DS.blit(catImg, catImgRectObj)

rawDescription: get_rect() over an image gets shifted in pygame

description: Get_rect() over an image gets shifted in pygame


code:
import random

def randDNA(n):
    return ''.join(random.choice("ATGC") for i in range(n))

def mutate(strand,times):
    nucleotides = list(strand)
    n = len(strand)
    for i in range(times):
        j = random.randint(0,n-1)
        nucleotides[i] = random.choice("ATGC")
    return ''.join(nucleotides)

def HammingClose(s,t):
    #assumes s and t are strings of the same length
    #returns True if s,t are Hamming distance at most 1
    #otherwise returns False

    clashes = 0
    for x,y in zip(s,t):
        if x != y:
            clashes += 1
            if clashes > 1: return False
    return True

def takeFingerPrint(strand,places):
    return ''.join(strand[i] for i in places)

def smudges(fp):
    s = set([fp])
    for i,c in enumerate(fp):
        s.update([fp[:i] + d + fp[(i+1):] for d in "ATGC" if d != c])
    return s

def summary(strandList, fpSize = 10):
    n = len(strandList)
    refStrand = strandList[0]
    ncount = 1 #count of refstrand + Hamming-neighbors
    position = {}

    for i,c in enumerate(refStrand):
        position[i] = dict.fromkeys("ATGC",0)
        position[i][c] += 1

    #take a random fingerprint of size fpSize
    places = random.sample(range(n),fpSize)
    refPrint = takeFingerPrint(refStrand,places)
    s = smudges(refPrint)

    for strand in strandList[1:]:
        fp = takeFingerPrint(strand,places)
        if fp in s: #maybe a hit!
            if HammingClose(strand,refStrand):
                ncount += 1
                for i,c in enumerate(strand):
                    position[i][c] += 1

    #assemble summary strand

    mode = []
    for i in range(len(refStrand)):
        c = "A"
        m = position[i]["A"]
        for x in "TGC":
            if position[i][x] > m:
                c = x
                m = position[i][x]
        mode.append(c)

    return(ncount,''.join(mode))

#example problem

strand = randDNA(10000)
strandList = [mutate(strand,5) for i in range(10000)]

n,s = summary(strandList,100)
print(n, "close strands found")
print("First 30 positions in summary strand are ", s[:30])

rawDescription: Would using hash in python speed up string/char comparison?


rawDescription: Importing package in Python

description: Importing package in Python


code: c.InteractiveShellApp.exec_lines = [ "def f(s): print s" ]

rawDescription: how to define functions in ipython configuration file?

description: Define functions in ipython configuration file


code: x.astype(np.int8, copy=False)

rawDescription: Repeating numpy values and specifying dtype


code:
email_lines = """\
<paste your lines with numbers>
""".splitlines()

rawDescription: Change Series of Numbers to List, python


rawDescription: how to move axes labels to near the arrows in matplotlib

description: Move axes labels to near the arrows in matplotlib


code: array2[:] =  [e for e in array2 if e not in set1]

rawDescription: Using arrays with other arrays in Python


code:
def add_verification(request):
    #get verification code
    ctx = {'verification': 'xxxxx'}

    #you can also check what path it is like
    #if request.path.contains('/someparticularurl/'):
    #    add verification

    return ctx

rawDescription: How to insert data to a template after render ? (django)

description: Insert data to a template after render ? (django)


code:
final={}
for classes in soup.find_all("div", "AssignmentClass"):
    grades = classes.findAll("span")[5]
    periods = classes.findAll("a", "asmt_link")
    for p, g in zip(periods, grades):
                final.setdefault(p.get_text(), g)

rawDescription: Python - Updating dictionary in a for loop


code:
I,J=np.where(sub==sub)
ind
Mat[2+I,0+J]    # 0 inplace of None for J

rawDescription: numpy ndarray indexing - retrieving indexes from tuple

description: Numpy ndarray indexing - retrieving indexes from tuple


code:
import numpy as np
import pandas as pd
import collections

np.random.seed(2016)
ncols = 5
nrows = 200000
nvals = 40000
MIN_OBS = 200

# nrows = 20
# nvals = 4
# MIN_OBS = 2

idx = np.random.randint(ncols, size=nrows).cumsum()
data = np.random.choice(np.arange(nvals), size=idx[-1])
data = np.array_split(data, idx[:-1])
data = map(','.join, [map(str, arr) for arr in data])
A = pd.Series(data)
A.loc[A == ''] = 'null'

def orig(A, MIN_OBS):
    temp_dict = collections.defaultdict(int)
    for k, v in A.iteritems():
        temp_list = v.split(',')
        for item in temp_list:
            temp_dict[item] += 1
    cols_to_make = []
    for k, v in temp_dict.iteritems():
        if v > MIN_OBS:
            cols_to_make.append('A_' + k)

    result_df = pd.DataFrame(0, index=A.index, columns=cols_to_make)
    for k, v in A.iteritems():
        temp_list = v.split(',')
        for item in temp_list:
            if ('A_' + item) in cols_to_make:
                result_df['A_' + item][k] = 1
    return result_df

def count(A, MIN_OBS):
    temp_dict = collections.Counter()
    for k, v in A.iteritems():
        temp_list = v.split(',')
        for item in temp_list:
            temp_dict[item] += 1
    temp_dict = {k:v for k, v in temp_dict.items() if v > MIN_OBS}
    return temp_dict

def alt(A, MIN_OBS):
    temp_dict = count(A, MIN_OBS)
    df = pd.DataFrame(0, index=A.index, columns=temp_dict)
    for col in df:
        df[col] = A.str.contains(r'^{v}|,{v},|,{v}$'.format(v=col)).astype(int)
    df.columns = ['A_{}'.format(col) for col in df]
    return df

rawDescription: Transform pandas Series with variable length comma separated values to Dataframe


code:
if ("aa" in attrs["show"] or "bb" in attrs["show"] or "cc" in attrs["show"] or
    "dd" in attrs["show"] or "ee" in attrs["show"] or "ff" in attrs["show"]):
    self.xx = xxxx

rawDescription: if command in python

description: If command in python


rawDescription: Python build a list by two different methods


code:
from ib.opt import Connection, message
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.ext.CommissionReport import CommissionReport
from ib.ext.TickType import TickType as tt

rawDescription: How to get the trading price and commission in Interactive Brokers (IBPY) after placing an order?

description: Get the trading price and commission in Interactive Brokers (IBPY) after placing an order


code:
import functools
def nested_list(depth):
  functools.reduce(lambda l, n: [l], range(depth), [])

rawDescription: Python: initialise list of list of list of ... etc


code: dict((z[0],list(z[1:])) for z in zip(list1,list2,list3))

rawDescription: How to map multiple lists to one dictionary?

description: Map multiple lists to one dictionary


code:
[[col1, col2, col3, col4], # Row 1
 [col1, col2, col3, col4], # Row 2
 [col1, col2, col3, col4], # Row 3
 [col1, col2, col3, col4]] # Row 4

rawDescription: Whats the best way of putting tabular data into python?


code:
strings = ['$', 'the', '$big', 'cat']
for s in strings:
  if s[0] != '$':
    print(s)

for s in strings:
  if not s.startswith('$'):
    print(s)

rawDescription: Very new to python, looking for some clarification


code: getcontext().prec = 102

rawDescription: Correctly compute square root digital expansions


code:
import sys
is_pypy = '__pypy__' in sys.builtin_module_names

import timeit
import random
if not is_pypy:
  import numpy
import bisect

n = 10000
m = 10000
q = 100

A = set()
while len(A) < n: A.add(random.randint(0,2*n))
A = list(A)

queries = set()
while len(queries) < m: queries.add(random.randint(0,2*n))
queries = list(queries)

# these two solve question one (find indices of queries that exist in A)
if not is_pypy:
  def fun11():
    for _ in range(q):
      numpy.nonzero(numpy.in1d(queries, A))[0]

def fun12():
  index = set(A)
  for _ in range(q):
    [i for i,x in enumerate(queries) if x in index]

# these three solve question two (find according entries of B)
def fun21():
  index = { k:i for i,k in enumerate(A, 1) }
  for _ in range(q):
    [index[i] for i in queries if i in index]

def fun22():
  index = { k:i for i,k in enumerate(A, 1) }
  for _ in range(q):
    list(filter(None, map(index.get, queries)))

def findit(keys, values, key):
  i = bisect.bisect(keys, key)
  if i == len(keys) or keys[i] != key:
    return None
  return values[i]

def fun23():
  keys, values = zip(*sorted((k,i) for i,k in enumerate(A,1)))
  for _ in range(q):
    list(filter(None, [findit(keys, values, x) for x in queries]))

if not is_pypy:
  # note this does not filter out nonexisting elements
  def fun24():
    I = numpy.argsort(A)
    ss = numpy.searchsorted
    maxi = len(I)
    for _ in range(q):
      a = ss(A, queries, sorter=I)
      I[a[a<maxi]]

tests = ("fun12", "fun21", "fun22", "fun23")
if not is_pypy: tests = ("fun11",) + tests + ("fun24",)

if is_pypy:
  # warmup
  for f in tests:
    timeit.timeit("%s()" % f, setup = "from __main__ import %s" % f, number=20)

# actual timing
for f in tests:
  print("%s: %.3f" % (f, timeit.timeit("%s()" % f, setup = "from __main__ import %s" % f, number=3)))

rawDescription: Python: Fast mapping and lookup between two lists


rawDescription: Writing List of Strings to Excel CSV File in Python


rawDescription: How can i get python to check if every term of a input is in list1, and if not print the term as is?

description: Get python to check if every term of a input is in list1, and if not print the term as is


code:
g=list(l)
g.remove(z)

rawDescription: Number sorting by a recursive function

description: Number sorting by a recursive function


code:
file_name_in = 'numeric_table.csv'
file_name_out = 'new_file.csv'

with open(file_name_in, 'rb') as f_in:
    reader = csv.reader(f_in)

    with open(file_name_out, 'wb') as f_out:
        writer = csv.writer(f_out)

        for row in reader:

            # manipulate row, change numbers, etc.

            writer.writerow(row) # Write row to new file

rawDescription: Re-writing a CSV file using csv

description: Re-writing a CSV file using csv


code:
def itemfreq(a):
    items, inv = np.unique(a, return_inverse=True)
    freq = np.bincount(inv)
    return np.array([items, freq]).T

rawDescription: Sorting a scipy.stats.itemfreq result containing strings


code:
from collections import Counter
from itertools import izip_longest

for dcts in data.values():
    for i, dct in enumerate(dcts):
        if i >= len(result):
            result.append(Counter(dct))
        else:
            result[i].update(dct)

rawDescription: Sum the nested dictionary values in python


rawDescription: Get attribute of a property in python

description: Get attribute of a property in python


rawDescription: Selenium Python: How to click on a <a> tag based on "onclick" text


code: k, v = kv

rawDescription: How to determine if object is a valid key-value pair in PySpark

description: Determine if object is a valid key-value pair in PySpark


rawDescription: How to remove convexity defects in a Sudoku square?

description: Remove convexity defects in a Sudoku square


rawDescription: is there something like coo_matrix but for sparse vectors?

description: Is there something like coo_matrix but for sparse vectors


code: combinations = [ [ {varName: val} for varName, val in zip(varNames, prod) ] for prod in it.product(*(variants[varName] for varName in varNames))]

rawDescription: Combinations from dictionary with list values using Python


code: dir(len)

rawDescription: IPython Notebook doesn't show full namespace


code: [k for d in l for k in d]

rawDescription: How can I get a list of all keys of dicts inside a list?

description: Get a list of all keys of dicts inside a list


code:
import asyncio
class Event_ts(asyncio.Event):
    #TODO: clear() method
    def set(self):
        #FIXME: The _loop attribute is not documented as public api!
        self._loop.call_soon_threadsafe(super().set)

rawDescription: asyncio: Wait for event from other thread

description: Asyncio: Wait for event from other thread


code:
def obsfucate_letters(letters):
    letters[0] = obsfucate_function(letters[0])
    letters[1] = obsfucate_function(letters[1])
    letters[2] = obsfucate_function(letters[2])
    letters[3] = obsfucate_function(letters[3])

    return letters

def obsfucate_function(default):
    import random as r
    randomnumber = r.random() * 100
    if randomnumber <= 16:
        letters1 = "!"
        return letters1
    elif randomnumber > 16 and randomnumber <= 30:
        letters1 = "%"
        return letters1
    elif randomnumber > 30 and randomnumber <= 45:
        letters1 = "&"
        return letters1
    elif randomnumber > 45 and randomnumber <= 60:
        letters1 = "*"
        return letters1
    elif randomnumber > 60 and randomnumber <= 75:
        letters1 = "#"
        return letters1
    elif randomnumber > 75 and randomnumber <= 90:
        letters1 = "@"
        return letters1
    else:
        return default

rawDescription: Return original value, python

description: Return original value, python


code: LOG_ENABLED = False

rawDescription: Is there any way to change the log message format in scrapy?


code:
myList = ['a' ,'b' , 'c' , 'd' , 'e']

my_dict = {}

for idx, val in enumerate(myList):
    my_dict["v{}".format(idx)] = val

rawDescription: Save for loop result in variable

description: Save for loop result in variable


code:
import urlparse, urllib

parts = urlparse.urlsplit(u'http://ne.wikipedia.org/wiki/मुख्य_पृष्ठ')
parts = parts._replace(path=urllib.quote(parts.path.encode('utf8')))
encoded_url = parts.geturl().encode('ascii')

rawDescription: Scraping a webpage with URL in Nepali (Non-English)


code:
x = X()
x.y.modify()
x.count

rawDescription: Composition - Reference to another class in Python


rawDescription: Python: Finding values after searching for a string in a text files


code:
#!/usr/bin/env python3.4

print("Content-Type: text/html\n\n")
distance = 10
print(distance)  #This is the body of the response

rawDescription: How do I return JSON-data from python to javascript?

description: Return JSON-data from python to javascript


code: meat

rawDescription: finding a record with a max value in python

description: Finding a record with a max value in python


code:
order_dict = dict(zip(b, range(len(b))))
sorted(a,key=lambda x: order_dict[x[0]])

rawDescription: Sorting list of lists by a third list of specified non-sorted order


code:
def do_string(a, b, c, op_string):
    return eval(op_string)

a = set([1,2,3])
b = set([4,5,6])
c = set([3,4])
print(do_string(a, b, c, "(a|b)^c"))  # =>  {1, 2, 5, 6}

# be aware! arguments are passed POSITIONALLY, not by name!
print(do_string(b, c, a, "(a|b)^c"))  # =>  {1, 2, 4, 5, 6}  !not what you expected!

rawDescription: Possible to pass set operators (operation) as a string argument to a function?


code:
for v in D1.values():
    if 3 in v:
        v.remove(3)
D1

rawDescription: How to remove a value but keep the corresponding key in a dictionary?

description: Remove a value but keep the corresponding key in a dictionary


code:
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager

def put_ipy(parent):
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()
    kernel_client.namespace  = parent

    def stop():
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel()

    layout = QtGui.QVBoxLayout(parent)
    widget = RichIPythonWidget(parent=parent)
    layout.addWidget(widget)
    widget.kernel_manager = kernel_manager
    widget.kernel_client = kernel_client
    widget.exit_requested.connect(stop)
    ipython_widget = widget
    ipython_widget.show()
    kernel.shell.push({'widget':widget,'kernel':kernel, 'parent':parent})
    return {'widget':widget,'kernel':kernel}

rawDescription: embedding ipython qtconsole and passing objects

description: Embedding ipython qtconsole and passing objects


code:
with open("text.txt", "r") as inp, open("out.txt", "w") as output:
   for line in inp:
       l = line.strip()
       if l.endswith("dev"):
           output.write("{} <- He's a developer\n".format(l))
       if l.endswith("supp"):
           output.write("{} <- He's a support guy\n".format(l))

rawDescription: Append a text in a file where the pattern matches


rawDescription: Pandas: join with outer product

description: Pandas: join with outer product


code:
cl = request.content_length
if cl is not None and cl > 3 * 1024 * 1024:
    abort(413)

rawDescription: Is it possible to limit Flask POST data size on a per-route basis?


code:
def setup(s): # executed on each node before jobs are scheduled
    # read data in file to global variable
    global data
    data = open(s).read()
    return 0

rawDescription: Is there a way to pass a variable to setup() in dispy?


code:
known_commands = {
    "boo"  : lambda: random.choice(["Winter is coming...","SURPRISE!","Mazel tov!"]),
    "xyzzy": xyzzy,
}

rawDescription: random.choice([x, y, z]) in python, why doesn't the seed change?

description: Random.choice([x, y, z]) in python, why doesn't the seed change


code:
import math

def map_nested(listbasket, function, levels): #listbasket is the list that contains lists
    totlist=[] #this list will store the list after the function has been mapped to it
    for listelement in listbasket:

        if levels<=2: #once we get to the level that just contains a list of lists
            newlist=list(map(function,listelement))
            totlist.append(newlist) #add to final mapped list
        else:
            totlist.append(map_nested(listelement, function, levels-1))
    return totlist

map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt, 3) # my test function

rawDescription: returning from recursive function in python

description: Returning from recursive function in python


code:
class UserReportedCountry(db.Model):
  country_name = db.StringProperty( required=True,
                          choices=['Afghanistan','Aring land Islands']
                         )

class UserReportedCity(db.Model):
  country = db.ReferenceProperty(UserReportedCountry, collection_name='cities')
  city_name = db.StringProperty(required=True)

class UserReportedStatus(db.Model):
  city = db.ReferenceProperty(UserReportedCity, collection_name='statuses')
  status = db.BooleanProperty(required=True)
  date_time = db.DateTimeProperty(auto_now_add=True)

rawDescription: How to send data generated from python to jquery datatable for rendering

description: Send data generated from python to jquery datatable for rendering


code:
def lager(layers=5, volume=0.407150407905):
    if layers < 1:
        return 0
    return (volume * (layers ** 2)) + lager(layers-1)

rawDescription: Recursive function not returning what I want


code: df.groupby(['Apple', 'Banana']).mean()

rawDescription: How can I get pivot_table to apply a function over combinations of values?

description: Get pivot_table to apply a function over combinations of values


code:
a.func_name
b.func_name

rawDescription: what is the difference for python between lambda and regular function?

description: What is the difference for python between lambda and regular function


rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


code:
def foo(a, b=1): pass
rstr(foo)

rawDescription: Is there a Python equivalent of R's str(), returning only the structure of an object?


code:
import binascii
import os
import tempfile
import Tkinter

iconhexdata = '000001000100101000000100180068030000160000002800000010000000' \
              '20000000010018000000000040030000130b0000130b0000000000000000' \
              '0000ffffff6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c' \
              '6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6dffffffffffff6c6c6d6c6c6d6c' \
              '6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c' \
              '6c6d6c6c6dffffffffffff6c6c6d6c6c6dffffffffffffffffffffffffff' \
              'ffffffffffffffffffffffffffffffffff6c6c6d6c6c6dffffffffffff6c' \
              '6c6d6c6c6dffffff6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c' \
              '6c6dffffff6c6c6d6c6c6dffffffffffff6c6c6d6c6c6dffffff6c6c6d6c' \
              '6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6d6c6c6dffffff6c6c6d6c6c6dff' \
              'ffffffffff6c6c6d6c6c6dfffffffffffffffffffffffffffffff2f4f7d6' \
              'dfe9b8cadb95b2cfedf2f66c6c6d6c6c6dfffffffffffffffffffffffff4' \
              'f7fac0d4e69bb9d6739dc65789ba3e78b03f78af4177ad4276abd2deeaff' \
              'ffffffffffffffffffffffffffffffffffdfe9f24178ad4178ad4178ad50' \
              '81b17398be9db8d3bed4e6bbd7ecadd7f3ffffffffffffffffffffffffff' \
              'fffffffffff8fafcaac2dac4d3e4dfe8f1f9fbfdfffffff4fafd91cff520' \
              'a3f10297eee4f4feffffffffffffffffffffffffffffffffffffffffffff' \
              'ffffffffffe7f4fd7fcaf6159def0595ec179fec82c7f4bad6f7fdfeffff' \
              'fffffffffffffffffffffffffffffdfeffdbf0fd7bc8f6119bed0695eb1a' \
              '9ded7ecaf5f0f8febfd3f73165e495b1f1ffffffffffffffffffffffffff' \
              'fffff6fbfe2fa6ee0695eb1b9eed86ccf5e8f6fdffffffd2dff93468e532' \
              '6ae5c7d6f8ffffffffffffffffffffffffffffffffffff96d2f784cbf5ea' \
              'f6fdffffffffffffe3eafb4275e72c66e4b6caf6ffffffffffffffffffff' \
              'fffffffffffffffffffffffffffffffffffffffffffffff3f6fd5784ea2c' \
              '66e499b5f2ffffffffffffffffffffffffffffffffffffffffffffffffff' \
              'fffffffffffffffffdfeff7097ed2c66e47a9eeeffffffffffffffffffff' \
              'fffffffffffffffffffffffffffffffffffffffffffffffdfeff85a7ef2c' \
              '66e4608cebf9fbfeffffffffffffffffffffffff00000000000000000000' \
              '000000000000000000000000000000000000000000000000000000000000' \
              '000000000000000000000000000000000000000000000000'

# create temp file
with tempfile.NamedTemporaryFile(delete=False) as iconfile:
    iconfile.write(binascii.a2b_hex(iconhexdata))

root = Tkinter.Tk()
root.title('stackoverflow!')
root.iconbitmap(iconfile.name)
root.minsize(200, 200)
Tkinter.Button(root, text='OK', command=root.quit).pack(expand=True)
root.mainloop()

os.remove(iconfile.name)  # delete temp file

rawDescription: Python Tkinter use string for icon bitmap


code:
import csv
import datetime

# tell the application how to interpret and do averages with special column types
ELAPSED_TIME_REFERENCE = datetime.datetime.strptime('0:0:0', '%H:%M:%S')
def get_elapsed(s):
    h, m, s = s.split(':')
    delta = datetime.timedelta(days=0, hours=int(h), minutes=int(m), seconds=int(s))
    return delta.total_seconds()

def get_int(s):
    return int(s.replace(',', ''))

def get_float(s):
    return float(s.replace(',', ''))

def numerical_average(values):
    return float(sum(values))/max(len(values), 1)

def elapsed_average(elapsed_times_s):
    average_elapsed_s = numerical_average(elapsed_times_s)
    delta = datetime.timedelta(seconds=average_elapsed_s)
    return delta

CONVERTER = 'converter'
AVERAGE = 'average'
HEADER_TO_TOOLS = {'Job Duration': {CONVERTER: get_elapsed,
                                    AVERAGE: elapsed_average},
                   'Job File Count': {CONVERTER: get_int,
                                      AVERAGE: numerical_average},
                   'Throughput (KB/sec)': {CONVERTER: get_float,
                                           AVERAGE: numerical_average},
                   'Protected Data Size(MB)': {CONVERTER: get_float,
                                               AVERAGE: numerical_average}}

def interpret_string(header, s):
    tools = HEADER_TO_TOOLS.get(header)
    if tools:
        return tools[CONVERTER](s)
    return s  # don't interpret if no interpreter exists

# collect all data as: {client_name: {header1: list_of_values, header2: list_of_values}}
data_dict = {}
with open('data.csv') as f:
    reader = csv.reader(f)
    headers = tuple(x.strip() for x in next(reader))  # first row
    for row in reader:
        client_name = row[0]
        this_client_data = data_dict.setdefault(client_name, {header: [] for header in headers})
        for header, s in zip(headers, row):
            s = s.strip()
            this_client_data[header].append(interpret_string(header, s))

# print the results
output_headers = ['**Client Name', 'Job Duration', 'Job File Count', 'Throughput (KB/sec)', 'Protected Data Size(MB)']
# print the headers first
print(', '.join(output_headers))
# print the client name and averages for each client
for server_name, server_data in data_dict.items():
    print_items = []
    for output_header in output_headers:
        header_values = server_data[output_header]
        tools = HEADER_TO_TOOLS.get(output_header)
        if tools:
            print_items.append(str(tools[AVERAGE](header_values)))
        else:
            print_items.append(header_values[0])  # they should all be the same if not numerical
    print(', '.join(print_items))

rawDescription: Python : CSV manipulate multiple column

description: Python : CSV manipulate multiple column


code:
for i in range(2, 8):
    primes = filter(lambda x: x == i or x % i, primes)

rawDescription: Finding Primes with Modulo in Python

description: Finding Primes with Modulo in Python


code:
import itertools
numberOfPairs = 2 # change this
lstNew = ["".join(i) for i in itertools.permutations(lst,numberOfPairs)]

rawDescription: List of numbers

description: List of numbers


rawDescription: Can one get hierarchical graphs from networkx with python 3?


code:
class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if width == 0 and height == 0 and \
           color == 'red' and emphasis == 'strong' or \
           highlight > 100:
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

rawDescription: I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines?


code:
import codecs, sys
for encoding in ('utf-8', 'cp1252'):
    out = codecs.open('%s.txt' % encoding, 'w', encoding)
    out.write('# coding = %s\n' % encoding)
    out.write(u'\u201chello se\u00f1nor\u201d')
    out.close()

rawDescription: Read a unicode file in python which declares its encoding in the same way as python source


code: np.c_[a, np.ones(3)]

rawDescription: How do I add Columns to an ndarray?

description: Add Columns to an ndarray


code:
def list_acl(wmi_acl):
    acl = []
    for entry in wmi_acl:
        trustee = entry.Trustee.Name
        if trustee and entry.Trustee.Domain:
            trustee = '%s\\%s' % (entry.Trustee.Domain, trustee)
        mask = entry.AccessMask
        if mask < 0:
            mask += 2 ** 32
        ace = Ace(entry.AceType, entry.AceFlags, mask,
                        entry.Trustee.SIDString, trustee)
        acl.append(ace)
    return acl

# Win32_LogicalFileSecuritySetting
# https://msdn.microsoft.com/en-us/library/aa394180
WQL_LFSS = 'SELECT * FROM Win32_LogicalFileSecuritySetting WHERE Path="%s"'
wmi_ns = wmi.WMI()

def get_file_security(path):
    path = os.path.abspath(path)
    os.stat(path) # ensure path exists
    lfss = wmi_ns.query(WQL_LFSS % (path,))[0]
    sd = lfss.GetSecurityDescriptor()[0]
    owner = sd.Owner.Name
    if owner and sd.Owner.Domain:
        owner = '%s\\%s' % (sd.Owner.Domain, owner)
    group = sd.Group.Name
    if group and sd.Group.Domain:
        group = '%s\\%s' % (sd.Group.Domain, group)
    dacl = sacl = ()
    if sd.ControlFlags & SE_DACL_PRESENT:
        dacl = tuple(list_acl(sd.DACL))
    if sd.ControlFlags & SE_SACL_PRESENT:
        sacl = tuple(list_acl(sd.SACL))
    return FileSecurity(lfss.Path,
                        lfss.OwnerPermissions,
                        owner, group,
                        sd.Owner.SIDString,
                        sd.Group.SIDString,
                        sd.ControlFlags,
                        dacl, sacl)

rawDescription: Python - Get windows folder ACL permissions


code:
from helloworld.helloworld_widget import HelloWorldWidget
hello = HellowWorldWidget()
hello

rawDescription: Import a iPython Custom Widget Function (File Structure?)


code:
import httplib
conn = httplib.HTTPConnection('localhost')
conn.request("GET", '/', headers={'Range': 'bytes=0-299'}) # <----
resp = conn.getresponse()
resp.status
resp.status == httplib.PARTIAL_CONTENT
resp.getheader('content-range')
content = resp.read()
len(content)

rawDescription: Python: How to download file using range of bytes?


rawDescription: Indentation of pformat() output

description: Indentation of pformat() output


code: {'q': None, 'b': True, 't': True}

rawDescription: Python OptParse combine multiple options


rawDescription: python string formatting from list with arbitrary item

description: Python string formatting from list with arbitrary item


code:
for n, args in enumerate(list_of_arglists, 1):
    plot(n, *args)

rawDescription: Use try/except to handle multiple plots

description: Use try/except to handle multiple plots


rawDescription: deleting element from python dictionary

description: Deleting element from python dictionary


code: dictRows = dict(zip(rowHeaders, leafIDs))

rawDescription: Sorting tuples based on another list

description: Sorting tuples based on another list


code:
import ast
def evaluate (expr, ref):
    if isinstance(expr, ast.Module):
        return evaluate(expr.body[0], ref)
    elif isinstance(expr, ast.Expr):
        return evaluate(expr.value, ref)
    elif isinstance(expr, ast.Call):
        args = [evaluate(x, ref) for x in expr.args]
        kwargs = {kw.arg: evaluate(kw.value, ref) for kw in expr.keywords}
        return evaluate(expr.func, ref)(*args, **kwargs)
    elif isinstance(expr, ast.Attribute):
        return getattr(evaluate(expr.value, ref), expr.attr)
    elif isinstance(expr, (ast.Str, ast.Num)):
        return ast.literal_eval(expr)

    # special case; look up names on the reference object
    elif isinstance(expr, ast.Name):
        return getattr(ref, expr.id)
    else:
        print('Unknown type', type(expr))

rawDescription: Python getattr callable function

description: Python getattr callable function


code:
graph = {'A': ['B', 'C'],
        'B': ['A', 'F'],
        'C': ['D', 'E'],
        'D': ['H', 'J', 'C'],
        'E': ['C', 'F'],
        'F': ['B', 'G'],
        'G': ['F', 'H'],
        'H': ['G', 'D', 'I'],
        'I': ['H', 'K'],
        'J': ['D', 'E', 'K'],
        'K': ['I', 'J']}

current_node = []
viewed_nodes = []

def traverse(into):
    if into in viewed_nodes:
        return

    viewed_nodes.append(into)

    for outto in graph[into]:
        if outto not in viewed_nodes:
            traverse(outto)

for node in graph:
    traverse(node)

print(sorted(viewed_nodes))

rawDescription: Depth Traversing a graph in Python

description: Depth Traversing a graph in Python


code:
STATIC_FILES_BUCKET = "myappstatic"
MEDIA_FILES_BUCKET = "myappmedia"
STATIC_URL = "http://XXXXXXXX.cloudfront.net/"
MEDIA_URL = "http://XXXXXXXX.cloudfront.net/"

DEFAULT_FILE_STORAGE = 'myapp.storage_backends.MediaFilesStorage'
COMPRESS_STORAGE = STATICFILES_STORAGE = 'myapp.storage_backends.StaticFilesStorage'

rawDescription: Django-compressor: how to write to S3, read from CloudFront?


rawDescription: How to find occurrences of list of letters efficiently with NLTK in Python?

description: Find occurrences of list of letters efficiently with NLTK in Python


code:
try:
    from functools import reduce  # Python 3 compatibility
except:
    pass

def compose(*funcs, **kwargs):
    """Compose a series of functions (...(f3(f2(f1(*args, **kwargs))))) into
    a single composite function which passes the result of each
    function as the argument to the next, from the first to last
    given.
    """
    return reduce(lambda f, g:
                    lambda *args, **kwargs: f(g(*args, **kwargs)),
                        reversed(funcs))

rawDescription: How can I automatically run all the functions in the module?

description: Automatically run all the functions in the module


code:
#!/usr/bin/python

import re
import sys
import datetime

# String from Date/Time Delta:
#  Takes a datetime.timedelta object, and converts the internal values
#  to a dd:HH:mm:ss:ffffff string, prefixed with "-" if the delta is
#  negative
def strfdelta(tdelta):

    # Handle Negative time deltas
    negativeSymbol = ""
    if tdelta < datetime.timedelta(0):
        negativeSymbol = "-"

    # Convert days to seconds, as individual components could
    # possibly both be negative
    tdSeconds = (tdelta.seconds) + (tdelta.days * 86400)

    # Capture +/- state of seconds for later user with milliseonds calculation
    secsNegMultiplier = 1
    if tdSeconds < 0:
        secsNegMultiplier = -1

    # Extract minutes from seconds
    tdMinutes, tdSeconds = divmod(abs(tdSeconds), 60)

    # Extract hours from minutes
    tdHours, tdMinutes = divmod(tdMinutes, 60)
    # Extract days from hours
    tdDays, tdHours = divmod(tdHours, 24)

    # Convert seconds to microseconds, as individual components
    # could possibly both be negative
    tdMicroseconds = (tdelta.microseconds) + (tdSeconds * 1000000 * secsNegMultiplier)

    # Get seconds and microsecond components
    tdSeconds, tdMicroseconds = divmod( abs(tdMicroseconds), 1000000)

    return "{negSymbol}{days}:{hours:02d}:{minutes:02d}:{seconds:02d}:{microseconds:06d}".format(
        negSymbol=negativeSymbol,
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)

# Date/Time delta from string
# Example: -1:23:32:59:020030 (negative sign optional)
def deltafstr(stringDelta):

    # Regular expression to capture status change events, with groups for date/time,
    #  instrument ID and state
    regex = re.compile("^(-?)(\d{1,6}):([01]?\d|2[0-3]):([0-5][0-9]):([0-5][0-9]):(\d{6})$",re.UNICODE)
    matchObj = regex.search(stringDelta)

    # If this line doesn't match, return None
    if(matchObj is None):
        return None;

    # Debug - Capture date-time from regular expression
    # for g in range(0, 7):
    #     print "Grp {grp}: ".format(grp=g) + str(matchObj.group(g))

    # Get Seconds multiplier (-ve sign at start)
    secsNegMultiplier = 1
    if matchObj.group(1):
        secsNegMultiplier = -1

    # Get time components
    tdDays = int(matchObj.group(2)) * secsNegMultiplier
    tdHours = int(matchObj.group(3)) * secsNegMultiplier
    tdMinutes = int(matchObj.group(4)) * secsNegMultiplier
    tdSeconds = int(matchObj.group(5)) * secsNegMultiplier
    tdMicroseconds = int(matchObj.group(6)) * secsNegMultiplier

    # Prepare return timedelta
    retTimedelta = datetime.timedelta(
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)

    return retTimedelta;

rawDescription: Python timedelta object - strfdelta and deltafstr functions for conversion of timedelta -> string -> timedelta


code:
from datetime import datetime, date, time

midnight = datetime.combine(date.today(), time.min)

rawDescription: What was midnight yesterday as an epoch time?


code: output = ''.join([x[0] for x in phrase.split()])[:-1]

rawDescription: using find in python

description: Using find in python


code:
import matplotlib.pyplot as plt
nx.draw(G)
plt.show()

rawDescription: Merging 3 dict()'s in python

description: Merging 3 dict()'s in python


code: value.split('W', 1)[0]

rawDescription: How to get part of string and pass it to other function in python?

description: Get part of string and pass it to other function in python


code:
url='https://raw.githubusercontent.com/108michael/ms_thesis/master/test_state_gdp'

df=pd.read_csv(url, index_col=0)

for c in df.columns:
    if str(c).startswith('20'):
        df[c] = pd.to_numeric(df[c], errors='coerce')

rawDescription: pandas: to_numeric for multiple columns

description: Pandas: to_numeric for multiple columns


code:
for item in items:
    item.setFlags(Qt.NoItemFlags)

rawDescription: How to Disable and Enable selection for a item in QListWideget using Python


rawDescription: Min index built-in function

description: Min index built-in function


code: Scrollbar(listNodes, orient="vertical")

rawDescription: Python Tkinter: Attach scrollbar to listbox as opposed to window


rawDescription: Is it possible to query multiple datastore keys in single query?


code:
import numpy
lookupNearest(5.1, 4.9)
lookupNearest(3.54, 6.9)

rawDescription: 2D Nearest Neighbor Interpolation in Python


rawDescription: Django template/form for user input

description: Django template/form for user input


code:
def get_numbers():
    numbers = []
    for file in get_files('folder'):
        line = get_line(file)
        components = line.split(' ')
        number = float(components[-1])
        numbers.append(number)
    return numbers

rawDescription: How to read datas from several files with python

description: Read datas from several files with python


code:
regex = re.compile(r"""
    -?    # Optional minus sign
   (?:    # Start of the first non-capturing group:
    \d+   #  Match a number (integer part)
    ()    #  Match the empty string, capture in group 1
   )?     # Make the first non-capturing group optional
   (?:    # Start of the second non-capturing group:
    \.\d* #  Match a dot and an optional fractional part
    ()    #  Match the empty string, capture in group 2
   )?     # Make the second non-capturing group optional
   (?:    # Start of the third non-capturing group:
    e     #  Match an e or E
    -?    #  Match an optional minus sign
    \d+   #  Match a mandatory exponent
    ()    #  Match the empty string, capture in group 3
   )?     # Make the third non-capturing group optional
  (?:     # Now make sure that at least the following groups participated:
   \2     #  Either group 2 (containing the empty string)
  |       # or
   \1\3   #  Groups 1 and 3 (because "1" or "e1" alone aren't valid matches)
  )""", re.I|re.X)

rawDescription: Regex for Matching a Floating Point Number which is not an Integer


code:
animals = {'dog':set(['bite']),
           'cat':set(['bite', 'scratch'])}

rawDescription: Check if value exists in nested lists

description: Check if value exists in nested lists


code: df.loc[mask_0] = 0

rawDescription: Fill NaN in candlestick OHLCV data

description: Fill NaN in candlestick OHLCV data


code:
with open('test_file.txt','r') as f :
 lines =list(f)

rawDescription: How to Empty Lines?

description: Empty Lines