rawDescription: Most efficient way of splitting strings like rubik's cube notations in python?


code: m = [row for row in l if 'a' in row[0]]

rawDescription: Filter array to show rows with a specific value in a specific column


code:
{'Death': True,
 'Death Time': datetime.datetime(2010, 11, 11, 13, 0),
 'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
 'Sex': 'Male',
 'Symptoms': ['got nausea', 'vomiting']}

{'Death': True,
 'Death Time': datetime.datetime(2010, 11, 11, 10, 0),
 'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
 'Sex': 'Female',
 'Symptoms': ['got heart burn', 'vomiting of blood']}

rawDescription: Medical information extraction using Python


code: {'_Test__wrapper': {'SKIP ME': 'wrapped value'}, 'wrapped_value': 'wrapped value', 'my': 'my'}

rawDescription: Python: retrieve  all properties of a class instance that uses the @property annotation


code:
def __getattr__(self, name):
    return self.tables[name]

rawDescription: Using Class method to add a Class variable


code:
import numpy as np

infile = np.loadtxt('foo1')
infile1 = np.loadtxt('foo2')

index = np.invert(infile==infile1).astype(int)
totalSum = sum(sum(index))

np.savetxt('outFile', index, fmt='%d')

rawDescription: Comparing the individual values in two separate files such that if same, assign value 0 else 1 in python


code:
# draw background
for y in range(32):
    ...

camera.update(player) # camera follows player. Note that we could also follow any other sprite

# update player, draw everything else
player.update(up, down, left, right, running, platforms)
for e in entities:
    # apply the offset to each entity.
    # call this for everything that should scroll,
    # which is basically everything other than GUI/HUD/UI
    screen.blit(e.image, camera.apply(e))

pygame.display.update()

rawDescription: Add scrolling to a platformer in pygame

description: Add scrolling to a platformer in pygame


rawDescription: Filter DataFrame rows that are lists

description: Filter DataFrame rows that are lists


rawDescription: What is Python 's default setting for width on String Operations and how is it different that "0"?


code:
doubles = dict()

for x in range(1, 13):
    doubles[x] = x * 2

rawDescription: Using a loop in Python to name variables


code:
for number, (start, end) in enumerate((item, item+(x//y-1)) for item in range(1, x, x//y)):
    print(number, "starts at", start, "and ends at", end)

rawDescription: Python split equally

description: Python split equally


code:
import numpy as np
a = np.matrix([1,2,3,4])
d = np.diag(a.A1)
print (d)

rawDescription: How to convert a column or row matrix to a diagonal matrix in Python?

description: Convert a column or row matrix to a diagonal matrix in Python


code:
for i in range(len(max(signs_list)), 0, -1):
    print ('{0:<8} {1:<8} {2}').format(
        'x' if len(signs_list[0]) >= i else '',
        'x' if len(signs_list[1]) >= i else '',
        'x' if len(signs_list[2]) >= i else '')
print ('{0:<8} {1:<8} {2}').format(test_string_list[0], test_string_list[1], test_string_list[2])
print ('{0:<8} {1:<8} {2}').format(test_list[0], test_list[1], test_list[2])

rawDescription: Basic Python List Excercise

description: Basic Python List Excercise


code: t

rawDescription: Resample time-series of position evenly in time


rawDescription: efficient way to count the element in a dictionary in Python using a loop

description: Efficient way to count the element in a dictionary in Python using a loop


rawDescription: Input to list and operate on it

description: Input to list and operate on it


code:
import string
string.capwords("john's school")

rawDescription: Python title() with apostrophes

description: Python title() with apostrophes


rawDescription: Counting qualitative values based on the date range in Pandas


rawDescription: Omit iterator in list comprehension?

description: Omit iterator in list comprehension


rawDescription: Getting unique items from a two dimensional array python


code:
class Team(Base):
    __tablename__ = "teams"

    id = Column(Integer, primary_key=True)
    name = Column(String)

    @property
    def matches(self):
        return self.matches_to + self.matches_from

class Match(Base):
    __tablename__ = "matches"
    id = Column(Integer, primary_key=True)
    first_opponent_id = Column(Integer, ForeignKey("teams.id"))
    second_opponent_id = Column(Integer, ForeignKey("teams.id"))

    first_opponent = relationship(
        "Team", backref=backref('matches_to'),
        foreign_keys=[first_opponent_id],
    )
    second_opponent = relationship(
        "Team", backref=backref('matches_from'),
        foreign_keys=[second_opponent_id],
    )

rawDescription: Backreferencing twice to the same name in sqlalchemy


code:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-m')
group.add_argument('-u')

args = parser.parse_args()  # will output a error message if '-m' or '-u' isn't supplied

rawDescription: Argument checks best practices

description: Argument checks best practices


rawDescription: How to merge two arrays together, concatenating the corresponding elements?

description: Merge two arrays together, concatenating the corresponding elements


code:
for i, elem in enumerate(a):
    if elem > 2200:
         z[i][str(i+1)] += 1

rawDescription: Python matching one list to dict values in another list


code:
def foo(cur=None):
    inside_larger_transaction = False
    if cursor is None:
        db = connect()
        cur = db.cursor()
        inside_larger_transaction = True
    try:
        cur.execute(...)
        if not inside_larger_transaction:
             conn.commit()
    except:

        conn.rollback()

rawDescription: Sharing MySQLdb transactions across functions


code:
class foo:
    baz = 51
    def __init__(self):
        self.bar = 42

rawDescription: How to know which vars are defined in a class

description: Know which vars are defined in a class


code:
with open('myfile.txt', 'r') as myfile:
    print([[myitem for myitem in item.strip().split(' ')] for item in myfile.read().split('< NEW DOCUMENT>') if item])

rawDescription: How to count the articles and place each in a list

description: Count the articles and place each in a list


code:
D1.rename( columns={0:'mean',1:'median',2:'sd'}, inplace=True) # should match the list order in S1
D1.reset_index(drop=True,inplace=True) # reset the funky index
#   mean  median   sd
#0    51  50.000  0.3
#1     2   0.816  0.2

rawDescription: Pandas How to convert from series to a data frame


rawDescription: How to efficiently modify all elements of a list of lists and add them to the existing list of lists

description: Efficiently modify all elements of a list of lists and add them to the existing list of lists


code: result = re.findall(r': (£\d*)', search_text)

rawDescription: Searching for text in Beautifulsoup

description: Searching for text in Beautifulsoup


code:
def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

sentence = input('Sentence: ')
width = int(input('Width: '))

print('+-' + '-' * width + '-+')

for line in chunkstring(sentence, width):
    print('| {0:^{1}} |'.format(line, width))

print('+-' + '-'*(width) + '-+')

rawDescription: Dynamic border around text in python

description: Dynamic border around text in python


code: dtype=tuple([np.object] + [float]*35)

rawDescription: Import 36 columns in python for plotting, first column is date


rawDescription: Python regular expression

description: Python regular expression


code:
class Singleton(object):
   _instance = None
   def __new__(cls, *args, **kw):
       if cls._instance is not None:
           return cls._instance
       self = object.__new__(cls, *args, **kw)
       cls._instance = self
       return self

rawDescription: Python metaclasses configure classes. But can we configure metaclasses?


code:
phraseList = []

phrase = input('Please enter a phrase: ')

while phrase != 'END':
    phraseList.append(phrase)
    phrase = input('Please enter a phrase: ')

print(phraseList)

rawDescription: Saving User Inputs into a List in Python 3.5.1


code:
x = set() # or []
while True:
    data = input()
    if data.lower() == "done":
        break
    if data in x:
        x.discard(data) # or .remove(data)
    else:
        x.add(data) # or .append(data)

rawDescription: How to remove duplicate from string/mixed list

description: Remove duplicate from string/mixed list


code: my_dict['value2'] = my_dict.get('value2', []) + ['new value 4', 'new value 5']

rawDescription: transform php code to python - append new values to the same key in dict

description: Transform php code to python - append new values to the same key in dict


code:
import csv
from collections import defaultdict
from pandas import DataFrame

rdr = csv.reader(open('mat.txt'), delimiter=' ', skipinitialspace=True)
datacols = defaultdict(list)

# skip header
rdr.next()
for spec, dat, num in rdr:
    datacols['species'].append(int(spec))
    datacols['dates'].append(dat)
    datacols['data'].append(int(num))

df = DataFrame(datacols)
df2 = df.pivot(index='dates', columns='species', values='data')

rawDescription: Convert three column text file to matrix


code:
class mylist(list):
    def __iter__(self):
        print('iter has been called')
        return super(mylist, self).__iter__()

m = mylist([1,2,3])
[x for x in m]

rawDescription: What is a better pythonic version of this conditional deleting?


code:
player.center_pos[0] = player.pos[0] + player.sprite.get_size()[0] / 2
player.center_pos[1] = player.pos[1] + player.sprite.get_size()[1] / 2

rawDescription: Different size sprites in sprite sheet

description: Different size sprites in sprite sheet


code: [(x, lst2[i]) for i, x in enumerate(lst)]

rawDescription: how to get tuples from lists using list comprehension in python

description: Get tuples from lists using list comprehension in python


code:
keys = valuesB.keys()
C = {'a': [x[0] for x in keys], 'b': [x[1] for x in keys], 'value': [valuesB[x] for x in keys]}

rawDescription: Merge dictionaries with key combinations


code:
def negate(number, bits = 32):
    return "{:0{}b}".format(~number & 2 ** bits - 1, bits)

rawDescription: How to create Python fixed length bits?

description: Create Python fixed length bits


code:
zeros = [format(n, '016b').count('0') for n in range(1<<16)]
ones = [format(n, '016b').count('1') for n in range(1<<16)]

rawDescription: Get the the number of zeros and ones of a binary number in Python


code:
def select(lst, indices):
    return (lst[i] for i in indices)

rawDescription: Accessing non-consecutive elements of a list or string in python


code: myinput = myinput.split(",")

rawDescription: python add elements in a tuple

description: Python add elements in a tuple


rawDescription: How to check python codes by reduction?

description: Check python codes by reduction


rawDescription: How to use Django's filesizeformat

description: Use Django's filesizeformat


code:
url = '%s%scame_from=%s' % (url, sep, quote(came_from))
resp.redirect(url, lock=1)

rawDescription: how to generate custom 403 HTTP responses in Plone (prevent redirect)

description: Generate custom 403 HTTP responses in Plone (prevent redirect)


code:
def addVectors(v1, v2):
    min_length = min(len(v1), len(v2))
    result = [a + b for a, b in zip(v1, v2)]
    return result + v1[min_length:] + v2[min_length:]

rawDescription: Add sum of values of two lists into new one


code:
import re
result = re.sub("\D", "", html_string)[1:]

rawDescription: Python - Parse String

description: Python - Parse String


rawDescription: wxPython: How do you specify the width of a specific column using one of the wx.sizer classes?

description: WxPython: How do you specify the width of a specific column using one of the wx.sizer classes


code:
filelist=['file1','file2']
for file in filelist:
    [row1, row2, row3] = np.loadtxt(file,unpack=True,skiprows=1)
    #Do Stuff

rawDescription: Python: np.loadtxt, read multiple files

description: Python: np.loadtxt, read multiple files


code:
def writefile():
    fil = open(file, 'w')       # open file
    fil.truncate()              # truncate the contents of the file
    fil.write("Name\tScore")    # write heading
    for score in scores:        # write each record
        fil.write("\n%s\t%s" % (score['name'], score['score']))
    fil.close()                 # close file

rawDescription: Write dictionary data to file

description: Write dictionary data to file


rawDescription: Fast doubling Fibonacci Python generator sequence


rawDescription: How to fill a numpy array with a gradient with a vectorized code?

description: Fill a numpy array with a gradient with a vectorized code


code:
class Seq(object):
    def __init__(self, seq):
        self.seq = seq
    def __repr__(self):
        return repr(self.seq)
    def __str__(self):
        return str(self.seq)
    def all(self):
        return Seq(self.seq[:])
    def head(self, count):
        return Seq(self.seq[:count])
    def tail(self, count):
        return Seq(self.seq[-count:])
    def odd(self):
        return Seq(self.seq[1::2])
    def even(self):
        return Seq(self.seq[::2])
    def reverse(self):
        return Seq(self.seq[::-1])

rawDescription: chain the function as shell pipe command in python

description: Chain the function as shell pipe command in python


code:
(bins[pos-1] == values).all()
import sys
for n in range(len(values)):
    sys.stdout.write("%g <= %g < %g\n"
            %(bins[pos[n]-1], values[n], bins[pos[n]]))

rawDescription: assigning points to bins

description: Assigning points to bins


code:
ImD - Success
ImD - Success
ImD - Success
['VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess', 'VoG - Sucess']

rawDescription: Can't pickle static method - Multiprocessing - Python


code:
class C:
    x = None

rawDescription: Using @property versus accessing variables directly


code:
def whitelabel_processor(request):
    current_domain = request.get_host()
    whitelabel = Whitelabel.objects.filter(primary_domain=current_domain).order_by('id')

    if whitelabel.count() != 0:
        config = {
            'SITE_NAME': whitelabel[0].name,
            'SITE_LOGO': whitelabel[0].logo,
            'SITE_DOMAIN': whitelabel[0].primary_domain
            }
    else:
        config = {
            'SITE_NAME': 'MY SITE',
            'SITE_LOGO': '/static/images/logo.png',
            'SITE_DOMAIN': 'http://%s' % Site.objects.get_current().domain
            }

    return config

rawDescription: What is the common practice for white labeling a Django site?


code:
operands = OneOrMore(Word(alphanums))
precedence = [
    (":", 2, opAssoc.LEFT),
    ("->", 2, opAssoc.LEFT),
    ]
parser = operatorPrecedence(operands, precedence)
def parse(s): return parser.parseString(s, parseAll=True)
print(parse('a:b -> c : d e'))
print(parse('caffeine : A1 antagonist -> caffeine : peripheral stimulant'))

rawDescription: syntactic whitespaces with pyparsing's operatorPrecedence

description: Syntactic whitespaces with pyparsing's operatorPrecedence


code:
import dis
def f(): "lose"

dis.dis(f)

rawDescription: How to use Python 3.4's enums without significant slowdown?

description: Use Python 3.4's enums without significant slowdown


code:
def bar(s):
    return s + '!'
x = 'blah'
x = bar(x)
x

rawDescription: Python: How do I pass a string by reference?


code:
def opendocx(file):
    '''Open a docx file, return a document XML tree'''
    mydoc = zipfile.ZipFile(file)
    xmlcontent = mydoc.read('word/document.xml')
    document = etree.fromstring(xmlcontent)
    return document

rawDescription: Text-Replace in docx and save the changed file with python-docx


code:
mydict = {"Pens": 1, "Pencils": 2, "Paper": 3}
with open('myfile.json' , 'r+') as f:
   d = json.load(f)
   d.update(mydict)
   f.seek(0)
   json.dump(d, f)

rawDescription: combine two json dictionary python

description: Combine two json dictionary python


code:
from lxml import etree
from cStringIO import StringIO

wbr_html = """\
<html>
  <head>
    <title>wbr test</title>
  </head>
<body>
  Test for a breakable<wbr>word implemenation change
</body>
</html>
"""

parser = etree.HTMLParser()
tree   = etree.parse(StringIO(wbr_html), parser)

result = etree.tostring(tree.getroot(),
                         pretty_print=True, method="html")
if result.split() != wbr_html.split(): # split, as we are not interested in whitespace differences
    print(result)
    print("not ok")
else:
    print("OK")

rawDescription: lxml and <wbr> tags

description: Lxml and <wbr> tags


rawDescription: Python use last x lines

description: Python use last x lines


rawDescription: How can i do calculations on subsets , Panda's way, without looping

description: Do calculations on subsets , Panda's way, without looping


code:
#!/usr/bin/env python3

import csv
import decimal

with open('CalledData', newline='') as csvfile:
    csv_r = csv.reader(csvfile, delimiter=',', quotechar='|')

    # btw this creates a dict, not a set
    collected_statistics = {}

    for row in csv_r:

        [country_code, number_called, call_price, call_duration] = row

        # Only to avoid the first line, but would be better to have a list of available
        # (and correct) codes, and check if the country_code belongs to this list:
        if country_code != 'CountryCode':

            call_price = call_price if call_price != 'None' else 0

            if country_code not in collected_statistics:
                collected_statistics[country_code] = {'CallDuration' : [int(call_duration)],
                                                      'CallPrice' : [decimal.Decimal(call_price)]}
            else:
                collected_statistics[country_code]['CallDuration'] += [int(call_duration)]
                collected_statistics[country_code]['CallPrice'] += [decimal.Decimal(call_price)]

    for country_code in collected_statistics:
        print(str(country_code) + ":")
        print("number of times called: " + str(len(collected_statistics[country_code]['CallDuration'])))
        print("total price: " + str(sum(collected_statistics[country_code]['CallPrice'])))
        print("total call duration: " + str(sum(collected_statistics[country_code]['CallDuration'])))

rawDescription: Python Adding multiple data points in a dict from CSV file


code:
class GenericSideEffect():
    def __init__(self, f, *args, **kwargs):
        self.v_function = f
        self.args = args
        self.kwargs = kwargs
        self._return_value = Exception("Never Called")

    def __call__(self):
        try:
            self._return_value = self.v_function(*self.args, **self.kwargs)
            return self._return_value
        except Exception as e:
            self.return_value = e
            raise e

    @property
    def return_value(self):
        if isinstance(self._return_value, Exception):
            raise self._return_value
        return self._return_value

rawDescription: Is it possible to query a Python mock object for the return values of its calls?


code:
from collections import deque

sentence = [0, 1, 2, 3, 4]

stack1 = deque(sentence)
stack2 = deque([])

print(stack1, stack2)

def do_it(st1, st2):
    item = st1.popleft()
    st2.append(item)

while stack1:
    do_it(stack1, stack2)
    # Do some stuff here
    do_it(stack1, stack2)

print(stack1, stack2)

rawDescription: For loop stacks and external functions without repeating popleft()


code:
#!/usr/bin/python

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self, word=None):
        self.write("word is %s\n" % word)
        self.write("uri is %s\n" % self.request.uri)
        self.write("q is %s\n" % self.get_argument("q"))

application = tornado.web.Application([

(r"/system/(.+)",MainHandler),

])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado Url Not Match with ? ("Interrogation") Sign


code:
adj_mat = numpy.loadtxt(filename)
net = networkx.from_numpy_matrix(adj_mat, create_using=networkx.DiGraph())

rawDescription: import csv matrix to create a weighted and directed network in networkx python

description: Import csv matrix to create a weighted and directed network in networkx python


code:
def logical_equiv(function1, function2, *args):
    return function1(*args) == function2(*args)

rawDescription: Getting the return value of functions passed in as variables


code:
import config
login(config.username, config.password)

rawDescription: Storing the secrets (passwords) in a separate file


code:
def display(request):
  return render_to_response('template.tmpl', {'obj': models.Book.objects.all()})

rawDescription: Display from a table using Django

description: Display from a table using Django


rawDescription: spliting list and adding values

description: Spliting list and adding values


code:
def iterate_tests(test_suite_or_case):
    """Iterate through all of the test cases in 'test_suite_or_case'."""
    try:
        suite = iter(test_suite_or_case)
    except TypeError:
        yield test_suite_or_case
    else:
        for test in suite:
            for subtest in iterate_tests(test):
                yield subtest

rawDescription: Python unittest - get TestCase id's from nested TestSuite


code:
from grades import s
# if your first script is called grades.py
import random

name = 'carl'
score = random.randrange(0,100)
grade = 11
# you can directly use it without initializing it again.
s.score(name,score,grade)

rawDescription: Python Multiple file program

description: Python Multiple file program


rawDescription: Pandas force matrix multiplication

description: Pandas force matrix multiplication


code:
class Stack:
    # rest elided

    def __iter__(self):
        return self

    def next(self):
        try:
            return self.items.pop()
        except IndexError:  # empty
            raise StopIteration  # signal iterator is done

rawDescription: Stacks iteration python3

description: Stacks iteration python3


code:
ID_COLUMN = 0 # Asset_ID
PROP_COLUMNS = [
    ('PropSVC', 1),
    ('PropSVN', 2),
    ('PropTSC', 3),
    ('PropTSN', 4),
]

rawDescription: Process CSV in Python

description: Process CSV in Python


code:
def grps(a):
    it = iter(a)
    prev = next(it)
    start, spk = prev[0], prev[2]
    for ele in it:
        if spk != ele[2]:
            yield [start, prev[1], spk]
            start = ele[0]
            spk = ele[2]
        prev = ele
    yield start, ele[1], spk

rawDescription: Mapping diagonal elements recursively and check for condition, Python


code:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

rawDescription: Consecutive indices of a Python list in for loop, without specifying indices


code:
{k: (dict1.get(k, 0), dict2.get(k, 0))
 for k in dict1.viewkeys() | dict2.viewkeys()}

rawDescription: Best way of adding two lists?

description: Best way of adding two lists


code:
from math import (floor, ceil)
def trunc_div(a, b):
    c = a / b
    return floor(c) if c > 0 else ceil(c)

rawDescription: Truncating division in Python 3.2

description: Truncating division in Python 3.2


code:
import numpy as np
a = np.array([[1, 5, np.nan, 6],
              [10, 6, 6, np.nan]]).transpose()
a

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

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


code:
my_honeycomb[0][0] # 'a'
my_honeycomb[2][3] # 'k'
my_honeycomb[1][7] # IndexError

rawDescription: Storing data in a hexagonal grid for word search Python


code:
if __name__ == '__main__':
    with open('report.log', 'r') as logfile:
        with open('report.csv', 'wb') as csvfile:
            csvwriter = csv.writer(csvfile)

            header = extract_fields(logfile)
            csvwriter.writerow(header)

            for line in logfile:
                d = convert_to_dict(line, header)
                csvwriter.writerow([d[cell] for cell in header])

rawDescription: Parse Specific Text File to CSV Format with Headers


code: myOldStrValue|int

rawDescription: Convert integer to string Jinja

description: Convert integer to string Jinja


code: pd.read_csv("oniwa.dat", sep="\t", index_col=False) # hooray!

rawDescription: pandas shifts column names and fills last column with NAN

description: Pandas shifts column names and fills last column with NAN


code: {a:{b:c} for a,b,c in e}

rawDescription: How to convert a tuple to a dict?

description: Convert a tuple to a dict


code:
def __init__(self):
    self.connection = MySQLdb.connect(host, user, password, db)
    self.cursor = self.connection.cursor()

rawDescription: Login into Server AND MySQL from Python

description: Login into Server AND MySQL from Python


code:
from ast import literal_eval
s = "('x',),('y',)"
literal_eval(s)

rawDescription: Prevent outer double quotes in my list

description: Prevent outer double quotes in my list


code:
import csv
list_results = ['False, 60, 40 ', 'True, 70, 30, ']
import csv
import sys
list_results = ['False, 60, 40 ', 'True, 70, 30, ']
writer = csv.writer(sys.stdout)
writer.writerow(('Correct?', 'Successes', 'Failures'))
for row in list_results:
    columns = [c.strip() for c in row.strip(', ').split(',')]
    writer.writerow(columns)
writer.writerows([c.strip() for c in r.strip(', ').split(',')]
                 for r in list_results)

rawDescription: csv: writer.writerows() splitting my string inputs

description: Csv: writer.writerows() splitting my string inputs


code:
from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse

class MockUrlConf(object):
    urlpatterns = patterns('', url(r'^foo/$', lambda request: None, name='foo'))

reverse('foo', MockUrlConf)

rawDescription: How to make a simple Django URLconf and reverse() on it for a test? (getting TypeError: unhashable type: 'list')

description: Make a simple Django URLconf and reverse() on it for a test? (getting TypeError: unhashable type: 'list')


code:
from contextlib import contextmanager

@contextmanager
def terminating(obj):
    try:
        yield obj
    finally:
        obj.terminate()

def computeStuff(arguments, globalData, concurrent=True):
    with terminating(multiprocessing.Pool(initializer=initWorker, initargs=(globalData,))) as pool:
        return pool.map(workerFunction, enumerate(arguments))

rawDescription: Why won't Python Multiprocessing Workers die?


code:
from selenium import webdriver
dr = webdriver.PhantomJS()
dr.get("http://50.17.237.182/PIM/")
print(dr.find_element_by_id("addressInput"))

rawDescription: Selenium webdriver with python to scrape dynamic page cannot find element


code:
A
A[:,None]

rawDescription: Row-wise scaling with Numpy

description: Row-wise scaling with Numpy


code:
from django.contrib.auth.models import User
from django.db import models
from tastypie.models import create_api_key

models.signals.post_save.connect(create_api_key, sender=User)

rawDescription: Django Tastypie: How to Authenticate with API Key


code: filtered_ls = [x for x in ls if okay(x)]

rawDescription: Iterating through a list using for loops in Python3


code:
"""This file is loaded when starting a new application instance."""
import sys
import os.path

# add `lib` subdirectory to `sys.path`, so our `main` module can load
# third-party libraries.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))

rawDescription: How do I manage third-party Python libraries with Google App Engine? (virtualenv? pip?)

description: Manage third-party Python libraries with Google App Engine? (virtualenv? pip?)


code:
from weakref import WeakKeyDictionary
from cPickle import dumps

class Monitor():
    def __init__(self):
        self.objects = WeakKeyDictionary()
    def is_changed(self, obj):
        current_pickle = dumps(obj, -1)
        changed = False
        if obj in self.objects:
            changed = current_pickle != self.objects[obj]
        self.objects[obj] = current_pickle
        return changed

class MyObject():
    def __init__(self):
        self.i = 1
    def change_somehow(self):
        self.i += 1

rawDescription: Python object that monitors changes in objects


code:
def spider_closed(self, spider):
    files = []

    for name, contents in self.files.items():
        contents.seek(0)

        files.append((name, 'text/plain', contents))

    return self.mail.send(
        to=self.recipients,
        subject="Crawler for %s finished" % spider.name,
        body="",
        attachs=files
    )

rawDescription: Emailing items and logs with Scrapy

description: Emailing items and logs with Scrapy


code:
for i, el in enumerate(x):
    for j in x[i:]:
        calc_something(el, j)

rawDescription: Calculate all unique permutations using nested loops in Python


code:
means
stacked = means.stack().reset_index(level=2)
stacked.columns = ['group_level', 'mean']
stacked.head(2)

rawDescription: Attributes/information contained in DataFrame column names


code:
def overlap(first_inter,second_inter):
    for f,s in ((first_inter,second_inter), (second_inter,first_inter)):
        #will check both ways
        for time in (f["starting_time"], f["ending_time"]):
            if s["starting_time"] < time < s["ending_time"]:
                return True
    else:
        return False

rawDescription: Checking two time intervals are overlapping or not


code:
POLYNOMIAL = 0x1021
PRESET = 0

def _initial(c):
    crc = 0
    c = c << 8
    for j in range(8):
        if (crc ^ c) & 0x8000:
            crc = (crc << 1) ^ POLYNOMIAL
        else:
            crc = crc << 1
        c = c << 1
    return crc

_tab = [ _initial(i) for i in range(256) ]

def _update_crc(crc, c):
    cc = 0xff & c

    tmp = (crc >> 8) ^ cc
    crc = (crc << 8) ^ _tab[tmp & 0xff]
    crc = crc & 0xffff
    print (crc)

    return crc

def crc(str):
    crc = PRESET
    for c in str:
        crc = _update_crc(crc, ord(c))
    return crc

def crcb(*i):
    crc = PRESET
    for c in i:
        crc = _update_crc(crc, c)
    return crc

rawDescription: CRC-CCITT 16-bit Python Manual Calculation


code:
Solution
# assign as variable because I'm going to use it more than once.
s = (df.index.to_series() / 5).astype(int)

df.groupby(s).std().set_index(s.index[4::5])

rawDescription: Pandas' equivalent of resample for integer index


rawDescription: How to add a value to a key in dictionary in Python

description: Add a value to a key in dictionary in Python


code:
import numpy as np
from sklearn.svm import SVC

x = np.random.randn(40, 7)  # 7 features, 40 samples
y = ['D', 'B', 'A', 'C'] * 10  # four classes
svc = SVC(kernel='linear').fit(x, y)

print(svc.classes_)  # ['A', 'B', 'C', 'D']
print(svc.coef_.shape)  # (6, 7)

rawDescription: Sklearn SVM coefficient attribute - how to get class name?


rawDescription: Create CSR matrix from x_index, y_index, value


code: [a-b for a, b in zip(data[key1], data[key2])]

rawDescription: Python - Subtract 2 lists from each other that are in a dictionary


code: re.search(r"\bis\b", String).start()

rawDescription: Python - Locating the position of a regex match in a string?


rawDescription: How to split a string to sequences of odd numbers?

description: Split a string to sequences of odd numbers


rawDescription: Scrapy not collecting data

description: Scrapy not collecting data


code: get_grad = theano.function([inputs, targets], grad)

rawDescription: Lasagne / Theano gradient values

description: Lasagne / Theano gradient values


code: stream = io.StringIO(unicode(request.FILES['foo'].read()), newline=None)

rawDescription: How can I access an uploaded file in universal-newline mode?

description: Access an uploaded file in universal-newline mode


rawDescription: Nested list to nested dictionary in python


code: map(lambda x:x[0].split(','),lis)

rawDescription: Split a delimiter in a list of list when delimiter may be both present and absent


code:
R,C = np.triu_indices(N,1)
out = np.einsum('ij,ij->j',pts[:,R],pts[:,C])

rawDescription: Processing upper triangular elements only with NumPy einsum


code:
def countPositive(nums):
    return len(filter(lambda x: x > 0, nums))

rawDescription: Writing a function in Python that returns a count of the numbers in an array that are greater than zero


code:
for item in thelist:
  thefile.write("%s\n" % item)

rawDescription: Writing a list to a file with Python

description: Writing a list to a file with Python


code:
li = ['1 ', '2', '3 ', '4', '5 ', '6', '7 ']
map(int, li)
list(map(int, li))
for elem in map(int, li):
    print(elem)

rawDescription: how to change the type of items in the list?

description: Change the type of items in the list


code:
from collections import Counter
string1 = "aadsfytggfbbhieenoohghgsfdetsuhbdfvd"
string2 = "dfgthhdqqaaiirrthhnnoogsfdet"
counter1 = Counter(string1)
counter2 = Counter(string2)
print(counter1)
# Counter({'f': 4, 'g': 4, 'd': 4, 'h': 4, 's': 3, 'b': 3, 'e': 3, 'o': 2,
#          't': 2, 'a': 2, 'i': 1, 'u': 1, 'n': 1, 'v': 1, 'y': 1})
print(counter2)
# Counter({'h': 4, 'd': 3, 't': 3, 'i': 2, 'f': 2, 'g': 2, 'o': 2, 'n': 2,
#          'q': 2, 'r': 2, 'a': 2, 's': 1, 'e': 1})

rawDescription: How to compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists

description: Compare the value of the key in Dict 1 is "==" or"!=" value of the same key in Dict2,if exists


rawDescription: output of numpy.where(condition) is not an array, but a tuple of arrays: why?

description: Output of numpy.where(condition) is not an array, but a tuple of arrays: why


rawDescription: theano error from keras

description: Theano error from keras


code:
m.tolist()[0][0] # seldom useful, though
m.flat[0]  # more frequently useful

rawDescription: Python Numpy Matrix - Return the value contained in the matrix?


code:
def on_button_clicked(b):
    choice = b.description
    b.color = 'white'
    b.background_color = 'green' if choice == correct else 'red'
    time.sleep(5)
    container.close()
    clear_output()
    redraw()

rawDescription: Using ipywidget for multiple choice test


code:
studentlist=[]
a=1
while a!=0:
    print ("""
1. Add new student records
2. Show all student records
3. Delete a student record
4. Dislay overall average coursework mark
5. Display overall average exam mark
6. Calculate average marks
0. Exit
Plese select an option
       """)
    a=int(input(""))
    if a==1:
        promptdict1 = {'name': 'Enter a students name: ', \
                       'cmark': 'Enter the students coursework mark: ', \
                       'emark': 'Enter the students exam mark: '}
        studentlist.append({'name': input(promptdict1['name']), \
                            'cmark': int(input(promptdict1['cmark'])), \
                            'emark': int(input(promptdict1['emark']))})
        print(studentlist[-1])
    if a==2:
        promptdict2 = {'name': 'Name:', \
                       'cmark': 'Courswork mark:', \
                       'emark': 'Exam mark:'}
        for student in studentlist:
            print(promptdict2['name'], student['name'])
            print(promptdict2['cmark'], student['cmark'])
            print(promptdict2['emark'], student['emark'], '\n')
    if a==3:
        name=input("Enter a students name: ")
        for n in studentlist:
            if n['name']==name:
                studentlist.remove(n)

rawDescription: Removing tuple from list

description: Removing tuple from list


code:
import numpy as np
import pandas as pd

df = pd.DataFrame({'2012': [10, 8, 11], '2013': [12, 9, 11], '2014': [11, 10, 13]},
                  index='Jan Feb Mar'.split())

result = df.stack()
dates = pd.to_datetime([' '.join(item) for item in result.index])
days = dates.days_in_month
result = (result / days).unstack()
print(result)

rawDescription: Applying cell wise function in a dataframe


code:
inds, gens = [], []
for i, p in df["Pos"].iteritems():
    for g in pos_to_gene[p]:
        inds.append(i)
        gens.append(g)
gene = pd.Series(gens, inds)

rawDescription: Adding list of values to rows, turning the dataframe into long format afterwards


code:
small_combinations = make_combinations(small_drivers, small_vehicles)
medium_combinations = make_combinations(medium_drivers, medium_vehicles)
large_combinations = make_combinations(large_drivers, large_vehicles)

all_combinations = small_combinations + medium_combinations + large_combinations

rawDescription: What is an elegant way to solve this max and min problem in Ruby or Python?


code:
import httplib
import logging
import random
import StringIO
import time
import unittest
from nova.api import openstack
from nova.auth import users
from nova.endpoint import cloud

rawDescription: What's the correct way to sort Python `import x` and `from x import y` statements?


code:
def fill(shape,value):
    if not shape: return value
    return [fill(shape[1:],value) for i in range(shape[0])]

rawDescription: Initialize arbitrarily shaped nested list


label: Anonymous lifestyle App cflw`2B2[h1s`lNzF@sPC1FtaCiK0VF@

rawDescription: Python: remove ^A in a string

description: Python: remove ^A in a string


code: ax3 = subplot(313,  sharex=ax1, sharey=ax1)

rawDescription: With MatPlotLib, how do I apply autoscaled axes from one graph to a separate graph?


rawDescription: Fill out login information with selenium


rawDescription: Change elements in 2d ndarray into arrays


rawDescription: How to split a string into a list, taking negative numbers into account?

description: Split a string into a list, taking negative numbers into account


rawDescription: mutable objects changed in-place means what?

description: Mutable objects changed in-place means what


rawDescription: world map without rivers with matplotlib / Basemap?

description: World map without rivers with matplotlib / Basemap


code: parts

rawDescription: Unpacking a list of dictionaries based on key matches in Python


code:
def removeCommonElements(a, b):
    for e in a[:]:
        if e in b:
            a.remove(e)
            b.remove(e)

rawDescription: Removing common elements in two lists

description: Removing common elements in two lists


code:
#!/usr/bin/python
from tumblr import Api
import sys

BLOG='example.tumblr.com'
USER='example@example.com'
PASSWORD='example'
api = Api(BLOG,USER,PASSWORD)
api.write_photo('http://example.org/somewhere/lolcat.jpg')

rawDescription: Post picture to Tumblr using Python

description: Post picture to Tumblr using Python


code:
dict1 = {}
dict1['a'] = [[1,2], [3,4]]
dict1['b'] = [[5, 6], [42, 69], [220, 284]]

dict1.values()

[pairlist for pairlist in dict1.values()]
# No real difference here, but we can refer to each list now.

[pair for pairlist in dict1.values() for pair in pairlist]

# Finally...
[pair[1] for pairlist in dict1.values() for pair in pairlist]

rawDescription: Generating a list from complex dictionary


code:
def mymaxfunction(item):
    return sum(map(int, item))
max([['1', '2', '3'], ['7', '8', '9']], key=mymaxfunction)

rawDescription: How to find the list in a list of lists whose sum of elements is the greatest?

description: Find the list in a list of lists whose sum of elements is the greatest


code:
def bitfield(n):
    return [1 if digit=='1' else 0 for digit in bin(n)[2:]]

rawDescription: Integer to bitfield as a list

description: Integer to bitfield as a list


rawDescription: why \* escapes even when it is a raw string?

description: Why \* escapes even when it is a raw string


code:
import csv
import sys

with open('csv2.txt') as fp:
    top_row = next(fp)
    sys.stdout.write(top_row)
    reader = csv.reader(fp, skipinitialspace=True)
    writer = csv.writer(sys.stdout)
    writer.writerows(row for row in reader if row[2] == '1944')

rawDescription: How do I search for a specific field in a csv file then print the entire row in Python

description: Search for a specific field in a csv file then print the entire row in Python


code: import xml.etree.ElementTree as ET

rawDescription: Python Build Script for VBA Add-In file

description: Python Build Script for VBA Add-In file


code:
x = np.array([73.33999634, 73.340], dtype = np.float64)
y = np.around(x, decimals = 3)
y

rawDescription: Rounding numpy float array read from img with python, values returned not rounded


code:
def voxel_adjacency(voxel_communities):
    n_voxels = voxel_communities.size
    comm_labels = sorted(set(voxel_communities))
    comm_counts = [(voxel_communities == l).sum() for l in comm_labels]

    blocks = numpy.zeros((n_voxels, n_voxels), dtype=bool)
    start = 0
    for c in comm_counts:
        blocks[start:start + c, start:start + c] = 1
        start += c

    ix = numpy.empty_like(voxel_communities)
    ix[voxel_communities.argsort()] = numpy.arange(n_voxels)
    blocks[:] = blocks[ix,:]
    blocks[:] = blocks[:,ix]
    return blocks

rawDescription: Fill scipy / numpy matrix based on indices and values


code:
self.Bind(EVT_WX_LOG_EVENT, self.onLogEvent)

def onLogEvent(self,event):
    '''
    Add event.message to text window
    '''
    msg = event.message.strip("\r")+"\n"
    self.logwindow.AppendText(msg) # or whatevery
    event.Skip()

rawDescription: How can I redirect the logger to a wxPython textCtrl using a custom logging handler?

description: Redirect the logger to a wxPython textCtrl using a custom logging handler


code:
True
False
False
True
False

rawDescription: What is the best way to check if all bits are 1?


code:
class EmailNewReleasePipeline(base_handler.PipelineBase):
    """Email followers about a new release"""
    # TODO: product_key is the name of the parameter, but it's built for albums ...

    def run(self, product_key, testing=False):
            # Send those emails ...
            yield mapreduce_pipeline.MapreducePipeline(...)

    def finalized(self):
        """Save product as launched"""
        ...
        product.launched = True
        product.put()

rawDescription: Mapreduce on GAE Python - Cause ReducePipeline to issue callback on finalize?


rawDescription: Work with tuple of dictionaries

description: Work with tuple of dictionaries


code:
rule_defs = {
'and': lambda r: (lambda d, r1, r2: (match_rule(r1, d) and match_rule(r2, d), [compile_rule(r[1]), compile_rule(r[2])]))}

rawDescription: Getting a return value from Lambda python


rawDescription: Initialise list correctly

description: Initialise list correctly


code:
coordinates = [2, 1]
### do stuff with coordinates
i, j = coordinates
return room[i][j]

rawDescription: More pythonic method of indexing with a list of coordinates


code:
def foo(m, self_from_class):
    for i in xrange(m):
        i * 2
        self_from_class.pbar_det.step(1)
        self_from_class.update()
        time.sleep(0.1)
    return i

class MainWindow(Frame):

    # ...

    def start_fun(self):
        res = foo(500, self)

rawDescription: how to embed a Tkinter progressbar in a function in Python

description: Embed a Tkinter progressbar in a function in Python


code: some_name = BooleanColumn(attrs={'span': {'style': 'color:blue'}})

rawDescription: django-tables2 edit yesno parameter for all BooleanColumn

description: Django-tables2 edit yesno parameter for all BooleanColumn


code:
from bs4 import BeautifulSoup, NavigableString

html = '''

        this is the text i do NOT want

    this is the text i want here

'''

soup = BeautifulSoup(html)
outer = soup.div
inner_text = [element for element in outer if isinstance(element, NavigableString)]

rawDescription: Get text of HTML tags without text of inner child tags


rawDescription: What is the proper way to print a nested list with the highest value in Python


code:
import zipfile
from lxml import etree

def get_epub_info(fname):
    ns = {
        'n':'urn:oasis:names:tc:opendocument:xmlns:container',
        'pkg':'http://www.idpf.org/2007/opf',
        'dc':'http://purl.org/dc/elements/1.1/'
    }

    # prepare to read from the .epub file
    zip = zipfile.ZipFile(fname)

    # find the contents metafile
    txt = zip.read('META-INF/container.xml')
    tree = etree.fromstring(txt)
    cfname = tree.xpath('n:rootfiles/n:rootfile/@full-path',namespaces=ns)[0]

    # grab the metadata block from the contents metafile
    cf = zip.read(cfname)
    tree = etree.fromstring(cf)
    p = tree.xpath('/pkg:package/pkg:metadata',namespaces=ns)[0]

    # repackage the data
    res = {}
    for s in ['title','language','creator','date','identifier']:
        res[s] = p.xpath('dc:%s/text()'%(s),namespaces=ns)[0]

    return res

rawDescription: Python library to extract 'epub' information


code:
main()
main()
main()

rawDescription: Numerical value of a name

description: Numerical value of a name


code:
from scipy.spatial import cKDTree

def with_kd_tree(qX, trainX, k):
    dist, ind = cKDTree(trainX[:, :2]).query(qX, k)
    return trainX[ind, 2].mean(1)

np.allclose(with_broadcasting(qX, trainX, 4),
            with_kd_tree(qX, trainX, 4))
# True

rawDescription: Calculating distance between a set of points using np matrix calculations


code:
import matplotlib.pyplot as plt

fig,ax = plt.subplots()
balls = ax.scatter([-3, -1, 1, 3], [0, 0, 0, 0], c = ['r', 'b', 'g', 'm'], s = 4e4)
ax.set_xlim(-6,6)
ax.set_ylim(-6,6)

plt.savefig('balls_01.png')

def switch_scatter(pathcoll,a,b):

    # Switch offsets
    offsets = pathcoll.get_offsets()[:]
    offsets[[a,b]] = offsets[[b,a]]

    # Switch facecolors
    facecolors = pathcoll.get_facecolors()
    facecolors[[a,b]] = facecolors[[b,a]]

    # Switch sizes
    sizes = pathcoll.get_sizes()
    sizes[[a,b]] = sizes[[b,a]]

    # Set the new offsets, facecolors and sizes on the PathCollection
    pathcoll.set_offsets(offsets)
    pathcoll.set_facecolors(facecolors)
    pathcoll.set_sizes(sizes)

switch_scatter(balls,2,1)

plt.savefig('balls_02.png')

rawDescription: Set properties for specific patch in matplotlib.collections.PathCollection


code:
import pandas as pd

df = pd.read_csv("in.csv")

print(df.groupby(("A","B")).sum())

rawDescription: How to identify "keys" of a tuple/list of 3-item tuples?

description: Identify "keys" of a tuple/list of 3-item tuples


code:
from _example import *

def _patched_spam_init():
    ''' Monkey-patch Spam.__init__ to force the first argument to be
        iterable.

    '''
    # Get handle to delegate.
    _Spam_init = Spam.__init__

    # Patched method that delegates to the original.
    def patch(self, value):
        try:
            (x for x in value)
        except TypeError:
            value = [value]
        return _Spam_init(self, value)

    # Set __init__ to the patched method.
    Spam.__init__ = patch

_patched_spam_init()

rawDescription: Boost Python iterable convertible masking non-iterable constructor


rawDescription: How to make mechanize script multthread in python

description: Make mechanize script multthread in python


code:
df
df['   CENSUS_REGION']
df['   CENSUS_REGION'][11511]

rawDescription: reading specific cell in csv using pandas

description: Reading specific cell in csv using pandas


code: re.split("\W+", "The# dog.is.yelling$at!Me to" )

rawDescription: replace special chars to space and create list

description: Replace special chars to space and create list


code:
clf = make_pipeline(ExtractNames(), DictVectorizer(), LogisticRegressionCV())
clf.fit(df_train['name'], df_train['gender'])
df_test['predicted'] = clf.predict(df_test['name'])

rawDescription: How to store predicted classes matching the pre-vectorized X in Python Scikit-learn?

description: Store predicted classes matching the pre-vectorized X in Python Scikit-learn


code: next_iter = sorted(set(prev_iter + segment))

rawDescription: How to make a partition structure

description: Make a partition structure


code:
tr = "AND apple AND orangeOR banana"
re.split(r'\s?(?:AND|OR)\s?',tr)
re.split(r'[A-Z ]+',tr)
[i for i in re.split(r'[A-Z ]+',tr) if i]
re.findall(r'[^A-Z ]+',tr)

rawDescription: Python: how to split a string by multiple strings


rawDescription: How to find all the indices of all the elements in a 2d matrix using Python?

description: Find all the indices of all the elements in a 2d matrix using Python


code:
out = A.T + A
np.fill_diagonal(out,np.diag(A))

rawDescription: Convert triangle matrix to square (Python | NumPy)?


code:
def show_magicians(names):
    for name in names:
        print(name)

def make_great(magicians_names):
    for i in range(len(magicians_names)):
        magicians_names[i] += ' The Great'

magicians_names = ['Marv', 'Wowzo', 'Trickster', 'Didlo']

make_great(magicians_names)
show_magicians(magicians_names)

rawDescription: Passing a list to a function to be modified


rawDescription: Analysing Json file in Python using pandas


code:
def paste(str, p=True, c=True):
    from subprocess import Popen, PIPE

    if p:
        p = Popen(['xsel', '-pi'], stdin=PIPE)
        p.communicate(input=str)
    if c:
        p = Popen(['xsel', '-bi'], stdin=PIPE)
        p.communicate(input=str)

paste('Hello', False)    # pastes to CLIPBOARD only
paste('Hello', c=False)  # pastes to PRIMARY only
paste('Hello')           # pastes to both

rawDescription: Is there a way to directly send a python output to clipboard?


rawDescription: Python Emulate strptime behavor

description: Python Emulate strptime behavor


code: "ny" in (sublist[1] for sublist in lst)

rawDescription: serching for nested item in nested list [python]

description: Serching for nested item in nested list [python]


code:
a = numpy.arange(10)
numpy.random.shuffle(a)
a
rolling_window(a, 3) == [8, 4, 0]

rawDescription: Python/NumPy first occurrence of subarray


code:
fig = plt.figure(figsize=(8.0,6.0))
ax1 = fig.add_subplot(221)

vmax=30
levels_max=30
vmin=0
levels = np.linspace(vmin,levels_max,100)

z_contourR = ax1.contourf(xlist,ylist,z_matrixR,levels=levels,vmax=vmax,vmin=vmin)
plt.xlabel('x')
plt.ylabel('y')
plt.title('real')
cbarR = plt.colorbar(z_contourR)

vmax=30
levels_max=100
vmin=0
levels = np.linspace(vmin,levels_max,100)

ax2 = fig.add_subplot(222)
z_contourI = ax2.contourf(xlist,ylist,z_matrixI,levels=levels,vmax=vmax,vmin=vmin)
plt.xlabel('x')
plt.ylabel('y')
plt.title('imaginary')
cbarI = plt.colorbar(z_contourR)

plt.tight_layout()
plt.show()

rawDescription: Python same colorbar for subplots of real / imaginary contour plots of function


code:
from collections import Counter
c = Counter('hello')
c
for i,x in c.items():
    print('{} - {}'.format(i,x))

rawDescription: How to remove duplicates from a list python

description: Remove duplicates from a list python


code:
args = json.loads(request.values.get("args"))
columns = args.get("columns")

rawDescription: How to process server side parameter sent from jquery datatables using Flask?

description: Process server side parameter sent from jquery datatables using Flask


code:
from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import orm, MetaData, Column, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import column_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base(bind=engine)

class Note(Base):
    __tablename__ = 'notes'

    id_item = Column(Integer, ForeignKey('items.id'), primary_key=True)
    name = Column(String(20), primary_key=True)
    value = Column(String(100))

    def __init__(self, name, value):
        self.name = name
        self.value = value

class Item(Base):
    __tablename__ = 'items'
    id = Column(Integer, primary_key=True)
    name = Column(String(20))
    description = Column(String(100))
    _notesdict = relation(Note,
                          collection_class=column_mapped_collection(Note.name))
    notes = association_proxy('_notesdict', 'value', creator=Note)

    def __init__(self, name, description=''):
        self.name = name
        self.description = description

Base.metadata.create_all()

rawDescription: Dictionary of tags in declarative SQLAlchemy?


code:
from cProfile import Profile
p = Profile()

p.runctx('my_function(args)', {'my_function': my_function, 'args': my_data}, {})
p.print_stats()

rawDescription: How to optimize the memory and time usage of the following algorithm in python

description: Optimize the memory and time usage of the following algorithm in python


code:
class Message(object):
    def __init__(self, title, link, body):
        self.title = title
        self.link = link
        self.body = body

    def __str__(self):
        return ...
    def __repr__(self):
        return self.__str__()

rawDescription: Using a constantly changing variable to define a list


code:
def nonconsumesplitconcat(regex,content):
    outer = re.split(regex,content)
    inner = re.findall(regex,content)+['']
    return [pair[0]+pair[1] for pair in zip(outer,inner)]

rawDescription: Splitting longer patterns using regex without losing characters Python 3+


code:
def logout(request):
    """
    Removes the authenticated user's ID from the request and flushes their
    session data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if hasattr(user, 'is_authenticated') and not user.is_authenticated():
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)

    request.session.flush()
    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()

rawDescription: Does the django authentication logout function delete's session row in django_session table?


rawDescription: How do I turn this json object into a panda dataframe?

description: Turn this json object into a panda dataframe


rawDescription: Python: List of all unique characters in a string


rawDescription: Only extracting text from this element, not its children


code:
cat_order = {cat: i for i, cat in enumerate(category)}
inventory_sorted = sorted(inventory.items(),
                          key=lambda i: (cat_order[i[1][0]], -i[1][1]))

rawDescription: python dictionary sorted by list

description: Python dictionary sorted by list


code:
def twoNumValues(myList):
    return len(myList) == 2 and all(isinstance(i, int) or isinstance(i, float) for i in myList)

rawDescription: How to make sure if parameter is a list of numbers? (python)

description: Make sure if parameter is a list of numbers? (python)


code:
from pyspark.mllib.linalg import SparseVector, DenseVector, Vectors

aRDD = sc.parallelize(a).mapValues(DenseVector)
bRDD = sc.parallelize(b).mapValues(create_sparce_matrix)

rawDescription: Multiply SparseVectors element-wise

description: Multiply SparseVectors element-wise


code:
button = tkinter.Button(frame, height=0, bg='blue',\
                    activebackground='blue',width = 0, text = " ", image = self.blank, \
                    command=lambda row=row_index, \
                        column=column_index: \
                        self.button_clicked(row,column))

rawDescription: Disabling a button but visually keeping it as if it wasn't disabled


code: pd.DataFrame({col: [getattr(df[col], func)() for func in ('mean', 'std')] for col in df}, index=('mean', 'std'))

rawDescription: Pandas how to apply multiple functions to dataframe


code:
import numpy as np
import scipy.constants as consts
import matplotlib.pyplot as plt

epsilon=0.0038*consts.eV  #changed eV
k = consts.k  #changed
T = np.arange(1,2000,0.1)
beta = 1.0/(k*T) #changed to 1.0 for safe measure; redundant

#partitionfunction
s=np.arange(1,31,2)[:,None]
Zodd = (3*(2*s+1)*np.exp(-(s**2+s)*epsilon*beta)).sum(axis=0)

#energy
ln_Zodd = np.log(Zodd)  #changed to np.log
#Epara = - (ln_Zodd[1:]-ln_Zodd[:-1])/(beta[1:]-beta[:-1])  #manual version
Epara = - np.diff(ln_Zodd)/np.diff(beta)

#heat capacity
Cpara=np.diff(Epara)/np.diff(T)[:-1]

#plot
x = k*T/epsilon
plt.plot(x[:len(Cpara)],Cpara / k,'r')  #fixed and simplified array indices
plt.axis([0, 7, 0, 1.5])
plt.ylabel('C_v/k')
plt.xlabel('kT/eps')
plt.show()

rawDescription: Suggestions on matlab/python conversion

description: Suggestions on matlab/python conversion


code: newthread(foo)(some, params)

rawDescription: How to toggle the action of a decorator in Python3

description: Toggle the action of a decorator in Python3


code:
with open('data.txt') as infp:
   for line in infp:
       line = line.rstrip()
       # rest of processing

rawDescription: Discarding the '\n' symbol when reading a file, python


code: theFunction = call_all(Bar, Foo)

rawDescription: Adding lines to a function

description: Adding lines to a function


code:
df['B&C'] = np.where(df.B.isnull() & df.C.isnull(), 'Not There', 'Present')
df['B&C']

rawDescription: How to compare two columns and create new dataframe

description: Compare two columns and create new dataframe


code: MyModel(foo=[my_key, my_key2])

rawDescription: How to order an ndb query by a repeated field that can be empty

description: Order an ndb query by a repeated field that can be empty


code:
import webapp2
import os

# Models
from models.Shout import Shout

# Controllers
from controllers.HomeHandler import HomeHandler
from controllers.LoginHandler import LoginHandler
from controllers.ProfileHandler import ProfileHandler

if os.environ['SERVER_SOFTWARE'].startswith('Development'):
    app_scheme = 'http'
else:
    app_scheme = 'https'

app = webapp.WSGIApplication([
    webapp2.Route(r'/login', LoginHandler, name='login', schemes=[app_scheme]),
    webapp2.Route(r'/profile', ProfileHandler, name='profile', schemes=[app_scheme]),
    webapp2.Route(r'/', HomeHandler)
], debug=True)

rawDescription: How to use WSGI to reroute a user from http to https

description: Use WSGI to reroute a user from http to https


code:
bibliography = [
    { 'name': 'bdhar', 'summary': 'questioner' },
    { 'name': 'msw', 'content': 'an answer' },
]

rawDescription: A more "pythonic" approach to "check for None and deal with it"


code: sum(len(l) for _, l in mylist)

rawDescription: Python: how can I count the occurrences in a list of tuples?


rawDescription: When and why should I use a namedtuple instead of a dictionary?


code:
f = open("testfile.txt",'w')
write_cols(data,3,f)
f.close()

rawDescription: python, zip:Discard extra elements

description: Python, zip:Discard extra elements


code:
def statusbar(self):
    ...
    self.labelNumberOfLines = tk.Label(self.frameStatus)
    self.labelLinePosition = tk.Label(self.frameStatus)
    ...

def get_position(self):
    line, column = self.textView.index('insert').split('.')
    self.labelNumberOfLines.configure(text="Lines: {0}".format(lines))
    self.labelLinePosition.configure(text="Character: {0}".format(column))

rawDescription: Imposible change text in a tkinter label


code: alist = blist = clist = dlist = elist = []

rawDescription: Python - Initializing Multiple Lists/Line


code:
a = numpy.random.random(100)

@numpy.vectorize
def values(i):
    try:
        return (a[i:] > a[i]).nonzero()[0][0] + i
    except IndexError:
        return -1 # no valid values found

b = values(numpy.arange(100))

rawDescription: Numpy vectorization algorithms to find first future element greater than current element


rawDescription: Which information is returned when I type the name of a function in the Python interpreter?


rawDescription: Function that returns all sub-sequences in a list that are successive


code:
try:
    st = os.stat(path)
except OSError:
    if debug:
        cherrypy.log('os.stat(%r) failed' % path, 'TOOLS.STATIC')
    raise cherrypy.NotFound()

# ...

# Set Content-Length and use an iterable (file object)
#   this way CP won't load the whole file in memory
content_length = st.st_size
fileobj = open(path, 'rb')
return _serve_fileobj(fileobj, content_type, content_length, debug=debug)

rawDescription: How to get CherryPy to follow symbolic links?

description: Get CherryPy to follow symbolic links


code:
class SuperList (list):
    def __iadd__ (self, other):
        if type(other) == list or type(other) == SuperList:
            return super(SuperList, self).__iadd__(other)
        return super(SuperList, self).__iadd__ ([other])

rawDescription: make python @property handle +=, -= etc

description: Make python @property handle +=, -= etc


code:
while True:
    if count>1:
        oldfml=fml
    count=count+1
    fml=getFml()
    fml=parseFml(fml)
    if oldfml == fml:
        ...

rawDescription: Comparing Strings in Python 3

description: Comparing Strings in Python 3


rawDescription: Dynamically Generating Pandas Views

description: Dynamically Generating Pandas Views


code:
for num in range(5):
    # Replace "print" below, with the code you want to repeat.
    print(num)

rawDescription: Python maths quiz random number

description: Python maths quiz random number


code: [[c, a] for c, a in zip(cities, airports)]

rawDescription: Using list comprehension in Python to do something similar to zip()?


code:
class TName(Base):
    end_time = Column(Integer)
    start_time = Column(Integer)
    calc_column = end_time + case([(end_time<start_time, 86400000)], else_=0 )

q2 = session.query(TName.calc_column).order_by(TName.calc_column)

rawDescription: Sqlalchemy order by calculated column

description: Sqlalchemy order by calculated column


code:
for pod in root.findall('.//pod'):
    print(pod.attrib['title'])
    for pt in pod.findall('.//plaintext'):
        if pt.text:
            print('-', pt.text)

rawDescription: Python Xml Parsing for Wolfram Api

description: Python Xml Parsing for Wolfram Api


code:
#!/usr/bin/env python3
import locale
import sys
from subprocess import CalledProcessError, STDOUT, check_output

def run(command, *, cwd=None, env=None):
    try:
        ignored = check_output(command, cwd=cwd, env=env,
                               stderr=STDOUT,
                               universal_newlines=True)
    except CalledProcessError as e:
        sys.stderr.write(e.output)
        sys.stderr.flush()
        return e.returncode
    else:
        return 0

rawDescription: environment variables using subprocess.check_output pythoon

description: Environment variables using subprocess.check_output pythoon


code:
def letters(input):
    return ''.join([c for c in input if c.isalpha()])

rawDescription: How do you filter a string to only contain letters?

description: Filter a string to only contain letters


code:
data_bp8 = butter_bandpass_filter(data,300,2000,20000,8)
data_bp2 = butter_bandpass_filter(data,300,2000,20000,2)

rawDescription: Most efficient way to filter a long time series Python


code:
class CIDRAdmin(admin.ModelAdmin):
    form = CIDRForm

rawDescription: Django admin CIDR type

description: Django admin CIDR type


code:
decrypt=input("Please enter the key you used to encrypt the above text: ")
key=(map(str,[ord(d) for d in decrypt]))
print(list(map(int,key)))

rawDescription: Python: Sum of numbers

description: Python: Sum of numbers


code:
s = ['''...''' ] #your data
ss = ''.join(s) #make string
ss = ss.split('\n') #split each element to list
print(set(ss)) #print set with unique data

rawDescription: removing duplicates in python and selenium

description: Removing duplicates in python and selenium


code: set('abc') < set('abc')

rawDescription: Comparing sets in python nlp

description: Comparing sets in python nlp


code:
def lemmma(file):
    lst=[]
    for i in file:
        lst.append(i)
    return lst

rawDescription: get a list in a function in python

description: Get a list in a function in python


code:
c= myClass()
c.x = 10
c.x
c.y

rawDescription: Python classes: linked attributes

description: Python classes: linked attributes


code: list_b= { item.replace('\n','') for item in list_b }

rawDescription: output list of special letters string with python

description: Output list of special letters string with python


code:
somelist = [("facultyX", "memberA", "Student"),
            ("facultyX", "memberB", "Student"),
            ("facultyX","memberC", "Programmer"),
            ("facultyY", "memberD", "Student"),
            ("facultyY", "memberE","PostDoc")]
result = {}
for fac, member, role in somelist:
    fac_data = result.setdefault(fac, {})
    fac_data.setdefault(role, []).append(member)

from pprint import pprint
pprint(result)

rawDescription: Group a list of tuples to dictionary in Python


code:
import selenium
from selenium import webdriver

try:
    browser = webdriver.Firefox()
    browser.get('mikekus.com')
except KeyboardInterrupt:
    browser.quit()

rawDescription: How to emulate a browser with JavaScript support via Mechanize?

description: Emulate a browser with JavaScript support via Mechanize


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

t = np.linspace(0, 2*np.pi, num=1000)

x = np.cos(t) / (np.sin(t)**2 + 1)
y = np.cos(t) * np.sin(t) / (np.sin(t)**2 + 1)

plt.plot(x, y)
plt.show()

rawDescription: Pyplot lemniscate

description: Pyplot lemniscate


code: d = dict(zip(keys, valuetuple))

rawDescription: Update values for multiple keys in python


code:
with open('thisisanew.txt','w') as outfile:
    for item in text:
        print(item, file=outfile)

rawDescription: Scrape websites and export only the visible text to a text document Python 3 (Beautiful Soup)


code:
import code
console = code.InteractiveConsole()
prompt = '>>>'
source = '''
1 + 1
2+5
"foo"
x = 1
x
y = (2+
     3)
y + x
'''.splitlines()
for line in source:
    print('{p} {l}'.format(p=prompt, l=line.rstrip()))
    prompt = '...' if console.push(line) else '>>>'

rawDescription: Is it possible to make Python interpret a script line by line and generate output as if from an interactive shell?


code:
def numLen(inputstring, index):
    char = inputstring[index]
    return inputstring.count(char)

rawDescription: Return repeated count of given string position


code:
@cherrypy.expose
def AddToCartJS(self, SKU, Quantity):
    CurrentShoppingCart = ShoppingCart()
    CartID = CurrentShoppingCart.AddToCart(SKU, Quantity)
    return CurrentShoppingCart.GetCartCount()

rawDescription: Python Javascript framework to use with cherrypy and Mako


rawDescription: How do I easily (and efficiently) delete a single element from array?

description: Easily (and efficiently) delete a single element from array


code:
cities = City.objects.filter(code__exact=12345).values("id",
                                                       "name",
                                                       "state__name",
                                                       "state__id")

rawDescription: How to get objects inside another object from a Query?

description: Get objects inside another object from a Query


code: function_in_library("Hello %s" % ', '.join(['%s'] * len(my_args)), my_args)

rawDescription: python - How to format variable number of arguments into a string?

description: Python - How to format variable number of arguments into a string


code:
def matches(first_string,second_string):
    while True:
        mbs = difflib.SequenceMatcher(None, list1, list2).get_matching_blocks()
        if len(mbs) == 1: break
        for i, j, n in mbs[::-1]:
            if n > 0: yield first_string[i: i + n]
            del first_string[i: i + n]
            del second_string[j: j + n]

rawDescription: find all common sequences of two list in python

description: Find all common sequences of two list in python


code:
with open('myfile.csv', 'rb') as f_in, open('myfile_filtered.csv', 'wb') as f_out:
    reader = csv.reader(f_in)
    writer = csv.writer(f_out)
    writer.writerows(filter_data(reader))

rawDescription: How to recount number in each class from a read csv

description: Recount number in each class from a read csv


code:
f = open('latex-styling.tex', 'r+');
PREAMBLE = f.read();

latex_elements = {
  # The paper size ('letterpaper' or 'a4paper').
  #'papersize': 'a4paper',

  # The font size ('10pt', '11pt' or '12pt').
  #'pointsize': '10pt',

  # Additional stuff for the LaTeX preamble.
  'preamble': PREAMBLE
}

rawDescription: Table of contents sidebar in Sphinx LaTeX PDF


code: pd.merge(frame_1, frame_2, how = 'left', left_on = 'county_ID', right_on = 'countyid')

rawDescription: Joining pandas dataframes by column names


rawDescription: How to get the count of particular values in a column using pandas

description: Get the count of particular values in a column using pandas


rawDescription: Python and remove duplicates in list of lists regardless of order within lists


code:
reverse = [(3, 7), (12,17)]
for start, end in reverse:
    lst[start:end] = reversed(lst[start:end])

rawDescription: Python3 Make a list that increments for a certain amount, decrements for a certain amount


code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
plt.show()

rawDescription: Pandas plot doesn't show

description: Pandas plot doesn't show


code:
from base64 import b64encode, b64decode

def convert(image):
    with open(image, "rb") as f, open("Puppy2.jpg", "wb") as t:
        conv = b64decode(b64encode(f.read()))
        t.write(conv)

rawDescription: Converting Images with Python

description: Converting Images with Python


code:
content = ['aba', 'abanga', 'abaptiston', 'abarelix']
unwanted_words = ['aba', 'aca', 'ada']
[word for word in content if word not in unwanted_words]

rawDescription: Python: search and replace - string delineation issue


rawDescription: What the heck kind of timestamp is this: 1267488000000


code: ModelAdmin.save_model(self, request, obj, form, change)

rawDescription: How to implement a script while saving a file in django admin panel?

description: Implement a script while saving a file in django admin panel


code:
groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)

rawDescription: Difference between iterating through a generator and converting to a list


rawDescription: Selecting random values from list until they are gone in Python


rawDescription: How to get the filtered dataframe for calculations while retaining the original one in pandas?

description: Get the filtered dataframe for calculations while retaining the original one in pandas


code:
kendalltau(df['x'], df['y'])
kendalltau(df['x'].values, df['y'])

rawDescription: using python's stats.kendalltau function

description: Using python's stats.kendalltau function


code:
form = DriverRideForm(request.POST)
if form.is_valid():
    ride = form.save(commit=False)
    ride.driver = request.user.userprofile
    ride.save()

rawDescription: django - Many To Many relationship issue

description: Django - Many To Many relationship issue


code:
from subprocess import call
call(['python','runProgram.py'])

rawDescription: Autorun python script from python

description: Autorun python script from python


code:
mask = data <= 0
mdata = np.ma.masked_array(data, mask)

rawDescription: How to apply a function on a subset of numpy.ndarray object

description: Apply a function on a subset of numpy.ndarray object


rawDescription: How to get values from a map and set them into a numpy matrix row?

description: Get values from a map and set them into a numpy matrix row


code:
class ShortRib(object):
    def __init__(self, owner):
        self.owner = owner

class MetaCow(type):
    def __new__(cls, name, base, attrs):
        attrs['shortRib'] = ShortRib(cls)
        return super(MetaCow, cls).__new__(cls, name, base, attrs)

class Cow(object):
    __metaclass__ = MetaCow

Cow.shortRib.owner

rawDescription: Python: class static member pointing to itself?


code:
import itertools as it

a = [{'apples': 99}, {'bananas': 556685}, {'apples': 88}, {'apples': 2345566}]

max((sum(i.values()[0] for i in v), k) for k,v in it.groupby(sorted(a), key=lambda x: x.keys()[0]))[1]

# 'apples'

rawDescription: Getting the item with the maximun value in list of dicts after grouping the dict by key


rawDescription: for-loops in Python modules

description: For-loops in Python modules


rawDescription: How to sort pandas pivot_table based on newest date within level?

description: Sort pandas pivot_table based on newest date within level


code:
for i,a in enumerate(your_arrays):
  rows, cols = a.shape
  if rows != N:
    your_arrays[i] = np.vstack([a, np.zeros((N - rows, cols), dtype=a.dtype)])

rawDescription: How to make a list of numpy arrays all have the same shape?

description: Make a list of numpy arrays all have the same shape


code:
class A(object):
    @decorate
    def test(self, arg):
        return arg + 1

rawDescription: Python __getattribute__ and wrapper of method


code:
import re
s = "RSQ(name['BAKD DK'], name['A DKJ'])"
expr = r"[\'\[\]]|\bname\b"
print(re.sub(expr, '', s))

rawDescription: Python regex - Replace single quotes and brackets


rawDescription: Is it possible to np.concatenate memory-mapped files?


rawDescription: Split a variable table in python

description: Split a variable table in python


code:
x = A.m
x is x

rawDescription: Why is a method not identical to itself?

description: Why is a method not identical to itself


code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

rawDescription: Change user agent for selenium driver

description: Change user agent for selenium driver


rawDescription: Pandas Datframe1 search for match in range of Dataframe2


code:
import csv

def read(filename):
    out_dict = {}
    with open(filename, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        next(csvfile) # skip the first row
        for row in reader:
            out_dict[row[0]] = float(row[1]), float(row[2])
            print(row)

    return out_dict

print(read('data.csv'))

rawDescription: Converting the contents of a CSV file into a dictionary


rawDescription: Combining columns and removing NaNs Pandas


rawDescription: How to get and show counts of values each column

description: Get and show counts of values each column


code:
f = Foo('eggs')
f.spam
f.__spam
f._Foo__spam
f._Foo__spam = 'ham'
f.spam

rawDescription: Python class which instances' atributes can't be edited


rawDescription: Building a table from Python nested dictionaries with missing values


rawDescription: How do I take a list of lists and rearrange them in python

description: Take a list of lists and rearrange them in python


code:
my_pil_image
my_pil_image_resized = my_pil_image.resize((50,50))
my_pil_image_resized
output = StringIO.StringIO()
my_pil_image_resized.save(output,format="JPEG")
contents = output.getvalue()
type(contents)
contents

rawDescription: How to put an image resized with Pillow into GridFS?

description: Put an image resized with Pillow into GridFS


code:
permutation = [[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]]

def permute(bits):
    return [[bits[i/4][i%4] for i in chunk] for chunk in permutation]

rawDescription: Bit permutation with index dictionary

description: Bit permutation with index dictionary


code: df3 = df3.reset_index().drop_duplicates(subset='index', keep='last').set_index('index')

rawDescription: Remove rows with duplicate indices (Pandas DataFrame and TimeSeries)


code: super(QLineEdit, self).__init__()

rawDescription: PyQt4: why do we need to pass class name in call to super()


code:
for data in content.get('data'):
    for k, v in data.items():
        if k == 'values':
            try:
                print(data[k][0])
            except KeyError:
                print('Nothing')

rawDescription: django get json values

description: Django get json values


rawDescription: how to run a function multiple times

description: Run a function multiple times


code:
email_string2 = "az <az@example.com>, bz <bz@example.com>"
re.findall(r'<([^>]+)>', email_string2)

rawDescription: How to eliminate email formatting in received email?

description: Eliminate email formatting in received email


rawDescription: 8-bytes int (long long) in Cython's array.array


code:
class AbstractExample():

    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def call_now_with_my_parameters(self, callable):
        callable(self.arg2, self.arg2)

def example_function(arg1,arg2):
    print("{},{}".format(arg1, arg2))

ae = AbstractExample(5, 7)
ae.call_now_with_my_parameters(example_function)

rawDescription: Abstract methods like in Java

description: Abstract methods like in Java


code:
d = {
  "key1" : {
      "key2" : "value2",
      "key3" : "value3",
      "key4" : "value4"
      },
  "key5" : {
      "key6": "value6",
      "key7" : "value7"
      }
 }
any(isinstance(value, dict) for value in d.values())

rawDescription: Find whether dictionary is simple key-value pair or nested dicts


code:
with open('path/to/file.gif') as f:
  img_content = f.read()

rawDescription: How to return image with GAE?

description: Return image with GAE


code:
name = ['sam', 'john', 'napoleon', 'tanaka', 'ming']
country = ['USA', 'England', 'France', 'Japan', 'China']
age = [23, 41, 19, 16, 55]
for x,y,z in zip(name,country,age):
    print("{0}; {1}; {2}".format(x,y,z))

rawDescription: Can i integrate multiple lists in python?

description: Integrate multiple lists in python


code:
a = np.array([[1,2],[3,4]], dtype=theano.config.floatX)
x = theano.shared(a)
print(x)

rawDescription: Using a shared variable in a function

description: Using a shared variable in a function


code:
f = df.groupby(['City', 'Date'])['Weight'].transform
df['Wt_Diff'] = f('max') - f('min')
df

rawDescription: performing math on dataframe variables after groupby in pandas and bringing results back to original dataframe

description: Performing math on dataframe variables after groupby in pandas and bringing results back to original dataframe


code:
import numpy
1.2738 * numpy.array(list_of_items)

rawDescription: Matrix scalar multiplication

description: Matrix scalar multiplication


code:
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id, ondelete='RESTRICT'), nullable=False)

rawDescription: How can "on delete restrict" be used in a model?


code:
for artist in data['results']['artistmatches']['artist']:
    image = max(artist['image'], key=lambda i: sizemap[i['size']])
    image_url = image['#text']

rawDescription: JSON dictionary lookup

description: JSON dictionary lookup


code:
def foo():
    class A(object):
        pass

rawDescription: Scope of classes inside of functions and classes inside of a class in python


rawDescription: Extract a column from a list of rows with Python


code:
from pyramid.renderers import get_renderer

def add_base_template(event):
    base = get_renderer('templates/base.pt').implementation()
    base2 = get_renderer('templates/base2.pt').implementation()
    event.update({'base': base, 'base2': base2})

rawDescription: Python Pyramid - Add multiple chameleon base templates


code:
x = Car.query(keys_only=True).fetch(100)
results = get_entities([i.to_old_key() for i in x])

for i in results:
    i['production_year'] = unicode(i['production_year'])

put_entities(results)

rawDescription: Migrating data when changing an NDB field's property type


rawDescription: Python: '{:,}'.format() why is this working?


code:
def print_saw(size, number):
    for s in range(size):
        print(('*' * (s + 1) + ' ' * (size - s - 1)) * number)

rawDescription: How to print shapes made of * in horizontal?

description: Print shapes made of * in horizontal


code:
def C(a, b):
    return list(itertools.combinations(range(1,a+1), b))

rawDescription: Finding combination of elements of a list


code: s = strings(i for i in range(400))

rawDescription: Any way to bypass namedtuple 255 arguments limitation?


code: ListB = ListB.append('New_Field_Name')

rawDescription: Python Append to a list returns none

description: Python Append to a list returns none


code: ['aaa', 'bb', 'ccccc', 'ddd']

rawDescription: Find all countinuous repeating characters using a simpler solution or preferably a regex


code: [plt.get_cmap('jet')(1. * i/n) for i in range(n)]

rawDescription: Use colormaps along with matplotlib cycler


rawDescription: How does re.match().groups() work?

description: How does re.match().groups() work


code:
aa = np.tile(a, (len(b), 1))
bb = np.tile(b, (len(a), 1))
cc = np.isclose(aa, bb.T)
np.any(cc, 0)
c = np.zeros(shape=a.shape)
result = np.where(np.any(cc, 0), a, c)

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


code:
times = []
for i in range(0, 24*4):
    times.append((datetime.combine(date.today(), time()) + timedelta(minutes=15) * i).time())
form = MyForm(instance=instance,
       options=[( choice.strftime("%H:%M:%S"), choice.strftime("%I:%M %p").lstrip('0') ) for choice in times])
return ...

rawDescription: Django Forms - Format Select Field Time Value as AM/PM


code:
def resolve(root, keys, default=None):
    for key in keys.split():
        try:
            root = root[key]
        except (TypeError, KeyError):
            try:
                root = root[int(key)]
            except (IndexError, ValueError, KeyError):
                return default

uri = resolve(entry_obj, 'media$group media$content 0 url', '')

rawDescription: Concise replacement for long list of Try-Except statement in Python?


code: [os.path.split(x)[1]  for x in  sorted(get_files("."),key = os.path.getmtime,reverse = True)[:5]]

rawDescription: How to retrieve the most recently created files in a directory

description: Retrieve the most recently created files in a directory


code:
for key in nameData:
    namelist.write('\nKPLR%09i-2009131105131'%int(key)) #no string concatenation

rawDescription: Looping a write command to output many different indices from a list seperately in Python


rawDescription: Make a new array selectively copying, with varying multiplicity, rows of old array in numpy


code:
keys_of_interest = ['a', 'b', 'c', 'd']
keys_for_func = ['a', 'b']  # with this approach you can apply a func to multiple keys

func = lambda x: x ** 2  # for demo
all_dicts = [{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
             {'a': 6, 'b': 7, 'c': 8, 'd': 9, 'e': 10}]

rawDescription: Filter item from a dict and process a subset


code:
class BaseTestCase(unittest2.TestCase):

    def __call__(self, result=None):
        try:
            self._pre_setup()
            super(BaseTestCase, self).__call__(result)
        finally:
            self._post_teardown()

    def _pre_setup(self):
        self.app = create_app()
        self.client = self.app.test_client()
        self._ctx = self.app.test_request_context()
        self._ctx.push()

    def _post_teardown(self):
        if getattr(self, '_ctx') and self._ctx is not None:
            self._ctx.pop()
        del self._ctx

rawDescription: Can I have all of my unit tests run in the Flask app context?

description: Have all of my unit tests run in the Flask app context


rawDescription: Pandas get specific rows from HDF5 by index


code:
def mSave():
  filename = asksaveasfilename(defaultextension='.txt',filetypes = (('Text files', '*.txt'),('Python files', '*.py *.pyw'),('All files', '*.*')))
  if filename is None:
    return
  file = open (filename, mode = 'w')
  name1 = TubeLenghtVal_1.get()
  name2 = TubeLenghtVal_2.get()

  # or whatever you assign the name of the variable, for me is TubeLenghtVal_2 = StringVar() and for integer I have Vol_Val = IntVar()
  all = name1 + " , " + name + " , " + (str(Vol_Val))
  file.write(all)
  file.close()

rawDescription: How to save text form a textbox (String and Int) in python 3.x tkinter

description: Save text form a textbox (String and Int) in python 3.x tkinter


code:
sqlContext.registerDataFrameAsTable(data, "myTable")
df2 = sqlContext.sql("SELECT Name AS name, askdaosdka as age from myTable")

df2.show()

# Output
#+-------+---+
#|   name|age|
#+-------+---+
#|Alberto|  2|
#| Dakota|  2|
#+-------+---+

rawDescription: How to change dataframe column names in pyspark?

description: Change dataframe column names in pyspark


rawDescription: Inline SVG Served By Python Script in Google App Engine Not Appearing


code: df2 = pd.DataFrame({'id': df["id"], 'value': df["value"]*2})

rawDescription: Python Pandas. Creating DataFrame with Series does not preserve dtype


code: SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = ['first_name', 'last_name']

rawDescription: Python-social-auth how can i get uid fullname etc. with facebook


rawDescription: Python: Trying to mock datetime.date.today() but not working


code:
def all_of(iterable, predicate):
    return all(predicate(e) for e in iterable)

rawDescription: Python version of C++ all_of

description: Python version of C++ all_of


code:
S
St
Sta
Stac
Stack
tackO
ackOv
ckOve
kOver
Overf
verfl
erflo
rflow

rawDescription: Flexible sliding window (in Python)

description: Flexible sliding window (in Python)


code:
begin_time = time.clock()
func(cnt)
tms.append(time.clock() - begin_time)

rawDescription: How to do profiling for this?

description: Do profiling for this


code: a['bar']

rawDescription: Why does overriding __contains__ break OrderedDict.keys?


code: a if b else c

rawDescription: pandas if then statement without looping

description: Pandas if then statement without looping


code:
import subprocess
subprocess.call(["python", "local_script_name.py"], cwd="script_dir")

rawDescription: How do I run Python script from a subdirectory?

description: Run Python script from a subdirectory


code:
df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
df
from collections import OrderedDict
df.apply(OrderedDict)

rawDescription: How to turn pandas dataframe row into ordereddict fast

description: Turn pandas dataframe row into ordereddict fast


code:
x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 2
# global: 0

rawDescription: Python nonlocal statement

description: Python nonlocal statement


code:
from itertools import permutations

def take(l, partition):
  if len(partition) == 1:
    for p in permutations(l):
      yield (p,)
  else:
    for p in permutations(l,partition[0]):
      for t in take([x for x in l if x not in p], partition[1:]):
        yield (p,) + t

rawDescription: Set partition with fixed size

description: Set partition with fixed size


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[0,1,0],[1,0,0],[0,0,1]]))

rawDescription: Index of columns where rows match criterion Python Pandas


code:
from sympy import *
x = symbols('x')
f1 = lambdify(x, diff(f(x)))

rawDescription: Use Boost-Python to calculate derivative of function defined in python


code:
class DragAndDrop(QListView):
    def __init__(self, parent):
        global listView
        super(DragAndDrop, self).__init__(parent)
        self.setAcceptDrops(True)
        self.setDragDropMode(QAbstractItemView.InternalMove)
        self.setFrameShadow(QFrame.Plain)
        self.setFrameShape(QFrame.Box)
        listView=self

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            super(DragAndDrop, self).dragEnterEvent(event)

    def dragMoveEvent(self, event):
        super(DragAndDrop, self).dragMoveEvent(event)

    def dropEvent(self, event):
        #global itemModel
        if event.mimeData().hasUrls():
            for url in event.mimeData().urls():
                if url.path()[-5:]==".pcap":
                    if itemModel.findItems(url.path()[1:].replace("/","\\")):
                        pass
                    else:
                        item=QStandardItem(url.path()[1:].replace("/","\\"))
                        item.setCheckable(True)
                        itemModel.appendRow(item)
                else:
                    pass
            event.acceptProposedAction()
            self.setModel(itemModel)
        else:
            super(DragAndDrop,self).dropEvent(event)

rawDescription: pyqt4 drag and drop files in Qlistview

description: Pyqt4 drag and drop files in Qlistview


code:
corpusFile = open(filename, mode = 'wb')
# ...
tagged_token = '\xdcml\xe4ut'
tagged_token = tagged_token.decode('ISO-8859-1')
corpusFile.write(tagged_token.encode('utf-8'))
corpusFile.write('\n')

rawDescription: Wanted Python to create a UTF-8 File, got an ANSI one. Why?


rawDescription: How to for loop in reverse?

description: For loop in reverse


code: browser.driver.set_page_load_timeout(10)  # 10 seconds

rawDescription: Splinter saves bodiless html

description: Splinter saves bodiless html


code: ['st-button mode="positive" width="small" can-click="{loadConference}"id="meetingPasswordButton"']

rawDescription: Include and neglect the text between 2 special characters


rawDescription: Datetime differences in Django using SQLite


code:
def package_filter(info):
    if info.isdir() or os.path.splitext(info.name)[-1] in ('.xml', '.class'):
        return info
    else:
        return None

with tarfile.TarFile('package.tgz', 'w:gz', filter=package_filter) as tar:
    for pathname in sys.argv[1:]:
        tar.add(pathname)

rawDescription: Create a package files python

description: Create a package files python


rawDescription: Python searching patterns in lists of strings


rawDescription: Make Tuples from Specific Pandas Columns


code:
import requests
r = requests.get('https://github.com/timeline.json')

rawDescription: Python Request HTTP Page and Use The Source Information


code:
pieces = [left, right, middle]
new_df = concat(pieces)

rawDescription: Union all type query with python pandas

description: Union all type query with python pandas


rawDescription: Binning in Pandas

description: Binning in Pandas


rawDescription: flip keys and values in dictionary python

description: Flip keys and values in dictionary python


code:
from datetime import datetime, timedelta
import leapseconds
leapseconds.gps_to_utc(datetime(1980,1,6) + timedelta(seconds=1092121243.0))

rawDescription: How to get current date and time from GPS unsegment time in python

description: Get current date and time from GPS unsegment time in python


rawDescription: Single and Double Quotes Auto-Switching

description: Single and Double Quotes Auto-Switching


code:
flist = []
for i in range(30):
    flist.append(lambda x, i=i: print(x * i))

rawDescription: python - Is it possible to create a list of "def"?

description: Python - Is it possible to create a list of "def"


rawDescription: Process CSV in Python

description: Process CSV in Python


code: df

rawDescription: Fill NaN in candlestick OHLCV data

description: Fill NaN in candlestick OHLCV data


code:
def max_at_ids(x, id, ids):
    # create a 1D view of x and id:
    r_x = x.ravel()
    r_id = id.ravel()
    sorter = np.argsort(r_id)

    # create new sorted arrays:
    r_id = r_id[sorter]; r_x = r_x[sorter]

    # unfortunatly there is no reduce functionality for np.max...

    ids = np.unique(ids) # create a sorted, unique copy, just in case

    # w gives the places where the sorted arrays id changes:
    w = np.where(r_id[:-1] != r_id[1:])[0] + 1

rawDescription: How to speed up a loop in python

description: Speed up a loop in python


code:
app = Flask(__name__)
app.config.from_object('config')

rawDescription: Using Google OAuth2 with Flask

description: Using Google OAuth2 with Flask


code: import re

rawDescription: Elegant Python function to convert CamelCase to snake_case?


code:
def my_view(request, exportCSV):
    # ... Figure out `queryset` here ...

    if exportCSV:
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment;filename=export.csv'
        writer = csv.writer(response)
        for cdr in queryset:
            writer.writerow([cdr['calldate'], cdr['src'], cdr['dst'], ])
        return response
    else:
        return render_to_response('templateX.html', {'queryset': queryset,
            'filter_form': filter_form, 'validated': validated},
            context_instance = RequestContext(request))

rawDescription: Generating CSV file with Django (dynamic content)


rawDescription: Regular expression to find any number in a string


code:
class TestClientProtocol(WebSocketClientProtocol):
    def __init__(self, assertion, close_condition, timeout, *args, **kwargs):
        self.assertion = assertion
        self.close_condition = close_condition
        self._received_msgs = []
        from twisted.internet import reactor
        #This is a way to set a timeout for your test
        #in case you never meet the conditions dictated by close_condition
        self.damocle_sword = reactor.callLater(timeout, self.sendClose)

    def onOpen(self):
        #After the connection has been established,
        #you can tell the server to send its stuff
        self.sendMessage(START)

    def onMessage(self, msg, binary):
        #Here you get the messages pushed from the server
        self._received_msgs.append(msg)
        #If it is time to close the connection
        if self.close_condition(msg):
            self.damocle_sword.cancel()
            self.sendClose()

    def onClose(self, wasClean, code, reason):
        #Now it is the right time to check our test assertions
        self.assertion.callback(self._received_msgs)

class TestClientProtocolFactory(WebSocketClientFactory):
    def __init__(self, assertion, close_condition, timeout, **kwargs):
        WebSocketClientFactory.__init__(self, **kwargs)
        self.assertion = assertion
        self.close_condition = close_condition
        self.timeout = timeout
        #This parameter needs to be forced to None to not leave the reactor dirty
        self.openHandshakeTimeout = None

    def buildProtocol(self, addr):
        protocol = TestClientProtocol(self.assertion, self.close_condition, self.timeout)
        protocol.factory = self
        return protocol

rawDescription: Trial unittests using Autobahn WebSocket


code:
p=phrases.strip().split('\n')
p

rawDescription: How can I count phrases and use the phrases as headers in Python?

description: Count phrases and use the phrases as headers in Python


rawDescription: Spark Window Functions - rangeBetween dates


rawDescription: create a data frame using lists

description: Create a data frame using lists


code: [{'id': year[0], 'year': year[1]} for year in YEAR_IN_SCHOOL_CHOICES]

rawDescription: Convert a Django Model Field Choices into a JSON


code:
class CakeAdmin(admin.ModelAdmin):
    inlines = [LinkedItemAdmin]

rawDescription: How to access a ManyToManyField between two apps using ContentTypes for Django admin?

description: Access a ManyToManyField between two apps using ContentTypes for Django admin


rawDescription: How to add to arrays such that matching elements become their own arrays

description: Add to arrays such that matching elements become their own arrays


code:
import matplotlib
for name, hex in matplotlib.colors.cnames.iteritems():
    print(name, hex)

rawDescription: Named colors in matplotlib

description: Named colors in matplotlib


code:
if not queue_empty:
    method, properties, body = channel.basic_get(queue, no_ack=True)
    callback_func(channel, method, properties, body)

rawDescription: How to consume RabbitMQ messages via pika for some limited time?

description: Consume RabbitMQ messages via pika for some limited time


code: existing_nodes.get((a, b), Node(a, b))

rawDescription: Dictionary of Objects to access by Reference


code:
from itertools import *
list(chain(*[lis[i-2:i+3] for i in ind]))

rawDescription: Search a list for item(s)and return x number of surrounding items in python


code:
namelist = {}

for f in lst_names:
    namelist[f] = [os.path.join(f, n) for n in os.listdir(f)]

rawDescription: Python--read files, save the file names and access to these files


code:
def chunks(l, n):
    return [l[i:i + n] for i in range(0, len(l), n)]

rawDescription: How to split one list in a list of x list with python?

description: Split one list in a list of x list with python


code:
from sqlalchemy import *
from sqlalchemy.orm import *

engine = create_engine('sqlite:///:memory:', echo='debug')

m = MetaData()

parent = Table('parent', m,
                Column('id', Integer, primary_key=True)
)

child = Table('child', m,
                Column('id', Integer, primary_key=True),
                Column('parent_id', Integer, ForeignKey('parent.id')),
                Column('sortkey', Integer)
                )

m.create_all(engine)

class Parent(object):
    def __init__(self, children):
        self.all_c = children

class Child(object):
    def __init__(self, sortkey):
        self.sortkey = sortkey

latest_c = select([func.max(child.c.sortkey)]).\
                where(child.c.parent_id==parent.c.id).\
                correlate(parent).\
                as_scalar()

mapper(Parent, parent, properties={
    'all_c':relation(Child),
    'latest_c':relation(Child,
                            primaryjoin=and_(
                                child.c.sortkey==latest_c,
                                child.c.parent_id==parent.c.id
                            ),
                            uselist=False
    )
})

mapper(Child, child)

session = sessionmaker(engine)()

p1, p2, p3 = Parent([Child('a'), Child('b'), Child('c')]), \
                Parent([Child('b'), Child('c')]),\
                Parent([Child('f'), Child('g'), Child('c')])

session.add_all([p1, p2, p3])
session.commit()

assert p1.latest_c.sortkey == 'c'
assert p2.latest_c.sortkey == 'c'
assert p3.latest_c.sortkey == 'g'

rawDescription: How do I define a SQLAlchemy relation representing the latest object in a collection?

description: Define a SQLAlchemy relation representing the latest object in a collection


rawDescription: How to calculate difference on previous within set of grouped rows in a dataframe

description: Calculate difference on previous within set of grouped rows in a dataframe


code:
from itertools import groupby
from operator import itemgetter
keys = ('time', 'power', 'usage')
groups = groupby(zip(*[d[k] for k in keys]), key=itemgetter(0))
lists = zip(*[[k] + map(sum, zip(*g)[1:]) for k, g in groups])
dict(zip(keys, lists))

rawDescription: How to sum 3 same sized sorted lists based on the identical elements of the first one in Python?

description: Sum 3 same sized sorted lists based on the identical elements of the first one in Python