code:
rand_int = 0
for c in rnd_str:
    rand_int <<= 8
    rand_int += ord(c)

rawDescription: Best seed for parallel process

description: Best seed for parallel process


code:
def get_values(instance, go_into={}, exclude=(), extra=()):
    """
    Transforms a django model instance into an object that can be used for
    serialization. Also transforms datetimes into timestamps.

    @param instance(django.db.models.Model) - the model in question
    @param go_into - relations with other models that need expanding
    @param exclude - fields that will be ignored
    @param extra - additional functions/properties which are not fields

    Usage:
    get_values(MyModel.objects.get(pk=187),
               {'user': {'go_into': ('clan',),
                         'exclude': ('crest_blob',),
                         'extra': ('get_crest_path',)}},
               ('image'))

    """

rawDescription: Django Serializer returns JSON for parent class objects only and leave child objects as same?


code: ri = int(255 * (r - rmin) / (rmax - rmin) )

rawDescription: working with tiff files in python

description: Working with tiff files in python


code: write_sheet.write(row_index, col_index, 'Cell contents')

rawDescription: How to collapse rows in excel using python?

description: Collapse rows in excel using python


code:
@selector.tag('a')
@selector.tag('b')
def foo():
    ...

#Or, equivalently:
@selector.tag('a', 'b')
def foo():
    ...

rawDescription: Decorator to tag functions as callable

description: Decorator to tag functions as callable


code:
import pandas as pd

df = pd.read_csv(r'D:\download\Sheet1.csv')

# `id_vars` helper list for `melt()`
id_vars = df.columns[df.columns.str.contains('provinces\.')].tolist()

# `value_vars` helper list for `melt()`
val_vars = df.columns[df.columns.str.contains('provinceFrequency\.')].tolist()

mlt = pd.melt(df, id_vars=id_vars, value_vars=val_vars)

mlt['variable'] = mlt['variable'].str.replace(r'provinceFrequency', 'provinces')

# add column with the _correct_ province
mlt['prov'] = mlt.apply(lambda row: row[row['variable']], axis=1)

new = mlt[['prov', 'value']].reset_index()

# free memory
del mlt

# set original df's index for joining in future
new['idx'] = new['index']%len(df)

# pivot (convert rows to columns)
pvt = pd.pivot_table(new, index='idx', columns='prov', values='value', aggfunc='first')

# free memory
del new

# join original `DF` with the pivoted DF `PVT` using index
rslt = df[['text','rank','date']].join(pvt)

print(rslt)

rawDescription: Reformatting my csv file by pandas (convert set of values to columns, matching another set to corresponding values)


code:
a1 = np.ones((2,), dtype=bool)
a2 = np.ones((4,), dtype=bool)
a3 = np.ones((3,), dtype=bool)

a1[1]= False
a2[1:3] = False
a3[1:] = False
a1[:, None, None] | a2[None, :, None] | a3[None, None, :]

rawDescription: Or'ing boolean arrays of different sizes


rawDescription: grabbing info from a table with loops (python)

description: Grabbing info from a table with loops (python)


rawDescription: Adding json object to unnamed set of json objections


code:
"foobar" is "foobar"   # The interpreter knows that the string literals are
a = "foobar"
b = "foobar"
a is b        # "foobar" comes from the pool, so it is still the same object.
b = "foo"     # Here, we construct another string "foobar" dynamically that is
b += "bar"    # physically not the same as the pooled "foobar".
a == b
a is b

rawDescription: Types for which "is" keyword may be equivalent to equality operator in Python


code:
dx, dy, dz = 1, 1, 2
scaling = np.array([dx, dy, dz])
data = np.random.rand(10, 15, 5)

rawDescription: Fast interpolation of regularly sampled 3D data with different intervals in x,y, and z


rawDescription: Idiomatic way of only selecting certain rows from a dataframe (whose index exists in other dataframes)


code:
tokens = ["Sentence 1.","And Sentence 2.","Or Sentence 3.",
          "New Sentence 4.","New Sentence 5.","And Sentence 6."]
result = list()
for token in tokens:
        if not token.startswith("And ") and not token.startswith("Or "): #trailing whitespace because of the cases like "Andy ..." and "Orwell ..."
            result.append([token])
        else:
            result[-1].append(token)

rawDescription: Recursively group sentences based on conjunctions


code:
class Config:
     ALL_CAPS_CONFIG = 'SOME VALUE'

class DevConfig(Config):
    pass

class TestConfig(Config):
    pass

class ProdConfig(Config):
    pass

configs = {
  'dev'  : DevConfig,
  'test' : TestConfig,
  'prod' : ProdConfig,
  'default' : ProdConfig
  }

rawDescription: How to serve different config settings in flask app to uwsgi using create_app?

description: Serve different config settings in flask app to uwsgi using create_app


code: setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')

rawDescription: How to change QPushButton text and background color

description: Change QPushButton text and background color


code:
import json
import tornado.httpserver
import tornado.ioloop
import tornado.web

class MyHandler(tornado.web.RequestHandler):
    def post(self):
        data = json.loads(self.request.body.decode('utf-8'))
        print('Got JSON data:', data)
        self.write({ 'got' : 'your data' })

if __name__ == '__main__':
    app = tornado.web.Application([ tornado.web.url(r'/', MyHandler) ])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8888)
    print('Starting server on port 8888')
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado application/json support

description: Tornado application/json support


code:
def foo(return_2nd=False):

    x = 2
    y = 2
    return (x+y) if not return_2nd else (x+y),(x-y)

rawDescription: Multiple return values in python

description: Multiple return values in python


code:
from google.appengine.ext import db

class User(db.Model):
    name = db.StringProperty()

class Software(db.Model):
    name = db.StringProperty()
    description = db.TextProperty()

class UserSoftwares(db.Model):
    user = db.ReferenceProperty(User, collection_name='users')
    software = db.ReferenceProperty(Software, collection_name='softwares')

rawDescription: Querying on multiple tables using google apps engine (Python)


code:
from collections import namedtuple
Point = namedtuple('P','x y')
pp = Point(1,2)
type(pp)

rawDescription: Use of class typenames in python

description: Use of class typenames in python


code:
from itertools import groupby, izip, chain, repeat
from operator import itemgetter

def float_int_avg(sequence):
    floats, ints = A[:len(A) // 2], A[len(A) // 2:]
    def _group(sequence):
        for k, g in groupby(izip(floats, ints), itemgetter(0)):
            vals = [el[1] for el in g]
            yield repeat(sum(vals, 0.0)/len(vals), len(vals))
    return floats + list(chain.from_iterable(_group(sequence)))

rawDescription: Perform calculation on one list depending on value of second list


rawDescription: Extracting URL link using regular expression re - string matching - Python


code: DataFrame(dict(td1 = df['date1']-df['date2'], td2 = df['date2']-df['date3'], td3=df['date3']-df['date4']))

rawDescription: getting time delta from pandas data frame

description: Getting time delta from pandas data frame


rawDescription: how to use groupby to avoid loop in python

description: Use groupby to avoid loop in python


code:
def PRHSX_message():
    prhsx_share_price = float(ystockquote.get_last_trade_price('PRHSX'))
    prhsx_daily_change = ystockquote.get_change('PRHSX')
    prhsx_total_shares = 47.527
    prhsx_starting_value = 2500
    prhsx_percent_change = (((prhsx_share_price * prhsx_total_shares) / prhsx_starting_value) - 1) * 100
    prhsx_current_value = prhsx_share_price * prhsx_total_shares
    prhsx_profit = prhsx_current_value - prhsx_starting_value

    prhsx_string = """\
T. Rowe Price Roth IRA Account
____________________________

Percent Change: {}
Share Price: {}
Current Value: ${:.2f}
Percent Growth: {:.2f}%
Profit: ${:.2f}""".format(
        prhsx_daily_change, prhsx_share_price, prhsx_current_value,
        prhsx_percent_change, prhsx_profit)

rawDescription: Why is Python printing braces here?

description: Why is Python printing braces here


code:
array([[[ True,  True,  True],
        [ True, False, False],
        [False, False,  True],
        [False,  True, False],
        [ True,  True, False]],

       [[ True, False, False],
        [ True,  True,  True],
        [False,  True, False],
        [False, False,  True],
        [ True, False,  True]],

       ...,
       ...,
       ...], dtype=bool)

rawDescription: Compare 2d numpy array to itself to form 3d array


code:
import os
import re
import sqlite3

DB_PATH = __name__ + '.db'

try:
    os.remove(DB_PATH)
except:
    pass

def re_fn(expr, item):
    reg = re.compile(expr, re.I)
    return reg.search(item) is not None

conn = sqlite3.connect(':memory:')
conn = sqlite3.connect(DB_PATH)
conn.create_function("REGEXP", 2, re_fn)
cursor = conn.cursor()

cursor.execute(
    'CREATE TABLE t1 (id INTEGER PRIMARY KEY, c1 TEXT)'
)
cursor.executemany(
    #'INSERT INTO t1 (c1) VALUES (?)', [('aaa"test"',),('blah',)]
    'INSERT INTO t1 (c1) VALUES (?)', [
        ('dupa / 1st Part',), ('cycki / 2nd Part',), ('fiut / 3rd Part',)
    ]
)
SEARCH_TERM = '3rd part'
cursor.execute(
    #'SELECT c1 FROM t1 WHERE c1 REGEXP ?',['2|3\w+part']
    'SELECT c1 FROM t1 WHERE c1 REGEXP ?',[SEARCH_TERM]
)
conn.commit()
data=cursor.fetchall()
print(data)

#
# sqlalchemy
#

import sqlalchemy as sa
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarative_base

DSN = 'sqlite:///' + DB_PATH

engine = sa.create_engine(DSN, convert_unicode=True)

conn = engine.connect()
conn.connection.create_function('regexp', 2, re_fn)

db = orm.scoped_session(orm.sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

Base = declarative_base(bind=engine)
meta = Base.metadata

class T1(Base):
    __table__ = sa.Table('t1', meta, autoload=True)

print(db.query(T1.c1).filter(T1.c1.op('regexp')(SEARCH_TERM)).all())

rawDescription: How to use regexp function in sqlite with sqlalchemy?

description: Use regexp function in sqlite with sqlalchemy


code:
c = Context({'foo': {'bar': 'world'}, 'bar': 'hello'})
t.render(c)

rawDescription: "bar" in a Django template expression is a literal?


code:
from base64 import b64encode

@app.route('/show/<int:id>')
def show(id):
    obj = A.query(A.id == id).fetch(1)[0]
    image = b64encode(obj.image)
    return render_template('show_a.html', obj=obj, image=image)

rawDescription: Display image stored as binary blob in template


code:
xx = pandas.Series(dict(a=44, b=55))
xx.a

rawDescription: Access Pandas Series item with dot notation like DataFrame


code:
_g = globals()
for o in opts:
    _g[o] = os.getenv(o)

rawDescription: Reducing variable name duplication when using os.getenv


rawDescription: Resizing small images in Python (numpy) to a multiple of the original size, accurately


code:
{ _id: ObjectId(...),
  _types: ["UserThings"],
  _cls: "UserThings",
  username: "dcrosta",
  things: {
    foo: "bar",
    baz: "quack"
  }
}

rawDescription: using key as value in Mongoengine

description: Using key as value in Mongoengine


code:
object_types = {'Profile': Profile, 'Company': Compnay}

...

get_object_or_404(object_types[object_type], uuid=uuid_from_request)

rawDescription: Django and python - use variable value as model's name


code:
def mod_inv (a, b):
    return pow(a, b - 2, b)

mod_val=10**9+7
current=[int(x) for x in raw_input().strip().split()]
m=current[0]-1
n=current[1]-1

hi,lo=max(m,n),min(m,n)
num_prod=1
den_prod=1
for each in xrange(1,lo+1):
    den_prod = (den_prod*each) % mod_val
    num_prod = (num_prod*(hi+each)) % mod_val

print (num_prod * mod_inv(den_prod, mod_val)) % mod_val

rawDescription: Placing of modulo operation in code

description: Placing of modulo operation in code


code:
if __name__ == '__main__':

    header = ['Name', ' Email', ' Status', ' Path']
    data_list = [('option_A', 'zyro@email.com', 'Not Copied', '/opt'),
                 ('option_B', 'zyro@email.com', 'Not Copied', '/usr')]

    app = QtGui.QApplication([])
    win = MyTableView(data_list, header)
    win.setGeometry(300, 200, 570, 450)
    win.show()
    app.exec_()

rawDescription: How to add QTreeView in a QTableView column

description: Add QTreeView in a QTableView column


code:
if session.a_set:
    do_something()

rawDescription: Python object state tracking idiom

description: Python object state tracking idiom


code:
from ctypes import CDLL, c_int, c_void_p
def log_omp(xs, out):
    lib = CDLL('./log_omp.so')
    lib.log_omp.argtypes = [c_int, np.ctypeslib.ndpointer(dtype=np.float32), np.ctypeslib.ndpointer(dtype=np.float32)]
    lib.log_omp.restype  = c_void_p
    n = xs.shape[0]
    out = np.empty(n, np.float32)
    lib.log_omp(n, out, xs)
    return out

rawDescription: Fast logarithm calculation

description: Fast logarithm calculation


code:
import os

os.path.isfile(file_to_check)

rawDescription: How to check if file already exists, if not, download on Python?

description: Check if file already exists, if not, download on Python


code:
elems = soup.find_all(True, class_='template_title')
print([elem.string for elem in elems])
# prints `['4']` for the given html snippet

rawDescription: Python 3 - Get text from tag in beautifulSoup


code:
def word_len_dict(my_string):
    input_list = my_string.split(" ")

    unique_set = set()
    dictionary = {}

    for item in input_list:
        word = item.lower()
        if word not in unique_set:
            unique_set.add(word)
            key = len(word)
            if key not in dictionary:
                dictionary[key] = []
            dictionary[key].append(word)

    return dictionary

rawDescription: Adding more than one value to dictionary when looping through string


code: listmatrixMap(lambda val,r,c:((r,c),val), a, indices=True)

rawDescription: Add two matrices in python

description: Add two matrices in python


code:
from compiler.ast import flatten
l = ['1','2',['3','4'],'5']
flatten(l)

rawDescription: how to unpack a nested list in Python

description: Unpack a nested list in Python


rawDescription: Creating a list of ctypes

description: Creating a list of ctypes


code:
with open('other.txt', 'w', encoding="ISO-8859-1") as f:
    f.writelines(movMat)

rawDescription: Python list of lists no loops

description: Python list of lists no loops


rawDescription: Python sort list by regular expression

description: Python sort list by regular expression


code: sum(x > 0 for x in frequencies)

rawDescription: Counting positive elements in a list with Python list comprehensions


rawDescription: Embedding python in multithreaded C application


code:
documents_df.registerTempTable("documents")
keywords_df.registerTempTable("keywords")

query = """SELECT document_id, keyword
    FROM documents JOIN keywords
    ON document_text LIKE CONCAT('%', keyword, '%')"""

like_with_hive_udf = sqlContext.sql(query)
like_with_hive_udf.show()

## +-----------+-------+
## |document_id|keyword|
## +-----------+-------+
## |          1|  spark|
## |          2| erlang|
## |          3|haskell|
## +-----------+-------+

rawDescription: How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?


code: from django.conf import settings

rawDescription: Using the correct settings constant in Django view


rawDescription: Python: DEAP: programatically handle number of func parameters


rawDescription: find submit button in selenium without id

description: Find submit button in selenium without id


code:
from collections import defaultdict
numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2"
numcount = defaultdict(int)
for num in numstring.split(','):
    numcount[num] += 1

rawDescription: python - Count number of occurences of each number

description: Python - Count number of occurences of each number


code:
class Communicator(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.message_box.editingFinished.connect(self.sendMessage)

    def sendMessage(self):
        server_socket = connect_to_server()
        message = self.ui.message_box.toPlainText()
        send_message(message, server_socket)

rawDescription: Handling key pressed in QLineEdit which instance is in QMainWindow


code:
for tag in session.query(Tag).\
        filter(Tag.alices.any()).\
        all():
    print(tag.name)

rawDescription: Sqlalchemy: Querying on m2m relations for polymorphic classes


code:
attribute_list = [ ( 1, 2, 3, 4, 5, 6),
                  (11,12,13,14,15,16),
                   # and so on
         ]

for attrs in attribute_list:
    container.append( TheClass( *attrs ) )

rawDescription: Best way to provide object attributes?

description: Provide object attributes


rawDescription: Using set in Python inside a loop

description: Using set in Python inside a loop


code:
dir(dict)
callable(dict.keys)

class foo(object):
    class_variable = 'Some String'
    def function():
        return 'Some String'
dir(foo)
callable(foo.class_variable)
callable(foo.function)

rawDescription: how to show all the methods to a particular class, or functions such as **kwargs?

description: Show all the methods to a particular class, or functions such as **kwargs


rawDescription: What is the format of the .tar.gz file for setting up firefox preference from selenium python?


code: my_out_file = open("/home/mytrace.txt", "w")

rawDescription: Python trace module - Trace lines as they are executed, but save to file, rather than stdout


rawDescription: How to find the smallest missing numbers from a list without using inbuilt functions or modules

description: Find the smallest missing numbers from a list without using inbuilt functions or modules


code:
print([node.data.strip() if isinstance(node, xml.dom.minidom.Text) else node.firstChild.nodeValue
       for node in child.childNodes])

rawDescription: python xml minidom get the full content of childnode that contains both child and text

description: Python xml minidom get the full content of childnode that contains both child and text


code: n = np.append(n, np.repeat(np.nan, 20))

rawDescription: Add "nan" to numpy array 20 times without loop


code:
A == B
# lists are in the same order with the same items.
all(a in B for a in A)
# all items in A are in B. (order not checked)
all(b in A for b in B)
# all items in B are in A. (order not checked)
all(A[i] == B[i] for i in range(len(A)))
# all items in A are in B. (order checked) (len(A) <= len(B))
all(B[i] == A[i] for i in range(len(B)))
# all items in B are in A. (order checked) (len(B) <= len(A))

rawDescription: Checking whether list in a dictionary is the same as another list?


code:
[ x for x in l if x[1] == "Plot" ]
[ x for x in l if x[1] == "unPlot" ]

rawDescription: How to separate a Python list into two lists, according to some aspect of the elements

description: Separate a Python list into two lists, according to some aspect of the elements


code:
myArray = []                     # initialize an empty array
for i in range(1,101):           # range produces a list [1,2,3, ... 99, 100]
    fileName = 'file' + str(i)   # converts i to string, then performs concatenation
    myArray.append(fileName)     # appends the concatenated string to the array

rawDescription: Array of strings using a range

description: Array of strings using a range


code:
blacklisted = ('bar.com', 'baz.com')
email = 'x@foobar.com'
email.endswith(blacklisted)

rawDescription: Best way to filter out emails and domains in python

description: Filter out emails and domains in python


code:
from functools import partial ##import partial, wich allows to apply arguments to functions returning a funtion with that arguments by default.
def build(self):
    boxLayout = BoxLayout(spacing=10,orientation='vertical')
    g = TextInput(text='Enter gratulation',
                  multiline=False,
                  font_size=20,
                  height=100)
    button = Button(text='Send')
    buttoncallback = partial(self.gratulation, g.text)
    button.bind(on_press=buttoncallback)
    ...

rawDescription: Kivy button binding function with argument


code:
with open(filename) as f_in:
    lines = (line.rstrip() for line in f_in) # All lines including the blank ones
    lines = (line for line in lines if line) # Non-blank lines

rawDescription: Python: Easiest way to ignore blank lines when reading a file


code:
l = list('abc0efg')
l[3] = 'd'
l
''.join(l)

rawDescription: Alternative to python string item assignment


code:
x = np.random.random((3, 2)) - 0.5
x
np.maximum(x, 0)
x * (x > 0)
(abs(x) + x) / 2

rawDescription: How to implement the ReLU function in Numpy

description: Implement the ReLU function in Numpy


code:
funcdec = globaldec()

@funcdec
def function1(state,arg1,**kwargs):
    print(state)

@funcdec
def function2(state,arg2,**kwargs):
    print(state)

rawDescription: Python "Multi-Level Decorator" - how does this work?


code:
dt=y.item().dtype
item=([[15.0]], [], ['5.0.1'], ['Android'])
array1 = np.array([[item]], dtype=dt)
array1

rawDescription: scipy and preserving mat file (.mat matlab data file) structure

description: Scipy and preserving mat file (.mat matlab data file) structure


code:
class Buffer:
    ''' A simple buffer that stores exactly one value '''
    latest = None
    @staticmethod
    def onNewReading(*args, **kwds): # or any parameters one fancies
        # Pack the results in a single object and store it
        Result.latest = (args, kwds)
    @staticmethod
    def onUserRequest():
        return Result.latest

rawDescription: Python thread-safe access without blocking or uncontrolled queue growth?


code: your_task.apply_async(foo, queue='bar')

rawDescription: Is there any way to make sure certain tasks are not executed in parallel?


rawDescription: How to perform the following ordered subset element test in Python?

description: Perform the following ordered subset element test in Python


code: zipcode = zipcode.replace(" ", "").upper()

rawDescription: How to return a value from a method back to the input value

description: Return a value from a method back to the input value


code:
# import the library
import pandas as PD

rawDescription: Filter numpy ndarray (matrix) according to column values


rawDescription: python parse bind configuration with nested curly braces

description: Python parse bind configuration with nested curly braces


code:
import csv
csvreader = csv.reader(logfile)
fields = csvreader.next()

table = 'mytable'

fields_fmt = ', '.join([ '`%s`' % f for f in fields ])
values_fmt = ', '.join(['%s'] * len(fields))
query = "INSERT INTO `atl`.`{0}` ({1}) VALUES ({2})".format(
#        self.table, fields_fmt, values_fmt)
        table, fields_fmt, values_fmt)
query

rawDescription: Python/MySQLdb import from CSV with data encapsulation


code: print(i)

rawDescription: Dice generator, Picking number of sides in PYTHON 3.3.4


code: "Successfully created the file: {0}.txt".format(iFile)

rawDescription: Python - How to modify text output using %s?


code:
import itertools as it
l = list(it.chain(*it.chain(*sets)))
print(list(chunks(l,3)))
# -> [['a', 'c', 'a'], ['e', 'b', 'c'], ['b', 'e', 'a'], ['z']]

rawDescription: converting 3d lists to 2d lists in python

description: Converting 3d lists to 2d lists in python


code:
from nanomsg import Socket, SUB

s = Socket(SUB)
s.connect('tcp://localhost:8080')
s.set_string_option(SUB, SUB_SUBSCRIBE, "topic")
while True:
    print(s.recv())

rawDescription: Publish-Subscribe and a Message bus Python


code: np.take(ev, np.searchsorted(time, t1, side='right')-1)

rawDescription: Resampling an array using predefined indices in Python


code:
set_b = set(b)
c = [x for x in a if x not in b]

rawDescription: Compare with each other, items inside two lists, in a for loop?


code: result_string = ", ".join("('{2}', '{4}')".format(*res) for res in results)

rawDescription: Python String Formatting, need to continuously add to a string


code:
from scipy.spatial.distance import cdist

dist = cdist(a[1:2], a)[0]

rawDescription: Is "norm" equivalent to "Euclidean distance"?


rawDescription: Does Python have a default Caching service


code:
table = webdriver.find_element_by_id("mytable")

rows = table.find_elements_by_tag_name("tr")
for row_index, row in enumerate(rows, start=1):
    cells = row.find_elements_by_tag_name("td")

    for column_index, cell in enumerate(cells, start=1):
        if "8" in cell.text:
            print("Found a match!")
            print(row_index, column_index)
            break

rawDescription: Python Selenium return HTML location

description: Python Selenium return HTML location


code:
Y = np.matrix(X)
Y.T * W * Y

rawDescription: Multiply Dense Rectangular Matrix by Sparse Matrix


code: ax.set_xticklabels(map(str, values))

rawDescription: matplotlib: setting xticklabels returned some "help" output

description: Matplotlib: setting xticklabels returned some "help" output


rawDescription: How would you group/cluster these three areas in arrays in python?


rawDescription: PyQt4 + matplotlib in a QScrollWidget

description: PyQt4 + matplotlib in a QScrollWidget


code:
import __builtin__
def sorted(services):
    return __builtin__.sorted(services, key=lambda s: s.sortkey())

rawDescription: can a python function call a global function with the same name?

description: Can a python function call a global function with the same name


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

rawDescription: How do you split a list into evenly sized chunks in Python?

description: Split a list into evenly sized chunks in Python


code:
import re
l = ['A','B','A','A','B','B','A']
pat = re.compile(r'BAA')
sequences = pat.findall(''.join(l))
sequences
len(sequences)

rawDescription: How to find defined sequence in the list?

description: Find defined sequence in the list


code:
from django.shortcuts import render
def index(request):
    return render(request, 'app/index.html', { 'foo': 'bar', })

rawDescription: Get template name in template tag ( Django )


code:
{1: array(['car', 'train'], dtype=object),
 2: array(['boot', 'computer', 'lipstick'], dtype=object)}

rawDescription: long-format pandas dataframe to dictionary

description: Long-format pandas dataframe to dictionary


code:
from foo.models import Map, ListField
map = Map()
map.spawn_locations
map.spawn_locations = [(1, 1), (-1, 12), (24, 52)]
map.spawn_locations
f = ListField()
f.get_prep_value(map.spawn_locations)

rawDescription: Storing and then accessing a pair of coordinates


code:
from Tkinter import *

root = Tk()
root.title("LabelFrame with embedded add voltmeters")
root.geometry("600x200+400+400")

def addmeter(parent):
        #Create frame for the voltmeter
    voltsmet1 = LabelFrame(parent, text = "Volts")
        #add Text box for the serial output.
    voltinfo = Text(voltsmet1, bg="BLACK",  height=10, width =20 )
        #add in reg command to find our data from queue and display it

        #packs the widgets on the grid for display
    voltsmet1.pack(side=LEFT, expand=True)
    voltinfo.pack(side=LEFT,  expand=True)

class wrapper(LabelFrame):
    def __init__(self,master):
        self.master = master
        self.create_wrapper()

    def create_wrapper(self):
        wrapper = LabelFrame(self.master, text = "Volt Meters")
        add_button = Button(wrapper, text="add", command=lambda:addmeter(wrapper))
        wrapper.pack()
        add_button.pack()

new= wrapper(root)
root.mainloop()

rawDescription: Calling an global function from inside a class. Python 2.7 using Tkinter


rawDescription: Running two methods (with arguments) simultaneously?


code:
blacklist = set('a b'.split())
answer = list(set(itertools.chain.from_iterable(v for k,v in dic.iteritems if k not in blacklist)))

rawDescription: Merge Dictionaries in Python

description: Merge Dictionaries in Python


code:
import datetime
end_time = 400 # this is the difference in your example, in seconds

str(datetime.timedelta(seconds = end_time))

rawDescription: Timer Python 3,3

description: Timer Python 3,3


code: lst3 = [(k, v, dict2[k]) for k, v in lst1]

rawDescription: Combine two lists of tuples by key

description: Combine two lists of tuples by key


code:
from nltk.corpus import wordnet as wn
x = [i.strip() for i in """corporal, dog, cat, distingus, Company, phone, authority, vhicule, seats, lightweight, rules, resident, expertise""".lower().split(",")]
x
y = [i for i in x if len(wn.synsets(i)) > 0]
y

rawDescription: How to use NLTK WordNet to check for incomplete words in Python?

description: Use NLTK WordNet to check for incomplete words in Python


code:
@memoize
def f(x):
    return f_norec(f,x)
return f

rawDescription: Why does Python's decorator syntax give faster memoization code than plain wrapper syntax?


code: valmap = {val:lst for lst in d.values() for val in lst}

rawDescription: How to access a list containing specific item in a dictionary?

description: Access a list containing specific item in a dictionary


rawDescription: How does the python difflib.get_close_matches() function work?


code: data.apply(lambda col1: data.apply(lambda col2: method(col1, col2)))

rawDescription: Distance matrix for rows in pandas dataframe


rawDescription: Python - Split a List into 2 by even or odd index?


code: np.concatenate(myArray, axis=1)

rawDescription: how can I flatten an 2d numpy array, which has different length in the second axis?

description: Flatten an 2d numpy array, which has different length in the second axis


code: newList = list(oldList)

rawDescription: Trying to duplicate a list and modify one version of it in Python 2


code:
k,l,m,n = 3,4,2,3
conc = np.array([np.ones([m,n],dtype=int)*i for i in range(k*l)])
np.vstack([np.hstack(conc[i:i+l]) for i in range(0,k*l,l)]).shape

rawDescription: Double loops for "concatenation of subarrays in bigger array"


code:
from math import *
import datetime

def fun(x):
    print(x)

fun("foo")

def fun2(x):
    return x

def get_date():
    print(pi)
    return datetime.datetime.now()
fun2("bar")

print("debug print")

print(fun2("hello world"))

print(get_date())

rawDescription: Import only functions from a python file


rawDescription: Replacing = with '\x' and then decoding in python


code:
import psutil

#..

proc = psutil.Process(process.pid)
for child in proc.children(recursive=True):
    child.kill()

proc.kill()

rawDescription: Kill a chain of sub processes on KeyboardInterrupt


code:
def attributelist(list_, attribute):
    "Inputs a list of instances and returns a list of a certain attribute of those instances"
    return [getattr(i, attribute) for i in list_]

rawDescription: Transform list of instances into list of instance attributes


code:
from collections import defaultdict
first = defaultdict(int)
second = defaultdict(lambda: defaultdict(int))
for line in skip_header(file):
    ip, path = parse(line)
    first[path] += 1
    second[ip][path] += 1

rawDescription: How to approach IIS log parsing in a Pythonic way?

description: Approach IIS log parsing in a Pythonic way


code: b = [[x, x == 4] for x in a]

rawDescription: list comprehension to create list of list

description: List comprehension to create list of list


rawDescription: Remove objects from query if None or Null


code:
from collections import OrderedDict
OrderedDict(sorted(yourdict.items(), key=lambda item: int(item[0].split()[0])))

rawDescription: Sort Python Dictionary by first four characters in Key


code:
from itertools import groupby

raw = [' '.join(w.split()[1] for w in words)
       for key, words in groupby(raw, key=lambda e: e.split()[0])]

rawDescription: Merge some part of the list together using python


code:
import pandas as pd
a = [['Lazy', 'Brown', 'Fox'], ['Jumps', 'Over'], ['Big', 'Blue', 'Sea']]
df = pd.DataFrame({'Name':list('ABC'), 'Group':[1,1,2]})
df['a'] = a
print(df.groupby(['Group'])['a'].sum())

rawDescription: Get the indicies of a dataframe to use on a list


rawDescription: sqlalchemy: get max/min/avg values from a table

description: Sqlalchemy: get max/min/avg values from a table


code: sys.getwindowsversion()[0] >= 6

rawDescription: Create NTFS junction point in Python

description: Create NTFS junction point in Python


rawDescription: I am having problems doing Word Sense Disambiguation in Python using Lesk algorithm


code:
root = etree.XML('<root></root>')
doc = etree.ElementTree(root)
transform = etree.XSLT(etree.XML(xslt))
res = transform(doc)

rawDescription: How can I return a text fragment from an XPath function?

description: Return a text fragment from an XPath function


code:
import locale
pprint(sorted(ranks, key=lambda x: int(locale.atoi(x["rank"]))))

rawDescription: How to convert dictionary values to int in Python?

description: Convert dictionary values to int in Python


code:
countries = []
for idx, city in enumerate(cities):
    country = raw_input("Where is " + city + " located? ")
    countries.append(country)
    # why did you need the index? enumerate is the way to go now....

rawDescription: How to index a user input list in Python 2.x?

description: Index a user input list in Python 2.x


code:
import pygame

# --- constants ----

size = width, height = 720, 480
speed = [2, 2]

#Colours

black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)

# --- functions ---

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def game_intro():

    largeText = pygame.font.Font('freesansbold.ttf',115)
    smallText = pygame.font.Font("freesansbold.ttf",20)

    text_vroom, text_vroom_rect = text_objects("V'Room!", largeText)
    text_vroom_rect.center = ((width/2),(height/2))

    text_go, text_go_rect = text_objects("GO", smallText)
    text_go_rect.center = ((75+(100/2)),(400+(50/2)))

    text_stop, text_stop_rect = text_objects("STOP", smallText)
    text_stop_rect.center = ((75+(100/2)),(400+(50/2)))

    text_exit, text_exit_rect = text_objects("Exit", smallText)
    text_exit_rect.center = ((550+(100/2)),(400+(50/2)))

    game_started = False

    intro = True

    while intro:

        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()

        screen.fill(blue)
        #screen.blit(BackgroundPNG,(0,0))

        # road and car - or title

        if game_started:
           screen.blit(road, (0,0))
           screen.blit(carImg, (350,370))
        else:
            screen.blit(text_vroom, text_vroom_rect)

        # Button GO/STOP

        if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
            pygame.draw.rect(screen, green_bright,(75,400,100,50))

            if click != None and click[0] == 1:
                # toggle True/False
                game_started = not game_started
        else:
            pygame.draw.rect(screen, green,(75,400,100,50))

        # draw GO or STOP
        if not game_started:
            screen.blit(text_go, text_go_rect)
        else:
            screen.blit(text_stop, text_stop_rect)

        # Button EXIT

        if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
            pygame.draw.rect(screen, red_bright,(550,400,100,50))

            if click != None and click[0] == 1:
                pygame.quit()
                quit()
        else:
            pygame.draw.rect(screen, red,(550,400,100,50))

        screen.blit(text_exit, text_exit_rect)

        pygame.display.flip()

        clock.tick(15)

# --- main ---

pygame.init()

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Broom! || BETA::00.0.3")

#Pictures
road = pygame.surface.Surface( size )
road.fill(black)

carImg =  pygame.surface.Surface( (10,10) )
road.fill(green)

clock = pygame.time.Clock()

game_intro()

rawDescription: Cannot get button to toggle a change in pygame


rawDescription: puzzled on how to slice a numpy array

description: Puzzled on how to slice a numpy array


code:
from collections import Counter

def find_repetition(p):
    """ Returns a lookup dictionary for repetitions. """
    lookup = Counter()
    while len(p) != 0:
        for i in xrange(len(p)):
            lookup[p[0:i]] += 1
        p = p[1:]
    return lookup

def repeats(p):
    a = find_repetition(p)
    rs = [i for i in a if a[i] > 1][1:]
    return [r for r in rs if r*2 in p]

rawDescription: Finding repetitions in a string

description: Finding repetitions in a string


code:
with open("file.csv","w") as f:
    for line in str_list:
        f.write(','.join(line.split()))
        f.write('\n')

rawDescription: Python: Write output in a csv-file

description: Python: Write output in a csv-file


code:
#just a sample code, cannot run directly

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options

from tornado.options import define, options
define("port", default=8080, help="server run on the given port", type=int)

class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("login.html")

    def post(self):
        username = self.get_argument("username")
        password = self.get_argument("password")

        #some judgement code here:
        #e.g. do some database operations, check if (username, password) pairs are correct
        #if so, set _auth_flag True, otherwise, _auth_flag=False
        [...]

        if _auth_flag:
            [...]  #if login successfully, execute this part
        else:
            [...] #if login failed, execute

if __name__ == "__main__":
    tornado.options.parse_command_line()

    app = tornado.web.Application([
           (r'/login', LoginHandler),
          ])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)

    tornado.ioloop.IOLoop.instance().start()

rawDescription: How to run a python log in system on a server along side html?

description: Run a python log in system on a server along side html


code:
from django.db.models.signals import pre_delete, post_delete
from django.dispatch import receiver

from myapp.models import ClusteringWIP

@receiver(pre_delete, sender=ClusteringWIP)
def on_instance_delete(sender, instance, **kwargs):
    instance.on_pre_delete()

rawDescription: Iterating through all foreign key related children of an abstract django model


code:
start_date = df.index.min() - pd.DateOffset(day=1)
end_date = df.index.max() + pd.DateOffset(day=31)

rawDescription: Converting PANDAS dataframe from monthly to daily


rawDescription: Averaging a list of dicts in Python

description: Averaging a list of dicts in Python


rawDescription: Grab Values Within a Dictionary in a Dictionary


code:
time.sleep(1)
with q_lock:
    work_q.put('word')
# word
# 1

time.sleep(1)
count = dev.count + 9
dev.set_count(count)
with q_lock:
    work_q.put('dog')
# dog
# 10

count = 'foo'
with q_lock:
    work_q.put('quit')
# quit
# 10
dev.join()

rawDescription: Threading and information passing -- how to


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

def plot_rect(data, delta=0.4):
    """data is a dictionary, {"Label":(low,hi), ... }
    return a drawing that you can manipulate, show, save etc"""

    yspan = len(data)
    yplaces = [.5+i for i in range(yspan)]
    ylabels = sorted(data.keys())

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_yticks(yplaces)
    ax.set_yticklabels(ylabels)
    ax.set_ylim((0,yspan))

    # later we'll need the min and max in the union of intervals
    low, hi =  data[ylabels[0]]
    for pos, label in zip(yplaces,ylabels):
        start, end = data[label]
        ax.add_patch(patches.Rectangle((start,pos-delta/2.0),end-start,delta))
        if start<low : low=start
        if end>hi : hi=end

    # little small trick, draw an invisible line so that the x axis
    # limits are automatically adjusted...
    ax.plot((low,hi),(0,0))

    # now get the limits as automatically computed
    xmin, xmax = ax.get_xlim()
    # and use them to draw the hlines in your example
    ax.hlines(range(1,yspan),xmin,xmax)
    # the vlines are simply the x grid lines
    ax.grid(axis='x')
    # eventually return what we have done
    return ax

# this is the main script, note that we have imported pyplot as plt

# the data, inspired by your example,
data = {'A':(1901,1921),
        'B':(1917,1935),
        'C':(1929,1948),
        'D':(1943,1963),
        'E':(1957,1983),
        'F':(1975,1991),
        'G':(1989,2007)}

# call the function and give its result a name
ax = plot_rect(data)
# so that we can further manipulate it using the `axes` methods, e.g.
ax.set_xlabel('Whatever')
# finally save or show what we have
plt.show()

rawDescription: Proper plot to use in matplotlib for this type of bar graph?


code:
from flask_restful import Resource
from app import api
from bar import Bar

class Foo(Resource):
    def get(self):
        related = api.url_for(Bar, foo=self.id)
        return {'Foo':self.id, 'related_bar':related}, 200

    def post(self):
        pass

rawDescription: How to access api.url_for in big Flask-Restful API

description: Access api.url_for in big Flask-Restful API


code:
def grow(amount):
    def _grow(particle):
        if random.randint(0,100) < particle.alive / 20:
            particle.size += amount
    return _grow

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
#groupby and set rolling count from column Block
data["Replicate"] = data.groupby(["Block", "Name"])["Block"].transform(pd.rolling_count, window=3)

rawDescription: groupby issues of not recognizing numeric column pandas python

description: Groupby issues of not recognizing numeric column pandas python


code:
def my_fn(x, b, a):
    y = np.zeros_like(x)
    nonzero = x != 0
    x = x[nonzero]
    y[nonzero] = b*(1/np.tanh(x/a) - a/x)
    return y

rawDescription: Iterating through python numpy array when used with scipy.optimize.curve_fit


code:
import xbmcaddon
addon = xbmcaddon.Addon()

my_hello_string = addon.getLocalizedString(32000)

rawDescription: How to input the strings in the label control for xbmc?

description: Input the strings in the label control for xbmc


code: settings = FormSettings.objects.get(form=app_name + self.__class__.name)

rawDescription: Dynamic form requirements in Django

description: Dynamic form requirements in Django


code: table.editItem(table.item(0, 1))

rawDescription: QTableWidget how to have a cell selected for editing from code and/or with single click


code:
title_pattern = re.compile("(?P<title>%s)" % re.escape(title), # <---
                           flags=re.IGNORECASE)
json3 = json.load(urllib2.urlopen(url3))
matched = any(isinstance(value, basestring) and title_pattern.search(value) for value in json3.itervalues())

rawDescription: Python: search through values of dict for regex


code:
def getOdds_gen_helper(p, q):
    """ generates odd numbers between integers p & q """

    # Define odd number string
    x = p
    while x <= q:
        if x % 2 == 0:
            x += 1

     # Calculate & print string
        else:
            yield x #!!! yield the values
            str(x).strip(", ")
            x += 2

rawDescription: I don't know how to strip the end of this line


code: my_dict = {k: v if len(v) > 1 else v[0] for k, v in tmp.values()}

rawDescription: Python- add to dictionary based on an incrementing value in 2 lists


rawDescription: Ewma in pandas but over rolling weekly data.


code: filename_str = unicode(my_path)

rawDescription: How to separate filename from path in python (PyQt4.QtCore.QString)

description: Separate filename from path in python (PyQt4.QtCore.QString)


code:
sys.version
os.system(r'mklink /D Windows C:\Windows')
islink('Windows')
islink('C:/Documents and Settings') # junction
readlink('Windows')
readlink('C:/Documents and Settings')

rawDescription: Having trouble implementing a readlink() function


code:
ps = db.prepare("SELECT * FROM information_schema.tables WHERE table_name = $1 LIMIT $2")
ps("tables", 1)

rawDescription: Best way of gluing strings in Python to compose SQL query


code:
class IdGenerator(object):
    def __init__(self):
        self.cur_id = 1
        self.lock = threading.Lock()
    def next_id(self):
        with self.lock:
            result = self.cur_id
            self.cur_id += 1
        return result

rawDescription: Python - Global counter

description: Python - Global counter


code:
factors = [1,2,3,4,6,12]
negatives = [-item for item in factors]

rawDescription: add a character in front of every element in a list

description: Add a character in front of every element in a list


code:
def mplist(somelist):
    someset = set(somelist)
    with open(up) as U:
        return [line for line in U if line.split(None, 1)[0] in someset]

rawDescription: Python: Looping over 2mln lines

description: Python: Looping over 2mln lines


code:
import sys

def find(abc):
    #base case
    if len(abc) == 2:
        if isinstance(abc[0], list) and isinstance(abc[1], list):
            re = find(abc[0] + abc[1:])
        elif isinstance(abc[1], list):
            re = find(abc[:1] + abc[1])
        elif isinstance(abc[0], list):
            re = find(abc[0] + abc[1:])
            # ^^^ fixed typo (ifs could be simplified by dropping first if)
        else:
            if abc[0] > abc[1]:
                re = (abc[0], abc[1])
            else:
                re = (abc[1], abc[0])
    # recursive step
    else:
        # CHANGE HERE
        if len(abc) == 0:   # @HACK: handle empty list
            return (sys.maxsize, sys.maxsize)
        # CHANGE ENDS
        if isinstance(abc[0], list):
            re = find(abc[0] + abc[1:])
        # if this element is integer
        else:
            current = abc[0]
            second, first = find(abc[1:])
            if (second < current):
                re = (second, first)
            elif (current > first) and (second >= current):
                re = (current, first)
            else:
                re = (first, current)
    return re # @TODO: possibly filter out maxsize in final result

rawDescription: Finding the second smallest int in list of list in Python 3 with recursion


code: df.groupby("A")["B"].apply(' ; '.join)

rawDescription: How to return a single row for rows that have duplicate values in Pandas

description: Return a single row for rows that have duplicate values in Pandas


code:
class NameParser:

    def __init__(self):
        self.getName

    def getName(self, name):
        listy = [] # where the needed output is put in
        splitName = name.split(' ')

        for i in range(len(splitName)):
            if i==(len(splitName)-1):#when the last word is reach
                listy.append('Surname: '+ splitName[i])
            else:
              listy.append('Name: '+ splitName[i])

        return listy

nr = NameParser()

print(nr.getName("ali opcode goren"))

# output: name: ali, name: opcode, surname: goren

rawDescription: How to return two values in Python

description: Return two values in Python


rawDescription: Pandas: transforming the DataFrameGroupBy object to desired format


code: z = [[y for y in row if y] for row in x.T]

rawDescription: Boxplotting Masked Arrays

description: Boxplotting Masked Arrays


code:
import requests
import xml.etree.ElementTree as ET

r = requests.get('url',  auth=('user', 'pass'))
tree = ET.parse(r.text)
root = tree.getroot()

rawDescription: Save XML response from GET call using Python


rawDescription: Extract Numbers and Size Information (KB, MB, etc) from a String in Python


code: backtrack(s, i+1, [x for x in stack], new_s)

rawDescription: Passing list (stack) in backtracing in python


code:
data = ((email[:10], email[10:]) for email in
        (x.readlines() for x in self.inbox.dex))
self.heads, self.bodies = zip(*data)

rawDescription: Can I apply a function to the variable in a for loop definition (Python)

description: Apply a function to the variable in a for loop definition (Python)


code:
if condition1:
    if condition2:
       if condition3:
           statement
       else:
           statement
    elif condition4:
       if condition5:
           statement
       else:
           statement

rawDescription: Conditional Statement in python

description: Conditional Statement in python


code: np.intersect1d(eqn_out, v)

rawDescription: Using Python List Comprehension to match values that exist in a 2d array and simple list


code: tempsorted = sorted(temp, key=lambda x: x.oscis)

rawDescription: Sum array objects by array object key

description: Sum array objects by array object key


code:
class B(list):
    """
    Some customization of this class...
    """
@property
def a(self):
    return (item.a for item in self)

rawDescription: Get attribute of all items in container python


code:
centralWidget = QtGui.QWidget(self)
self.setCentralWidget(centralWidget)
mainLayout = QtGui.QHBoxLayout(centralWidget)
self.scoreTable = QtGui.QTableWidget(self)
self.scoreTable.setRowCount(len(StudentNames))
self.scoreTable.setColumnCount(1)
self.scoreTable.setVerticalHeaderLabels(StudentNames)
self.scoreTable.setHorizontalHeaderLabels(['Scores'])
for i, score in enumerate(StudentScores):
    item = QtGui.QTableWidgetItem(str(score))
    self.scoreTable.setItem(i, 0, item)

mainLayout.addWidget(self.stack)
mainLayout.addWidget(self.scoreTable)

rawDescription: Is it possible to horizontally add a QTableWidget to a layout?


code: n = math.sqrt(numpy.dot(A,A.conj()))

rawDescription: multiplying two nparray together python

description: Multiplying two nparray together python


code: z = re.findall(r"(\S+).*(?:\sA\s|\sCNAME\s)", db)

rawDescription: How to match an OR expression without grouping it?

description: Match an OR expression without grouping it


code:
b = B()
b.a = target
b.save()

rawDescription: How to bind event on create of object in SqlAlchemy?

description: Bind event on create of object in SqlAlchemy


code:
unq_i, inv_i = np.unique(i, return_inverse=True)
unq_ci = np.bincount(inv_i, weights=cij)
unq_i
unq_ci

rawDescription: Vectorized version of for-loop + numpy.where


rawDescription: how use alias in sqlachemy

description: How use alias in sqlachemy


code:
def my_pop(l):
    new = []
    l = list(l)
    for i in l:
        if l[-1] == i:
            pass
        else:
            new.append(i)
    return new

rawDescription: Python-Stuck when trying to manually implement the pop method for lists


code: titles = [d['Title'] for d in obj_1['d']['results']]

rawDescription: Extracting info from a python dictionary


code:
class docstring_str(str):
    def __new__(cls, v, __doc__=''):
        s = super(docstring_str, cls).__new__(cls, v)
        s.__doc__ = __doc__
        return s

s = docstring_str('Test', 'docstring')
s
s.__doc__

rawDescription: Implementing a class property that preserves the docstring


code:
def __init__(self):
    self.seeds = set()
    self.cache = dict()

rawDescription: improve my code to group same words in a large list python and comparison to other code

description: Improve my code to group same words in a large list python and comparison to other code


code:
def foo():
        foo = ('String', 'Tuple', 'From', 'Python' )
        return foo

rawDescription: Passing python array to bash script (and passing bash variable to python function)


code:
dx = ndimage.sobel(preSobel, 0)  # horizontal derivative
dy = ndimage.sobel(preSobel, 1)  # vertical derivative

rawDescription: 3d sobel algorithm in python?

description: 3d sobel algorithm in python


code:
import types
a.barFighters = types.MethodType( barFighters, a )
a.barFighters
a.barFighters()

rawDescription: Adding a Method to an Existing Object Instance


code:
def something():
    foo = 'bar'

rawDescription: Python within python

description: Python within python


rawDescription: Python: Read several json files from a folder


rawDescription: Any method to denote object assignment?

description: Any method to denote object assignment


code:
import re
import requests

L = []
for i in range(1):      # Number of pages plus one
     url = "http://www.pga.com/golf-courses/search?page={}&searchbox=Course+Name&searchbox_zip=ZIP&distance=50&price_range=0&course_type=both&has_events=0".format(i)
     r = requests.get(url)
     ownership = re.findall('(?<=
)([^<]+)',r.text)
     address = re.findall('(?<=
)([^<]+)', r.text)
     L.extend(zip(ownership,address))

rawDescription: Scraping and Parsing a website for information


code:
from matplotlib import pyplot as plt
from matplotlib import colors as mcolors
import numpy as np

N = 21
zvals = 100*np.random.randn(N, N)
fig = plt.figure(2)
ax = fig.add_subplot(111)
cmap2 = mcolors.LinearSegmentedColormap.from_list(
    'my_colormap', ['blue','green','brown'], 256)

img2 = plt.imshow(zvals,interpolation='nearest',
                  cmap=cmap2, origin='lower')
plt.colorbar(img2, cmap=cmap2)
step = 5
locs = range(0, N, step)
ax.set(
    xticks=locs,
    xticklabels=['$2^{{{}}}$'.format(i-5) for i in locs],
    yticks=locs,
    yticklabels=['$2^{{{}}}$'.format(i-15) for i in locs])
plt.show()

rawDescription: Python How to set axes for a matplotlib plot


rawDescription: How do I specify "%-*s" in new-style .format()?

description: Specify "%-*s" in new-style .format()


code: circle = circle + 1

rawDescription: save variables on a while loop

description: Save variables on a while loop


code:
self.my_items,self.my_prices = [],[]
items = [("item1",50),("item2",75),("item3",88)]
for i,(itemName,itemPrice) in enumerate(items):
    self.my_items.append(wx.StaticText(self.frame,-1,itemName,pos=(50,start+i*50)))
    self.my_prices.append(wx.StaticText(self.frame,-1,itemPrice,pos=(250,start+i*50)))

rawDescription: How to update wxStatic Text in wxpython?

description: Update wxStatic Text in wxpython


code:
lib = ctypes.WinDLL('mylibrary.dll')
#lib = ctypes.WinDLL('full/path/to/mylibrary.dll')
func = lib['myFunc']#my func is double myFunc(double);
func.restype = ctypes.c_double
value = func(ctypes.c_double(42.0))

rawDescription: Python import dll

description: Python import dll


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Polygon
np.random.seed(1977)

def main():
    gradient_fill(np.array([1,2,3,4]),np.array([2,-1,-2,1]))
    plt.show()

def gradient_fill(x, y, fill_color=None, ax=None, **kwargs):
    """
    Plot a line with a linear alpha gradient filled beneath it.

    Parameters
    ----------
    x, y : array-like
        The data values of the line.
    fill_color : a matplotlib color specifier (string, tuple) or None
        The color for the fill. If None, the color of the line will be used.
    ax : a matplotlib Axes instance
        The axes to plot on. If None, the current pyplot axes will be used.
    Additional arguments are passed on to matplotlib's ``plot`` function.

    Returns
    -------
    line : a Line2D instance
        The line plotted.
    im : an AxesImage instance
        The transparent gradient clipped to just the area beneath the curve.
    """
    if ax is None:
        ax = plt.gca()

    line, = ax.plot(x, y, **kwargs)
    if fill_color is None:
        fill_color = line.get_color()

    zorder = line.get_zorder()
    alpha = line.get_alpha()
    alpha = 1.0 if alpha is None else alpha

    z = np.empty((100, 1, 4), dtype=float)
    rgb = mcolors.colorConverter.to_rgb(fill_color)
    z[:,:,:3] = rgb
    z[:,:,-1] = np.linspace(0, alpha, 100)[:,None]

    xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
    im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax],
                   origin='lower', zorder=zorder)

    xy = np.column_stack([x, y])
    xy = np.vstack([[xmin, 0], xy, [xmax, 0], [xmin, 0]])
    clip_path = Polygon(xy, facecolor='none', edgecolor='none', closed=True)
    ax.add_patch(clip_path)
    im.set_clip_path(clip_path)

    ax.autoscale(True)
    return line, im

main()

rawDescription: python area chart with gradient color between the line and y=0

description: Python area chart with gradient color between the line and y=0


code:
class B(object):
    __slots__ = ['only_one_attribute']
    def __init__(self):
        self.only_one_attribute = 'one'
    def add_attr(self):
        self.another_attribute = 'two'
b = B()
b.add_attr()

rawDescription: Python Class Fields

description: Python Class Fields


code:
CACHE = {}

class Example(object):
    @property
    def foo(self):
        if self not in CACHE:
            CACHE[self] = ...  # do the actual computation
        return CACHE[self]

rawDescription: How to combine SQLAlchemy's @hybrid_property decorator with Werkzeug's cached_property decorator?

description: Combine SQLAlchemy's @hybrid_property decorator with Werkzeug's cached_property decorator


code:
df["freq"] = 1
df["freq"] = df.groupby(["Year", "Region"]).transform(lambda x: x.sum())

rawDescription: Calculate Frequency of item in list

description: Calculate Frequency of item in list


code:
import os

PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT

MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    os.path.join(SITE_ROOT, 'staticfiles'),
)

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(SITE_ROOT, 'templates'),
)

rawDescription: show images in Django templates

description: Show images in Django templates


code:
eg = '78 56 78 1 7 '
eg_list = eg.split()
eg_list
int(eg[0])
int(eg_list[0])

rawDescription: I want to loop through a string of numbers


code: class EqM_list(EqMixin, list): pass

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


code:
def f1(LoD, idd):
    desired_lst = []
    for item in LoD:
        if item['id'] == idd:
            desired_lst.append(item)

    return desired_lst

def f2(LoD, idd):
    return [d for d in LoD if d['id']==idd]

def f3(LoD, idd):
    return list(filter(lambda x: x['id']==idd, LoD) )

rawDescription: Python: Fetch item in list where dict key is some value using lambda


code:
with open('newfoo.py', 'wb') as f:
    for name, value in foo.__dict__.items():
        f.write('{} = {!r}\n'.format(name, value))

rawDescription: Exporting a python module (to string or py file)


code:
d = {}
with open(filename) as f:
    for line in f.read().split('\n'):
        key, value = line.split()
        d[key] = value

rawDescription: How to read from file, turn into a dictionary and write to the same file

description: Read from file, turn into a dictionary and write to the same file


rawDescription: python find duplicate lists in list of lists

description: Python find duplicate lists in list of lists


code: choices=[(item.pk, item.some_other_method()) for item in some_queryset]

rawDescription: Use method other than __unicode__ in ModelChoiceField Django


rawDescription: Find sets of disjoint sets from a list of tuples or sets in python


code:
to_change = ("is_diabetic", "is_inpatient")

for d in result:
    for k in to_change:
        if k in d:
            if d[k] == 1:
                d[k] = "Yes"
            else:
                d[k] = "No"

rawDescription: Updating values for only certain keys in a list of dicts in python


code:
import ast
d = {'abc': 1, 'def': 2}
with open("file","w") as f: f.write(str(d))

with open("file","r") as f: ast.literal_eval(f.read())

type(_)

rawDescription: Interesting Behavior with Dictionary and ast.literal_eval


rawDescription: Read a command prompt output in a separate window in python


code:
print(zebra_line(x=30,y=350, text="Test"))
print(zebra_line(x=30,y=350, text="Test", font=1234))

rawDescription: default argument in bound function

description: Default argument in bound function


code:
from tkinter import *

class AppetiserClass:
    meal1 = 0
    root = Tk()
    app = Frame(self.root)

    def __init__(self):
        self.root.title("Appetiser Page")
        self.root.geometry("1920x1080")

        self.app.grid()

        Label(self.app, text = "", width = 75, height = 20).grid(row = 1, column = 0, sticky = N)

        self.DisplayButton = Button(self.app, text = self.meal1)
        self.DisplayButton.grid(column = 1, row = 2, sticky = W)
        self.DisplayButton.config(height = 10, width = 10 )

        self.Plus1Button = Button(self.app, text = "+1", command=self.plus1, bg="green")
        self.Plus1Button.grid(column = 2, row = 2, sticky = W)
        self.Plus1Button.config(height = 10, width = 10 )

        self.Neg1Button = Button(self.app, text = "-1", command=self.neg1, bg="green")
        self.Neg1Button.grid(column = 3, row = 2, sticky = W)
        self.Neg1Button.config(height = 10, width = 10 )

        self.root.mainloop()

    def plus1(self):
        self.meal1 += 1
        self.DisplayButton["text"]=str(self.meal1)

    def neg1(self):
        self.meal1 -= 1
        self.DisplayButton["text"]=str(self.meal1)

if __name__ == "__main__":
    AppetiserClass()

rawDescription: Tkinter - Python 3 - Adding an Increment Counter into a class window?


code:
import re
my_str = "abcdefgfaabbbffbbbbbbfgbb"
len(max(re.compile("(b+b)").findall(my_str)))
# max([len(i) for i in re.compile("(b+b)").findall(my_str)]) also works

rawDescription: Counting longest occurence of repeated sequence in Python


code: (data - data.mean())/data.std()

rawDescription: How should the values of a list be scaled such that they meet standard deviation and mean requirements?


code:
class myWidget(QWidget):

    def __init__(self):
        super().__init__()

        # Slider
        self.mySlider = QSlider(Qt.Horizontal)

rawDescription: PyQt5 add custom QWidget to QLayout

description: PyQt5 add custom QWidget to QLayout


code:
import time
import matplotlib.pyplot as plt

x = range(10)
y = range(10)

# Xtick labels
ticks = [ctime(val) for val in x]
plt.plot(x,y)

# Plot ticks with a rotation
plt.xticks(x, ticks, rotation=12)

plt.show()

rawDescription: My xticks are pushed to the left

description: My xticks are pushed to the left


code:
class NestedTuples:
    def __init__(self, num):
        self.tuple = tuple((x, []) for x in range(num))

rawDescription: Initializes a class with n-nested tuples


code:
import cv2
cv2.imshow('', im)
cv2.waitKey()
cv2.destroyAllWindows()

rawDescription: Opencv Python display raw image

description: Opencv Python display raw image


code:
from my_module import ProcessManager

my_args = ...
ProcessManager.set_process(my_args)

...

ProcessManager.kill_process()

rawDescription: Storing subprocess object in memory using global singleton instance


code:
def __getitem__(self, k):
    if self.mypattern.match(k):
        return 1
    else:
        raise KeyError("Key {} does not match pattern {}".format(k, self.mypattern))

rawDescription: proper way to subclass object for __getitem__() in python if emulating a dict

description: Proper way to subclass object for __getitem__() in python if emulating a dict


code:
import Queue
import threading

def basic_worker(queue):
    while True:
        item = queue.get()
        # do_work(item)
        print(item)
        queue.task_done()
def basic():
    # http://docs.python.org/library/queue.html
    queue = Queue.Queue()
    for i in range(3):
         t = threading.Thread(target=basic_worker,args=(queue,))
         t.daemon = True
         t.start()
    for item in range(4):
        queue.put(item)
    queue.join()       # block until all tasks are done
    print('got here')

basic()

rawDescription: setDaemon function in thread

description: SetDaemon function in thread


rawDescription: Serializing a Python namedtuple to json

description: Serializing a Python namedtuple to json


code:
class ModelControllerMetaclass(type):
  def __init__(cls, name, bases, dct):
    if 'options' not in dct or not hasattr(dct['options'], 'model'):
      raise RuntimeError('You accidentally the model!')
    dct['_model'] = dct['options'].model
    # Some more manipulation of dct['options']
    del dct['options']
    type.__init__(cls, name, bases, dct)

class ModelController(object):
  __metaclass__ = ModelControllerMetaclass
  class options:
    model = None

class ArticleModelController(ModelController):
  class options:
    model = 'Some model goes here'

class InvalidModelController(ModelController):
  pass

rawDescription: How do I customise subclassing behaviour or require subclassing in a particular way?

description: Customise subclassing behaviour or require subclassing in a particular way


rawDescription: Pandas select and write rows that contain certain text


code:
import requests
r = requests.get(url)
r.status_code

rawDescription: HTTP Error 403: Forbidden urlib2 Python 2.7


code:
class clsmaker(object):
    def __init__(self, N):
    	self.N = N
    def __call__(self, X):
    	return X * self.N

rawDescription: python factory functions compared to class

description: Python factory functions compared to class


rawDescription: Issues with using argparse with listcomprehensions


rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


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


rawDescription: Python - read table with empty fields from file


code:
int2ip = lambda n: socket.inet_ntoa(struct.pack('!I', n))
print(int2ip(3232235525))
# -> '192.168.0.5'

rawDescription: python increment ipaddress

description: Python increment ipaddress


code: matches = re.findall(r'ABC\s*(\d+)', page)

rawDescription: Finding first non-digit character with .find in Python


code:
def parse_item(self, response):
    l = TargetLoader(TargetsItem(), response)

    l.add_xpath('title', '//title/text()')
    l.add_value('link', response.url)

    return l.load_item()

rawDescription: curly bracket issue when inserting scrapy crawler results to postgresql

description: Curly bracket issue when inserting scrapy crawler results to postgresql


code:
_product = lambda s: reduce(lambda x, y: x * y, s)
_SMALL = 1e-20

rawDescription: What is the total bigram count returned for NLTK BigramCollocationFinder?


code:
for (key, val) in d.items():
    if val < sl:
          d[key] = (val,True)
    else:
          d[key] = (val,False)

rawDescription: Adding multiple values to a key in python dictionaries


code:
if not any(test_string in text for test_string in ["doc", "pdf", "xls", "jpg"]):
    filtered.append(text)

rawDescription: Python Logic in searching String

description: Python Logic in searching String


code:
s = min((s for s in squares if len(values[s])>1),
        key=lambda s: len(values[s]))

rawDescription: Underscore _ as variable name in Python

description: Underscore _ as variable name in Python


code:
class DummyPopen(object):
    def __init__(self, *args, **kw):
        print('Popen({})'.format(
            ', '.join([repr(arg) for arg in args] +
                      ['{}={!r}'.format(*pair) for pair in kw.items()])))
        self.returncode = 1

    def wait(self):
        return 1

    # et cetera

rawDescription: extending subprocess.Popen through inheritence

description: Extending subprocess.Popen through inheritence


code:
import htmlmin

with open('file.html', 'r') as f:
    content = f.read()
    minified = htmlmin.minify(content, remove_empty_space=True)

rawDescription: Shortening HTML files

description: Shortening HTML files


code:
data = ['header', 1, 2, 3, 4]

with open("infile", 'r') as inf, open("infile.2", 'w') as outf:
    outf.writelines('%s,%s\n' % (s.strip(), n) for s, n in zip(inf, data))

rawDescription: adding string at the end of the file python

description: Adding string at the end of the file python


code:
t1 = Test()
t1.function(1)
t2 = Test(lambda self, x: self.dicty[x]['width'])
t2.function(1)

rawDescription: __init__ with function as parameter (using the NetworkX)


rawDescription: Check what numbers in a list are divisible by certain numbers?


code:
if (next_qi < qi + lcs_len   # If the next qLCS overlaps
and next_ri < ri + lcs_len   # If the next rLCS start overlaps
and next_ri + lcs_len > ri): # If the next rLCS end overlaps
    del candidate_lcs[qi] # Delete dupilicate LCS.

rawDescription: Commenting with line continuation

description: Commenting with line continuation


code: [float(n.split()[3]) for n in lines]

rawDescription: How to generate an array/list from an output using .split() in Python 2.6

description: Generate an array/list from an output using .split() in Python 2.6


rawDescription: Python: Format output string, right alignment


code:
import unicodedata as ud

astr=u"\N{LATIN SMALL LETTER E}" + u"\N{COMBINING ACUTE ACCENT}"
combined_astr=ud.normalize('NFC',astr)

rawDescription: Precompose Unicode Character Sequences in Python


code:
update_map = {}

def update(instance):
     #do the update
     update_map[instance] = update_map.get(instance,0)+1

def get_update_count(instance):
     return update_map[instance] or 0

rawDescription: How to improve a simple caching mechanism in Python?

description: Improve a simple caching mechanism in Python


code:
from multiprocessing import Pool
import time
import random

def myfunc():
    a = random.randint(0,3)
    time.sleep(a)
    return a

print("Starting...")

p = Pool(processes=8)
SOME_LIST = p.map(myfunc, range(p._processes))
p.close()
p.join()

print("Stopping...")
print(SOME_LIST)

rawDescription: Managing Processes from Python multiprocessing module


code:
def plot(ax, data):
    ax.plot(a*np.cos(theta), a*np.sin(theta), color='black')
    im = ax.pcolormesh(x, y, data)
    ax.set(aspect=1)
    fig.colorbar(im, ax=ax, shrink=0.5)

rawDescription: adding line plot to imshow and changing axis marker

description: Adding line plot to imshow and changing axis marker


code:
rewards = Reward.objects.all()
rewards = [(x.id, x.name) for x in rewards]  # returns a list of tuples for the id and name fields (if such fields exist)

rawDescription: Using dehydrate in Tastypie to return all objects


code:
class Person:
    def walk(self):
        ...

rawDescription: What are the character limitations to Django model's related_name in a relationship?


code:
import Mudules.module1 as moudle1
import Widgets.widget1 as coolUI

rawDescription: PYTHONPATH set when loading Idle in virtual environment


code:
minor = np.zeros([nrows-1, ncols-1])
for row in xrange(nrows):
    for col in xrange(ncols):
        minor[:row,:col] = matrix[:row,:col]
        minor[row:,:col] = matrix[row+1:,:col]
        minor[:row,col:] = matrix[:row,col+1:]
        minor[row:,col:] = matrix[row+1:,col+1:]
        ...

rawDescription: Speed up python code for computing matrix cofactors


rawDescription: Mercurial's showconfig with the proper encoding?


rawDescription: Is that a tag list or something else?

description: Is that a tag list or something else


rawDescription: set multi index of an existing data frame in pandas

description: Set multi index of an existing data frame in pandas


rawDescription: Adding '-' into string in dataframe

description: Adding '-' into string in dataframe


code:
CELERY_QUEUES = (
    Queue('celery', Exchange('celery', type='direct'), routing_key='celery',
          consumer_arguments={'x-priority': 0}),
    Queue('hipri', Exchange('hipri', type='direct'), routing_key='hipri',
          consumer_arguments={'x-priority': 10}),
)

rawDescription: How do I set consumer priority in celery - rabbitmq set up?

description: Set consumer priority in celery - rabbitmq set up


code: s.apply(lambda x: pd.Series(1, index=x))

rawDescription: Cumulative sum with missing categories in pandas


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: List comprehension with multiple variables


code: timeit('f(l)', 'from __main__ import testlist as l, nl_join_concat as f', number=10000)

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


code: winpath = r'\\network\path'

rawDescription: I am trying to add r'' to a variable and tried below but its not working


rawDescription: Name of a function returning a generator


code:
import subprocess
import threading
import time
import sys

if sys.version_info.major >= 3:
    import queue
else:
    import Queue as queue
    input = raw_input

def read_stdout(stdout, q):
    it = iter(lambda: stdout.read(1), b'')
    for c in it:
        q.put(c)
        if stdout.closed:
            break

_encoding = getattr(sys.stdout, 'encoding', 'latin-1')
def get_stdout(q, encoding=_encoding):
    out = []
    while 1:
        try:
            out.append(q.get(timeout=0.2))
        except queue.Empty:
            break
    return b''.join(out).rstrip().decode(encoding)

def printout(q):
    outdata = get_stdout(q)
    if outdata:
        print('Output:\n%s' % outdata)

if __name__ == '__main__':

    ARGS = ["shellcomm.bat"]   ### Modify this

    #setup
    p = subprocess.Popen(ARGS, bufsize=0, stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    q = queue.Queue()
    encoding = getattr(sys.stdin, 'encoding', 'utf-8')

    #for reading stdout
    t = threading.Thread(target=read_stdout, args=(p.stdout, q))
    t.daemon = True
    t.start()

    #command loop
    while 1:
        printout(q)
        if p.poll() is not None or p.stdin.closed:
            break
        cmd = input('Input: ')
        cmd = (cmd + '\n').encode(encoding)
        p.stdin.write(cmd)

    #tear down
    for n in range(4):
        rc = p.poll()
        if rc is not None:
            break
        time.sleep(0.25)
    else:
        p.terminate()
        rc = p.poll()
        if rc is None:
            rc = 1

    printout(q)
    print('\nReturn Code: %d' % rc)

rawDescription: Getting output from and giving commands to a python subprocess


code:
for (key, value) in records:
    d[key] = d.get(key, 0) + value

rawDescription: How to update the values in a dict cleanly?

description: Update the values in a dict cleanly


rawDescription: FileNotFoundError when creating a file using a variable in Python 3.5.1


rawDescription: Split Series by string length

description: Split Series by string length


code:
def get_customfield_value(results, custom_field):
    field_value = results.fields.__getattribute__(results.fields,custom_field)
    return field_value

rawDescription: JIRA Python use a string to access class


rawDescription: how to append data using openpyxl python to excel file from a specified row?

description: Append data using openpyxl python to excel file from a specified row


code: open('file.txt', 'w').close()

rawDescription: how to erase the file contents of text file in Python

description: Erase the file contents of text file in Python


code:
from django.db import models

class Director(models.Model):
    name = models.CharField(max_length=128)
    # maybe some other fields...

class Film(models.Model):
    title = models.CharField(max_length=128)
    director = models.ForeignKey(Director)
    created_at = models.DateField()

rawDescription: DJANGO: how to create a web query form?

description: DJANGO: how to create a web query form


code: d = collections.OrderedDict(el.split(':') for el in your_list)

rawDescription: Python: Parse list of 'key:value' elements to dictionary of 'key': value pairs


rawDescription: Python match raw HTTP POST data

description: Python match raw HTTP POST data


code:
command = Command("ls -lah")
command.run(timeout=5)

rawDescription: Is it possible to output text from a Python script to the terminal as an executable command?


rawDescription: Getting indices of both zero and nonzero elements in array


code:
d = defaultdict(dict)
d.setdefault('bar', 42)
d.setdefault('bar', 30)
d

rawDescription: Python's collections.defaultdict returns default value correctly unless the key isn't referenced first


code:
from flask import Flask
from rq import Queue
from redis import Redis
import os
import urllib.parse as urlparse

app = Flask(__name__)

def function_to_queue():
    return "finished"
# Tell RQ what Redis connection to use and parse url from the global variable that was added by the addon
redis_url = os.getenv('REDISTOGO_URL')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
q = Queue(connection=conn)  #no args implies the default queue

@app.route('/')
def hello():
    ob = q.enqueue(function_to_queue) #Add previously defined function to queue
    return "k?"
if __name__ == '__main__':
    app.run()

rawDescription: How to execute function after returning Flask response (hosted on Heroku)?

description: Execute function after returning Flask response (hosted on Heroku)


code:
sentence = 'Hello how are you doing today?'
lengths = []
for word in sentence.split():
    lengths.append(len(word))

rawDescription: Change code to use list comprehension

description: Change code to use list comprehension


code: my_lookup = dict(cursor)

rawDescription: Getting dictionary from psycopg2

description: Getting dictionary from psycopg2


code:
policy_data = ... # stuff above
enc_policy = base64.b64_encode(policy_data.encode('utf8'))
signed = base64.b64_encode(hmac.new(AWS_SECRET, enc_policy, hashlib.sha1))

rawDescription: Creation of StringToSign

description: Creation of StringToSign


rawDescription: How to format numbers in Python 3 sortable into strings?

description: Format numbers in Python 3 sortable into strings


code: HAYSTACK_WHOOSH_PATH = os.path.join(CLIENT_ROOT, 'whoosh')

rawDescription: Django and SaaS. How to use separate database for each Django site?


code:
aa = np.tile(a, (len(b), 1))
bb = np.tile(b, (len(a), 1))

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


code:
l = [(1,2),(3,4)]
list(chain.from_iterable(l))

rawDescription: Parsing through a dictionary of tuples

description: Parsing through a dictionary of tuples


code:
from bs4 import BeautifulSoup as bs

xml = """<Test_input_data>
    <web_pins type="list" orientation="column">
        <web_pin_id type="column_definition" data_type="int" index="1"/>
        <pin_center_node type="column_definition" data_type="int" index="2"/>
        <journal_center_node type="column_definition" data_type="int" index="3"/>
         1  1012  5011
         2  2012  5012
         3  3012  5013
    </web_pins>
</Test_input_data>"""
soup = bs(xml)
tag = soup.find("web_pins")
text = tag.text #Here you get your text!
##P.S. you can also use:
soup.web_pins.text

rawDescription: How to extract strange XML-table via Python

description: Extract strange XML-table via Python


code:
native = '\033[m'
sys.stdout.write(native)

rawDescription: python in terminal - how to get current colour?

description: Python in terminal - how to get current colour


code:
from collections import namedtuple
foo = namedtuple('foo', ('bar', 'baz'))
f = foo(42, 38)
f.someattribute = 42
f.bar

rawDescription: How to protect class attributes in Python?

description: Protect class attributes in Python


code:
apple_lover_key_names = WhoLikes.get_by_key_name('apples')
apple_lovers = UserModel.get_by_key_names(apple_lover_key_names.users)

rawDescription: modelling the google datastore/python

description: Modelling the google datastore/python


rawDescription: Compare and replace items in a string

description: Compare and replace items in a string


code:
s
re.findall(r'(\d+) to (\d+)', s)

rawDescription: Rewrite a CSV : from a ; x to y kg ; to a ;x ; y


code:
def closest(pt, others):
    return min(others, key = lambda i: distance(pt, i))

rawDescription: Shortest distance between one point and a group of others?


code: [dateFrom + datetime.timedelta(delta_day) for delta_day in range(0, delta.days+1)]

rawDescription: python, datetime.date: difference between two days

description: Python, datetime.date: difference between two days


code:
def test():
    output = False
    exec('output=True')
    print(output)

test()

rawDescription: One-liner to set a variable value with signal handler function in response to a signal from GUI?


code:
def get_variables(arg1, arg2):
    variables = {"argument 1": arg1,
                 "argument 2": arg2,
                }
    return variables

rawDescription: How to use extra arguments passed with Variable file - Robot framework

description: Use extra arguments passed with Variable file - Robot framework


rawDescription: How can I match values from first row of array with values from first column to create a json?

description: Match values from first row of array with values from first column to create a json


code:
import cv
import numpy as np

def draw_circles(storage, output):
    circles = np.asarray(storage)
    for circle in circles:
        Radius, x, y = int(circle[0][3]), int(circle[0][0]), int(circle[0][4])
        cv.Circle(output, (x, y), 1, cv.CV_RGB(0, 255, 0), -1, 8, 0)
        cv.Circle(output, (x, y), Radius, cv.CV_RGB(255, 0, 0), 3, 8, 0)

orig = cv.LoadImage('eyez.png')
processed = cv.LoadImage('eyez.png',cv.CV_LOAD_IMAGE_GRAYSCALE)
storage = cv.CreateMat(orig.width, 1, cv.CV_32FC3)
#use canny, as HoughCircles seems to prefer ring like circles to filled ones.
cv.Canny(processed, processed, 5, 70, 3)
#smooth to reduce noise a bit more
cv.Smooth(processed, processed, cv.CV_GAUSSIAN, 7, 7)

cv.HoughCircles(processed, storage, cv.CV_HOUGH_GRADIENT, 2, 32.0, 30, 550)
draw_circles(storage, orig)

cv.ShowImage("original with circles", orig)
cv.WaitKey(0)

rawDescription: What are the correct usage/parameter values for HoughCircles in OpenCV for Iris detection?


code:
forms[2].set_value("LOOK!!!! I SET THE VALUE OF THIS UNNAMED CONTROL!",
                       nr=5)

rawDescription: Use mechanize to submit form without control name


code:
class ClassName(object):
    def __init__(self, **kw):
         self._name = ''
         for attr, val in kw.items():
               if val == None:
                  continue
               setattr(self, '_' + attr, val)

    def getName(self): return self._name
    name = property(getName)

cl = ClassName(name='name1')
cl2 = ClassName(name='name2')
li = list()
li.append(cl)
li.append(cl2)

rawDescription: Python classes - each class call new id

description: Python classes - each class call new id


code:
for phase, actions in results:
    while actions:
        action = actions.pop()
        # etc...

rawDescription: python deque/list filtering

description: Python deque/list filtering


code:
parse_string = ("http://www.google.pl/search?q=%s&restofurl" %
               '%2C'.join(tag.strip() for tag in tags_list))

rawDescription: Parsing a list into a url string

description: Parsing a list into a url string


code:
if any(value & p for p in (self.PINPUT, self.PINPUTDOWN, self.PINPUTNONE)):
    do_something()

rawDescription: Pythonic way of checking bit values

description: Pythonic way of checking bit values


code:
def getMethod(path):
    names = path.split('.')
    return reduce(getattr, names[1:], __import__(names[0]))

getMethod('sys.stdin.write')

rawDescription: Calling a method of a class, the classname is a variable


code:
def myfunc(key1 = 'val1',
           key2 = 'val2',
           key3 = 'val3'):
    return key1, key2, key3

rawDescription: Python PEP8 conventions

description: Python PEP8 conventions


code: from datetime import timedelta

rawDescription: How to import part of a module in python?

description: Import part of a module in python


rawDescription: Why there is a "array" in the result of split? (Python)


rawDescription: How to perform an operation on this tuple and convert to another tuple in Python?

description: Perform an operation on this tuple and convert to another tuple in Python


code:
from time import sleep
import json
from django.http import HttpResponse
from django.shortcuts import render

def main_view(request):
    return render(request, 'index.html')

def ajax_view(request):
    sleep(10) #This is whatever work you need
    pi1 = "This is pi1" #I just made pi1/pis1 random values
    pis1 = "This is pis1"
    context = {
        "pi1" : pi1,
        "pis1" : pis1,
    }
    data = json.dumps(context)

    return HttpResponse(data, content_type='application/json')

rawDescription: Django - How to use asynchronous task queue with celery and redis


code: m = [[0] * 2 for _ in xrange(3)]

rawDescription: How do I initialize a one-dimensional array of two-dimensional elements in Python?

description: Initialize a one-dimensional array of two-dimensional elements in Python


code:
import matplotlib.pyplot as plt

fig=plt.figure(figsize=(8,4))
ax1=fig.add_subplot(121,projection='polar')
ax2=fig.add_subplot(122,projection='polar')

ax1.yaxis.grid(linewidth=3)

plt.show()

rawDescription: Polar plot with Python changing the thickness of my grid


code: QListWidget

rawDescription: PySide / PyQt QStyledItemDelegate list in table


code:
class MacroSyntaxElement(object):
  def __init__(self, *p, name=None):
    self.subelements = p
    self.name = name

rawDescription: Pythonic macro syntax

description: Pythonic macro syntax


code:
['borlamd', 'borlame', 'borlamf', 'borland', 'borlane', 'borlanf', 'borlaod', 'borlaoe', 'borlaof']
['hdllo', 'hello', 'hfllo']

rawDescription: solution to this recursive function questions?

description: Solution to this recursive function questions


code:
import os
import re
b = open ('Filter_Lines.txt','w')
DRIVE = "E:" #windows
SEP = os.path.sep

if (SEP=="\\"):
    SEP="\\\\"

with open('filetest') as f:
    for line in f:
        repl = (re.sub( DRIVE +'.*'+SEP,'',line))
        b.write(repl)

b.close()

rawDescription: Remove file path with backslash (////) from a text file


code:
lbl, nlbls = label(a)
lbl
nlbls

rawDescription: How to group elements of a numpy array with the same value in separate numpy arrays

description: Group elements of a numpy array with the same value in separate numpy arrays


code:
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

THETA, PHI = np.ogrid[0:2*np.pi:40j, 0:np.pi:30j]

X = 10 * np.cos(THETA) * np.sin(PHI)
Y = 10 * np.sin(THETA) * np.sin(PHI)
Z = 10 * np.ones_like(THETA) * np.cos(PHI)

def func(THETA, PHI):
    mask = (THETA < np.pi/2) & (np.pi/3 < PHI) & (PHI < 2 * np.pi/3)
    return np.where(mask, 1, 0.5)

C = func(THETA, PHI)

x = X.ravel()
y = Y.ravel()
z = Z.ravel()

c = C.ravel()
ax.scatter(x, y, z, c=c, s=30, vmin=0, vmax=1)
ax.set_aspect('equal')
plt.show()

rawDescription: Matplotlib boolean coloring

description: Matplotlib boolean coloring


rawDescription: Interpolate and fill pandas dataframe with datetime index


code:
#! /bin/env python
import hashlib
def filemd5(filename, block_size=2**20):
    f = open(filename)
    md5 = hashlib.md5()
    while True:
        data = f.read(block_size)
        if not data:
            break
        md5.update(data)
    f.close()
    return md5.digest()

if __name__ == "__main__":
    a = filemd5('/home/neo/todo')
    b = filemd5('/home/neo/todo2')
    print(a == b)

rawDescription: check files for equality

description: Check files for equality


code: x

rawDescription: Numpy loadtxt rounding off numbers

description: Numpy loadtxt rounding off numbers


code:
import bisect

class RangeClass(object):

    def __init__(self,address,size):
        self.address=address
        self.size=size
    def __str__(self):
        return '[{0},{1})'.format(self.address,self.address+self.size)
    def __lt__(self,other):
        return self.address<other.address

rangelist=sorted([RangeClass(i,1) for i in (1,3,4,5,7.5)])
starts=[r.address for r in rangelist]

def find_range(value):
    start_idx=bisect.bisect(starts,value)-1
    try:
        r=rangelist[start_idx]
    except IndexError:
        return None
    start=r.address
    end=r.address+r.size
    if start<=value<end:
        return rangelist[start_idx]
    return None

print(','.join(str(r) for r in rangelist))

for value in (0,1,1.5,2,3,4,5,6,7,8,9,10):
    r=find_range(value)
    if r:
        print('{v} in {r}'.format(v=value,r=str(r)))
    else:
        print('{v} not in any range'.format(v=value))

rawDescription: Which is the fastest way to search a value within a set of many "range" objects in Python


code:
import re
pat = re.compile(r'^--\s*(?P<name>\w+).*')

def get_data(file):
    '''gets the numbers till you find "/"
    '''
    arr = []
    for line in file:
        numbers = line.split()
        if numbers[-1] == '/':
            arr.extend(numbers[:-1])
            break
        else:
            arr.extend(numbers)
    return arr

for line in file:
    if line.startswith('--'):
        name = pat.match(line).groups()[0]
        arrays[name] = get_data(file)

rawDescription: Complicated ASCII file parsing with Python


code:
def __init__(self):
    self.page_num = 0
    self.driver = webdriver.Firefox()
    dispatcher.connect(self.spider_closed, signals.spider_closed)

rawDescription: Scrapy and Selenium : only scrap two pages


code:
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.plot([1,2,3])
text = '
Description of the chart:

asdfsa fasdf qwer fsdaf er qw asdcdsafqwer dacfas dfqwetr cvxy fsa'
plotdesc(fig, text, iwidth='500px')

rawDescription: How to display a text paragraph next to figure in jupyter/ipython notebook

description: Display a text paragraph next to figure in jupyter/ipython notebook


code:
CODE={
    'ENDC':0,  # RESET COLOR
    'BOLD':1,
    'UNDERLINE':4,
    'BLINK':5,
    'INVERT':7,
    'CONCEALD':8,
    'STRIKE':9,
    'GREY30':90,
    'GREY40':2,
    'GREY65':37,
    'GREY70':97,
    'GREY20_BG':40,
    'GREY33_BG':100,
    'GREY80_BG':47,
    'GREY93_BG':107,
    'DARK_RED':31,
    'RED':91,
    'RED_BG':41,
    'LIGHT_RED_BG':101,
    'DARK_YELLOW':33,
    'YELLOW':93,
    'YELLOW_BG':43,
    'LIGHT_YELLOW_BG':103,
    'DARK_BLUE':34,
    'BLUE':94,
    'BLUE_BG':44,
    'LIGHT_BLUE_BG':104,
    'DARK_MAGENTA':35,
    'PURPLE':95,
    'MAGENTA_BG':45,
    'LIGHT_PURPLE_BG':105,
    'DARK_CYAN':36,
    'AUQA':96,
    'CYAN_BG':46,
    'LIGHT_AUQA_BG':106,
    'DARK_GREEN':32,
    'GREEN':92,
    'GREEN_BG':42,
    'LIGHT_GREEN_BG':102,
    'BLACK':30,
}

def termcode(num):
    return '\033[%sm'%num

def colorstr(astr,color):
    return termcode(CODE[color])+astr+termcode(CODE['ENDC'])

if __name__=='__main__':
    astr='yippy skippy'
    # for num in range(300):
    #     color=termcode(num)
    #     print('%s: %s'%(num,color+astr+termcode(CODE['ENDC'])))
    for key in sorted(CODE.keys()):
        print('%s: %s'%(key,colorstr(astr,key)))

    print(colorstr('Red','RED'))

rawDescription: print colorful string out to console with python

description: Print colorful string out to console with python


code:
def c(): "formatted docstring works %s"

c.__doc__
c.__doc__ %= 'after'
c.__doc__

rawDescription: How to put a variable into Python docstring

description: Put a variable into Python docstring


code:
bites = u'Ç'.encode('ISO8859-1')
unikode = u'Ç'
import sys
reload(sys)   # please don't ever actually use this hack, guys
sys.setdefaultencoding('ISO8859-1')
bites == unikode

rawDescription: How could python treat unicode and non-unicode tuple as equal?


code:
import matplotlib.pyplot as plt
from matplotlib import cm
ax = pylab.contourf(RA,Dec,dists, levels=[1, 5, 10, 15], cmap=plt.cm.spectral)
cbar=pylab.colorbar()

rawDescription: matplotlib: how can I convert a XYZ scatter to a pixel image?

description: Matplotlib: how can I convert a XYZ scatter to a pixel image


code:
with tb.open_file('myfile.h5', 'r') as f:
    x = f.root.mytable.cols.x[::4]
    y = f.root.mytable.cols.y[::4]

f = scipy.interpolate.interp1d(x, y)
ynew = f(xnew)

rawDescription: How to Interpolate Over Data in Pytables Efficiently


code:
df2 = pd.DataFrame({'Absolute Time':[randrange(start=df1.ATime.iloc[0], stop=df1.ATime.iloc[-1]) for i in range(100)]})
df2 = df2.sort_values('Absolute Time').reset_index(drop=True)

rawDescription: Python Pandas dataframe

description: Python Pandas dataframe


code: 'contains(%s)' % a

rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


code:
# This function takes a string with commas separating raw user input, and
# returns a list of valid tags made by sanitizing the strings between the
# commas.
def parseTags(str):
    # First, we split the string on commas.
    rawTags = str.split(',')

    # Then, we sanitize each of the tags.  If sanitizing gives us back None,
    # then the tag was invalid, so we leave those cases out of our final
    # list of tags.  We can use None as the predicate because sanitizeTag
    # will never return '', which is the only falsy string.
    return filter(None, map(sanitizeTag, rawTags))

# This function takes a single proto-tag---the string in between the commas
# that will be turned into a valid tag---and sanitizes it.  It either
# returns an alphanumeric string (if the argument can be made into a valid
# tag) or None (if the argument cannot be made into a valid tag; i.e., if
# the argument contains only whitespace and/or punctuation).
def sanitizeTag(str):
    # First, we turn non-alphanumeric characters into whitespace.  You could
    # also use a regular expression here; see below.
    str = ''.join(c if c.isalnum() else ' ' for c in str)

    # Next, we split the string on spaces, ignoring leading and trailing
    # whitespace.
    words = str.split()

    # There are now three possibilities: there are no words, there was one
    # word, or there were multiple words.
    numWords = len(words)
    if numWords == 0:
        # If there were no words, the string contained only spaces (and/or
        # punctuation).  This can't be made into a valid tag, so we return
        # None.
        return None
    elif numWords == 1:
        # If there was only one word, that word is the tag, no
        # post-processing required.
        return words[0]
    else:
        # Finally, if there were multiple words, we camel-case the string:
        # we lowercase the first word, capitalize the first letter of all
        # the other words and lowercase the rest, and finally stick all
        # these words together without spaces.
        return words[0].lower() + ''.join(w.capitalize() for w in words[1:])

rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code:
class A(object):
    def f(self):
        print("A.f()")

class B(A):
    def f(self):
        print("B.f()")

a = A()
a.f()
b = B()
b.f()

rawDescription: How can I decide to call an overrided method in child class from either parent or child class?

description: Decide to call an overrided method in child class from either parent or child class


rawDescription: Floating Point Equality Handling in Python


rawDescription: Python - fabric module missing all of a sudden


code:
from itertools import permutations
airports = ["airport1", "airport2", "airport3", "airport4", "airport5"]
[airports[:1] + list(x) + airports[-1:] for x in permutations(airports[1:-1])]

rawDescription: How to append the first item of list to the end of all permutations of that list?

description: Append the first item of list to the end of all permutations of that list


code:
from module_where_logger_is_defined import Logger

class MyCustomClass(object):

    def __init__(self):
        self.logger = Logger(self.__class__.__name__).get()   # accessing the "private" variables for each class

    def do_something():
        ...
        self.logger.info('Hello')

    def raise_error():
        ...
        self.logger.error('some error message')

rawDescription: How to configure Logging in Python

description: Configure Logging in Python


code:
import unicodedata
output = unicodedata.normalize('NFD', my_unicode).encode('ascii', 'ignore')

rawDescription: How to convert unicode accented characters to pure ascii without accents?

description: Convert unicode accented characters to pure ascii without accents


rawDescription: Partial matching GAE search API

description: Partial matching GAE search API


code:
trial = Trial.objects.get(id=give-trial-id)
user = User.objects.get(id=give-assessor-id)
trail.assessors.add(user)

rawDescription: Django: Including standard User table as foreign key in my models?


code:
from datetime import datetime

d = datetime.now()
d.strftime('%m/%d/%Y %H:%M:%S')
Out[7]: '11/06/2013 18:59:38'

rawDescription: Python - how to convert ctime to '%m/%d/%Y %H:%M:%S'


code:
import lxml.etree as ET

xml = '''\
<root>
    <keyword_group>
        <headword>sell/buy</headword>
    </keyword_group>
</root>
'''

root = ET.fromstring(xml)
headword = root.find('.//headword')
if headword is not None:
    words = headword.text.split('/')
    parent = headword.getparent()
    parent.remove(headword)
    for word in words:
        ET.SubElement(parent, 'word').text = word

print(ET.tostring(root, encoding='unicode'))

rawDescription: I want to split text of a node and then put each of them into independent element


rawDescription: Python regex -- extraneous matchings

description: Python regex -- extraneous matchings


code:
from flask import Flask

app = Flask(__name__)
app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379',
    CELERY_RESULT_BACKEND='redis://localhost:6379'
)
celery = make_celery(app)

@celery.task()
def add_together(a, b):
    return a + b

rawDescription: How do I run a long-running job in the background in Python

description: Run a long-running job in the background in Python


code:
def transform_line(line):
    if line != "":
        if line[0].isdigit():
            print("O")
        elif line[0] in {"+", "-"}:
            print("U")
    else:
        print("None")
    return line

with open("./testStage1.txt", 'r') as osrc:
    osrc.seek(291)
    lines = [transform_line(line) for line in osrc]
    #Do whatever you need with your line list

rawDescription: readline function returning empty string

description: Readline function returning empty string


code:
for line in file:
    output.write(line) # save as is
    while 'SAMPLE' in line or 'RUNS' in line:
       line = next(file, "") # move to the next line
       output.write(line.replace('AB', 'XX')) # save replacing AB with XX

rawDescription: Search and replace string under specific line


rawDescription: How to set a range of values in numpy to nan?

description: Set a range of values in numpy to nan