code:
def igpay(astring):
    words = astring.split()
    modified_words = []
    for ch in words:
        vowel = isvowel(ch)
        if vowel == 0:
            ch = ch.replace(ch, (format(ch + "way")))
        else:
            ch = ch.replace(ch, (format(ch[vowel:] + ch[:vowel] + "ay")))
        modified_words.append(ch.strip())
    return ' '.join(modified_words)

rawDescription: Converting a sentence into piglatin

description: Converting a sentence into piglatin


code:
from git import *
from time import (time, altzone)
import datetime
from cStringIO import StringIO
from gitdb import IStream

repo = Repo('path/to/repo')

message = 'Commit message'

tree = repo.index.write_tree()
parents = [ repo.head.commit ]

# Committer and Author
cr = repo.config_reader()
committer = Actor.committer(cr)
author = Actor.author(cr)

# Custom Date
time = int(datetime.date(2013, 1, 1).strftime('%s'))
offset = altzone
author_time, author_offset = time, offset
committer_time, committer_offset = time, offset

# UTF-8 Default
conf_encoding = 'UTF-8'

comm = Commit(repo, Commit.NULL_BIN_SHA, tree,
      author, author_time, author_offset,
      committer, committer_time, committer_offset,
      message, parents, conf_encoding)

rawDescription: How can I specify the committed_date of a Commit using GitPython?

description: Specify the committed_date of a Commit using GitPython


code:
def deserializeProcessWrapperFromFile(filename):
    # Get process pid from file
    process = ProcessWrapper.__new__()
    process._process_pid = process_pid
    return process

rawDescription: Common practice of __new__ constructor?

description: Common practice of __new__ constructor


code:
def test(padded_name):
    names = ['albert', 'bob', 'charlie']
    return any(padded_name.find(name) >= 0 for name in names)

filtered_names = filter(test,padded_names)

rawDescription: Creating a list by searching for substrings in python


code: sorted_surnames = [n for (i, n) in sorted(zip(ind, surnames), key=lambda x: x[0])]

rawDescription: how to use numpy.lexsort without cycles

description: Use numpy.lexsort without cycles


code:
import math
from scipy.optimize import fsolve

class Fred(object):
    M0 = 5.0
    n = 5

    def f(self, x, t):
        return (x - math.sin(x) -self.M0 - self.n*t)

    def test(self, t):
        return fsolve(self.f, 1, args=(t))

rawDescription: Solving an equation with scipy's fsolve

description: Solving an equation with scipy's fsolve


code:
print(["FizzBuzz"
          if x%15 == 0
          else
             "Fizz"
                 if x%3 == 0
                 else
                   "Buzz"
                      if x % 5 == 0
                      else
                         x
       for x in range(1,101)])

rawDescription: Python - Using ifs, elifs and else in list comprehensions with their respective results


rawDescription: Encoding custom python objects as BSON with pymongo


code: ABCDEFGHIJKLMNOPQRSTUVWXYZ

rawDescription: How Do I Queue My Python Locks?

description: How Do I Queue My Python Locks


rawDescription: How to parse the header files of the pcap file?

description: Parse the header files of the pcap file


code:
def price():
    price = capacity() * 4 * which_node_type() * which_node_feature() * aspect_count()

rawDescription: i have a formula, trying to put it into python and this is what i have so far, whats the issue with it?

description: I have a formula, trying to put it into python and this is what i have so far, whats the issue with it


code: days = (dates + pd.DateOffset(months=1, days=-1)).day

rawDescription: Applying cell wise function in a dataframe


code:
test > 1
test > 10000
test > x

rawDescription: How can I represent an infinite number in Python?

description: Represent an infinite number in Python


rawDescription: clicking on a link via selenium in python

description: Clicking on a link via selenium in python


code:
def get_data_locations():
    """ Find data locations from the first sheet in document. """
    first_sheet = Range('Sheet1', 'A1:Z200').value
    coordinates = [[x, y] for x, row in enumerate(first_sheet, 1)
                   for y, z in enumerate(row, 1) if z == 'CO']
    return coordinates

rawDescription: Uncool List Comprehension

description: Uncool List Comprehension


code:
diffs = data - data.mean(1,keepdims=True)
cov3D = np.einsum('ijk,ijl->ikl',diffs,diffs)/data.shape[1]

rawDescription: Quickly compute eigenvectors for each element of an array in python


code:
class DictTable(dict):
    # Overridden dict class which takes a dict in the form {'a': 2, 'b': 3},
    # and renders an HTML Table in IPython Notebook.
    def _repr_html_(self):
        html = ["
"]
        for key, value in self.iteritems():
            html.append("
")
            html.append("{0}	".format(key))
            html.append("{0}	".format(value))
            html.append("
")
        html.append("
")
        return ''.join(html)

rawDescription: Python dictionary as html table in ipython notebook


rawDescription: search substrings and replace them after analyzing

description: Search substrings and replace them after analyzing


code:
class BaseRequest:
    name = None

class FooRequest(BaseRequest):
    name = 'I-95'

    def response(self):
        return "foo"

class BarRequest(BaseRequest):
    name = 'P-22'

    def response(self):
        return "bar"

class RequestManager:

    def __init__(self):
        self.requests = {
            FooRequest.name: FooRequest,
            BarRequest.name: BarRequest
        }

    def generate_request(self, name):
        if name in self.requests:
            return self.requests[name]()

    def register_request(self, request_class):
        assert issubclass(request_class, BaseRequest), \
            'Request class not a subclass of BaseRequest'
        assert hasattr('name', request_class) and isinstance(request_class.name, str), \
            'Request name not correctly configured'
        self.requests[request_class.name] = request_class

rawDescription: Creating a set of Python classes

description: Creating a set of Python classes


code: data = ['very Awesome Book','Awesome Book discount']

rawDescription: Python, extract tags and also get position of word


code:
import dis
dis.dis(f)

rawDescription: python: string comparison do not work as expected

description: Python: string comparison do not work as expected


code:
dictlist = [{1: 'One'}, {2: 'Two'}, {1: 'One', 7: 'Seven'}]

result = []
for d in dictlist:
    if 1 in d:
        result.append(d[1])
    elif 7 in d:
        result.append(d[7])
    # else:
    #     Possibly do something here?

rawDescription: How to implement if-else using n for n in m iteration

description: Implement if-else using n for n in m iteration


code:
def count_positions(positions):
    positions = np.sort(positions)
    diff = np.ones(len(positions), 'bool')
    diff[:-1] = positions[1:] != positions[:-1]
    count = diff.nonzero()[0]
    count[1:] = count[1:] - count[:-1]
    count[0] += 1
    uniqPositions = positions[diff]
    return uniqPositions, count

rawDescription: create intersection from two or more 2d numpy arrays based on common value in one column

description: Create intersection from two or more 2d numpy arrays based on common value in one column


code:
bitarray.bitarray([1, 1, 0, 1])
bitarray.bitarray([True, True, False, True])
bitarray.bitarray([range(3), [5.829048], [], ['can', 'I', 'help', 'you?']])

rawDescription: What is the most efficient way to concatenate and store long bit-strings?


code:
l = threading.local()
l
l.ok = "yes"
l.__dict__
l.__dict__.clear()
l.__dict__
l.ok

rawDescription: How do I clear a Python threading.local object?

description: Clear a Python threading.local object


code: file.write("Multiple of 1000!\r\n" * sum(1 for i in a2 if i % 1000 == 0))

rawDescription: How do I maximize efficiency with numpy arrays?

description: Maximize efficiency with numpy arrays


code:
dict((k,))
dict[k]

rawDescription: Tuple with nested list into dictionary

description: Tuple with nested list into dictionary


code:
def foo():
    print("World")

print("Hello")

foo()

rawDescription: How does Python interpret its code?

description: How does Python interpret its code


code:
csvfile = newcsv(data, csvheader, fieldnames)

response = HttpResponse(csvfile.getvalue(), content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=stock.csv'
return response

rawDescription: How to generate a file without saving it to disk in python?

description: Generate a file without saving it to disk in python


code: first_col = ColumnDefn('Name', 'left', -1, 'name', isEditable=True)

rawDescription: python ObjectListView has a single un-editable column

description: Python ObjectListView has a single un-editable column


code:
api = CrestAPI()
parsed_url = api.market.types()

rawDescription: function that gets field as parameters

description: Function that gets field as parameters


code:
from bs4 import BeautifulSoup

with open('file.html', 'r') as f:
    html_file_as_string = f.read()
soup = BeautifulSoup(html_file_as_string, "lxml")
for div in soup.find_all('div', {'class': 'my_class'}):
    for p in div.find('p'):
        p.string.replace_with(p.string.strip())
with open('file', 'w') as f:
    f.write(soup.renderContents())

rawDescription: How to perform re substitutions on <p> tags within a specific class?

description: Perform re substitutions on <p> tags within a specific class


code:
df = pd.DataFrame({'RVFCAST':rv1fcast, 'RV1':rv1, 'RV5':rv5, 'RV22':rv22,})
df = df[df.RVFCAST != ""]
df = df.astype(float)

Model = smf.ols(formula='RVFCAST ~ RV1 + RV5 + RV22', data = df).fit()
mdl = Model.get_robustcov_results(cov_type='HAC',maxlags=1)

rawDescription: Summary not working for OLS estimation

description: Summary not working for OLS estimation


code:
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height

rawDescription: determine matplotlib axis size in pixels

description: Determine matplotlib axis size in pixels


code:
import os
os.system("echo 'hello world'")
os.system("rsync -rav pi@192.168.2.34:python ~/")

rawDescription: Python Program rsync

description: Python Program rsync


code:
my_file = open("file_containing_encrypted_message")
data = my_file.read()

rawDescription: Python RSA Decrypt for class using vs2013


rawDescription: creating subclass form class returning pandas dataFrame

description: Creating subclass form class returning pandas dataFrame


code: filtered = [d for d in sortedDates if minD < d < maxD]

rawDescription: Splice list of date objects in Python

description: Splice list of date objects in Python


code:
df
f = {'A':['sum','mean'], 'B':['prod']}
df.groupby('GRP').agg(f)

rawDescription: Apply multiple functions to multiple groupby columns


rawDescription: python: shuffle characters in string to get all possible string combinations

description: Python: shuffle characters in string to get all possible string combinations


code:
import re
A = [ 'cat', 'doXXXg', 'monkey', 'hoBBBrse', 'fish', 'snake']
B = ['XXX', 'BBB']
blacklist = re.compile('|'.join([re.escape(word) for word in B]))
[word for word in A if not blacklist.search(word)]

rawDescription: Delete item from list if it contains a substring from a "blacklist"


code:
lookup = defaultdict(list)
wholelookup = defaultdict(list)
pat = re.compile('[a-z](\d+)[a-z]', re.I)

with open('summaryfile.txt') as mydata:
    for s_line in mydata:
        values = s_line.split('\t')
        code = re.match(pat, values[-1])
        if code:
            lookup[values[-2]].append(code.group(1))
            wholelookup[values[-2]].append(s_line)

rawDescription: How to read line in python using defaultdict?

description: Read line in python using defaultdict


code:
def selectAllCheckChanged(self):
    model = self.listview.model()
    model.blockSignals(True)
    try:
        for index in range(model.rowCount()):
            item = model.item(index)
            if item.isCheckable():
                if self.select_all_cb.isChecked():
                    item.setCheckState(QtCore.Qt.Checked)
                else:
                    item.setCheckState(QtCore.Qt.Unchecked)
    finally:
        model.blockSignals(False)

rawDescription: Creating a toggling "Check All" checkbox for a ListView


code: df[df['swiss']]

rawDescription: How to normalize text in a list that is itself in a column of Pandas dataframe?

description: Normalize text in a list that is itself in a column of Pandas dataframe


code:
board = [[0]*8 for i in xrange(8)]
for pos in random.sample(xrange(64), 16):
    board[pos//8][pos%8] = 1

rawDescription: Python — Randomly fill 2D array with set number of 1's


code:
{'vegetable': ['tomato', 'spinach'],
 'fruit': ['watermelon', 'grapes'],
 'meat': ['beef']}

rawDescription: Python group and splice: splicing the result returned from itertools.groupby


code:
def merge(a, b):
    if isinstance(b, dict) and isinstance(a, dict):
        a_and_b = set(a).intersection(b)
        every_key = set(a).union(b)
        return dict((k, merge(a[k], b[k]) if k in a_and_b else
                     deepcopy(a[k] if k in a else b[k])) for k in every_key)
    return deepcopy(b)

rawDescription: Merging hierarchy of dictionaries in Python


code:
import timeit
timeit.Timer("re.findall(r'.{1,2}', 'ABCDXYv')", setup='import re').repeat()
timeit.Timer("re.findall(r'..?', 'ABCDXYv')", setup='import re').repeat()

rawDescription: Splitting a string into 2-letter segments


code:
with open("data.dat","w") as f:
    f.write(' '.join(map(str,arr)))

rawDescription: How to write a tuple of floats to the file space separated with only one call to write in python?

description: Write a tuple of floats to the file space separated with only one call to write in python


code:
ip = '1.1.1.1/32'

# Note Drop the cidr notation as it is not necessary for addressing in python
ip_temp = ip.split('/')[0]
ip_temp = ip_temp.split('.')
# Note this does not handle the edge conditions and only modifies the last octet
if int(ip_temp[-1]) % 2 == 0:
    remote = int(ip_temp[-1]) + 1
else:
    remote = int(ip_temp[-1]) -1
remote_ip = ".".join(ip_temp[:3]) + "." + str(remote)

rawDescription: getting remote ip from local ip

description: Getting remote ip from local ip


code:
from ast import literal_eval
with open('log.csv', 'rt') as logFile:
    logreader = csv.reader(logFile)
    for row in logreader:
        a = literal_eval(row[3])
        b = literal_eval(row[4])

rawDescription: Strip double quotes from list

description: Strip double quotes from list


code:
df /= (df.iloc[0]*w)
df

rawDescription: How to apply a weight factor per column in a DataFrame

description: Apply a weight factor per column in a DataFrame


code: from __main__ import *

rawDescription: Pass variable between python scripts

description: Pass variable between python scripts


code:
# create a test file of 'Line X of Y' type
with open('/tmp/lines.txt', 'w') as fout:
    start,stop=1,11
    for i in range(start,stop):
        fout.write('Line {} of {}\n'.format(i, stop-start))

rawDescription: How to not print the last line

description: Not print the last line


code:
D_values = {}
for path in glob("F:\Thermal Motion\*.txt"):
    t, x, y = np.loadtxt(path, unpack=True)

    # Add a list of computed D values to the D_values dictionary.
    D_list = []
    for i in range(len(x)):
        D = ((x[i] - x[0])**2 + (y[i] - y[0])**2)**0.5
        D_list.append(D)
    D_values[path] = D_list

rawDescription: Making subarray from function on multiple arrays


rawDescription: del function not working properly

description: Del function not working properly


code:
names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
filter(lambda x:'aet' in x, names)

rawDescription: Grep on elements of a list

description: Grep on elements of a list


code:
import sys
import imp
import os

path = [p for p in sys.path if p != os.path.dirname(__file__)]
f, pathname, desc = imp.find_module('datetime', path)
std_datetime = imp.load_module('datetime', f, pathname, desc)
# if this^ is renamed to datetime, everything breaks!
f.close()

class CallableModule(object):

    def __init__(self, module, fn):
        self.module = module
        self.fn = fn

    def __call__(self, *args, **kwargs):
        return self.fn(*args, **kwargs)

    def __getattr__(self, item):
        try:
            return getattr(self.fn, item)
        except AttributeError:
            return getattr(self.module, item)

sys.modules['datetime'] = CallableModule(std_datetime, std_datetime.datetime)

rawDescription: How to make statement `import datetime` bind the datetime type instead of the datetime module?

description: Make statement `import datetime` bind the datetime type instead of the datetime module


code:
l = [1,2,3,4,5,6,7,8]
chunk = int(round(len(l)/3.0))
result = [l[i:i+chunk] for i in range(0,len(l),chunk)]
result
l = [1,2,3,4,5]
chunk = int(round(len(l)/3.0))
result = [l[i:i+chunk] for i in range(0,len(l),chunk)]
result

rawDescription: How do you divide list into equal parts?

description: Divide list into equal parts


code: dispatcher = {'foo': foo, 'bar': bar}

rawDescription: python - Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?

description: Python - Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function


code:
class MyFactory(OKFactory):

    class Meta:
        exclude = ['object']

    object = factory.SubFactory(MyOtherFactory)
    related__param = factory.SelfAttribute('object')
    related__otherrelated__param = factory.LazyAttribute(lambda myobject: 'admin%d_%d' % (myobject.level, myobject.level - 1))
    related = factory.RelatedFactory(YetAnotherFactory)  # Will be called with {'param': object, 'otherrelated__param: 'admin1_2'}

rawDescription: Passing an object created with SubFactory and LazyAttribute to a RelatedFactory in factory_boy


code: session.execute("INSERT INTO <table> (key, time) VALUES (%s, %s)", (key, long(timestamp * 1000)))  # scale to milliseconds

rawDescription: Cassandra python driver event_time

description: Cassandra python driver event_time


code:
from bs4 import BeautifulSoup
from urllib import request

page = request.urlopen('http://www.federalreserve.gov/econresdata/researchdata/feds200628_1.html').read()
soup = BeautifulSoup(page)

desired_table = soup.findAll('table')[2]
data = {}

# Find the columns you want data from
headers = desired_table.findAll('th')
desired_columns = []
column_count = 0
for th in headers:
    if 'SVENY' in th.string:
        data[th.string] = {'column': headers.index(th), 'data': []}
        column_count += 1

# Iterate through each row grabbing the data from the desired columns
rows = desired_table.findAll('tr')

for row in rows[1:]:
    date = row.findAll('th')[0].text
    cells= row.findAll('td')

    for header,info in data.items():
        column_number = info['column']
        cell_data = [date,cells[column_number].text]
        info['data'].append(cell_data)

rawDescription: Trouble parsing HTML page with Python

description: Trouble parsing HTML page with Python


code:
from myapp.views import simple_chart
...
...
...
url(r'^simple_chart/$', simple_chart, name="simple_chart"),
...
...

rawDescription: how to embed bokeh graphs into django templates without using the "bokeh-server executable"?

description: Embed bokeh graphs into django templates without using the "bokeh-server executable"


code:
import os
import csv

def go():
    search_strings = ('value1', 'value2', 'value3')    # target strings to be found in file name
    data = []
    folder = folderentry.get()  # reads path for 'folder'

    for path, subdirs, files in os.walk(folder):
        for name in files:
            extracted_strings = []
            for s in search_strings:
                if s not in name:
                    s = 'NOT FOUND!'
                extracted_strings.append(s)
            data.append(extracted_strings)

    with open('some.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(data)

rawDescription: Write multiple lists into csv. file in Python


code:
L = [['largest', 'artlegs'], ['spear', 'pears', 'reaps'], ['monster', 'sternom']]
M = max(len(xs[0]) for xs in L)
[xs for xs in L if len(xs[0]) == M]

rawDescription: Length of string in sublist within a list python


code:
recent=np.datetime64(0,'D')
recent

rawDescription: Finding most recent datetime in list before a given datetime


code:
def _key_slice_to_index_slice(items, key_slice):
    try:
        if key_slice.start is None:
            start = None
        else:
            start = next(idx for idx, (key, value) in enumerate(items)
                         if key == key_slice.start)
        if key_slice.stop is None:
            stop = None
        else:
            stop = next(idx for idx, (key, value) in enumerate(items)
                        if key == key_slice.stop)
    except StopIteration:
        raise KeyError
    return slice(start, stop, key_slice.step)

class SlicableDict(OrderedDict):
    def __getitem__(self, key):
        if isinstance(key, slice):
            items = self.items()
            index_slice = _key_slice_to_index_slice(items, key)
            return SlicableDict(items[index_slice])
        return super(SlicableDict, self).__getitem__(key)

    def __setitem__(self, key, value):
        if isinstance(key, slice):
            items = self.items()
            index_slice = _key_slice_to_index_slice(items, key)
            items[index_slice] = value.items()
            self.clear()
            self.update(items)
            return
        return super(SlicableDict, self).__setitem__(key, value)

    def __delitem__(self, key):
        if isinstance(key, slice):
            items = self.items()
            index_slice = _key_slice_to_index_slice(items, key)
            del items[index_slice]
            self.clear()
            self.update(items)
            return
        return super(SlicableDict, self).__delitem__(key)

rawDescription: How can you slice with string keys instead of integers on a python OrderedDict?

description: Slice with string keys instead of integers on a python OrderedDict


rawDescription: Stripping chars in python

description: Stripping chars in python


code:
for widget in qApp.allWidgets():
    if isinstance(widget, QtGui.QLineEdit):
        widget.clear()

rawDescription: PyQt Collection of QLineEdit objects

description: PyQt Collection of QLineEdit objects


code:
import csv

f = open('infile', newline='')
reader = csv.reader(f)
for row in reader:
    for field in row:
        print('-- {}'.format(field))

rawDescription: Extracting string between quotes split across multiple lines in Python


code:
import ujson
from pandas.io.json import json_normalize

with open('data.json') as f:
    data = ujson.load(f)

df = json_normalize(data, 'address', ['region', 'street-address'])

pd.set_option('display.expand_frame_repr', False)
print(df)

rawDescription: pandas slicing nested values along with other columns

description: Pandas slicing nested values along with other columns


code: recur = lambda l:len(l) if not isinstance(l,(tuple,list)) else sum(map(recur,l))

rawDescription: Lambda recursion over list in Python

description: Lambda recursion over list in Python


code: df.plot(kind='scatter', x='lon', y='lat', s=df['Total']*50, c=df['Total'], cmap=cmap)

rawDescription: Draw different sized circles on a map

description: Draw different sized circles on a map


code:
# This is the query we want to persist in a new table:
query= sourceSession.query(Pet.name, Pet.race).filter_by(race='cat')

# Build the schema for the new table
# based on the columns that will be returned
# by the query:
metadata = MetaData(bind=dest_engine)
columns = [Column(desc['name'], desc['type']) for desc in query.column_descriptions]
column_names = [desc['name'] for desc in query.column_descriptions]
table = Table("newtable", metadata, *columns)

# Create the new table in the destination database
table.create(dest_engine)

# Finally execute the query
destSession = DestSession()
for row in query:
    destSession.execute(table.insert(row))
destSession.commit()

rawDescription: SQLAlchemy - copy schema and data of subquery to another database


code: items = [(sum(map(a.get, sorted(a)[:i])), sum(map(a.get, sorted(a)[:i+1])), key) for i, key in enumerate(sorted(a))]

rawDescription: Generate tuples of intervals from dict in Python


code:
x== 1
x== 2
x== 3
x== 4
x== 5
x== 6
x== 7
block== '7 In such a night, when passing clouds give place,\n'
block== "8 Or thinly veil the heav'ns' mysterious face;\n"
block== '9 When in some river, overhung with green,\n'
x== 8
x== 9
x== 10
x== 11
x== 12
x== 13
x== 14
block== '14 And where the sleepy cowslip sheltered grows;\n'
block== '15 Whilst now a paler hue the foxglove takes,\n'
block== '16 Yet checkers still with red the dusky brakes\n'
x== 15
x== 16
x== 17
x== 18
x== 19
x== 20
x== 21
block== '21 When odors, which declined repelling day,\n'
block== "22 Through temp'rate air uninterrupted stray;\n"
block== '23 When darkened groves their softest shadows wear,\n'
x== 22
x== 23
x== 24
x== 25

rawDescription: Using python to process a chunk of a file every x lines


code: next(line.split()[-1] for line in s.split('\n') if 'NetName:' in line)

rawDescription: How to find text in a column with Python

description: Find text in a column with Python


code:
def my_long_doc_function(arg1, arg2):
    """This docstring is long, it's a little looonger than the 80 charachters
    limit.

    """

rawDescription: Docstrings - one line vs multiple line

description: Docstrings - one line vs multiple line


code:
import random
def rand_tuple():
    """ Return a random 5-tuple """
    return tuple( random.random() for _ in range(5) )

#100 random 5-tuples
lst = [ rand_tuple() for _ in range(100) ]

#sort the list using method 1
sorted_lst = sorted(lst, key = lambda x: (x[2],x[4],-x[0],x[1]))

#sort the list in place using method 2
lst.sort(key = itemgetter(1))  #<- Rightmost tuple element first!!!
lst.sort(key = itemgetter(0), reversed = True)
lst.sort(key = itemgetter(2,4))

print (lst == sorted_lst) #True -- Results are the same :-)

rawDescription: Sorting tuples in python using different orders for different fields


code: username in credentials

rawDescription: Python Login Script; Usernames and Passwords in a separate file


code:
data = {}
with open('scores.txt') as fobj:
    for line in fobj:
        name, score = line.split()
        data.setdefault(name, []).append(int(score))

for name, scores in data.items():
    avg = sum(scores[-3:]) / min(3, len(scores))
    print('{} your average was {}'.format(name, avg))

rawDescription: Finding the average of a list

description: Finding the average of a list


code:
matrices = [np.matrix(np.random.randn(3,4)) for i in range(10)]
for i, m in enumerate(matrices):
    matrices[i] = np.hstack((m, np.ones((m.shape[0], 1), dtype=m.dtype)))

rawDescription: Adding a new column to a list of matrixs(arrays)


code:
plt.pcolormesh(X, Y, Z, vmin=0, vmax=1)
plt.colorbar()

rawDescription: Calculating and plotting count ratios with Pandas


code: values = information

rawDescription: Sqlite thinks I lack bindings

description: Sqlite thinks I lack bindings


code:
all(v > 0 for v in pairs.itervalues())
all(v < 3000 for v in pairs.itervalues())

rawDescription: Check if any value of a dictionary matches a condition


code:
one
two
three
four
five
six
seven
eight
nine
ten

rawDescription: Turning list from text file into python list


code:
import shelve
d = shelve.open('score.txt')
score = d['score']           # the score is read from disk

rawDescription: Saving the highscore for a python game

description: Saving the highscore for a python game


rawDescription: Is it possible to find all elements with a custom html attribute in Beautiful Soup?


code:
import __builtin__
import numpy as np
{name for name in set(dir(np)).intersection(dir(__builtin__)) if not name.startswith('__') and getattr(__builtin__, name) != getattr(np, name)}

rawDescription: matplotlib.pyplot vs matplotlib.pylab

description: Matplotlib.pyplot vs matplotlib.pylab


code:
from collections import defaultdict
uniques = defaultdict(int)
with open('test.csv','r') as in_file, open('final.csv','w') as out_file:
    seen = set() # set for fast O(1) amortized lookup
    for line in in_file:
        uniques[line] +=1

    seen = set(k for k in uniques if uniques[k] == 1)
    for itm in seen:
        out_file.write(itm)

rawDescription: Python extract unique values from CSV

description: Python extract unique values from CSV


code:
def printText(self, target, text="wow"):
    target.setText(text)

rawDescription: Writing modular codes in python

description: Writing modular codes in python


code:
import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('bucket-name')
for obj in gcs:
    s3_obj = bucket.Object(gcs.key)
    s3_obj.put(Body=gcs.data)

rawDescription: copy file from gcs to s3 in boto3

description: Copy file from gcs to s3 in boto3


code:
buckets1000 = np.where(np.logical_and(tobebuckets > 500, tobebuckets <= 1000),
                       1000, 1001)
buckets500 = np.where(np.logical_and(tobebuckets > 100, tobebuckets <= 500),
                      500, buckets1000)
buckets100 = np.where(np.logical_and(tobebuckets > 50, tobebuckets <= 100),
                      100, buckets500)
buckets50 =  np.where(np.logical_and(tobebuckets > 10, tobebuckets <= 50),
                      50, buckets100)
buckets10 = np.where(np.logical_and(tobebuckets > 0, tobebuckets <= 10),
                     10, buckets50)
buckets = np.where(tobebuckets <= 0, 0, buckets10)

rawDescription: how to make long line as pep8 compatible in python?

description: Make long line as pep8 compatible in python


rawDescription: Extracting all the k-cores using networkx


code: res, idx = vq.kmeans2(data, 3)

rawDescription: Using scipy's kmeans2 function in python


code:
import sys
sys.exit(42)

rawDescription: SBCL Run Shell Command

description: SBCL Run Shell Command


code:
import numpy as np

from itertools import product

class IterableNumber:
    def __init__(self, digits):
        self.digits = digits
        self.zero_indices = np.where(self.digits==0)[0]
        self.length = len(self.zero_indices)

    def __iter__(self):
        for x in product(range(10), repeat=self.length):
            self.digits[self.zero_indices] = np.array(x)
            yield self.digits

rawDescription: Iterator for variable number of nested loops


code:
# Create the figure and subplot
fig = plt.figure()
ax = fig.addsubplot(111)

# Tinker with labels and spines
ax.set_xlabel(...)
ax.set_ylabel(...)
[a.label.set_color('black') for a in (ax.xaxis, ax.yaxis)]
...

# Plot data and save figures
for mol in mols:
    for energy, density in data:
        ax.cla() # or ax.clear()
        p, = ax.plot(density, energy, 'ro')

        fig.savefig(mol+".png")
        p.remove() # removes specific plot from figure

rawDescription: Looping over data and creating individual figures


code: sorted(cities, key=lambda item: item.name)

rawDescription: Sorting a List of Tuples (Python)

description: Sorting a List of Tuples (Python)


rawDescription: Returning .txt file contents

description: Returning .txt file contents


code:
def takeSection(sequence):
    it = iter(sequence)
    a = -1
    group = []
    while True:
        try:
            a, last = next(it), a
        except StopIteration:
            if group:
                yield group
            return
        if a < 0 and last >= 0:
            if group:
                yield group
            group = [a]
        else:
            group.append(a)

rawDescription: How to organize data that alternates between negative and positive values in Python

description: Organize data that alternates between negative and positive values in Python


rawDescription: Difference between super() and calling directly


code:
s = sp.symbols('(x/L)')
expr2.collect(x*u**5).subs(y, s)

rawDescription: Sympy factoring in Python

description: Sympy factoring in Python


code: [(k, adict[k]) for k in sorted(adict, key=adict.get, reverse=True)]

rawDescription: python, convert a dictionary to a sorted list by value instead of key

description: Python, convert a dictionary to a sorted list by value instead of key


code:
from itertools import chain , groupby
s=[zip(*i) for i in zip(list1,list2)]
[(set(i).pop(),sum(j)) for i,j in [zip(*i) for i in [list(g) for _,g in groupby(sorted(chain(*s)),lambda x : x[0])]]]

rawDescription: Reorganise list in list python

description: Reorganise list in list python


code:
with open('file', 'r') as target_file:
    replacement_text = target_file.read()

rawDescription: Parse HTML files then edit them in python


code:
import maya.mel as mel
cmds.curve(d=1, p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)] )
maya.mel.eval("nurbsCurveToBezier");

rawDescription: python maya: How do i create a linear bezier curve?

description: Python maya: How do i create a linear bezier curve


code:
wrapped = np.array(df['dir'])
wrapped[wrapped > 355] = 0
plt.hist(wrapped, bins=np.arange(0,370,10), align='left')

rawDescription: How to plot periodic data with matplotlib

description: Plot periodic data with matplotlib


code: row = np.random.randn(100)

rawDescription: pandas efficient dataframe set row

description: Pandas efficient dataframe set row


rawDescription: Finding which array contributes the maximum value for classification


code:
# Python 2.7
plotter = reload(plotter)

rawDescription: how to have one file work on objects generated by another in spyder

description: Have one file work on objects generated by another in spyder


code:
class Statistician(list):

    KEYS = {'RSI':0, 'MACD':1, 'CAPRATIO':2, 'OTHER':3}

    def __init__(self):
        list.__init__(self)

    def read_stocks(self, stocks):
        for stock in stocks:
            self.read_stock(stock)

    def read_stock(self, stock):
        self.append(stock)

    def stock_stats(self, stock_info):
        if stock_info not in Statistician.KEYS.keys() :
            raise Exception('Unknow stock_info category. Please use one of the following value : {0}'.format(str(list(Statistician.KEYS.keys()))))
        return list(map(lambda x: x[Statistician.KEYS[stock_info]],self))

if __name__ == "__main__":
    stocks = [('rsi1', 'macd1','capratio1','other1'),
              ('rsi2','macd2','capratio2','other2'),
              ('rsi3', 'macd3','capratio3','other3')]
    statistician = Statistician()
    for stock in stocks :
        statistician.read_stock(stock)

    print(statistician.stock_stats('RSI'))
    print(statistician.stock_stats('MACD'))

rawDescription: multiple call to a function to return a list of accumulated result

description: Multiple call to a function to return a list of accumulated result


code:
def __init__(self):
    self.do_map = dict(this=self.do_this, that=self.do_that)

rawDescription: Using a class dictionary to map to instance methods in Python


code: binrep = "".join(bytetable[x] for x in open("file", "rb").read())

rawDescription: Getting Raw Binary Representation of a file in Python


rawDescription: Python Datetime: All Items From Yesterday


code:
import time

filename = 'my_file.txt'
while True:
    try:
        with open(filename, 'rb') as _:
            break
    except IOError:
        time.sleep(3)

rawDescription: Python wait and check if file is created completely by external program


code:
app = Flask(__name__)
app.config.from_object('config')## add this line... .
db = SQLAlchemy(app)

rawDescription: Create an sqlite db and save it by means of python and flask


code:
indexes = list(Profile.objects.filter(full_name=full_name, birthday=birthday)
                              .values_list('idx', flat=True)[:1])
profile_idx = indexes[0] if indexes else None

rawDescription: Getting a single value from MySQL on Django (Python)


code:
prog = ["mysql", "-u", "ve", "--execute", 'insert into foo values ("snargle", 2)']
subprocess.call(prog)

rawDescription: Why is subprocess.Popen not waiting until the child process terminates?


code:
p = subprocess.Popen(["./AO_FelixStrategy_UnitTest",
                      "--bats", "31441", "--chix", "12467",
                      "--enxutp", "31884", "--turq", "26372",
                      "--symbol", "SOGN", "--target_date", '2009-Oct-16'],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE)

rawDescription: why does python.subprocess hang after proc.communicate()?

description: Why does python.subprocess hang after proc.communicate()


code:
import config
config.dburl = 'sqlite:///test.db'

rawDescription: 'from X import a' versus 'import X; X.a'


rawDescription: Search for an XML node in a parent by string with python


code:
items = {
  'an apple': 'apple.png',
  'a pear': 'pear.png',
  'an orange': 'orange.png'
}

rawDescription: Returning HTML elements from a view in Django


rawDescription: How to 'update' or 'overwrite' a python list

description: 'update' or 'overwrite' a python list


code:
coring = defaultdict(set)
for i,j in zip(score, match):
    coring[i].add(j)

coring

rawDescription: if key, value pair exist in a dictionary skip python

description: If key, value pair exist in a dictionary skip python


code:
for item in data['members'][0]:
    print(item)

rawDescription: Retrieving items from a dictionary data type created from a JSON request


code:
for row in cursor:
    process(row)

rawDescription: How to use Python list comprehension (or such) for retrieving rows when using MySQLdb?

description: Use Python list comprehension (or such) for retrieving rows when using MySQLdb


rawDescription: Regex to help split up list into two-tuples


code:
class C(object):
    def a(self):
        return 12

rawDescription: How works pre-defined descriptors in functions?


code: filter(lambda l: not l.startswith('taska'), list_1)

rawDescription: How to identify an odd item in a list of items using python

description: Identify an odd item in a list of items using python


code:
create_table_parts = reduce(lambda ctp, patt: cleanlist(ctp, *patt),
                            patterns, create_table_parts)

rawDescription: Less repeating yourself for re.sub with lists


code:
df.Amount.pct_change().shift(-1)*100
df['pct_diff'] = df.Amount.pct_change()*100
df

rawDescription: Calculating forward or backwards with pandas dataframes


code:
class ActiveManager(models.Manager):
    def get_query_set(self, active=True):
        return super(ActiveManager, self).\
            get_query_set().filter(pub_date__lte=timezone.now(), is_active=active)\
                           .order_by('-pub_date')

class InctiveManager(InctiveManager):
    def get_query_set(self):
        return super(InctiveManager, self).get_query_set(is_active=False)

class LatestManager(InctiveManager):
    def get_query_set(self):
        return super(LatestManager, self).get_query_set(is_active=True)\
                                         .filter(num_choices__gte=2)\
                                         .annotate(num_choices=Count('choice'))

class Poll(models.Model):
    ...

    objects = models.Manager()
    active = ActiveManager()
    inctive = InctiveManager()
    latest = LatestManager()

rawDescription: Organizing code in Django views

description: Organizing code in Django views


code:
@view_config(route_name='startBokehServer',renderer = 'json',permission='view')
def startBokehServer_view(request):

    # plotDataRev is dictionary containing data requested from web page
    with open('pyramidanalysis/temp/reversal_data.txt','wb') as handle:
      pickle.dump(plotDataRev,handle)
    bokeh_pid=str(subprocess.Popen(['/bokeh-server','-D','blaze_config.py'],stdout=subprocess.PIPE).pid)
    request.session['bokehPID']=bokeh_pid

rawDescription: Configure Blaze and start Bokeh server from Pyramid web-application


code:
from itertools import product, starmap
from collections import namedtuple

def named_product(**items):
    Product = namedtuple('Product', items.keys())
    return starmap(Product, product(*items.values()))

rawDescription: Name parts of iterables in itertools.products


code:
def cal_key(fk):
    present_keys = ModelA.objects.filter(fk=fk).order_by('-key').values_list('key',flat=True)
    if present_keys:
        return present_keys[0]+1
    else:
        return 0

rawDescription: Django Model Auto Increment Primary Key Based on Foreign Key


code:
COLOURS = ('blue', 'green', 'orange', 'red', 'yellow', 'white')

def colour_changer(button, colours=COLOURS):
    """Creates a callback to change the colour of the button."""
    colour_cycle = itertools.cycle(colours)
    def command():
        """The callback to change a single button's colour."""
        button.configure(bg=next(colour_cycle))
    return command

rawDescription: How do I use itertools.cycle with multiple objects?

description: Use itertools.cycle with multiple objects


code: df

rawDescription: Re-index dataframe by new range of dates


code:
import ipaddress
it = ipaddress.ip_network('10.0.0.0/8').subnets(new_prefix=22)
networks = [(str(n.network_address), str(n.broadcast_address)) for n in it]
len(networks)
networks[0]
networks[-1]

rawDescription: Get a list of subnets matching a given CIDR


code: x == [list(i) for i in zip(*x)]

rawDescription: I want to check whether my rows and columns are same


code:
DATABASE_NAME = 'osqa'             # Or path to database file if using sqlite3.
DATABASE_USER = 'root'               # Not used with sqlite3.
DATABASE_PASSWORD = 'PASSWD'               # Not used with sqlite3.  put bitnami here
DATABASE_ENGINE = 'mysql'  #mysql, etc

rawDescription: Installing OSQA on windows (local system)


code:
while some_queue_is_not_empty():
    run_external_process(some_queue)

def external_process(queue):
    item = queue.pop()
    # do processing here

rawDescription: multiprocessing Programming guidelines unclear

description: Multiprocessing Programming guidelines unclear


code:
k = np.array([0,1,2,3,4,5,6,5,4,10])
lm_i = np.where(np.diff(np.sign(np.diff(k))) > 0)[0] + 1
mlm = np.min(k[lm_i])
mlm_i = lm_i[np.argmin(k[lm_i])]

rawDescription: Is there a fast way to compare one element in a numpy array to the rest of the elements in that array?


rawDescription: Building a dictionary from a tab delimited file in a pythonic way


code: project_data = {}

rawDescription: Insert post data into MongoDB

description: Insert post data into MongoDB


code:
def text_capture(test):
        mtext = test.get()
        print(test)
        print(mtext)
        print(test.get())

rawDescription: Store data from Entry widget tkinter

description: Store data from Entry widget tkinter


code:
r = requests.head('http://pymotw.com/2/urllib/index.html',headers={'Accept-Encoding': 'identity'})
r.headers['content-length']

rawDescription: get file size before downloading using HTTP header not matching with one retrieved from urlopen

description: Get file size before downloading using HTTP header not matching with one retrieved from urlopen


code:
import yaml

class ExplicitDumper(yaml.SafeDumper):
    """
    A dumper that will never emit aliases.
    """

    def ignore_aliases(self, data):
        return True

rawDescription: Is it possible to emit valid YAML with anchors / references disabled using Ruby or Python?


code:
@pytest.fixture()
def tester(request):
    """ create tester object """
    # how to use the list below for arg?
    _tester = MyTester(request)
    return _tester

rawDescription: py.test: Pass a parameter to a fixture function

description: Py.test: Pass a parameter to a fixture function


code:
class A:
    pass

class B:
    pass

A.friend = Friend(B)
B.friend = Friend(A)

rawDescription: How to access globals from a different point in code

description: Access globals from a different point in code


code:
def nearest_neighbors_kd_tree(x, y, k) :
    x, y = map(np.asarray, (x, y))
    tree =scipy.spatial.cKDTree(y[:, None])
    ordered_neighbors = tree.query(x[:, None], k)[1]
    nearest_neighbor = np.empty((len(x),), dtype=np.intp)
    nearest_neighbor.fill(-1)
    used_y = set()
    for j, neigh_j in enumerate(ordered_neighbors) :
        for k in neigh_j :
            if k not in used_y :
                nearest_neighbor[j] = k
                used_y.add(k)
                break
    return nearest_neighbor

rawDescription: finding nearest items across two lists/arrays in Python

description: Finding nearest items across two lists/arrays in Python


rawDescription: Replace elements in numpy array using list of old and new values


rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


code:
screen.blit(map1, (0,0),
            (camera[0], camera[1], screen.get_width(), screen.get_height())
           )

rawDescription: Python Pygame Camera Movement

description: Python Pygame Camera Movement


code:
from __future__ import print_function
import sys
import math

word = sys.argv[1]

rawDescription: I cannot figure out how to manipulate strings in a couple different ways


code:
# original.py

original_list = [1,2,3]

rawDescription: Extending a list in one module from another -- without any lines in the old module?


code: [[1 if j <= 1 else 2 for i in range(3)] for j in range(3)]

rawDescription: Python: List comprehension to assign different values


rawDescription: Python Image Library - Convert pixels to 2D list


rawDescription: Throwing out elements in a python list of pairs


rawDescription: count the dictionary keys in a list

description: Count the dictionary keys in a list


code:
def contour_to_image(con, original_image):
    # Get the rect coordinates of the contour
    lm, tm, rm, bm = rect_for_contour(con)

    con_im = original_image.crop((lm, tm, rm, bm))

    if con_im.size[0] == 0 or con_im.size[1] == 0:
        return None

    con_pixels = con_im.load()

    for x in range(0, con_im .size[0]):
        for y in range(0, con_im.size[1]):
            # If the pixel is already white, don't bother checking it
            if con_im.getpixel((x, y)) == (255, 255, 255):
                continue

            # Check if the pixel is outside the contour. If so, clear it
            if cv2.pointPolygonTest(con, (x + lm, y + tm), False) < 0:
                con_pixels[x, y] = (255, 255, 255)

    return con_im

def findAndColorShapes(input_file, shapes_dest_path):
    im = cv2.imread(input_file)
    imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(imgray, 220, 255, 0)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    i = 0

    for con in contours:
        con_im = contour_to_image(con, Image.open(input_file))
        if con_im is not None:
            con_im.save(shapes_dest_path + "%d.png"%i)
            i += 1

rawDescription: OpenCV - Drawing contours as they are

description: OpenCV - Drawing contours as they are


code:
import numpy
data = numpy.array([[ 1, 2, 5 ]])
mask = numpy.array([[0,1,0]])

numpy.ma.masked_array(data, ~mask) #note this probably wont work right for non-boolean (T/F) values
#or
numpy.ma.masked_array(data, numpy.logical_not(mask))

rawDescription: Numpy inverse mask

description: Numpy inverse mask


code:
def Density_distribution(H0, Rh, r, z, rho0, Rc, Rd):
      return Density(float(rho0), r, Rc, Rd) * np.exp(-z / Thickness_H(H0, r, Rh))

rawDescription: define three functions into one in python

description: Define three functions into one in python


rawDescription: 2D Sorting with NumPy - sort 1 row and have the other follow the sorting


code: somelist[:] = [x for x in somelist if not determine(x)]

rawDescription: Remove items from a list while iterating in Python


code:
def func(a,b):
    print (a,b)

args=(1,2)
func(*args)

rawDescription: Calling python function with an unknown number of arguments


rawDescription: How to operate with values in the same column in .csv files

description: Operate with values in the same column in .csv files


code:
for t in lines:
    print(t[1])

rawDescription: Access elements of a comma separated list with tuples in Python


code:
if form.is_valid():
    chapter = form.save()
    # Now chapter.parent() == book

rawDescription: Set parent in a ModelForm in Google App Engine


code:
order = ['a', 'n', 'A', 'N']
sorted(['A', 'n', 'N', 'a'], key=order.index)

rawDescription: Change the way sorted works in Python (different than alphanumeric)


code:
for i in range(2, l + 1):
    replace_index = "//form[@id='SubAvailSelectForm']/font/table[2]/tbody/tr[%d]/td[1]/small" % (i,)
    job_count_array[replace_index] = sel.get_text(replace_index)

rawDescription: How to gracefully break up a long string

description: Gracefully break up a long string


code:
given_dict = OrderedDict((j[0],j[1]+[given_list[i]]) for i,j in enumerate(given_dict.items()))
given_dict

rawDescription: Zipping items from a list with lists from an ordered dictionary in Python


code:
cursor.execute(
    "insert into mytable (rating, name) values (%s, %s);",
    ("5.0 (7)", "HOPPE'S No. 9")
)

rawDescription: How to handle apostrophes in MySQL-Python?

description: Handle apostrophes in MySQL-Python


code: diff = np.gradient(Z)

rawDescription: Can I get first derivative for kernel density estimation in python?

description: Get first derivative for kernel density estimation in python


rawDescription: Python List: Pythonic way to get unique items in given List from a given Set


code:
import fileinput

input = fileinput.input()
for line in input:
    for j in range(int(line)):
        solve(*[int(i) for i in input.next().split()])

rawDescription: Read n test cases from file in Python

description: Read n test cases from file in Python


rawDescription: How to keep the current figure when using ipython notebook with %matplotlib inline?

description: Keep the current figure when using ipython notebook with %matplotlib inline


code:
import sys
sys.executable

rawDescription: Get python install path from running script


rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


code:
from datetime import date
import random, string
def random_date(): return date.fromordinal(random.randint(730000, 740000))

def random_key(): return ''.join([random.choice(string.ascii_lowercase) for _ in range(10)])

list_of_dictionaries = [{random_key(): random_date() for _ in range(random.randint(1, 3))} for _ in range(5)]
list_of_dictionaries
min(list_of_dictionaries, key=lambda d: min(d.values()))

rawDescription: Python: file oldest date value in a list of objects


code: data[test_cols == test_vals]

rawDescription: Create a new array from numpy array based on the conditions from a list


code:
for name in os.listdir("."):
    if name.endswith(".txt"):
        print(name)

rawDescription: Getting Every File in a Directory, Python


code:
values = food_to_food_type.values()
dict( zip( values, map( values.count, values ) ) )

rawDescription: How can I "map" a dict to change only the values in Python


rawDescription: How to *not* display 'NaN' in ipython notebook (html table of pandas dataframe)?


rawDescription: Efficient Python implementation of numpy array comparisons


code:
import os

filenames =['testfile1.csv','testfile2.csv']

for file in filenames:
    if os.path.isfile(file):
        print("File exists.")
    else:
        print("File does not exist.")

rawDescription: Using a reference list to find specific files by name


code:
if key[pygame.K_RIGHT] and key[pygame.K_LEFT]:
    if pygame.K_RIGHT in was_pressed:
        # the left one's the new one!
        self.x -= dist # move left
    elif pygame.K_LEFT in was_pressed:
        # the right one's the new one!
        self.x += dist # move right
    else:
        # both freshly pressed at once, what now?!
        pass  # assume e.g they "cancel each other out"
elif key[pygame.K_RIGHT]:
    was_pressed = {pygame.K_RIGHT}
    self.x += dist # move right
elif key[pygame.K_LEFT]:
    was_pressed = {pygame.K_LEFT}
    self.x -= dist # move left
else:
    was_pressed = set()

rawDescription: Python pygame, moving an object

description: Python pygame, moving an object


code:
arr
np.argwhere(arr)

rawDescription: Numpy binary matrix - get rows and columns of True elements


code:
s = '2013-06-05T11:01:02.955 LASTNAME=Jone FIRSTNAME=Jason PERSONNELID=salalm QID=231412 READER_NAME="CAZ.1 LOBBY LEFT TURNSTYLE OUT" ACCESS_TYPE="Access Granted" EVENT_TIME_UTC=1370480141.000 REGION=UTAH'
split = shlex.split(s)
split

rawDescription: how to separate string from unformed string

description: Separate string from unformed string


code:
schoolPopulation = open("SchoolPopulation.txt", "r")
results = {}
for line in schoolPopulation:
    parts = line.split(",")
    name = parts[0].lower()
    val = int(parts[1])
    if name in results:
        results[name] += val
    else:
        results[name] = val
print(results)
schoolPopulation.close()

rawDescription: Python 3.X combining similar lines in .txt files together


code:
from random import choice
from string import lowercase
n = 10

string_val = "".join(choice(lowercase) for i in range(n))

rawDescription: In Python, how do I create a string of n characters in one line of code?


code:
q = sess.query(table1, table2, table3.string_column)
q = q.subquery()

rawDescription: selecting whole entities from SQLAlchemy subqueries

description: Selecting whole entities from SQLAlchemy subqueries


code: {'profile': {'dma_targets': 5678}}

rawDescription: Python Best Way to construct Dictionary from Inputs


code: found = re.findall('|'.join(re.escape(x) for x in searchList), cleanText)

rawDescription: Fastest way in python to search for multiple items in a body of text


code:
def listgen(n):
    return map(int, ''.join(map(str, range(1, n + 1))))

rawDescription: Creating a list of numbers one through nth Python


code: self.user = User.objects.create_user(username='user', email='email@example.com', password='pass')

rawDescription: Create a simple password for unittest user using PASSWORD_HASHERS


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

rawDescription: SQLAlchemy - Dictionary of tags

description: SQLAlchemy - Dictionary of tags


code:
ARR2 = [True, True, True,]
all(ARR2)

rawDescription: AND operation for Boolean array's elements


code:
df[['Start', 'End']] = df['Time'].str.extract('(?P<Start>.+) - (?P<End>.+)')
del df['Time']
df['Start'] = pd.DatetimeIndex(df['Start'])
df['End'] = pd.DatetimeIndex(df['End'])

rawDescription: Pandas Python: Merging every two rows in one dataframe


code:
for key, value in template.items():
    template[key] %= values_dict

rawDescription: Python dictonary with string placeholders and defaults


code:
class testClass:
    class Color(Enum):
        red = 1
        blue = 2
        green = 3
    red = Color.red
    blue = Color.blue
    green = Color.green

    def setValue(self, color):
        self.value = color

rawDescription: Using an Enum as a flag in a class, Python


rawDescription: BFS algorithm in Python

description: BFS algorithm in Python


code:
def locate_min(a):
    min_indicies = []
    smallest = min(a)
    for index, element in enumerate(a):
            if smallest == element: # check if this element is the minimum_value
                    min_indicies.append(index) # add the index to the list if it is

    return smallest, min_indicies

rawDescription: Python - getting all the min elements and its indices from a list


code:
tmp = []
for i in a:
    if i[-1] != 0:
        tmp.append(i)
a = tmp

rawDescription: Removing items from a list in python

description: Removing items from a list in python


code:
class Resource(ModelResource):
    angular_t = fields.CharField(attributes='angular_t', null=True)

rawDescription: How to Map a Django model field to some user defined value


code:
heapq.nsmallest(k, range(len(input_list)), key=input_list.__getitem__)  # O(NlogK)
numpy.argpartition(numpy.array(input_list), k)[:k].tolist()  # O(N)

rawDescription: fastest method of getting k smallest numbers in unsorted list of size N in python?

description: Fastest method of getting k smallest numbers in unsorted list of size N in python


code: sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

rawDescription: Converting JSON String to Dictionary, Not List (Python)


code:
with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print(row)

    f.seek(0)
    next(reader)

    for row in reader:
        print('Stack Overflow')

rawDescription: Loop over rows of csv.DictReader more than once


code:
storage_locations = [ '/' ]
max((shutil.disk_usage(path).free, path) for path in storage_locations)

rawDescription: Find path from tuple with most free space


code:
from django.apps import apps

z = ContentType.objects.get(model='modelb')
ModelB = apps.get_model(z.app_label, 'ModelB')

rawDescription: Querying a django model using a model name string input


code:
for rowi, row in enumerate(reader):
    for coli, value in enumerate(row):
        if rowi >= 2:
            value = int(value)
        sheet.write(rowi, coli, value)

rawDescription: read csv file with header and data, and convert to xls file

description: Read csv file with header and data, and convert to xls file


code:
from collections import Counter
L=['d','f','d','c','c','f','d','f']
Counter(L)

rawDescription: python count list item occurences and put result in list

description: Python count list item occurences and put result in list


rawDescription: comparing two text files and remove duplicates in python

description: Comparing two text files and remove duplicates in python


rawDescription: How to iterate over time periods in pandas

description: Iterate over time periods in pandas


code:
from sqlalchemy import String
from sqlalchemy.types import TypeDecorator

class StringFloat(TypeDecorator):
    impl = String

    def process_literal_param(self, value, dialect):
        return str(float(value)) if value is not None else None

    process_bind_param = process_literal_param

    def process_result_value(self, value, dialect):
        return float(value) if value is not None else None

rawDescription: Convert string to float SQLAlchemy

description: Convert string to float SQLAlchemy


code:
from time import strptime

format = '%I:%M%p' # format to striptime

epg_time_1 = strptime('9:30PM', format)
epg_time_2 = strptime('10:10PM', format)
epg_time_3 = strptime('10:30PM', format)

prog_clock = strptime('10:00PM', format)

if epg_time_2 == prog_clock:
    print("WORKING 1")

elif prog_clock > epg_time_1 and epg_time_2 > prog_clock:
    print("WORKING 2")

elif epg_time_3 == prog_clock:
    print("WORKING 3")

elif epg_time_3 < prog_clock:
    print("WORKING 4")

rawDescription: compare the int in the strings

description: Compare the int in the strings


code:
if amount >= 500:
    while 0 < amount:
        amount -= 500
        fivehundreds += 1

rawDescription: All cash change is only for one bill

description: All cash change is only for one bill


rawDescription: Output issue calculating moving average

description: Output issue calculating moving average


code:
def split_into(s, n):
    size, remainder = divmod(len(s), n)
    start = 0
    for i in range(n):
        length = size + (i < remainder)
        yield s[start:start + length]
        start += length

rawDescription: Split a string into exactly N pieces

description: Split a string into exactly N pieces


code:
def get_name(obj):
    """Get the name of an object (variable) from the globals dict.

    Argument:
       - obj : The variable that we want to get the name of.

    Return:
       - A string representing the name of the object if it was found else return None.

    """

    for name, value in globals().items():
         if value is obj:
             return name

rawDescription: Generating evalable python code: all combinations of functions in disjunctive normal form


code:
rows = range(10,15)
cols = range(5,8)
A[rows][:,cols]

rawDescription: Using numpy to Obtain Submatrix

description: Using numpy to Obtain Submatrix


code:
from copy import deepcopy

srt_dict = deepcopy(a)
srt_dict["searchResult"].sort(key=lambda d: d["ranking"], reverse=True)

rawDescription: Sorting by nested dictionary in Python dictionary


code:
_sentinel = object()

def transform_point(self, x=_sentinel, y=_sentinel):
    if x is _sentinel:
        x = self.x
    if y is _sentinel:
        y = self.y

rawDescription: Default to class variables in a python class method?


code:
import zipfile
import os
import sys

zipped_files_dir = 'Z:\Dev\some_files'

def get_folder_names():
    path_list = []
    for folder_name in os.listdir(zipped_files_dir):
        path_list.append(folder_name)
    return path_list

def get_folder_directories(folder_list):
    for folder in folder_list:
        pathname = os.path.abspath(os.path.join(zipped_files_dir, folder))
        print(pathname)

def main():
    get_folder_directories(get_folder_names())

rawDescription: full file path for zipped folder in python

description: Full file path for zipped folder in python


code: score

rawDescription: efficiently do weighted count the elements in the list

description: Efficiently do weighted count the elements in the list


code:
from collections import defaultdict
count = defaultdict(int)
for x in my_csv_reader:
    count[x[3]] += 1

rawDescription: Add new keys to a dictionary while incrementing existing values


code: [n for n, (i, s) in enumerate(t) if s == 'str_3']

rawDescription: Python Nested lists and iteration

description: Python Nested lists and iteration


code:
list_of_dicts =[{'genres': ['Thriller'], 'year': '2014'}, {"year": '2014'}]
set(genre for d in list_of_dicts for genre in d.get('genres', []))

rawDescription: Remove inner list in list of lists

description: Remove inner list in list of lists


rawDescription: Python load json file with UTF-8 BOM header


code:
class cls(object):
   pass
cls = singleton( cls )

rawDescription: Why isn't the instances variable lost after executing the function?


rawDescription: Python requests urlencode without sending any request


code: reduce(dict.__getitem__, l, d)

rawDescription: Any Functional Programming method of traversing a nested dictionary?


code:
m = np.array([[0,0,0],[1,1,0],[1,1,0]])
m
[np.bincount(m[i]) for i in range(m.shape[1])]
np.apply_along_axis(np.bincount, 1, m)

rawDescription: Can numpy bincount work with 2D arrays?

description: Can numpy bincount work with 2D arrays


code:
h = """

              Some Other Text

 List1 Element1

 List1 Element2

 List1 Element3

          Signaling Text

 List2 Element1

 List2 Element2

 List2 Element3

  """

from lxml import html
tree = html.fromstring(h)
print(tree.xpath('//td[contains(.,"Signaling Text")]/following::td[@class = "lists"]/ul/li/text()'))

rawDescription: Getting list based on text lxml

description: Getting list based on text lxml


code:
from random import randint

# number of coin flips to simulate
num = 100

# simulate the coin flips
flips = [randint(1,2) for x in range(num)]

# count up the results
heads = flips.count(1)
tails = flips.count(2)

# print the results to the console
print("{0} Coin Flips".format(num))
print("{0} Heads".format(heads))
print("{0} Tails".format(tails))

rawDescription: Python ( Heads or Tails Counter )

description: Python ( Heads or Tails Counter )


code: [a for a in re.split(r'([A-Z][a-z]*)', 'MgSO4') if a]

rawDescription: Splitting a string by capital letters

description: Splitting a string by capital letters


code: re.sub("foo|bar", "yay", "foo bar baz")

rawDescription: python replace two optional strings with a third (looking for a neat way)

description: Python replace two optional strings with a third (looking for a neat way)


code:
name, owner,"local file names"
foo,bar,"foo the foo"
foofoo,bar,"bar the bar"

rawDescription: Cant print list out of python function

description: Cant print list out of python function


code:
with open ("newhosts.txt", "w") as thefile:
    thefile.write("\n".join(map(", ".join, hostnameIP)))

rawDescription: python write list to file

description: Python write list to file


code: urllib.urlopen(url, post_args)

rawDescription: a (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib

description: A (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib


code:
def f3_simple(n):
    i = n                         # "length": O(1)
    condition = i>0               # comparison: O(1)
    while condition:              # executed O(n) times per function call
        r1 = range(i)               # range(i): O(i)
        for j in r1:                # executed O(n) times per WHILE iteration
            r2 = range(j, 10**5)      # range(j, 10**5): O(10**5 - j) = O(1)
            for k in r2:              # executed O(1) times per OUTER FOR iteration
                print(i)                # print: O(1)
        i -= 2                      # decrement: O(1)
        condition = i>0             # comparison: O(1)

rawDescription: python complexity calculation

description: Python complexity calculation


code:
a =  1326048  # /100=  13260.48 ; s=2
b =   234493  # /100=   2344.93 ; s=2
c = 34756334  # /100= 347563.34 ; s=2
# All three numbers are in the same scale, so they can be added directly.  Scale of the result is the same as the numbers (s=2)
d = a + b + c  # /100; s=2
# In multiplication, scale of the result is the sum of the scale of the factors.
# This has the advantage that the scale of operands can be different.
e = a * b  # /10000; s=4
# But we want to go back to 2 decimals quickly.  So, round to 2 decimals.  And yes, division subtracts scales.
e = ( e + 50 ) // 100  # /100 s=2

rawDescription: Rounding Error in Python

description: Rounding Error in Python


code: matching_results = [t for t in list_ if t[0] == c_code]

rawDescription: How can I get a Tuple from a list in python (3.3)

description: Get a Tuple from a list in python (3.3)


code:
def region_from_segment( image, segment ):
    '''given a segment (rectangle) and an image, returns it's corresponding subimage'''
    x,y,w,h= segment
    return image[y:y+h,x:x+w]

rawDescription: Python Image Matching. Find mxm image from nxn image


rawDescription: How would I sort a hierarchical list into a tree/pyrimid model of dicts?


code:
from shutil import move
from tempfile import NamedTemporaryFile

with open('file.csv', 'rb') as csvfile, NamedTemporaryFile(dir=".", delete=False) as temp:
    rowlist = csv.reader(csvfile)
    for row in islice(rowlist, 6, 12):
        if row[0] == "data_type":
            continue
        elif row[0] == "fields":
            temp.write(islice(rowlist, 1, None))
        else:
            temp.write(row)

move(temp.name,"file.csv")

rawDescription: python: how to delete row and modify specific list string from CSV

description: Python: how to delete row and modify specific list string from CSV


code:
from collections import OrderedDict

class myClass():
    biography = OrderedDict()
    def setupDict(self):
        self.biography["Name"] = "Some name here"

rawDescription: Append to Python dictionary from method

description: Append to Python dictionary from method


code:
import pandas as pd
df_old = pd.read_csv("legacyFile.csv")
df_new = pd.read_csv("NewMapping.csv")
df_merged = df_old.merge(df_new, left_on="ID", right_on="LEGACY_ID", how="outer")
df_merged.to_csv("combined.csv", index=False)

rawDescription: Python: Combining two CSV files with header row and matched values with DictReader and DictWriter


code:
from pyspark.sql.functions import lit

df_with_timestamp.where(
    df_with_timestamp.timestamp > lit(now - timedelta(minutes=5)))

rawDescription: Column filtering in PySpark

description: Column filtering in PySpark


code:
a = np.arange(1, 10)
b = np.random.rand(100) * 10
c = np.searchsorted(a, b, side='right')
b[c == 0]
b[c == 1]

rawDescription: Speed up comparison of floats between lists


rawDescription: Obtaining the combination of elements in a dictionary


rawDescription: nested classes in Python

description: Nested classes in Python


rawDescription: Extracting specific src attributes from script tags


rawDescription: Python re.search - searching from left to right


code:
import numpy as np
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
np.random.seed(2016)

def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples.
      - Every float is sandwiched between two RGB values.
      - The floats indicate locations (on a scale from 0.0 to 1.0) where the
        color map transitions from one RGB color to the next.
      - The floats should be in increasing order
      - The first and last values in the sequence are the first and last
        colors in the color map.
    http://stackoverflow.com/q/16834861/190597 (unutbu)
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)

# There are 103 integers from 0 to 102 (inclusive)
idx = np.linspace(0, 1, 103)
c = mcolors.ColorConverter().to_rgb
mygreen = make_colormap([c('burnt red'),
                         c('yellow green'), idx[1], c('yellow green'),
                         (0,1,0), idx[2], (0,1,0),  # RGB (0,1,0) is standard green?
                         c('dark green')])

arr = np.random.randint(0, 103, size=(11, 11))
print(np.where(arr==0))
print(np.where(arr==1))
plt.imshow(arr, interpolation='nearest', cmap=mygreen, vmin=0, vmax=102)
plt.colorbar(ticks=list(range(0, 100, 10))+[102])
plt.show()

rawDescription: Discrete then linear colormap in matplotlib


code:
class BinaryOperation(ParsedObject):
    def queryString(self):
        joinstr = ' %s ' % self.op
        return joinstr.join(t.queryString() for t in self.tokens[0::2])
class OrOperation(BinaryOperation):
    op = "OR"
class AndOperation(BinaryOperation):
    op = "AND"
or_term.setParseAction(OrOperation)
and_term.setParseAction(AndOperation)

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


rawDescription: How to access individual predictions in Spark RandomForest?

description: Access individual predictions in Spark RandomForest


code:
m = np.tril(np.ones((s,s)),1)
m * m.T
m = np.tril(np.ones((s,s)),2)
m * m.T

rawDescription: Constructing a special matrix in numpy dynamically


code: filter(name="Employee")

rawDescription: Multi-Group rules in view to enforce redirect?


code:
cum_dist = np.linspace(0.,1.,len(ser))
ser_cdf = pd.Series(cum_dist, index=ser)

rawDescription: Plotting CDF of a pandas series in python


code:
sentinel = object()

def foo(self, value=sentinel):
    if value is not sentinel:
        print("You passed in something else!")

rawDescription: Using None as parameter to keyword argument


code:
import sys
writer = csv.writer(sys.stdout)
keys = sorted(all_custom_vals)
writer.writerow(['ID', 'STUFF'] + keys)
for row in results:
    items = [row['ID'], row['STUFF']]
    for key in keys:
        items.append(row.get(key, '<no value>'))
    writer.writerow(items)

rawDescription: Convert values in CSV column to individual columns


code:
class MyOrderedField(int):
  creation_counter = 0

  def __init__(self, val):
    # Set the instance's counter, to keep track of ordering
    self.creation_counter = MyOrderedField.creation_counter
    # Increment the class's counter for future instances
    MyOrderedField.creation_counter += 1

rawDescription: How can I get fields in an original order?

description: Get fields in an original order


rawDescription: Python/Numpy C++ extension: memory issue


code: from django.core.management import execute_from_command_line

rawDescription: Execute manage.py from python shell

description: Execute manage.py from python shell


rawDescription: python date on file want to strip off microseconds

description: Python date on file want to strip off microseconds


code:
df = pd.DataFrame({col: pd.Series(range(df[col].min(),
                                        df[col].max() + 1)) for col in df.columns })
print (df)

rawDescription: Appending variable length columns in Pandas dataframe Python


rawDescription: Find Monday's date with Python

description: Find Monday's date with Python


rawDescription: Numpy multiplication of vectors of different size avoiding for loops


code: fdf.pivot_table('percent', rows='row', cols='col', aggfunc='sum').values

rawDescription: pandas aggregated data to a numpy array : data structure conversion

description: Pandas aggregated data to a numpy array : data structure conversion


rawDescription: Python file string comparison

description: Python file string comparison


code:
if name == "Sam":
    print ("Your name is Sam")

rawDescription: Why doesn't the result of input() match what I expect to get?


code:
c = [1,2,3]
def multiply(x, y, z):
    return x * y * z
def add(x, y):
    return x + y
my_math = { "+":add,
            "*":multiply}
print(str(my_math["+"](*c)))
print(str(my_math["*"](*c)))

rawDescription: About functions dispatch in python3

description: About functions dispatch in python3


code:
data.remove(value) #data.discard(value) if you don't care if the item exists.
data.add(new_value)

rawDescription: What are the pythonic way to replace a specific set element?


code:
with open(filename, 'rb') as f:
    reader = csv.DictReader(f)
    things = list(reader)

rawDescription: Copying dicts from csv to a new dict-python


code:
def human_readable(self, x):
    if x == 0: return '0'
    magnitude = int(log10(abs(x)))
    if magnitude > 13:
        format_str = '%i T'
        denominator_mag = 12
    else:
        float_fmt = '%2.1f ' if magnitude % 3 == 1 else '%1.2f '
        illion = (magnitude + 1) // 3
        format_str = float_fmt + ['', 'K', 'M', 'B', 'T'][illion]
        denominator_mag = illion * 3
    return (format_str % (x * 1.0 / (10 ** denominator_mag))).lstrip('0')

rawDescription: Python formatting large values

description: Python formatting large values


code:
class Foo(object):
    def __getattribute__(self,name):
        attr = object.__getattribute__(self, name)
        if hasattr(attr, '__call__'):
            def newfunc(*args, **kwargs):
                print('before calling %s' %attr.__name__)
                result = attr(*args, **kwargs)
                print('done calling %s' %attr.__name__)
                return result
            return newfunc
        else:
            return attr

rawDescription: Intercept method calls in Python

description: Intercept method calls in Python


rawDescription: How to run all tests in a python file from a python script?

description: Run all tests in a python file from a python script


code:
grouped = df.groupby('A')
grouped['C'].agg([np.sum, np.mean, np.std])

rawDescription: applying an operation to multiple columns having multiple columns in the result

description: Applying an operation to multiple columns having multiple columns in the result


code:
A
x

rawDescription: Broadcasting issues with numpy.linalg.lstsq


code:
dill.dumps(ff, byref=False)
dill.dumps(ff, byref=True)

rawDescription: Why dill dumps external classes by reference, no matter what?


code:
string_part = 'ping -W 2 -c 2  64.233.{}.{}'

for i in range(160, 165):
     for j in range(5):
          prompt = string_part.format(i, j)
          proc = subprocess.Popen(prompt, shell=True, stdout=subprocess.PIPE)
          result, _ = proc.communicate()

rawDescription: Implementing ping using Python

description: Implementing ping using Python


code:
def recurse(left, right, combinations):
    if len(right) > 1:
        recurse(left + ' ' + right[:2], right[2:], combinations)
    if len(right) > 0:
        recurse(left + ' ' + right[:1], right[1:], combinations)
    if len(right) == 0:
        combinations.append(left)
def get_combinations(base):
    combinations = []
    recurse('', base, combinations)
    return combinations
print('\n'.join(print_combinations('abcde')))

rawDescription: Get all combination of two elements with distance 1


rawDescription: How can I select all DataFrame rows that are within a certain distance of a given value in a specific column?

description: Select all DataFrame rows that are within a certain distance of a given value in a specific column


code:
def saveImage():
    global pic
    toSave = filedialog.asksaveasfile(mode='w',defaultextension='.jpg')
    pic.save(toSave)

rawDescription: Having some trouble converting a tk PhotoImage back to a PIL image to save


code: widget.bind('<Return>', event_handler)

rawDescription: Function when entered in text box?

description: Function when entered in text box


code:
def comp_len(o1, o2):
    return len(o1) == len(o2)
group(["foo", "bar", "blub", "blah", "bonk"], comp_len)

rawDescription: Gather elements from list into lists of lists of equal elements?


code:
all_keys = set([u'Cyp26_G_R1', u'Cyp26_G_rep1', u'Time'])

specie_name_and_initial_values = set(['[Cyp26_R1R2_RARa]', '[Cyp26_SRC3_1]', '[18-OH-RA]', '[p38_a]', '[Cyp26_G_rep1]', '[Cyp26]', '[Cyp26_G_a]', '[SRC3_p]', '[mRARa]', '[np38_a]', '[mRARa_a]', '[RARa_pp_TFIIH]', '[RARa]', '[Cyp26_G_L2]', '[atRA]', '[atRA_c]', '[SRC3]', '[RARa_Ser369p]', '[p38]', '[Cyp26_mRNA]', '[Cyp26_G_L]', '[TFIIH]', '[Cyp26_SRC3_2]', '[Cyp26_G_R1R2]', '[MSK1]', '[MSK1_a]', '[Cyp26_G]', '[Basal_Kinases]', '[Cyp26_R1_RARa]', '[4-OH-RA]', '[Cyp26_G_rep2]', '[Cyp26_Chromatin]', '[Cyp26_G_R1]', '[RXR]', '[SMRT]'])

specie_name_and_initial_values = set(s.strip("[]") for s in specie_name_and_initial_values)

print(all_keys.intersection(specie_name_and_initial_values))

rawDescription: Regular expressions matching words which contain the pattern but also the pattern plus something else


code:
myLists = list()
for x in range(22):
    myLists.append( [0,0,0,0,0] )

rawDescription: How Can I name a list inside a 'FOR' loop

description: Name a list inside a 'FOR' loop


code: x = np.random.pareto(shape, size) + lower

rawDescription: How to generate random numbers in specyfic range using pareto distribution in Python

description: Generate random numbers in specyfic range using pareto distribution in Python


code:
#!/usr/bin/env python
# b.py

from a import foo

foo()

rawDescription: How do I find out in which file or module is my function called?

description: Find out in which file or module is my function called


code:
import pandas as pd
writeHeader = True

for i in range(1,4):
    data = [{'name': 'Company'+str(i), 'city': 'New York'}]

    stuff = []
    for element in data:
        stuff.append(element)

    df = pd.DataFrame(columns=["name",
                               "city"])

    for record in stuff:
        df = df.append(record, ignore_index=True)

    if writeHeader is True:
        df.to_csv('test.csv', mode='a', header=True, index=False)
        writeHeader = False
    else:
        df.to_csv('test.csv', mode='a', header=False, index=False)

rawDescription: Keep header while appending to Pandas dataframe w/ Python


code:
with open('existing.csv', 'rb') as infile, open('out_file.csv', 'wb') as outfile:
    reader = csv.reader(infile)
    header = next(reader) # get header
    writer = csv.writer(outfile)
    # create list with old header and new
    writer.writerow(header+["list1", "list2", "list3"])

rawDescription: Adding headers to a csv file

description: Adding headers to a csv file


code:
import imaplib
import socket

class IMAP(imaplib.IMAP4):
    def __init__(self, host='', port=imaplib.IMAP4_PORT, timeout=None):
        self.timeout = timeout
        # no super(), it's an old-style class
        imaplib.IMAP4.__init__(self, host, port)

    def open(self, host='', port=imaplib.IMAP4_PORT):
        self.host = host
        self.port = port
        self.sock = socket.create_connection((host, port), timeout=self.timeout)
        # clear timeout for socket.makefile, needs blocking mode
        self.sock.settimeout(None)
        self.file = self.sock.makefile('rb')

rawDescription: Does Python's imaplib let you set a timeout?


code:
Y = np.zeros(1000)

def peaker(Y, alpha=0.01, df=2, loc=-0.005, size=-.0015, threshold=0.001, decay=0.5):
    peaking = False
    for i, v in enumerate(Y):
        if not peaking:
            peaking = np.random.random() < alpha
            if peaking:
                Y[i] = loc + size * np.random.chisquare(df=2)
                continue
        elif Y[i - 1] < threshold:
            peaking = False

        if i > 0:
            Y[i] = Y[i - 1] * decay

peaker(Y)

rawDescription: find peaks location in a spectrum numpy

description: Find peaks location in a spectrum numpy


code:
import csv
with open('local_file.csv', 'w') as my_csv:
    csv_writer = csv.writer(my_csv, delimiter=',')
    csv_writer.writerows(sorted(decoded.items()))

rawDescription: Saving a dictionary as a file with columns which i can continously add to


code:
usa_date = datetime.datetime.strptime(
    usa_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
canada_date = datetime.datetime.strptime(
    canada_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
usa_date, canada_date
max(usa_date, canada_date)

rawDescription: How do I quickly compare dates from parsed XML in Python?

description: Quickly compare dates from parsed XML in Python


rawDescription: How to load txt and sum hours?

description: Load txt and sum hours


code: import numpy as np

rawDescription: sum function in python

description: Sum function in python


code:
import timeit
print(timeit.timeit(get_dictionary_value))
# 0.06353...

print(timeit.timeit(get_if_value))
# 6.3684...

rawDescription: Python - get object - Is dictionary or if statements faster?


code:
import tkinter

root = tkinter.Tk()
var  = tkinter.IntVar()

label  = tkinter.Label(root, textvariable=var)
button = tkinter.Button(root, command=lambda: var.set(var.get() + 1), text='+1')

label.pack()
button.pack()

root.mainloop()

rawDescription: tkinter variable in another class

description: Tkinter variable in another class


code:
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x for x, y in enumerate(tuple_list) if y[1] == 7]
[x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']

rawDescription: Using Python's list index() method on a list of tuples or objects?


code:
if kind in ('linear', 'nearest'):
    # Make a "view" of the y array that is rotated to the interpolation
    # axis.
    minval = 2
    if kind == 'linear':
        self._call = self._call_linear
    elif kind == 'nearest':
        self.x_bds = (x[1:] + x[:-1]) / 2.0
        self._call = self._call_nearest
else:
    minval = order + 1
    self._call = self._call_spline
    self._spline = splmake(x, y, order=order)

rawDescription: In SciPy, what is 'slinear' interpolation?


code:
glScissor(selectionLeft, selectionBottom, selectionWidth, selectionHeight);
glEnable(GL_SCISSOR_TEST);

rawDescription: Selecting 3D surfaces with a selection box (in two different ways)


code:
class WTS(dict):
    def __missing__(self, key):
        if key[1] == somevalue:
            return 1
        else:
            return 0

rawDescription: How to use defaultdict to create a dictionary with a lambda function?

description: Use defaultdict to create a dictionary with a lambda function


code:
with open(rtf_filename, "a") as f:
    f.write(template_append % data_source)

rawDescription: Python - removing last line of target when appending


code:
execfile('foo-bar.py')
baz

rawDescription: How to import python module when module name has a '-' dash or hyphen in it?

description: Import python module when module name has a '-' dash or hyphen in it


code:
import re
x_date = []
fp = open("results_file.txt")
for i, line in enumerate(fp):
    if (i >= line_start) and (i <= line_end):
        line = re.match("(.{10})(.{8})(.{8})(.{12})(.{12})(.{12})(.{12})", line).groups()
        x_date_temp = line[0]
        x_date.append(x_date_temp)

rawDescription: python split strings of a text file

description: Python split strings of a text file


code:
import csv

with open('sample_state_census.csv', 'rb') as census_file:
    reader = csv.reader(census_file, delimiter='\t')
    census_header = next(reader, None)  # store header
    census = {row[9]: row for row in reader}

rawDescription: How can I merge two csv files by a common column, in the case of unequal rows?

description: Merge two csv files by a common column, in the case of unequal rows


code: subtracted_data = np.array([data[i] - avgs[i] for i in range(len(data))])

rawDescription: Trouble indexing lists of NUMPY arrays properly


code:
import re
inputstring = 'FED590498'
characters, numbers = re.search(r'([A-Z]+)(\d+)', inputstring).groups()
characters
numbers

rawDescription: Parsing String with Python

description: Parsing String with Python


code: dict(enumerate(L, start=1))

rawDescription: Python dictionary comprehension example

description: Python dictionary comprehension example


code:
sigma, epsilon, k = 0, 10**-10, 1
while True:
    addition = 1.0/(k**3)
    if addition < epsilon:
        break
    else:
        sigma += addition
    k += 1

rawDescription: Approximate an infinite sum within some epsilon


code:
import os.path
os.path.isfile = lambda path: path == '/path/to/testfile'

rawDescription: How do I mock the filesystem in python unit tests

description: Mock the filesystem in python unit tests


code:
def somefunc(keys, dct):
    vals = [dct[k][0] for k in keys]
    return sum(vals) / float(len(vals))

rawDescription: Using list comprehension

description: Using list comprehension


code:
class Player():
    def __init__(self):
        self.life = randint(25,30)
        self.maxhealth = self.life
        self.attack = 5
        self.name = ""

rawDescription: In python, how do I call a class multiple times and have randint be random?


code:
a = np.array(['True', 'False', 'True', 'False'], dtype=object)
a
a == "True"

rawDescription: Numpy Convert String Representation of Boolean Array To Boolean Array


code:
class EZTcomm(bytearray):

    def __init__(self, *args, **kwargs):
        bytearray.__init__(self, *args, **kwargs)
        self.check = CRC(self)

rawDescription: Inheriting and modifying __init__() method


code:
line = line.split()
line = line[0:7] + [" ".join(line[7:])]

rawDescription: Read text file and take region names in Python


code: [random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))]

rawDescription: which random am i looking for to achieve this:

description: Which random am i looking for to achieve this:


code: pd.rolling_mean(pivot, 90, center=True, min_periods=1)

rawDescription: Sliding window average across time axes

description: Sliding window average across time axes


code:
import cPickle
cPickle.dumps({'foo': 'bar'})
cPickle.loads(_)

rawDescription: How do I serialize a Python dictionary into a string, and then back to a dictionary?

description: Serialize a Python dictionary into a string, and then back to a dictionary


rawDescription: Generating raw_inputs based on user input? [Python]


code:
answers = []
while time.time() - start < 60:
    answers.append(input(questions[questionNum]))
    questionNum +=1

rawDescription: How to change number in Mad Libs game?

description: Change number in Mad Libs game


code:
status = raw_input("Host? (Y/N) ")
if status=="Y":
    print("host")
    serverprozess = Process(target= spawn_server)
    serverprozess.start()

ip = raw_input("IP-Address: ")
clientprozess = Process (target = spawn_client, args = (ip, ))
clientprozess.start()

rawDescription: raw input and multiprocessing in python

description: Raw input and multiprocessing in python


rawDescription: Numba JIT changing results if values are printed


rawDescription: Implicit functions, looking to perform different math functions based on a key


code: Session.query(Item).filter(keywords_condition, Item.date == date.today())

rawDescription: mysql sqlalchmey keywords search

description: Mysql sqlalchmey keywords search


code:
#!/usr/bin/env python3
from tkinter import *
from tkinter import ttk
root = Tk()
def viewall(*args):
    global tx, tx2
    eval('tx.yview(*args)')
    eval('tx2.yview(*args)')
tx = Text(root, background='white', width = '20', height = '8')
tx2 = Text(root, background='white', width = '20', height = '8')
rolly = ttk.Scrollbar(root, orient=VERTICAL, command=viewall)
tx['yscrollcommand'] = rolly.set
tx2['yscrollcommand'] = rolly.set
tx.grid(row=0, column=0, sticky=(N, W, E, S))
tx2.grid(row=0, column=1, sticky=(N, W, E, S))
rolly.grid(row=0, column=2, sticky=(N, W, E, S))
root.mainloop()

rawDescription: How to scroll two parallel text widgets with one scrollbar?

description: Scroll two parallel text widgets with one scrollbar


code:
def handle(request):

    # Post request containing the key.
    if request.method == 'POST' and 'my_data' in request.POST.keys():

        # Retrieving the value.
        my_data = request.POST['my_data']

    # ...

rawDescription: Populating backend script for Django form


code: sorted(lst, key=value_to_time)

rawDescription: Python - sorting a tuple, characters over numbers


code:
def action_link(self, obj):
    app_name = obj._meta.app_label
    url_name = obj._meta.module_name
    data_id = obj.id

    return """

Edit

Delete

         """.format(
         obj._meta.app_label,
         obj._meta.module_name,
         obj.id)
action_link.allow_tags = True
action_link.short_description = 'Actions'

rawDescription: How can i have delete and edit link in django admin change list page

description: Have delete and edit link in django admin change list page


code:
def iter_leafs(d):
    for key, val in d.items():
        if isinstance(val, dict):
            yield from iter_leafs(val)
        else:
            yield val

rawDescription: Iterate through items of an arbitrary layered dictionary in Python


code:
def linear_kernel(X, Y):
    return X.dot(Y.T)

X = np.random.randn(10, 20)
gram = linear_kernel(X, X)

rawDescription: SKLearn Kernel PCA "Precomputed" argument


rawDescription: Python replace year mentions like '85 with 1985


code:
[comb for comb in
    (scipy.misc.comb(n, r, exact=True)
     for n in range(1,maxn+1) for r in range(0,n+1))
 if comb > threshold]

rawDescription: List comprehension with repeated computation


code:
POST /test_index/_search
{
   "query": {
      "range": {
         "timestamp": {
            "gt": "now-12h"
         }
      }
   }
}

rawDescription: Elasticsearch date range returns no hits


rawDescription: Python default metaclasses

description: Python default metaclasses


code:
isinstance(1, int)
isinstance(1, float)
isinstance(1.1, float)
isinstance(1.1, int)

rawDescription: Overloaded constructor in Python from C++ perspective


rawDescription: How to create subsequences for sequence e.g. [1,2,3] not including non-adjacent subsequences (e.g. [1,3]) in Python

description: Create subsequences for sequence e.g. [1,2,3] not including non-adjacent subsequences (e.g. [1,3]) in Python


code:
import pygame
from pygame.locals import * #This lets you use pygame's constants directly.

for event in pygame.event.get():
    if event.type == MOUSEBUTTONDOWN:  #Better to seperate to a new if statement aswell, since there's more buttons that can be clicked and makes for cleaner code.
        if event.button == 1:
            for object in clickableObjectsList:
                object.clickCheck(event.pos)

rawDescription: How do I respond to mouse clicks on sprites in PyGame?

description: Respond to mouse clicks on sprites in PyGame


code:
X.T.dot(L).shape
X.T.dot(L)[0,0]

rawDescription: scipy.sparse dot extremely slow in Python

description: Scipy.sparse dot extremely slow in Python


code:
for trial in trialList:
    # set images.
    targetstim.image = trial['target']
    distractorstim.image = trial['distractor']

    # Display and wait for answer. Let's record reaction times in the trial, just for fun.
    win.flip()
    response = event.waitKeys(keyList = ['space'], timeStamped=True)
    trial['rt'] = response[0][1]  # first answer, second element is rt.

rawDescription: Shuffle two lists in the same order in python


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

raw = range(20)
mls = range(20)
ax = {}
blues = plt.get_cmap('Blues')
reds = plt.get_cmap('Reds')
greens = plt.get_cmap('Greens')

fig = plt.figure()

ax[1] = fig.add_subplot(3, 2, 1)
ax[1].set_title('Raw SIFs')
ax[1].grid(True)
ax[1].set_ylabel('K_I')

ax[3] = fig.add_subplot(3, 2, 3)
ax[3].grid(True)
ax[3].set_ylabel('K_II')

ax[5] = fig.add_subplot(3, 2, 5)
ax[5].grid(True)
ax[5].set_xlabel('Vertex')
ax[5].set_ylabel('K_III')

ax[2] = fig.add_subplot(3, 2, 2)
ax[2].set_title('MLS SIFs')
ax[2].grid(True)
ax[2].set_ylabel('K_I')

ax[4] = fig.add_subplot(3, 2, 4)
ax[4].grid(True)
ax[4].set_ylabel('K_II')

ax[6] = fig.add_subplot(3, 2, 6)
ax[6].grid(True)
ax[6].set_xlabel('Vertex')
ax[6].set_ylabel('K_III')

for i, raw_step in enumerate(raw):
    Raw_Vertex = np.arange(10)
    Raw_KI = Raw_Vertex*(i+1)
    Raw_KII = Raw_Vertex*(i+1)
    Raw_KIII = Raw_Vertex*(i+1)
    ax[1].plot(Raw_Vertex, Raw_KI, 'o-', color = blues(1 - float(i)/(len(raw)-1)))
    ax[3].plot(Raw_Vertex, Raw_KII, 'o-', color = greens(1 - float(i)/(len(raw)-1)))
    ax[5].plot(Raw_Vertex, Raw_KIII, 'o-', color = reds(1 - float(i)/(len(raw)-1)))

for i, mls_step in enumerate(mls):
    MLS_Vertex = np.arange(10)
    MLS_KI = MLS_Vertex**2*(i+1)
    MLS_KII = MLS_Vertex**2*(i+1)
    MLS_KIII = Raw_Vertex**2*(i+1)

    ax[2].plot(MLS_Vertex, MLS_KI, 'o-', color = blues(1 - float(i)/(len(mls)-1)))
    ax[4].plot(MLS_Vertex, MLS_KII, 'o-', color = greens(1 - float(i)/(len(mls)-1)))
    ax[6].plot(MLS_Vertex, MLS_KIII, 'o-', color = reds(1 - float(i)/(len(mls)-1)))

plt.show()

rawDescription: how to make colors in line graph fade in matplotlib and python

description: Make colors in line graph fade in matplotlib and python


code:
result = np.einsum('ijklmm->ijklm', arr)
result.shape
# (2, 3, 4, 5, 6)

rawDescription: Numpy einsum broadcasting

description: Numpy einsum broadcasting


code:
# main.py
import webapp2
from pages import DefaultPage
class MainHandler(webapp2.RequestHandler):
    def get(self):
        page = DefaultPage()
        self.response.write(page.display())

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

rawDescription: How to prevent a user from directly accessing my html page

description: Prevent a user from directly accessing my html page


code: reduce(lambda a,b: a|b, [x, y, z])

rawDescription: How do I use the union and intersection on a list of Counters of unknown length?

description: Use the union and intersection on a list of Counters of unknown length


rawDescription: how to plot Probability density Function (PDF) of inter-arrival time of events?

description: Plot Probability density Function (PDF) of inter-arrival time of events


code: dict2 = { key : val[0] for key, val in dict1.items() }

rawDescription: Dictionary comprehension containing dictionary elements


code:
with open("C:\\Python34\\Python Challenge\\Q2\\Q2.txt") as f:
    f = f.read()
    f = f.translate(None,"!@#$%&()*^")
    print(f)

rawDescription: Python Challenge #2 Elimination

description: Python Challenge #2 Elimination


code:
dog = Dog(4)
dog.fire()

rawDescription: How to add same methods/properties to a set of subclasses derived from common class

description: Add same methods/properties to a set of subclasses derived from common class


code:
# __init__.py
# re-export run.run as run
from .run import run

rawDescription: If module 'example' contains both function 'run' and submodule 'run', can I count on 'from example import run' to always import the former?


code:
import itertools

def ip_range(input_string):
    octets = input_string.split('.')
    chunks = [map(int, octet.split('-')) for octet in octets]
    ranges = [range(c[0], c[1] + 1) if len(c) == 2 else c for c in chunks]

    for address in itertools.product(*ranges):
        yield '.'.join(map(str, address))

rawDescription: Python - Generate a list of IP addresses from user input


code:
import itertools
sum(itertools.imap(f, xlist))

rawDescription: Quickest way to sum(f(x)) in Python

description: Quickest way to sum(f(x)) in Python


code: myList = [f1, f2, None, f3, None, 24, "string", 50]

rawDescription: Python: How to access only some boolean elements of a list with a loop?


code: pd.melt(df,id_vars=['Team Name','Nb of teammates'],value_vars=['Team Leader One','Team Leader Two']).dropna()

rawDescription: Python Pandas inserting new rows with colums values


code:
x = FrozenDict(a=1, b=2)
y = FrozenDict(a=1, b=2)
x is y
x == y
x == {'a': 1, 'b': 2}
d = {x: 'foo'}
d[y]

rawDescription: What would a "frozen dict" be?

description: What would a "frozen dict" be


code:
from itertools import product
lis = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
points = list(product([0, 1, -1], repeat=2))[1:]

get_adj_items(0, 0, 3, 3, lis)
get_adj_items(1, 1, 3, 3, lis)

rawDescription: Reading adjacent elements in graph in python


code:
with file("...", 'r') as f:
    g = generate_tokens(f.read())

rawDescription: USing a Scanner Import

description: USing a Scanner Import


rawDescription: python regex: skip word

description: Python regex: skip word


rawDescription: Comparing two files and printing similar lines


rawDescription: Error while trying to interpolate across rows in pandas dataframe


code:
newl = []
for i in l:
    temp = (i[0], [])
    for j in i[1]:
        temp[1].append((j[0]+j[1])/2.0)
    newl.append(temp)

rawDescription: mean average on the contents of a list

description: Mean average on the contents of a list


code:
all_home_games = team.home_games.all()
away_against_dodgers = team.away_games.filter_by(name='Dodgers').all()
some_date = DateTime(...)
all_games_before_date = team.games.filter(Game.date < some_date).all()

rawDescription: Two Columns joining the same table with SqlAlchemy


code: from math import *

rawDescription: naming collision in namespaces in modules of python

description: Naming collision in namespaces in modules of python


code: cc = np.isclose(aa, bb.T)

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