code:
import re

runIdRegex = re.compile(r'AA (\d+)')

def processFile(fileHandle):
    lastNumber = None  # Last run number, necessary so we know if there's been a gap or if we're in a new block of ten.
    line = fileHandle.next()
    while line is not None:  # None is being used as a special value indicating we've hit the end of the file.
        processData = False
        match = runIdRegex.match(line)
        if match:
            runNumber = int(match.group(1))
            if lastNumber == None:
                # Startup/first iteration
                processData = True
            elif runNumber - lastNumber == 1:
                # Continuation, see if the tenths are the same.
                lastNumberTens = lastNumber / 10
                runNumberTens = runNumber / 10
                if lastNumberTens != runNumberTens:
                    processData = True
            else:
                processData = True

            # Always remember where we were.
            lastNumber = runNumber

            # And grab and process data.
            line = dataBlock(fileHandle, process=processData)
        else:
            try:
                line = fileHandle.next()
            except StopIteration:
                line = None

def dataBlock(fileHandle, process=False):
    runData = []
    try:
        line = fileHandle.next()
        match = runIdRegex.match(line)
        while not match:
            runData.append(line)
            line = fileHandle.next()
            match = runIdRegex.match(line)
    except StopIteration:
        # Hit end of file
        line = None

    if process:
        # Data processing call here
        # processData(runData)
        pass

    # Return line so we don't lose it!
    return line

rawDescription: Python perform actions only at certain locations in text file


rawDescription: python check if one before last digit is odd

description: Python check if one before last digit is odd


rawDescription: Plotting datetime output using matplotlib


code: pixel_string = ','.join([str(x) for x in pixel_list])

rawDescription: Python: Serial Transmission

description: Python: Serial Transmission


rawDescription: how to sort a scipy array with order attribute when it does not have the field names?

description: Sort a scipy array with order attribute when it does not have the field names


code:
import datetime
import pandas as pd

iterables = [['bar', 'baz', 'foo', 'qux'], pd.Index([datetime.date(2014, 10, 3)])]
columns = pd.MultiIndex.from_product(iterables)
df = pd.DataFrame(np.random.randn(4, 4),columns=columns)
print(df.columns[0])

rawDescription: How can I keep this Pandas column type as datetime when using MultiIndex?

description: Keep this Pandas column type as datetime when using MultiIndex


code:
from scrapy.item import Item, Field

class CraigItem(Item):
    title = Field()
    link = Field()

rawDescription: Extract text from an extracted new page from main page


code:
def close(self):
        """close the whole package /module, it's time to make reports !

        if persistent run, pickle results for later comparison
        """
        if self.file_state.base_name is not None:
            # load previous results if any
            previous_stats = config.load_results(self.file_state.base_name)
            # XXX code below needs refactoring to be more reporter agnostic
            self.reporter.on_close(self.stats, previous_stats)
            if self.config.reports:
                sect = self.make_reports(self.stats, previous_stats)
                if self.config.files_output:
                    filename = 'pylint_global.' + self.reporter.extension
                    self.reporter.set_output(open(filename, 'w'))
            else:
                sect = Section()
            if self.config.reports or self.config.output_format == 'html':
                self.reporter.display_results(sect)
            # save results if persistent run
            if self.config.persistent:
                config.save_results(self.stats, self.file_state.base_name)
        else:
            self.reporter.on_close(self.stats, {})

rawDescription: How does pylint remember scores from previous runs?


code:
def divby10(x): return x//10

distribution = []
for k, g in it.groupby(data, key=divby10):
    L = len(list(g))
    if L < 3: continue
    distribution.append(k+1)

rawDescription: Python: create a distribution from a list based on number of items that fall within certain ranges


code: df

rawDescription: In python/pandas how to search for nearest value?


code: value = integrate(lambda x: 2 * x + 3, 1, 2)

rawDescription: Python: How to integrate a math function using only math module?


code:
def __del__(self):
    for f in self.destroyCallback:
        f.destroyedObjectListener(self)

rawDescription: using python WeakSet to enable a callback functionality

description: Using python WeakSet to enable a callback functionality


code:
DDL(
    "CREATE UNIQUE INDEX doc_year_num_uniq ON %(fullname)s "
    "(EXTRACT(YEAR FROM date), number)"
).execute_at('after-create', Document.__table__)

rawDescription: Compound UniqueConstraint with a function


code:
index = np.array([0,1])
index1, index2 = np.ix_(index, index)
index1
index2
a[index1, index2]
a[np.ix_(index, index)]

rawDescription: puzzled on how to slice a numpy array

description: Puzzled on how to slice a numpy array


code:
def my_precision(x, n):
    return '{:.{}f}'.format(x, n)

rawDescription: How can I format a float to variable precision in Python?

description: Format a float to variable precision in Python


code: ' '.join('_'.join(pieces[i:i+2]) for i in xrange(0, len(pieces), 2))

rawDescription: Python replace every odd occurrence of space with "_"


code:
def update(self):
    self.tmr.stop()#Prevent the timer from entering again.
    line = self.raw.read()
    ardString = map(ord, line)
    for number in ardString:
        numb = float(number/77.57)
        self.cnt += 1
        x = self.cnt/20

        self.xValues.append(x)
        self.yValues.append(numb)
        #self.data.append({'x': x , 'y': numb})
    #x = [item['x'] for item in self.data]
    #y = [item['y'] for item in self.data]
    self.curve.setData(x=x, y=y)
    self.tmr.start()#restart the timer (resets the timeout)

rawDescription: Live plot using PyQtGraph is drawing even with the device disconnected


code:
v0, v1, v2 = (points[triangles[:,i]] for i in range(3))
areas = np.linalg.norm(np.cross(v1 - v0, v2 - v0), axis=1) / 2
areas

rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


code:
@app.route('/register', methods=['PUT'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    if username is None or password is None:
        abort(400)  # missing parameters

    user = User.query.filter_by(username=username).first()
    if user:
        abort(400)  # user exists
    else:
        user = User(user=user)
        user.hash_password(password)
        db.session.add(user)
        db.session.commit()

        # How do we generate a token?
        redirect("login_success", code=307)

@app.route("login_success", methods=["GET", "POST"])
@jwt_required()
def login_success():
    return "Redirected Success!"

rawDescription: Internal Redirect in Flask

description: Internal Redirect in Flask


rawDescription: Check whether each row of a matrix is in another matrix [Python]


code:
parser = argparse.ArgumentParser()
sub_parser = parser.add_subparsers(dest='cmd')
parser_a = sub_parser.add_parser('a')
parser_a.add_argument("a", choices = ["1", "2"])
parser_b = sub_parser.add_parser('b')
parser_c = sub_parser.add_parser('c')
args = parser.parse_args()

rawDescription: How to parse optional arguments using python argparse?

description: Parse optional arguments using python argparse


code:
from ctypes import *
class POINT(Structure):
    _fields_ = [("x", c_int),
                ("y", c_int)]

point = POINT(10, 20)
...
my_library.my_c_function(POINTER(point))

rawDescription: Passing a Python Object to C module

description: Passing a Python Object to C module


code: range_str = ",".join(["%s-%s" % item for item in zipped])

rawDescription: Adding parts of a line to make a sequence line (python)


code:
COLORS = {
    'blue': 'Boys love this.',
    'pink': 'You must be a lady.',
    'red': 'You are hot!',
    }

def color():
    print('You found the color here.')
    while True:
        answer = input('What is your favorite color? ').lower()
        if answer in COLORS:
            print(COLORS[answer])
            return
        else:
            print('I don\'t know such a color.')

def food():
    print('Don\'t eat so much!')

rawDescription: How to iterate through modules with user input?

description: Iterate through modules with user input


code:
def save_last(iterable):
        for i in iterable:
            yield i
        replace.last_index = i[0] #Save the last value
it = save_last(it)

rawDescription: Generator which leaves a placeholder at the beginning and at the end of the input iterator intact


code:
xmlstr = """
<?xml version="1.0"?>
<aws:UrlInfoResponse xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/">
  <aws:Response xmlns:aws="http://awis.amazonaws.com/doc/2005-07-11">
    <aws:OperationRequest>
      <aws:RequestId>ccf3f263-ab76-ab63-db99-244666044e85</aws:RequestId>
    </aws:OperationRequest>
    <aws:UrlInfoResult>
      <aws:Alexa>
        <aws:ContentData>
          <aws:DataUrl type="canonical">google.com/</aws:DataUrl>
          <aws:SiteData>
            <aws:Title>Google</aws:Title>
            <aws:Description>Enables users to search the world's information, including webpages, images, and videos. Offers unique features and search technology.</aws:Description>
            <aws:OnlineSince>15-Sep-1997</aws:OnlineSince>
          </aws:SiteData>
          <aws:LinksInCount>3453627</aws:LinksInCount>
        </aws:ContentData>
        <aws:TrafficData>
          <aws:DataUrl type="canonical">google.com/</aws:DataUrl>
          <aws:Rank>1</aws:Rank>
        </aws:TrafficData>
      </aws:Alexa>
    </aws:UrlInfoResult>
    <aws:ResponseStatus xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/">
      <aws:StatusCode>Success</aws:StatusCode>
    </aws:ResponseStatus>
  </aws:Response>
</aws:UrlInfoResponse>
"""

rawDescription: python alexa result parsing with lxml.etree

description: Python alexa result parsing with lxml.etree


code:
base = ShowBase()
mySound = base.loader.loadSfx("path/to/the_tone.wav")

rawDescription: How to keep playing a sound at a given frequency and volume in Python?

description: Keep playing a sound at a given frequency and volume in Python


code:
class B(object):
    A = A()

rawDescription: callable object as method of a class - Can I get `self` to be the class that owns the method?

description: Callable object as method of a class - Can I get `self` to be the class that owns the method


code: count = lambda x: methodcaller('count', x) # from operator import methodcaller

rawDescription: How to sort list of strings by count of a certain character?

description: Sort list of strings by count of a certain character


code:
import copy

tmp = {}
for med in copy.deepcopy(meds):
    ...

rawDescription: Merging a list of dicts in python based on common element


code:
s = set([1, 2])
fs = frozenset(s)
adict = {}
adict[s] = 42   # a set as key does not work
adict[fs] = 42  # a frozenset as key works
s.add(s)        # a set as value in a set does not work
s.add(fs)       # a frozenset as value in a set works

rawDescription: frozenset() - Example of when one might use them

description: Frozenset() - Example of when one might use them


code:
for key, values in original.items():
    target.update(zip(values, [key] * len(values)))

rawDescription: What is the pythonic way to reverse a defaultdict(list)?


code:
#user class
class myclass:
    def __getitem__(self,keys):
        keys = keys.split(',')
        return tuple(getattr(self, attr) for attr in keys)

    def __setitem__(self,keys,values):
        keys = keys.split(',')
        if len(keys) != len(values):
            raise ValueError('too many values to unpack (expected %d)'%len(keys))
        for attr,val in zip(keys, values):
            setattr(self, attr, val)
    def __delitem__(self,keys):
        keys = keys.split(',')
        for attr in keys:
            delattr(self, attr)

rawDescription: A member tuple (as opposed to member variable) of a class?


code:
from collections import namedtuple
from pprint import pprint
df = pd.DataFrame({1: [1,2,3], 2:[3,4,5]})
df['index'] = df.index
df
dfr = namedtuple('row', map(lambda x: 'col_' + str(x), df.columns))
res = tuple(map(lambda x: dfr(*x), df.values))
pprint(res)

rawDescription: Memoize a costly computation of a data frame


code:
foo = re.compile(r'^(\(.*?\)) (.*)$')
result = foo.match(s1)
result.group(1) + ', ' + result.group(2)

rawDescription: Python re.compile, split string into two while preserving delimiter


code:
celery_app.send_task('tasks.test1', args=[self.id], kwargs={}, queue='queue1')
celery_app.send_task('tasks.test2', args=[self.id], kwargs={}, queue='queue2')

rawDescription: Executing two tasks at the same time with Celery


code: json.dumps({'success': True, 'data': [dict(d, Week='1238') for d in celldict.values()]})

rawDescription: format python output to json

description: Format python output to json


code:
#!/usr/bin/env python

def printAndReturnNothing():
    x = "hello"
    print(x)

def printAndReturn():
    x = "hello"
    print(x)
    return x

def main():
    ret = printAndReturn()
    other = printAndReturnNothing()

    print("ret is: %s" % ret)
    print("other is: %s" % other)

if __name__ == "__main__":
    main()

rawDescription: Python: What is the Formal Difference Between Print and Return?


code:
def compare(s, t):
    return sorted(s) == sorted(t)

rawDescription: How to efficiently compare two unordered lists (not sets) in Python?

description: Efficiently compare two unordered lists (not sets) in Python


rawDescription: $unwind with group and count

description: $unwind with group and count


code:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Change the table name from the old model name to the new model name
        # ADD THIS LINE (using the correct table names)
        db.rename_table('usergroups_myuser_group', 'usergroups_myusergroup')

    def backwards(self, orm):
        # Provide a way to do the migration backwards by renaming the other way
        # ADD THIS LINE (using the correct table names)
        db.rename_table('usergroups_myusergroup', 'usergroups_myuser_group')

    models = {
        'usergroups.myusergroup': {
            'Meta': {'object_name': 'MyUserGroup'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        }
    }

    complete_apps = ['usergroups']

rawDescription: Renaming a django model class-name and corresponding foreign keys with south, without loosing the data


rawDescription: Deterministic and non uniform long string generation from seed


code:
from itertools import islice

first, second = islice(zip(*list_values), 2)

rawDescription: multiple assignments in one line for loop python

description: Multiple assignments in one line for loop python


rawDescription: How to optimize a python script which runs for 4**k times?

description: Optimize a python script which runs for 4**k times


code:
from ctypes import *
ll = CDLL("./libdll.so")

# user defined types
class ll_Info(Structure): pass
class ll_DLL_Boolean(Structure): pass
class ll_DLL_SrchOrigin(Structure): pass
class sys_select_fd_set(Structure): pass
class ll_List(Structure): pass
class sys_time_timeval(Structure): pass
class ll_DLL_SrchDir(Structure): pass
class ll_DLL_Return(Structure): pass
class ll_DLL_SearchModes(Structure): pass
class ll_DLL_InsertDir(Structure): pass

# functions
ll.DLL_CreateList.restype = POINTER(ll_List)
ll.DLL_CreateList.argtypes = (POINTER(POINTER(ll_List)),)
ll.DLL_DestroyList.restype = None
ll.DLL_DestroyList.argtypes = (POINTER(POINTER(ll_List)),)
ll.DLL_Version.restype = c_char_p
ll.DLL_Version.argtypes = ()
ll.DLL_IsListEmpty.restype = ll_DLL_Boolean
ll.DLL_IsListEmpty.argtypes = (POINTER(ll_List),)
ll.DLL_IsListFull.restype = ll_DLL_Boolean
ll.DLL_IsListFull.argtypes = (POINTER(ll_List),)
ll.DLL_CurrentPointerToHead.restype = ll_DLL_Return
ll.DLL_CurrentPointerToHead.argtypes = (POINTER(ll_List),)
ll.DLL_CurrentPointerToTail.restype = ll_DLL_Return
ll.DLL_CurrentPointerToTail.argtypes = (POINTER(ll_List),)
ll.DLL_DecrementCurrentPointer.restype = ll_DLL_Return
ll.DLL_DecrementCurrentPointer.argtypes = (POINTER(ll_List),)
ll.DLL_DeleteCurrentRecord.restype = ll_DLL_Return
ll.DLL_DeleteCurrentRecord.argtypes = (POINTER(ll_List),)
ll.DLL_DeleteEntireList.restype = ll_DLL_Return
ll.DLL_DeleteEntireList.argtypes = (POINTER(ll_List),)
ll.DLL_FindNthRecord.restype = ll_DLL_Return
ll.DLL_FindNthRecord.argtypes = (POINTER(ll_List),POINTER(ll_Info),c_ulong,)
ll.DLL_GetCurrentRecord.restype = ll_DLL_Return
ll.DLL_GetCurrentRecord.argtypes = (POINTER(ll_List),POINTER(ll_Info),)
ll.DLL_GetNextRecord.restype = ll_DLL_Return
ll.DLL_GetNextRecord.argtypes = (POINTER(ll_List),POINTER(ll_Info),)
ll.DLL_GetPriorRecord.restype = ll_DLL_Return
ll.DLL_GetPriorRecord.argtypes = (POINTER(ll_List),POINTER(ll_Info),)
ll.DLL_InitializeList.restype = ll_DLL_Return
ll.DLL_InitializeList.argtypes = (POINTER(ll_List),c_size_t,)
ll.DLL_IncrementCurrentPointer.restype = ll_DLL_Return
ll.DLL_IncrementCurrentPointer.argtypes = (POINTER(ll_List),)
ll.DLL_InsertRecord.restype = ll_DLL_Return
ll.DLL_InsertRecord.argtypes = (POINTER(ll_List),POINTER(ll_Info),ll_DLL_InsertDir,)
ll.DLL_RestoreCurrentPointer.restype = ll_DLL_Return
ll.DLL_RestoreCurrentPointer.argtypes = (POINTER(ll_List),)
ll.DLL_SaveList.restype = ll_DLL_Return
ll.DLL_SaveList.argtypes = (POINTER(ll_List),c_char_p,)
ll.DLL_SetSearchModes.restype = ll_DLL_Return
ll.DLL_SetSearchModes.argtypes = (POINTER(ll_List),ll_DLL_SrchOrigin,ll_DLL_SrchDir,)
ll.DLL_StoreCurrentPointer.restype = ll_DLL_Return
ll.DLL_StoreCurrentPointer.argtypes = (POINTER(ll_List),)
ll.DLL_SwapRecord.restype = ll_DLL_Return
ll.DLL_SwapRecord.argtypes = (POINTER(ll_List),ll_DLL_InsertDir,)
ll.DLL_UpdateCurrentRecord.restype = ll_DLL_Return
ll.DLL_UpdateCurrentRecord.argtypes = (POINTER(ll_List),POINTER(ll_Info),)
ll.DLL_GetSearchModes.restype = POINTER(ll_DLL_SearchModes)
ll.DLL_GetSearchModes.argtypes = (POINTER(ll_List),POINTER(ll_DLL_SearchModes),)
ll.DLL_GetCurrentIndex.restype = c_ulong
ll.DLL_GetCurrentIndex.argtypes = (POINTER(ll_List),)
ll.DLL_GetNumberOfRecords.restype = c_ulong
ll.DLL_GetNumberOfRecords.argtypes = (POINTER(ll_List),)

rawDescription: Python ctypes pointer to pointer to structure


code:
means = np.arange(10)

samples = np.random.normal(means, 1)

rawDescription: Python: NxM array of samples drawn from NxM normal distributions


code:
for line in sp.stdout:
    do_stuff_with(line)

rawDescription: How to store multiple stdout results in a variable?

description: Store multiple stdout results in a variable


code:
df = pd.DataFrame(data)
df['OrigDate'] = df.index.format()
df

rawDescription: pandas's resample with fill_method: Need to know data from which row was copied?

description: Pandas's resample with fill_method: Need to know data from which row was copied


code:
try:
    aa = foo()
except Exception:
    aa = None

if aa is None:
    try:
        aa = bar()
    except Exception:
        aa = 0

rawDescription: Best way to write "try elsetry" in python?

description: Write "try elsetry" in python


code: pp.pprint([elem['error'] for elem in ast.literal_eval(data)['results'] if 'error' in elem])

rawDescription: How to convert python string data to list or in dict?

description: Convert python string data to list or in dict


code:
class MyTestCase(ElementRemovingTestCase):
    def tearDown(self):
        super(MyTestCase, self).tearDown()
        print('Tearing down {}'.format(self))

rawDescription: Calling a function after or before tearDown of each unit testcase


code:
print("You entered ", imp_height_flt, "\" which converts into "
      "%.2f" % imp_height_converted, "m.",
      sep='')

rawDescription: How to eliminate white space after backslash (Python 3.4)

description: Eliminate white space after backslash (Python 3.4)


rawDescription: Python 3 Print Variables

description: Python 3 Print Variables


rawDescription: Optimize runtime of calling 'in' many times on same string


code: file.write("""a=input("What would you like?\\n")""")

rawDescription: How can I write to a file but keep \n as it is rather than adding a new line in python?

description: Write to a file but keep \n as it is rather than adding a new line in python


code:
def getData(rawDataPath):
    path = rawDataPath
    allfiles = glob.glob(os.path.join(path, "*.csv"))
    dataframes = (pd.read_csv(fname, header=None, names=['date', fname])
                  for fname in allfiles)
    return reduce(partial(pd.merge, on='date', how='outer'), dataframes)

rawDescription: trying to read multiple .csv into separate data-frame columns

description: Trying to read multiple .csv into separate data-frame columns


code:
def numberList(items):
     number = 1
     for item in items:
         yield str((number, item))
         number = number + 1

item_lines = '\n'.join(numberList(['red', 'orange', 'yellow', 'green']))

rawDescription: Python: Return list result problem in a function


code:
[inst for inst in instances
      if all(get_key_value(inst, pkey) == kw[pkey] for pkey in primary_keys)]

rawDescription: Find object in a list with multiple primary keys in Python


code:
parent = node()
child = node()
parent.farmer = True
parent.copy(child)

rawDescription: Python: Parent and Child responding to child-specific changes in boolean values. Why is this happening?


code:
from kivy.config import Config
Config.set('graphics', 'fullscreen', 'auto')

rawDescription: How do I turn off fullscreen in Kivy?

description: Turn off fullscreen in Kivy


code:
from module import address_dict
print(address_dict)

rawDescription: Can I make a dictionary available to multiple python scripts?

description: Make a dictionary available to multiple python scripts


code:
def importlines():
    with open('C:/scripts/nagios/filename.txt') as mf:
        return [l.split()[0] for l in mf]

rawDescription: Importing file data to a list from a function


code:
import pandas as pd
import random
import matplotlib.pylab as plt

x = [random.randint(10,20) for r in range(100)]
y = [random.randint(0,10) for r in range(100)]

df = pd.DataFrame([x,y]).T

plt.plot(df)

plt.legend(['a','b'],loc='upper left')

plt.show()

rawDescription: Use dataframe column names as labels in pylab.plot


code:
new = {}
for key, value in dic.items():
    if '_' not in key:
        new[key] = value
        continue

    for new_key, new_value in zip(key.split('_'), value):
        new[new_key] = new_value.split('_')

rawDescription: split a key in a dic and its values to multiple keys/values

description: Split a key in a dic and its values to multiple keys/values


rawDescription: How can I locate a onmouseover element using Selenium in Python?

description: Locate a onmouseover element using Selenium in Python


code: df2 = df2.set_index('date2')

rawDescription: Joining dataframes with different datetime frequencies


code:
df["dummy"] = 1
dm = df.pivot("author", "paper").fillna(0)
dout = dm.dot(dm.T)
dout

rawDescription: Transform dataframe to get co-author relationships


code:
class Son:
    father = models.ForeignKey(Father)

rawDescription: Relation 1 to N in Django

description: Relation 1 to N in Django


code:
c = SGDClassifier(loss="log", alpha=1)
c.fit(X, y)
c.predict_proba(X)

rawDescription: How to get SGDClassifier to reflect uncertainty

description: Get SGDClassifier to reflect uncertainty


code:
def safe_range(a, b):
    return range(0, max(a,b), min(a,b))

safe_range(3, 10)   # => (0, 3, 6, 9)

rawDescription: Python : what would be the ouput of range(x,y) if x>y


code:
# getting data
#...
from bs4 import BeautifulSoup
from collections import namedtuple
soup = BeautifulSoup(data)
# thats where the data are collected
rows = list()
# named tuple to store the relevant data of one player
Player = namedtuple('Player', ['name', 'team', 'goals', 'assists', 'points'])
# getting every row of the tbody in the specified table
for tr in soup.select('table.data.stats tbody tr'):
    # put text-contents of the row in a list
    cellStrings = [cell.find(text = True) for cell in tr.findAll('td')]
    # add it to the
    rows.append(
        Player(
            name=cellStrings[1],
            team=cellStrings[2],
            goals=cellStrings[5],
            assists=cellStrings[6],
            points=cellStrings[7]
        )
    )

rawDescription: Beautiful Soup Extracting Data After href (not url)


code:
def some_view():
    # some action
    return redirect(redirect_url())

rawDescription: Redirect back in Flask

description: Redirect back in Flask


code: f = lambda a, k: np.fliplr(np.triu(np.fliplr(a), k=k-a.shape[0]+1))

rawDescription: Zero out matrix higher diagonal using numpy


rawDescription: sorting elements out of the list

description: Sorting elements out of the list


code:
import sys
from queue import Queue, Empty
from PySide import QtCore, QtGui

class LogReceiver(QtCore.QObject):
    mysignal = QtCore.Signal(str)

    def __init__(self, queue, *args, **kwargs):
        QtCore.QObject.__init__(self, *args, **kwargs)
        self.queue = queue

    def run(self):
        self.active = True
        while self.active:
            try:
                text = self.queue.get(timeout=1.0)
                self.mysignal.emit('text')
            except Empty:
                continue
        print('finished')

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.queue = Queue()
        self.thread = QtCore.QThread(self)
        self.receiver = LogReceiver(self.queue)
        self.receiver.moveToThread(self.thread)
        self.thread.started.connect(self.receiver.run)
        self.thread.start()

    def closeEvent(self, event):
        print('close')
        self.receiver.active = False
        self.thread.quit()
        self.thread.wait()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

rawDescription: 'QThread: Destroyed while thread is still running' on quit


code:
from my_package.web_api import app
from cherrypy.wsgiserver import CherryPyWSGIServer

server = CherryPyWSGIServer(
    ('0.0.0.0', 80),
    app,
    server_name='My_App',
    numthreads=30)

try:
    server.start()
except KeyboardInterrupt:
    server.stop()

rawDescription: How to launch a Bottle application over a CherryPy standalone web server?

description: Launch a Bottle application over a CherryPy standalone web server


code:
sqrt((x - y).T.dot(x - y))
sqrt((x - y).dot((x - y).T))

rawDescription: What actually happens when broadcasting a NumPy array


code:
# -*- coding: utf-8 -*-
from webob import multidict

def from_fieldstorage(cls, fs):
    """Create a dict from a cgi.FieldStorage instance.
    See this for more details:
    http://code.google.com/p/googleappengine/issues/detail?id=2749
    """
    import base64
    import quopri

    obj = cls()
    if fs.list:
        # fs.list can be None when there's nothing to parse
        for field in fs.list:
            if field.filename:
                obj.add(field.name, field)
            else:
                # first, set a common charset to utf-8.
                common_charset = 'utf-8'
                # second, check Content-Transfer-Encoding and decode
                # the value appropriately
                field_value = field.value
                transfer_encoding = field.headers.get('Content-Transfer-Encoding', None)
                if transfer_encoding == 'base64':
                    field_value = base64.b64decode(field_value)
                if transfer_encoding == 'quoted-printable':
                    field_value = quopri.decodestring(field_value)
                if field.type_options.has_key('charset') and field.type_options['charset'] != common_charset:
                    # decode with a charset specified in each
                    # multipart, and then encode it again with a
                    # charset specified in top level FieldStorage
                    field_value = field_value.decode(field.type_options['charset']).encode(common_charset)
                    # TODO: Should we take care of field.name here?
                    obj.add(field.name, field_value)
    return obj

multidict.MultiDict.from_fieldstorage = classmethod(from_fieldstorage)

rawDescription: google app engine + python: uploading to blobstore causes wrong encoding

description: Google app engine + python: uploading to blobstore causes wrong encoding


code:
# use new locatedExpr to get the value, start, and end location
# for each value
linedefn = OneOrMore(locatedExpr(value))('values')

rawDescription: pyparsing whitespace match issues

description: Pyparsing whitespace match issues


code:
products = db.session.query(
    Product,
    # Product.diff_orders,
    # Product.diff_requests,
    # Product.qty_stock + Product.diff_requests - Product.diff_orders,
).order_by((Product.qty_stock + Product.diff_requests - Product.diff_orders).desc())
for x in products:
    print(x)

rawDescription: Order by issue when outer joining two tables in sqlalchemy


code:
g = globals()
for i in range(n + 1):
  g['model_' + str(i)] = ConcreteModel()

rawDescription: Defining multiple models in Pyomo/AMPL

description: Defining multiple models in Pyomo/AMPL


code:
plt.plot(x, [i for (i,j) in y], 'ro')
plt.plot(x, [j for (i,j) in y], 'bo')

rawDescription: Matplotlib scatter plot with 2 y-points per x-point


code:
some_user_type = UserType.objects.get(user_id=some_user_pk)
like_count = some_user_type.userlike_set.all().count()

rawDescription: Django, getting related objects in a loop of objects


code:
import timeit
a_tuple = (1,0)
def ft_bool():
    if a_tuple:
        pass

def ft_len_gt():
    if len(a_tuple) > 0:
        pass

def ft_len_ne():
    if len(a_tuple) != 0:
        pass

timeit.timeit('ft()', 'from __main__ import ft_bool as ft')
timeit.timeit('ft()', 'from __main__ import ft_len_gt as ft')
timeit.timeit('ft()', 'from __main__ import ft_len_ne as ft')

rawDescription: "Non-equal" or "greater than" is quicker?


code: features['contains(%s)' % word] = (word in document_words)

rawDescription: Naive Bayes Classifier error

description: Naive Bayes Classifier error


code:
def get_first(line):
    return line.split(None, 1)[0]
def readline():
    with open("a.txt",'r') as file, open("b.txt",'r') as file2:
        string = set(map(get_first,file2))
        for line in file:
            if line.strip() in string:
                print(line.rstrip())
            else:              ##if spl not in string print new line
                print()
readline()

rawDescription: Compare lines in two .txt files, print out new line for not contained words


code:
def isHappy(n):
    stop = {1}
    while n not in stop:
        stop.add(n)
        n = sum(int(d)**2 for d in str(n))
    return n == 1

rawDescription: Why doesn't this code work (Leetcode in Python)?


rawDescription: Find numbers in Python list which are within a certain distance of each other


code:
def decimalToBase3(num):
   if 0 <= num < 3: return num
   result = ""
   while num:
       num, digit = divmod(num, 3)
       result = str(digit) + result
   return int(result)

rawDescription: Improve efficiency of modules

description: Improve efficiency of modules


rawDescription: gotchas where Numpy differs from straight python?

description: Gotchas where Numpy differs from straight python


code:
def numEven(num):
    return num%2==0

def moreThan100(num):
    return num>100

def adding30(num):
    return num+30

evens, bigs, plus30s = [], [], []
for num in numbers:
    if numEven(num):
        evens.append("%d is even." % num)
    if moreThan100(num):
        bigs.append("%d is greater than 100." % num)
    plus30 = adding30(num)
    plus30s.append("If you add 30 to %d, you get: %d" % (num,plus30))

print_list(*events)
print_list(*bigs)
print_list(*plus30s)

rawDescription: Python: Calling Functions Inside of a ForLoop


rawDescription: Python how to print separate counters from a loop/add them together?


code:
xfloor = math.floor(float(x))
zsqrt = math.sqrt(float(z))

rawDescription: turning variables that use 'str()' into numbers

description: Turning variables that use 'str()' into numbers


code:
#get rid of items with fewer than 2 occurrences.
corpus=corpus[corpus.groupby('label').label.transform(len)>1]

from sklearn.cross_validation import StratifiedShuffleSplit
sss=StratifiedShuffleSplit(corpus['label'].tolist(), 1, test_size=0.5, random_state=None)

train_index, test_index =list(*sss)
training_data=corpus.iloc[train_index]
test_data=corpus.iloc[test_index]

rawDescription: How to split Test and Train data such that there is garenteed at least one of each Class in each

description: Split Test and Train data such that there is garenteed at least one of each Class in each


code:
def getNGramBeginsWords(nGram, length):
    wlist = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
    nGram = nGram.upper()
    words = []
    length = int(length) # force to an int
    assert isinstance(n, int) # or do this if you prefer to get an exception on all invalid input
    for line in wlist:
        stripline = line.strip().upper() # you keep doing this
        # you can merge these two ifs
        if (len(stripline) == length) and stripline.endswith(nGram):
            words.append(stripline)
    return words

rawDescription: Passing in Global Variables in Python

description: Passing in Global Variables in Python


code:
for key,value in countries.iteritems():
    if some_strng in value:
        code_country.append([key,countries[key]])

rawDescription: need to iterate through dictionary to find slice of string

description: Need to iterate through dictionary to find slice of string


code: data = {k: filter(bool, v) for k, v in data.iteritems()}

rawDescription: How to remove empty entries from a list in a dictionary using python

description: Remove empty entries from a list in a dictionary using python


code:
a = np.zeros(5)
[a, a, a, a]

rawDescription: Initializing list of numpy arrays

description: Initializing list of numpy arrays


code:
def power_of_two(x):
    print(str(x))
    play_again(x)

def play_again(x):
    power_of_two(x+1)

power_of_two(1)

rawDescription: Is it acceptable to have two functions that run each endlessly?


code:
def func(mystr):
  a = []
  b = {'a':'b','c':'d','e':'f'}
  for i in mystr:
    if i in b:           # i in b works the same as i in b.keys()
      a.append(b[i])     # look up the key(i) in the dictionary(b) here
  return a

rawDescription: Working with python dictionaries

description: Working with python dictionaries


code:
# clear_models.py
from django.core.management.base import BaseCommand, CommandError
from django.db.models.loading import get_model

class Command(BaseCommand):
    help = 'Removes all records from specified models'

    def add_arguments(self, parser):
        parser.add_argument('model', nargs='+', type=str)

    def handle(self, *args, **options):
        models = []
        for model_string in options['model']:
            try:
                model = get_model(model_string)  # should be: app_name.model_name
            except:
                raise CommandError('Model "%s" does not exist' % model_string)
            else:
                models.append(model)
        for model in models:
            model.objects.all().delete()
        self.stdout.write('Successfully removed all records from %s' % options['model'])

rawDescription: Deleteing all rows for a django model from the command line while leaving the database intact


rawDescription: How to get the first and last second in python using datetime module

description: Get the first and last second in python using datetime module


rawDescription: Sort on the last octet of an IP address in a Python list


code:
class FakeDate(datetime.date):
     @classmethod
     def today(cls):
         return cls(1999, 12, 31)
     def __add__(self, other):
         res = super(FakeDate, self).__add__(other)
         return type(self)(res.year, res.month, res.day)

FakeDate.today() + datetime.timedelta(days=1)

rawDescription: How to mock the "+" operator in python (specifically datetime.date + datetime.timedelta)

description: Mock the "+" operator in python (specifically datetime.date + datetime.timedelta)


code:
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, glob
search_dir = r"e:\test"
files = filter(os.path.isfile, glob.glob(search_dir + "\\*.bas"))
file_date_tuple_list = []
for x in files:
    d = os.path.getmtime(x)
    #tuple with file and date, add it in a list
    file_date_tuple = (x,d)
    file_date_tuple_list.append(file_date_tuple)
#sort the tuple list by the second element which is the date
file_date_tuple_list.sort(key=lambda x: x[1])

rawDescription: How to make a chronological list of files, with the file modification date

description: Make a chronological list of files, with the file modification date


rawDescription: Python loop through list starting at index


code:
import fileinput,re

def  modify_file(file_name,pattern,value=""):
    fh=fileinput.input(file_name,inplace=True)
    for line in fh:
        replacement=value + line
        line=re.sub(pattern,replacement,line)
        sys.stdout.write(line)
    fh.close()

rawDescription: Find a string and insert text after it in Python


code:
found = False
buffer = '' # what is left from the previous run...
while not found:
    rd = ser.read(50)
    buffer += rd
    sp = buffer.split(chr(107), 1)
    if len(sp) == 2:
        pkt = chr(107) + sp[1] # candidate for a valid packet
        if pkt[1] == chr(105): #
            while len(pkt) < 107: # TODO add a timeout condition here...
                rd = ser.read(107 - len(pkt))
                pkt += rd
            found = True
        else:
            buffer = pkt[1:] # process this further...
    else: # no 107 found; empty the buffer.
        buffer = ''
# Now we have a pkt of 107 bytes and can do whatever we want with it.

rawDescription: How to find first byte of a serial stream with python?

description: Find first byte of a serial stream with python


code:
try:
    import xmlrpclib  # Python 2
except ImportError:
    import xmlrpc.client as xmlrpclib  # Python 3

pypi = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')

package_name = "Flask-Login"

packages = pypi.search({"name": package_name})
package = next(package for package in packages if package["name"] == package_name)
release_data = pypi.release_data(package_name, package["version"])

print(package_name)
print(package["version"])
print(release_data["summary"])
print(release_data["home_page"])

rawDescription: How can I get a list of package locations from a PIP requirements file?

description: Get a list of package locations from a PIP requirements file


rawDescription: In Django I have a complex query where I need only the unique values through a foreign key, is this possible?


code:
reader_iter = iter(reader)  # <-- using this in both loops
for line in reader_iter:
    all_decisions.append(map(int, line))
    if all_decisions[-1][4] != 1:
        for _, kline in zip(range(4), reader_iter): # zip stops after range(4). we only need kline
            all_decisions.append(kline)

rawDescription: Continue to read in file after if statement


code:
datetime.strptime(BS.font.contents[0].strip(), '%b %d')
datetime.datetime(1900, 7, 28, 0, 0)

rawDescription: Python string operation, extract text between html tags


code: my_list.sort(key=lambda x: x[-1])

rawDescription: pythonic way to sort a list of lists by the last item of the inner list

description: Pythonic way to sort a list of lists by the last item of the inner list


code:
for snap in snapshots:
    start_time = datetime.datetime.strptime(snap.start_time[:-5], '%Y-%m-%dT%H:%M:%S')
    if start_time > real_user_time:
        snap.delete()

rawDescription: Python script for EC2 snapshots, use datetime to delete old snapshots


code:
v=StringVar()
e=Entry(win,textvariable=v)
# the columnspan make the entry widget strech over more columns
e.grid(row=0, column=0, columnspan=4, sticky=W+E)

b1.grid(row=1,column=0, sticky=W+E)
b2.grid(row=1,column=1, sticky=W+E)
b3.grid(row=1,column=2, sticky=W+E)
b4.grid(row=2,column=0, sticky=W+E)
b5.grid(row=2,column=1, sticky=W+E)
b6.grid(row=2,column=2, sticky=W+E)
b7.grid(row=3,column=0, sticky=W+E)
b8.grid(row=3,column=1, sticky=W+E)
b9.grid(row=3,column=2, sticky=W+E)

rawDescription: Creating a calculator in TkInter, text field displacing buttons


code:
from selenium.webdriver.support import expected_conditions as EC
wait_text = 'file=http://'
element = WebDriverWait(driver, 10).until(
        EC.text_to_be_present_in_element((By.ID, "myDynamicElement"), wait_text)
    )

rawDescription: Scraping the mp3 file from flash player after the conversion


code: allprocs = [mkproc(f) for f in (foo, bar, baz)]

rawDescription: python multiprocessing dynamically created processes and pipes

description: Python multiprocessing dynamically created processes and pipes


code:
def transform(li):
    for i in xrange(len(li)):
        if li[i][0].endswith('ing') and i > 0 and li[i-1][1]:
            li[i] = (li[i], 'VBG')

rawDescription: lookbehind in a for loop

description: Lookbehind in a for loop


code:
@ndb.tasklet
def callback(entity):
  email = friend_dic['email']
  lastUpdated = friend_dic['lastUpdated']
  userKey = Key('User', email)
  query = ndb.gql('SELECT * FROM StatusUpdates WHERE ANCESTOR IS :1 AND modifiedDate > :2', userKey, lastUpdated)
  status_updates = yield query.fetch_async()
  raise ndb.Return(status_updates)

qry = ndb.gql("SELECT * FROM Relationships WHERE friend_to = :1", user.key)
updates = yield qry.map_async(callback)
#updates will now be a list of status updates

rawDescription: Efficient way to query in a for loop in Google App Engine?


rawDescription: Left outer Join Pandas Data Frame using contains


code:
from django.conf.urls.defaults import patterns
urlpatterns = patterns ('',
    (r'^/', 'myapp.urls'),
)

rawDescription: How do I successfully pass a function reference to Django’s reverse() function?

description: Successfully pass a function reference to Django’s reverse() function


rawDescription: Can I trust the order of a dict to remain the same each time it is iterated over?

description: Trust the order of a dict to remain the same each time it is iterated over


code:
from scipy.sparse import coo_matrix

N = a.size
L = a.max()
data = np.ones(N,dtype=int)
sparse_out = coo_matrix((data,(np.arange(N),a.ravel()-1)), shape=(N,L))

rawDescription: Convert a 2d matrix to a 3d one hot matrix numpy


code:
class CourseAdmin(admin.ModelAdmin):
    model = Course
    inlines = (GradeInline,)

rawDescription: Is it possible to filter choices on a foreign key in Django Admin panel?


code:
#!/usr/bin/env python
from plumbum import local

script1, script2 = local["/script1.pl"], local["/script2.pl"]
(script1 < "input_file" | script2 > "output_file")()

rawDescription: Using POpen to send a variable to Stdin and to send Stdout to a variable


code:
from settings import settings as PROJECT_DEFAULT

PREPEND_WWW = False
DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_pyscopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'somesecretname',                      # Or path to database file if using sqlite3.
        'USER': 'somesecretuser',                      # Not used with sqlite3.
        'PASSWORD': 'somesecretpassword',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

INSTALLED_APPS += PROJECT_DEFAULT.INSTALLED_APPS + ('debug_toolbar',)

rawDescription: How do I access imported local settings without a circular import?

description: Access imported local settings without a circular import


code:
for ax in all_axes:
    ax.scatter([4.6], [20])

rawDescription: Add the same point to all subplots

description: Add the same point to all subplots


code:
import subprocess
p = subprocess.Popen(["/usr/bin/passwd", username])

rawDescription: Safe way to execute commands on linux server when part of command is from a user input


code:
# file test_sub_class.py:
from unittest import TestCase
from mock import Mock

import sub_class
import base_class
MODULE_MOCK = Mock()
sub_class.module_to_patch = MODULE_MOCK
base_class.module_to_patch = MODULE_MOCK

class TestSubClass(TestCase):

    def test_sub_class_init(self):
        self.base_class = base_class.base_class()
        self.assertTrue(MODULE_MOCK.foo.called)

        self.sub_class = sub_class.sub_class()
        self.assertTrue(MODULE_MOCK.faa.called)

rawDescription: patching the same module in two different files with the same mock

description: Patching the same module in two different files with the same mock


code:
import sys

if __name__ == "__main__":
    for text in sys.stdin:
        text_in_script = 'test'

        # warning: rstrip() removes all whitespace; see rstrip() docs for alternatives
        print(text.rstrip() == text_in_script)

rawDescription: Why are strings from sys.stdin different from hardcoded strings in my script?


code:
# jkl
mypart['other'] = [item for item in part.find('p').contents
                   if not isinstance(item, bs.Tag) and item.string.strip()]

rawDescription: How to extract tags from HTML using Beautifulsoup in Python

description: Extract tags from HTML using Beautifulsoup in Python


rawDescription: Dealing with Windows line-endings in Python


code:
C[3,1]
C[tuple(idx)]

rawDescription: Index of multidimensional array

description: Index of multidimensional array


rawDescription: Python SKLearn: Logistic Regression Probabilities


code:
names = OrderedDict([('person_number', int),
                     ('name', str),
                     ('first', to_inch),
                     ('second', float),
                     ('third', float)])

rawDescription: Finding the top 10 and converting it from centimeters to inches - Python


rawDescription: Django dynamic file upload path

description: Django dynamic file upload path


rawDescription: how to use column names as values in a pandas data frame?

description: Use column names as values in a pandas data frame


code:
dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')])
X=np.ones((n,m),dtype=dt0)
X.strides
X.shape

rawDescription: Change stride of numpy array (altering data)


code:
import collections
import itertools

freqs = collections.OrderedDict([
    ('e', 12.702), ('t', 9.056), ('a', 8.167), ('o', 7.507),
    ('i', 6.749), ('n', 6.749), ('s', 6.327), ('h', 6.094),
    ('r', 5.987), ('d', 4.253), ('l', 4.052), ('c', 2.782),
    ('u', 2.758), ('m', 2.406), ('w', 2.360), ('f', 2.228),
    ('g', 2.015), ('y', 1.974), ('p', 1.929), ('b', 1.492),
    ('v', 0.978), ('k', 0.772), ('j', 0.153), ('x', 0.150),
    ('q', 0.095), ('z', 0.074)])

my_coded_string = """NTCGPDOPANFLHJINTOOFITOVJHJCTMMHIHEMTCPFDWTSOFSHTOGFWTE
TTJJTBTOOFSZOVEOCHCVCHPJHOCGTOHNQMTOCNTCGPDCGFCSTQMFBTO
FBGFSFBCTSHJCGTQMFHJCTYCXHCGFAHYTDDHAATSTJCBGFSFBCTSHJC
GTBHQGTSCTYCCGHONTCGPDQSTOTSWTOCGTMTCCTSASTRVTJBZHJCGTQ
MFHJCTYCFJDOPPJTBFJOTFSBGAPSCGTQMFHJCTYCASPNFIHWTJBHQGT
SCTYCEZBPNQFSHJICGTASTRVTJBZPATFBGMTCCTSFIFHJOCCGTLJPXJ
BPNNPJASTRVTJBZHJCGTVJDTSMZHJIMFJIVFIT"""

def translate(coded):
    coded_lines = coded.split('\n')
    letters = collections.defaultdict(float)
    for letter in itertools.chain(*coded_lines):
        letters[letter] += 1

    mapping = dict(zip(
        (i[0] for i in sorted(letters.items(),
                              key=lambda x: x[-1], reverse=True)),
        freqs.keys()))

    return '\n'.join(''.join(mapping[letter] for letter in line)
                     for line in coded_lines)

print(translate(my_coded_string))

rawDescription: Replace all occurrences of all chars within a string with another chars without interfering one with eachother


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter

x=np.array([1., 2., 3.])
y=2.*x*1.e7

MyFig = plt.figure()
MyAx = MyFig.add_subplot(111)

def sci_notation(x, pos):
    return "${:.1f} \\times 10^{{6}}$".format(x / 1.e7)

MyFormatter = FuncFormatter(sci_notation)

MyAx.axes.yaxis.set_major_formatter(MyFormatter)

MyAx.plot(x,y)

plt.show()

rawDescription: How to set offset with matplotlib

description: Set offset with matplotlib


rawDescription: Converting Timestamps in Python to UNIX Timestamps


code: second_set = {a[0] for a in second_list}

rawDescription: Python: nested list comprehension

description: Python: nested list comprehension


code: sum(map(float, s.split(',')))

rawDescription: Summing elements of string in Python

description: Summing elements of string in Python


code:
correct_order = ['AAA', 'AA+', 'BBB+', 'BBB', 'BB+']
list(sorted("BBB BBB+ BB+ AAA AA+ BBB+ BBB AA+".split(), key=lambda s:correct_order.index(s)))

rawDescription: Custom Sort List Using a Reference Order


code: df = ... # Python DataFrame

rawDescription: How to use a Scala class inside Pyspark

description: Use a Scala class inside Pyspark


code: BBACBCACCABACCBCABCC

rawDescription: How to plot events on time on using matplotlib

description: Plot events on time on using matplotlib


code:
def convert(data_structure):
    sentences = []
    tags = []

    for sentence in data_structure:
        sentence_words = []
        sentence_tags = []

        for word, tag in sentence:
            sentence_words.append(word)
            sentence_tags.append(tag)

        sentences.append(sentence_words)
        tags.append(sentence_tags)

    return (sentences, tags)

rawDescription: Convert a list of lists of tuples to a tuple of lists of lists in python


code:
js_args = hxs.select('//script[contains(., "lb_fb_cpn_init")]').re(r'(\[{names:(?:.+?)\]),')
len(js_args)

rawDescription: Scrapy hxs.select() not selecting all results


code:
def posNumAvg(values):
    x = []
    average = 0

    for i in values:
        if i > 0:
            x.append(i)
    average = sum(x) / len(x)

    return average

rawDescription: Trying to learn how to python have, I am curious about appeand and dictionaries...am i doing this correctly?


code:
A2.sum(axis=1)  # the fastest compile csr method
A2.A.sum(axis=1)  # same, but with a dense intermediary
[np.sum(l.data) for l in A2]  # iterate over the rows of A2
[np.sum(A2.getrow(i).data) for i in range(A2.shape[0])]  # iterate with index
[np.sum(l) for l in A2.tolil().data]  # sum the sublists of lil format
np.add.reduceat(A2.data, A2.indptr[:-1])  # with reduceat

rawDescription: Scipy.sparse.csr_matrix: How to get top ten values and indices?


code:
def upload(request):
    # Your treatment here.
    # Post the data to amazon S3.
    urllib2.urlopen("https://me.s3.amazonaws.com/", your_data)
    ...

rawDescription: How to pass variables to a form before it is processed

description: Pass variables to a form before it is processed


code:
import pprint
import json
import requests
from lxml import etree

r = requests.get('http://mtgoclanteam.com/Cards?edition=DTK')
doc = etree.HTML(r.text)

script = doc.xpath('id("templatemo_content")/script')[0].text
found = False
result = None
for line in script.splitlines():
    if found:
        if '[' in line:
            result=line
            break
    if 'aaData' in line:
        found = True

if result:
    result =json.loads('[' + result + ']')
    pprint.pprint(result)

rawDescription: Issue Parsing a site with lxml and xpath in python


code:
from dateutil.parser import parse
s = "03:00 PM - 05:00 PM"
parse(s, fuzzy_with_tokens=True)

rawDescription: Python: Converting a string representing a time range to a struct_time object


code:
a = np.arange(10)
b = np.arange(10)
np.savez_compressed('file.npz', a=a, b=b)

rawDescription: Storing and loading numpy arrays as files


code:
#Just check if they are all multiplicatives of 2
np.all((array[2::2,2::2] % 2) == 0) # Gives you True
#Just check if they are all multiplicatives of 3
np.all((array[2::2,2::2] % 3) == 0) # Gives you False

rawDescription: List of objects: how to extract attributes from a particular region or slice?


code:
for i, j in zip(list1, list2[::-1]):
    print(i, j)

rawDescription: Iterate backwards and forwards over two lists at the same time in Python


code:
import itertools as it

return sum(it.imap(doSomething, originalList), [])

rawDescription: How can I use a list comprehension to extend a list in python?

description: Use a list comprehension to extend a list in python


rawDescription: Is tzinfo=tzutc() same as +00:00 in python?


code:
def do_twice(f, g):
    f(g)
    f(g)

def print_spam(s):
    print (s)

do_twice(print_spam,'lol')

rawDescription: Python function inside of a function

description: Python function inside of a function


code: return gstr.mean(axis=(-2,-1))

rawDescription: Python code to quickly reduce the resolution of an image using numpy


rawDescription: Find dependencies in a python source/script


code:
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'IndexBudgetCode':['Nexusapp_341800', 'Nexusweb_120000', 'Primweb_1900000'],
    'AssociateID':['ppc_fli_1111', 'ooc_htl_1010', 'ppc_fli_9999,ppc_fli_1777']})
df = df.set_index(['IndexBudgetCode'])

result = pd.DataFrame(((index, item)
                       for index, row in df['AssociateID'].str.split(',').iteritems()
                       for item in row),
                      columns=['IndexBudgetCode', 'AssociateID'])
print(result)

rawDescription: Duplicate a list in a Pandas Dataframe into a new row


category: AAA DDD

title: XX

rawDescription: Python JSON data dump with mulitple values


code: train_x, train_y = train_set

rawDescription: how to unpack pkl file

description: Unpack pkl file


code:
class fcount2(object):
    def __init__(self, inner_func):
        self.inner_func = inner_func
        if not hasattr(self.inner_func, 'count'):
            self.inner_func.count = 0
        if not hasattr(self.inner_func, 'block_count'):
            self.inner_func.block_count = 0
        self.context_manager = False
    def __call__(self, *args, **kwargs):
        if self.context_manager:
            self.inner_func.block_count += 1
        else:
            self.inner_func.count += 1
        return self.inner_func(*args, **kwargs)
    def __enter__(self):
        self.context_manager = True
        return self
    def __exit__(self, exception_type, exception_value, tb):
        if exception_type is not None:
            return False
        self.context_manager = False
        return self
    @property
    def count(self):
        return self.inner_func.count
    @property
    def block_count(self):
        return self.inner_func.block_count

rawDescription: Python Decorator Class: How to correctly count function calls in a with block


rawDescription: 'leet' program - getting all permutations


code: import itertools as IT

rawDescription: wxPython Button to load multiple images

description: WxPython Button to load multiple images


code:
def rule(f):
    f.rule = True
    return f

class RuleType(type):
    def __init__(self, name, bases, attrs):
        self.rules = {}
        for attr, value in attrs.iteritems():
            if getattr(value, 'rule', False):
                self.rules[attr] = value
        super(RuleType, self).__init__(name, bases, attrs)

class RuleBase(object):
    __metaclass__ = RuleType

class RuleClass(RuleBase):
    @rule
    def foo(self):
        pass

rawDescription: python decorator to modify variable in current scope

description: Python decorator to modify variable in current scope


code:
builder = gtk.Builder()
builder.add_from_file("GUI.xml")
builder.connect_signals(self)
self.window1 = builder.get_object("window1")
self.window1.show()

rawDescription: How to reuse a widget tree from a glade file with GtkBuilder?

description: Reuse a widget tree from a glade file with GtkBuilder


code:
class Person:

    def __init__(self, first_name, last_name, phone_number):
        self.first_name = first_name
        self.last_name = last_name
        self.phone_number = phone_number

rawDescription: Program consisting of multiple classes

description: Program consisting of multiple classes


rawDescription: Python 3.5 combine two CSV by matching multiple columns


rawDescription: Match character from string with binary list


rawDescription: Include entire directory in python setup.py data_files


code:
import urllib
s = u'Здравей'
urllib.quote(s.encode('utf-8'))
# %D0%97%D0%B4%D1%80%D0%B0%D0%B2%D0%B5%D0%B9

rawDescription: Python string and UTF-8 problems

description: Python string and UTF-8 problems


code:
from django.contrib.gis.db.models.functions import Distance
Activity.objects.annotate(
  distance=Distance('location__coords',somepoint)
).order_by('distance')

rawDescription: Calculating near gps coordinates in django


code: return type(EmployeeForm)('EmployeeForm', (forms.Form, ), EmployeeForm.__dict__)

rawDescription: Difference between returning modified class and using type()


code:
import os

ini_file = os.environ['TEST_INI']

rawDescription: pass test config (test.ini) through nosetests to pyramid

description: Pass test config (test.ini) through nosetests to pyramid


code: STATIC_ROOT = os.path.join(BASE_DIR, 'static')

rawDescription: django static folder name change

description: Django static folder name change


code: filter(lambda item: item['username'] != 'bob', l)

rawDescription: How to remove an object from a list in python?

description: Remove an object from a list in python


code:
def on_button_clicked(self, widget):
    ps = Gtk.PaperSize.new_custom("cc", "cc", 210, 297, Gtk.Unit.MM)
    st = Gtk.PrintSettings()
    s = Gtk.PageSetup()
    s.set_paper_size(ps)
    s.set_bottom_margin(4.3, Gtk.Unit.MM)
    s.set_left_margin(4.3, Gtk.Unit.MM)
    s.set_right_margin(4.3, Gtk.Unit.MM)
    s.set_top_margin(4.3, Gtk.Unit.MM)
    s.set_orientation(Gtk.PageOrientation.LANDSCAPE)
    # ret =  Gtk.print_run_page_setup_dialog(self, s, st)
    pd = Gtk.PrintOperation()
    pd.set_n_pages(1)
    pd.set_default_page_setup(s)
    pd.connect("begin_print", self.bg)
    pd.connect("draw_page", self.draw_page)
    # print(ret, s, st)
    pd.set_export_filename("test.pdf")
    result = pd.run(Gtk.PrintOperationAction.EXPORT, None) #play with action, but for test export first; if it's ok, then action.PRINT
    print (result)  # handle errors etc.
    # Gtk.PaperSize.free(ps) - not needed in py

rawDescription: Creating print job in gtk3/python

description: Creating print job in gtk3/python


code:
import select
import sys

print('Press enter to continue.', end='', flush=True)
r, w, x = select.select([sys.stdin], [], [], 600)

rawDescription: Python: wait for user input, and if no input after 10 minutes, continue with program


code:
import matplotlib.pyplot as plt
N =100
menMeans = range(N)
ind = range(N)
ticks = ind
fig = plt.figure()
ax = fig.add_subplot(111)
rects1 = ax.bar(ind, menMeans, align = 'center')
ax.set_xticks(range(0,N,10))
ax.set_xticklabels( range(0,N,10), rotation=45 )
plt.show()

rawDescription: Matplotilb bar chart: diagonal tick labels


code: df.groupby( ['date', 'name'] )['name'].aggregate(len).unstack( ).fillna( 0 )

rawDescription: Calculating previous chance figure for use in chi square test


code: re.findall(r',\d\d(?: |$)', tgt, flags=re.M)

rawDescription: Regex require certain ending on string

description: Regex require certain ending on string


code:
class BaseView(TemplateView):
   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
        return super(BaseView, self).dispatch(*args, **kwargs)

rawDescription: Django Url group only for Authenticated Users


code:
import numpy as np
def blockshaped(arr, nrows, ncols):
    """
    Return an array of shape (n, nrows, ncols) where
    n * nrows * ncols = arr.size

    If arr is a 2D array, the returned array should look like n subblocks with
    each subblock preserving the "physical" layout of arr.
    """
    h, w = arr.shape
    return (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1,2)
               .reshape(-1, nrows, ncols))

rawDescription: Slice 2d array into smaller 2d arrays

description: Slice 2d array into smaller 2d arrays


code:
root = Tk()
root.title("Lazy Button 2")
root.geometry("500x500")
app = Application(root)
root.mainloop()

rawDescription: Creating buttons with Python GUI

description: Creating buttons with Python GUI


code:
ps("</dev/null /var/tmp/KernelbootRun.sh >/dev/null 2>&1")
ps("</dev/null ps aux | grep processCreator.py | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1")

rawDescription: How can i let the BASH script run as process? So that even the Python script is killed the BASH script runs forever?

description: Let the BASH script run as process? So that even the Python script is killed the BASH script runs forever


code: sum([i**2 for i in lst])

rawDescription: sum squared values in FreqDist, python

description: Sum squared values in FreqDist, python


code:
likes = values[0]
comments = values[2]
shares = values[4]

rawDescription: Substrings from string in python

description: Substrings from string in python


rawDescription: Python's implementation of Permutation Test with permutation number as input


rawDescription: Saving matplotlib figure with add_axes

description: Saving matplotlib figure with add_axes


code: [s for s, t in zip(stuffs, types) if t == "animal"]

rawDescription: Print out indexes of same values in file/list


rawDescription: "Cloning" row or column vectors

description: "Cloning" row or column vectors


code:
f = open('filename string');
lines = f.readlines()

rawDescription: File and space in Python

description: File and space in Python


rawDescription: django model for list of objects' relations to each other?

description: Django model for list of objects' relations to each other


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

rawDescription: deleting items from a dictionary with a given list

description: Deleting items from a dictionary with a given list


code: print ("Your first digit is", response[0])

rawDescription: I'm not sure of a way to go about this task using Python code


code:
for i in combinations(s, 2):
    inter = i[0] & i[1]
    # processes the intersection set result "inter"

rawDescription: Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists


rawDescription: how to calculate the dot product of two arrays of vectors in python?

description: Calculate the dot product of two arrays of vectors in python


code: [s + mystring for s in mylist]

rawDescription: Appending the same string to a list of strings in Python


code:
from Crypto.Cipher import AES
from hashlib import md5
import base64

password = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
input = 'hello world'

BLOCK_SIZE = 16

def pad (data):
    pad = BLOCK_SIZE - len(data) % BLOCK_SIZE
    return data + pad * chr(pad)

def unpad (padded):
    pad = ord(padded[-1])
    return padded[:-pad]

def _encrypt(data, nonce, password):
    m = md5()
    m.update(password)
    key = m.hexdigest()

    m = md5()
    m.update(password + key)
    iv = m.hexdigest()

    data = pad(data)

    aes = AES.new(key, AES.MODE_CBC, iv[:16])

    encrypted = aes.encrypt(data)
    return base64.urlsafe_b64encode(encrypted)

def _decrypt(edata, nonce, password):
    edata = base64.urlsafe_b64decode(edata)

    m = md5()
    m.update(password)
    key = m.hexdigest()

    m = md5()
    m.update(password + key)
    iv = m.hexdigest()

    aes = AES.new(key, AES.MODE_CBC, iv[:16])
    return unpad(aes.decrypt(edata))

output = _encrypt(input, "", password)
print(output)
plaintext = _decrypt(output, "", password)
print("'" + plaintext + "'")

rawDescription: Encrypting and Decrypting with python and nodejs


code:
rev_aliases = {}
for name, nick_list in aliases.iteritems():
    for nick in nick_list:
        rev_aliases[nick] = name

rawDescription: Swapping keys and values with nested value items


code:
def all_chainable(klass):
    for k, v in klass.__dict__.items():
        if not k.startswith('_') and callable(v):
            setattr(klass, k, chainable(v))
    return klass

rawDescription: DRYout a class-based chainable API

description: DRYout a class-based chainable API


rawDescription: How to determine colors at intervals in a matplotlib colormap

description: Determine colors at intervals in a matplotlib colormap


code: results = np.zeros([nrows, 5])

rawDescription: Vectorizing the addition of results to a numpy array


code:
import argparse

parser = argparse.ArgumentParser(usage='Any text you want\n')

rawDescription: python argparse print usage text after description

description: Python argparse print usage text after description


code:
query = None
for genre in genres:
    if query is None:
        query = Q(genre__genre=genre) | Q(genre__parent__genre=genre)
    else:
        query = query & (Q(genre__genre=genre) | Q(genre__parent__genre=genre))

    Track.objects.filter(query).distinct()

rawDescription: Django Many-to-many query fulfilling a specific condition


rawDescription: Find Closest Vector from a List of Vectors | Python


code:
from collections import Counter
Counter(zip(*d.values()))

rawDescription: Parse positions of dictionary values into a list


code:
import os
usernames = set(os.listdir('/path/to/directory/with/usernames/'))

f = open('/path/to/6 million')
resultlist = [line.split()[1] for line in f if line[1] in usernames]

common = open('/path/to/filf','w')
common.write('\n'.join(resultlist) + '\n')
common.close()

rawDescription: Comparing 40 million lines in a file with 6 million list items in Python


code:
u = Url(url)
del u.args['page']
url = str(u)

rawDescription: Is there a better way to write this URL Manipulation in Python?


code: weight = sum(weights.get(word, 0) for word in sentence.split())

rawDescription: Optimizing the search of a string in a phrases. Don't know which Python structures I need to use


code:
# output formatting and indentation by me

keys
def keyfunc(item):
  if item[-1].isalpha():
    return item[:-1]
  return item

items = [sorted(subitems)[-1]
         for _, subitems
         in itertools.groupby(keys, keyfunc)]
items

rawDescription: Selecting items matching a specific condition from a list


code:
objectname.responseoperationcode # this returns the value
objectname.responseoperationcode = "SUCCESS" # this sets the value

rawDescription: Getter and Setter for member variable in Python


code:
@property
def a(self):
    for item in self:
        yield item.a

rawDescription: Get attribute of all items in container python


code: sort = "some default"

rawDescription: In my code i am getting a name error saying the name 'sort' is not defined


code:
# content.py
import pygame
from pygame.locals import *

def init():
    pygame.display.init()

def morestuff():
    "do some more stuff"

if __name__ == '__main__':
    init()
    morestuff()

rawDescription: Way around Python imports within imports?


rawDescription: Adding a program icon in Python GTK

description: Adding a program icon in Python GTK


code:
class Chunker(object):
    """Split `iterable` on evenly sized chunks.

    Leftovers are remembered and yielded at the next call.
    """
    def __init__(self, chunksize):
        assert chunksize > 0
        self.chunksize = chunksize
        self.chunk = []

    def __call__(self, iterable):
        """Yield items from `iterable` `self.chunksize` at the time."""
        assert len(self.chunk) < self.chunksize
        for item in iterable:
            self.chunk.append(item)
            if len(self.chunk) == self.chunksize:
                # yield collected full chunk
                yield self.chunk
                self.chunk = []

rawDescription: Iteration over list slices

description: Iteration over list slices


code:
voxMapBeamlet = sparse.coo_matrix((voxMap_beamlet_val,(voxMap_beamlet_iInd,voxMap_beamlet_jInd)),shape=(1055736,8500))
voxMapBeamlet = voxMapBeamlet.tocsr()

rawDescription: Accessing a large number of unsorted array elements in Python


code:
app.menu = [
    rumps.MenuItem('About', icon='pony.png', dimensions=(18, 18)),
    'Preferences',
    None,  # separator
    {'SubMenu':
        {"Child Menu One": ["Item 1", "Item 2"],
         "Child Menu Two": ["Item 1", rumps.MenuItem("Item 2")]}},
    None
]

rawDescription: Creating Sub Menu for Menu item using Rumps python on Mac OS


rawDescription: Python UDP server on ubuntu not working

description: Python UDP server on ubuntu not working


code:
from operator import attrgetter
map(attrgetter('my_attr'), my_list)

rawDescription: How to extract from a list of objects a list of specific attribute?

description: Extract from a list of objects a list of specific attribute


code:
def h(i):
    f()
    return g(i)

def g(i):
    return i + 1

def f():
    print("Non-pure function")

h(1)
cleaned_globals = {'g': g}
newfunc = type(h)(h.__code__, cleaned_globals, h.__name__, h.__defaults__, h.__closure__)
newfunc(1)
cleaned_globals['f'] = lambda: print('Injected function')
newfunc(1)

rawDescription: Change what dictionary serves as a function's global scope


code:
mask = df['EvntType']==1
# 0     False
# 1      True
# ...
# 9      True
# 10    False
# Name: EvntType, dtype: bool

rawDescription: Iterate through rows in pandas dateframe in a cleaner way using .iterrows() and keep track of rows inbetween specific values


code:
id = [x[0] for x in fetched]
data = [x[2] for x in fetched]

rawDescription: Get component from Array sqlite

description: Get component from Array sqlite


code:
'Aug 23, 2011 10:31:35 AM This is the start of the text.\n      This is more Text.\nThis is another line\nThis is another line\n      This is more.\n'

'Aug 23, 2011 10:41:00 AM This is the next in the series.\nThis is another line\n      This is more Text.\nThis is another line\n      This is another line\n      This is more.\n'

'Aug 24, 2011 10:41:00 AM This is the next in the series.\nThis is another line\n      This is more Text.\nThis is another line\n      This is another line\n      This is more. '

rawDescription: Return all lines following a matched date and time up, but not including the next date and time?


rawDescription: Dynamically instantiate object of the python class similar to PHP new $classname?


code:
expr = Forward()
identifier = Word(alphas+'_', alphanums+'_')
expr = Forward()
function_call = Group(identifier + LPAR + Group(expr) + RPAR)

unop = oneOf("+ -")
binop = oneOf("+ - * / %")
operand = Group(Optional(unop) + (function_call | number | identifier))
binexpr = operand + binop + operand

expr << (binexpr | operand)

bnf = expr

rawDescription: How to get pyparser to work in a particular form

description: Get pyparser to work in a particular form


rawDescription: Change prompt to user with each loop pass


rawDescription: Is there a way to generate a list of indices using numpy


rawDescription: Python - How to add space on each 3 characters?


rawDescription: What is good way to negate an integer in binary operation in python?


rawDescription: Python - Safe Indexing with boolean

description: Python - Safe Indexing with boolean


rawDescription: Issue with pexpect match

description: Issue with pexpect match


code:
if char == m:
   return True
elif aStr == '' or len(aStr) == 1:
    return False
else:
    ...

rawDescription: Using a recursive bisection algorithm to check if character is in string


code:
import json

def transform(data):
    ts  = data[:18].strip()
    jss = data[18:].strip()
    jsj = json.loads(jss)
    jsj['ts'] = ts
    return json.dumps(jsj)

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
rdd = sc.textFile('/sparkdemo/sample.data')
tbl = sqlContext.jsonRDD(rdd.map(transform))
tbl.registerTempTable("myOrder")

sqlContext.sql("select ts, recordType, data.keycol, data.col1, data.col2 data from myOrder").collect()

rawDescription: How to map structured data to schemaRDD in Spark?

description: Map structured data to schemaRDD in Spark


code:
def transform(a, c=255/2):
    return c - np.abs(c - a)

ranking = transform(arr).argsort(axis=-1)

rawDescription: Iterating a function over the RGB values of individual pixels


code:
# Add an grouping column.
nbr_images = (df['col1'] == 'image').sum()
nbr_attributes = len(df)/nbr_images
df['image_group'] = np.repeat(range(nbr_images), nbr_attributes)

rawDescription: Pivot groups of row data into columns using Pandas


code: excludes = dict(("%s__isnull" % ro.get_accessor_name(), False) for ro in related)

rawDescription: How to filter objects in Django that do not have any other objects pointing to them?

description: Filter objects in Django that do not have any other objects pointing to them


code:
class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title')

class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        exclude = ('birth_date',)

rawDescription: How to create Django FormWizard for one Model?

description: Create Django FormWizard for one Model


code:
convert(32)
convert(68)
convert(150)
convert(250)

rawDescription: Mapping a range of integers to a single integer


code:
python

import django

django.get_version() # you should get '1.3.0 final'

quit()

rawDescription: Virtualenv for different version of django


code:
toggler = FullscreenToggler(window)
window.connect_object('key-press-event', FullscreenToggler.toggle, toggler)

rawDescription: Simple way to toggle fullscreen with F11 in PyGTK


rawDescription: How can I print out the string "\b" in Python

description: Print out the string "\b" in Python


code:
import numpy as np

a = array([1,2,3,4,5,6])
b = array([1,4,5])

c = np.in1d(a,b)

rawDescription: NumPy: Comparing Elements in Two Arrays

description: NumPy: Comparing Elements in Two Arrays


code: type(measured)

rawDescription: Is @measured a standard decorator? What library is it in?


code: import os

rawDescription: Why do we sometimes need to import module1.module2 but sometimes not?


code:
from itertools import chain, imap
from operator import methodcaller

dict(chain.from_iterable(imap(methodcaller('iteritems'), lst)))

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


code: self.nums = []

rawDescription: How can I execute more a command based on the Button that called it? (Classes and tkinter)

description: Execute more a command based on the Button that called it? (Classes and tkinter)


code:
def process(indict, current_key=None, outerdict=None):
    if outerdict is None:
        outerdict = {}
    for key, value in indict.iteritems():
        newkey = current_key + '__' + key if current_key else key
        if type(value) is not dict:
            outerdict[newkey] = value
        else:
            process(value, current_key=newkey, outerdict=outerdict)
    return outerdict

rawDescription: Python: Twitter API tweets/search: Flatten nested dictionary to columns


code:
s = "flour, 100, grams"
s.split(",")
s.split(",")[1] # index the middle element (Python is zero-based)

rawDescription: How to extract a number from a string in Python?

description: Extract a number from a string in Python


code: np.allclose(C, D)

rawDescription: triple tensor product in numpy

description: Triple tensor product in numpy


code:
for month, subdf in df.groupby(['month']):
    ...

rawDescription: creating multiple dataframes which contain subsets of an orginal pandas dataframe

description: Creating multiple dataframes which contain subsets of an orginal pandas dataframe


rawDescription: Fit a curve using matplotlib on loglog scale


code: myTabWidget.setStyleSheet('QTabBar { font-size: 18pt; font-family: Courier; }')

rawDescription: PyQt4: Change text size and font on QTabBar


code:
messages = zip(message, newkeyword)
sums = [alphabet.find(m) + alphabet.find(n) for m, n in messages]

rawDescription: How to store multiple numbers and then add to each individual one

description: Store multiple numbers and then add to each individual one


code:
class CustomBooleanField(models.BooleanField):

    def from_db_value(self, value, expression, connection, context):
        if value is None:
            return value
        return int(value) # return 0/1

rawDescription: Django model.BooleanField as 0/1

description: Django model.BooleanField as 0/1


code:
import random

namecount = 5
namelist=[]
for i in range(0, namecount):
  namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]

nameindex = random.randint(0, namecount)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

rawDescription: Python: can't assign to literal

description: Python: can't assign to literal


code:
x = 10
y = 20
{k: v for k,v in locals().iteritems() if '__' not in k and 'pdb' not in k}

rawDescription: How to print all variables values when debugging Python with pdb, without specifying each variable?

description: Print all variables values when debugging Python with pdb, without specifying each variable


rawDescription: Assume zero for subsequent dimensions when slicing an array


code:
def func(a, *b):
    c = np.array([1,a,a**2,a**3])
    d = np.array(b[0])
    return sum(c*d)

rawDescription: SUM does not work

description: SUM does not work


code:
def const_function(c):
    def helper(x):
        return c
    return helper # don't call it

rawDescription: Trying to set function as parameter

description: Trying to set function as parameter


rawDescription: How do I make better use of logging module in my program?

description: Make better use of logging module in my program


code:
from datetime import time

morning_start = time(7)
morning_end = time(12)
evening_start = time(18)
evening_end = time(22)

periods = {'morning':[morning_start, morning_end], 'evening':[evening_start, evening_end]}

rawDescription: Bin timestamp into custom periods

description: Bin timestamp into custom periods


code:
if list_of_ids:
    results = models.Object.query.filter(models.Object.id.in_(list_of_ids)).paginate(page, 10, False)
else:
    results = EmptyPaginator()

rawDescription: empty paginate object sqlalchemy

description: Empty paginate object sqlalchemy


code:
date_str='Jun 03, 2010 at 22:22PM'
date=dt.datetime.strptime(date_str,'%b %d, %Y at %H:%M%p')
print(date)
# 2010-06-03 22:22:00

rawDescription: Convert 12hr date/time string to 24hr datetime


code:
def genDDict(dim=3):
    if dim==1:
        return collections.defaultdict(int)
    else:
        return collections.defaultdict(lambda: genDDict(dim-1))

rawDescription: nesting defaultdicts in an arbitrary depth

description: Nesting defaultdicts in an arbitrary depth


code: embed()

rawDescription: Can I use IPython in an embedded interactive Python console?

description: Use IPython in an embedded interactive Python console


code:
for w in words:
     if re.search('^[a-zA-Z]+$', w) == None:
          continue

rawDescription: How do I find only whole words using re.search?

description: Find only whole words using re.search


code: __metaclass__ = MetaClassName

rawDescription: Converting Python2 to Python3 with metaclasses resulted in a wrong flow


rawDescription: Linear regression with matplotlib / numpy


rawDescription: Grouping CheckboxSelectMultiple Options in Django


code:
import collections

by_hour = collections.defaultdict(list)
for f in dir_files:
    t = os.path.getmtime(dir + '/' + f)
    mod_time = datetime.datetime.fromtimestamp(t)
    mod_hour = datetime.datetime(*mod_time.timetuple()[:4])
    # for example, (2013, 1, 8, 21)
    by_hour[mod_hour].append(f)

rawDescription: Python - group files by modified date [hour]


rawDescription: Python parse XML variables from a single tag


code:
import cPickle
cPickle.dump(obj, open('save.p', 'wb'))
obj = cPickle.load(open('save.p', 'rb'))

rawDescription: Is something like ConfigParser appropriate for saving state (key, value) between runs?


code:
import matplotlib.ticker as mtick

def generate(data_):
    data, time = data_
    img = StringIO.StringIO()
    sns.set_style("darkgrid")
    plt.plot(time, data)
    plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1E')) #this line solves the problem
    plt.savefig(img, format=format_)
    img.seek(0)
    x = base64.b64encode(img.getvalue())
    return x

rawDescription: How to set float values as scientific notation in matplotlib?

description: Set float values as scientific notation in matplotlib


code:
# a.py
print('a')
import b
import c

# b.py
import a
print('b')

# c.py
import a
print('c')

rawDescription: Would multiple circular imports degrade performance?


code:
import re
qs = "param1=1234&param2=abcd&param3=efgh&param4=ijkl"
name = "param2"
rx = '(^|&)' + name + '=[^&]*'
re.sub(rx, '', qs)

rawDescription: Python RegEx Remove / Replace

description: Python RegEx Remove / Replace


code:
import webapp2

config = {'foo': 'bar'}

app = webapp2.WSGIApplication(routes=[
    (r'/', 'handlers.MyHandler'),
], config=config)

rawDescription: Passing parameters to a webapp2.RequestHandler object in python


rawDescription: How to alter attributes in Tkinter

description: Alter attributes in Tkinter


rawDescription: Creating a single regex rather than a nested statement


code: my_function() == {'this': 'is', 'a': 'dictionary'}

rawDescription: How do I test dictionary-equality with Python's doctest-package?

description: Test dictionary-equality with Python's doctest-package


code:
values2 = np.vstack([np.sin(3 * thetas), np.cos(6 * thetas)])
polar_heat(values2, fraction=0.6)

rawDescription: Python plot data as a function of angle in a ring


rawDescription: pandas: how to run a pivot with a multi-index?

description: Pandas: how to run a pivot with a multi-index


code: b = struct.pack('4B', *data)

rawDescription: combine four bytes and convert to float

description: Combine four bytes and convert to float


code:
# Create a data source
ds = bokeh.models.sources.ColumnDataSource(dict(x=df['date'], y=[0,3,2]))
# Define the line glyph
line = bokeh.models.glyphs.Line(x='x', y='y', line_width=4, line_color='blue')
# Add the data source and glyph to the plot
p.add_glyph(ds, line)

rawDescription: Add additional curve to bokeh chart

description: Add additional curve to bokeh chart


code:
import numpy as np
np.random.seed(1)

def mahalanobis_sqdist(x, mean, Sigma):
   '''
   Calculates squared Mahalanobis Distance of vector x
   to distibutions mean
   '''
   Sigma_inv = np.linalg.inv(Sigma)
   xdiff = x - mean
   sqmdist = np.dot(np.dot(xdiff, Sigma_inv), xdiff)
   return sqmdist

def mahalanobis_sqdist2(d, mean, Sigma):
   Sigma_inv = np.linalg.inv(Sigma)
   xdiff = d - mean
   return np.einsum('ij,im,mj->i', xdiff, xdiff, Sigma_inv)

def using_loop(d1, mean, Sigma):
    expected = []
    for r in d1:
        expected.append(mahalanobis_sqdist(r[0:4], mean1, Sig1))
    return np.array(expected)

d1 = np.random.random((25,4))
mean1 = np.array([ 5.028,  3.48 ,  1.46 ,  0.248])
Sig1 = np.cov(d1[0:25, 0:4].T)

expected = using_loop(d1, mean1, Sig1)
result = np.apply_along_axis(mahalanobis_sqdist, 1, d1, mean1, Sig1)
result2 = mahalanobis_sqdist2(d1, mean1, Sig1)
assert np.allclose(expected, result)
assert np.allclose(expected, result2)

rawDescription: python-numpy: Apply a function to each row of a ndarray

description: Python-numpy: Apply a function to each row of a ndarray


code:
import random
[random.randrange(0, 11, 2) for _ in range(20)]

rawDescription: Random number between specific values

description: Random number between specific values


code:
class TAG(object):
    def __init__(self, contents=None, **attributes):
        self.contents = contents
        self.attributes = attributes

class H1(TAG):
    tag = 'H1'

class H2(TAG):
    tag = 'H2'

rawDescription: Python: HTML generation performance improvement


code:
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from direct.showbase.ShowBase import ShowBase

class MyApp(ShowBase):

    def __init__(self):
        ShowBase.__init__(self)
        self.qtApp = QApplication(sys.argv)
        label = QLabel("Hello World")
        label.show()
        self.m = loader.loadModel("frowney")
        self.m.reparentTo(render)

    def step(self):
        self.qtApp.processEvents()  #manual step trough Qt loop
        taskMgr.step()              #manual step trough Panda3D loop
        return 0                    #PyOS_InputHook expects an integer

if __name__ == "__main__":
    app = MyApp()
    while 1: app.step()

rawDescription: IPython iterate main loop manually?

description: IPython iterate main loop manually


code:
n = df.price_point.value_counts().high
m = df.price_point.value_counts().low

df = pd.DataFrame(data={'price':['high', 'high', 'low', 'low', 'low', 'low']})
df.price.value_counts().high

2

rawDescription: Store the counts for a specific value in a column in Pandas dataframe


code:
with open('input.txt') as fin, open('output.txt', 'w') as fout:
    for line in fin:
        fout.write(fixline(line))

rawDescription: Match a specific number of characters in string and delete python


code:
# focus element in the URL
#http://example.com/route/123
@app.route('/route')
@app.route('/route/<id>')
def route(id = None):
    # id is sent as an argument
    return render_template('my-form.html', id = id)

rawDescription: render html page /#:id using flask

description: Render html page /#:id using flask


code:
import sys

Base = declarative_base()
if len(sys.argv) > 1 and sys.argv[1] == '--use-alt-db':
    engine = create_engine('mysql://user:pass@alt_host/db_name')
else:
    engine = create_engine('mysql://user:pass@main_host/db_name')

table = Table('something', Base.metadata, autoload_with=engine)

class Something(Base):
    __table__ = table

rawDescription: How to dynamically create classes inside a module-level initialize() method in Python

description: Dynamically create classes inside a module-level initialize() method in Python


code: a, b = b, a + b

rawDescription: Fibonacci sequence python

description: Fibonacci sequence python


rawDescription: Encoding a numeric string into a shortened alphanumeric string, and back again


code:
class CurrentCompanyManager(models.Manager):
    def __init__(self,field,*args,**kwargs):
        super(CurrentCompanyManager,self).__init__(*args,**kwargs)
        self.__field_name = field

    def on(self,company):
        return self.filter( **{  self.__field_name + '__id__exact':company.id } )

rawDescription: Django: limiting model data

description: Django: limiting model data


code:
for df_,file in zip(list_df,file_names):
    df_.loc[:,'filename'] = file

rawDescription: Python - List comprehension expression for assigning values from list to list of DataFrames


code: e = root.xpath('.//a[text()="TEXT A"]')

rawDescription: How to use lxml to find an element by text?

description: Use lxml to find an element by text


code:
urlpatterns = patterns('books.views',
  (r'^books/$', 'index'),
  (r'^books/(\d+)/$', 'get'))

rawDescription: Django ease of building a RESTful interface


code:
import timeit
L = range(10)
def foo(a, b): pass

def p(b): return foo(1, b)

timeit.timeit('map(p, L)', 'from __main__ import foo, L; from functools import partial; p = partial(foo, 1)')
timeit.timeit('map(p, L)', 'from __main__ import foo, L; p = lambda b: foo(1, b)')
timeit.timeit('map(p, L)', 'from __main__ import foo, L, p')

rawDescription: Map function and input function parameters


code:
def my_variables(request):
    return {
        "var1": True,
        "var2": "foo",
        "var3": 42,
    }

rawDescription: Django import variables from file

description: Django import variables from file


code:
raw_data = reader.ptb_raw_data(FLAGS.data_path)
train_data, valid_data, test_data, vocabulary = raw_data

rawDescription: getting word from id at Tensorflow RNN sample

description: Getting word from id at Tensorflow RNN sample


code:
import ssl
import urllib2

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
# other settings (see ssl.create_default_context() implementation)
urllib2.urlopen('https://example.com', context=context).close()

rawDescription: I want to choose the Transport Layer Security protocol in urllib2


code:
# makes the list ['host2.example.com', '192.168.0.7', 'web server']
line.split('#')

# takes the labels list and matches them up:
# [('dns', 'host2.example.com'),
#  ('ip', '192.168.0.7'),
#  ('description', 'web server')]
zip(labels, line.split('#'))

# takes each tuple and makes the first item the key,
#  and the second item the value
dict(...)

rawDescription: python: read and split files in to list of dictionaries

description: Python: read and split files in to list of dictionaries


code: map(sum, zip(*arra))

rawDescription: Iterating and selecting a specific array from a multidimensional array in Python


code:
# Hypothetically, let's say that the current user makes the most sense
# This is just an example, for the sake of the thing
user = Authors.get(current_user.id)
ContentForm.author = QuerySelectField('Author', get_label='name', default=user)

rawDescription: SQLAlchemy/WTForms: set default selected value for QuerySelectField


code: d = {'abc': print}

rawDescription: dictionary of built in methods in python

description: Dictionary of built in methods in python


code:
import glob
import os

files_to_remove = ['*.jpg', '*.txt', '*.gif']
for files_glob in files_to_remove:
    for filename in glob.glob(files_glob):
        os.remove(filename)

rawDescription: Calling list items in subprocess

description: Calling list items in subprocess


code:
record_list
user_ages = dict(((d['firstname'], d['lastname']), d['age']) for d in record_list)
user_ages

rawDescription: python: creating histogram out of dictionary

description: Python: creating histogram out of dictionary


code:
def getCode(i):
    with open('temp.txt') as f:
            for index, line in enumerate(f):
                    if index == i:
                            code = line
                            return code
getCode(2)

rawDescription: Basic python file-io variables with enumerate


code:
line = '20 30 i love you'.split()
a = int(line[0])
b = int(line[1])
word_list = line[2:]

rawDescription: Read each word and rest of line in Python?


code:
lists = [list1, list2, list3]
next(l for l in lists if 9 in l)

rawDescription: Concatenate List Object Name with a Number and Retain the List Python


rawDescription: Dynamically creating variables, while doing map/apply on a dataframe in pandas to get key names for the values in Series object returned


code: res_1 = (single * actg).sum(axis=-1)

rawDescription: Python: How to perform division according to its representation?


rawDescription: Best way to provide object attributes?

description: Provide object attributes


code:
def foo(a, b=None, c=None, d=None):
    if b is None: b = 1
    if c is None: c = 2
    if d is None: d = 3

rawDescription: What is the most pythonic way to call a method with optional parameters?


rawDescription: How do I turn a list of tuples into a dictionary while keeping redundant values?

description: Turn a list of tuples into a dictionary while keeping redundant values


code:
male_names = df[df.sex == "M"].name
female_names = df[df.sex == "F"].name
gender_ambiguous_names = list(set(male_names).intersection(set(female_names)))

rawDescription: comparing column values based on other column values in pandas

description: Comparing column values based on other column values in pandas


code: parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)

rawDescription: PyQt Tree Widget, adding check boxes for dynamic removal


code:
from copy import deepcopy

copy = deepcopy(some_list)

rawDescription: python list.pop() modifies original list (not just copy)

description: Python list.pop() modifies original list (not just copy)


code:
def schema(x):
    if x == 'M':
        step=1
    else:
        step=2
        return step

rawDescription: Return function value to range argument step


code:
def indexingversion(data, bin_start, bin_end, bin_step):
    x = np.array(data)
    bin_edges = np.arange(bin_start, bin_end + bin_step, bin_step)
    bin_number = bin_edges.size - 1
    cond = np.zeros((x.size, bin_number), dtype=bool)
    for i in range(bin_number):
        cond[:, i] = np.logical_and(bin_edges[i] < x,
                                    x < bin_edges[i+1])
    return [list(x[cond[:, i]]) for i in range(bin_number)]

rawDescription: How can i group data based on range of values

description: Group data based on range of values


code: c = a + b

rawDescription: How to add 2 objects of a class by overide __add__ method?

description: Add 2 objects of a class by overide __add__ method


code:
import datetime as dt
cur.execute("""SELECT *
               FROM people_counter
               WHERE time_stamp BETWEEN %s and %s;""",
            (dt.date(2015,6,1), dt.date(2015,6,30)))

rawDescription: Psycopg2, selection based on date/time

description: Psycopg2, selection based on date/time


code:
nested_dictionary = {'a': {'b': 'c', 'd': 'e', 'f': 'g'}, 'h': {'i': 'j', 'k': 'l', 'm': 'n'}}
nested_dictionary['a']
nested_dictionary['a']['f']

rawDescription: Dictionary as value in dictionary

description: Dictionary as value in dictionary


code:
instance = form.save(commit=False)
instance.save()

rawDescription: Automatically attaching the logged in user to a post he/she creates


rawDescription: column matrix representation in python

description: Column matrix representation in python


code:
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

rawDescription: How can I add a custom footer to Sphinx documentation? (reStructuredText)

description: Add a custom footer to Sphinx documentation? (reStructuredText)


code:
result = {}
for key in alist[0]:
    result[key] = [d[key] for d in alist]

rawDescription: concatenate dictionaries over a key

description: Concatenate dictionaries over a key


code: f /= np.sqrt(np.sum(f**2, axis=1))[...,np.newaxis]

rawDescription: Parallel array manipulations in numpy

description: Parallel array manipulations in numpy


code: logger = logging.getLogger(__name__) # __name__ == '__main__'

rawDescription: Suspend the formating of the logger, then go back to it


rawDescription: Concatenate or print list elements with a trailing comma in Python


code:
for l in lines:
   pair = l.split(':', 1)
   if len(pair) == 2 and pair[0] == 'File':
        filename=pair[1].strip()
        break

rawDescription: What is this python function looking for?


code:
soup.root.contents[0].name
# u'level1'

rawDescription: Editing XML as a dictionary in python?

description: Editing XML as a dictionary in python


code: main()

rawDescription: I need to get my main function working

description: I need to get my main function working


rawDescription: new python pandas dataframe column based on value of variable, using function

description: New python pandas dataframe column based on value of variable, using function


Montreal city

osm_key: boundary

state: Quebec

osm_type: R

osm_value: administrative

country: Canada

type: Feature

type: Point

type: FeatureCollection

rawDescription: Python: Read several json files from a folder


code:
# Setup our various global variables
population_mean = 7
population_std_dev = 1
samples = 100
histogram_bins = 50

# And setup our figure.
from matplotlib import pyplot
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)

from numpy.random import normal
hist_data = normal(population_mean, population_std_dev, samples)
ax.hist(hist_data, bins=histogram_bins, normed=True, color="blue", alpha=0.3)

from statsmodels.nonparametric.kde import KDEUnivariate
kde = KDEUnivariate(hist_data)
kde.fit()

#kde.supprt and kde.density hold the x and y values of the KDE fit.
ax.plot(kde.support, kde.density, color="red", lw=4)

#Gaussian function - though you can replace this with something of your choosing later.
from numpy import sqrt, exp, pi
r2pi = sqrt(2*pi)
def gaussian(x, mu, sigma):
  return exp(-0.5 * ( (x-mu) / sigma)**2) / (sigma * r2pi)

#interpolation of KDE to produce a function.
from scipy.interpolate import interp1d
kde_func = interp1d(kde.support, kde.density, kind="cubic", fill_value=0)

rawDescription: Python: Overlap between two functions (PDF of kde and normal)


code:
def gen(n, k):
    for x in itertools.combinations(range(n), k):
        for y in itertools.product([-1,1], repeat=k):
            zero = [0] * n
            for a, b in zip(x, y):
                zero[a] = b
            yield zero

rawDescription: How to generate these vectors quickly in Python?

description: Generate these vectors quickly in Python


code:
def my_pop(l):
    return l[:-1]

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


code:
from time import sleep
from org.apache.pig.tools.pigstats import PigStatusReporter

@outputSchema('i:int')
def tester(foo):
    # Sleeps for a total of 3 minutes

    e = PigStatusReporter.getInstance()
    e.progress()
    sleep(60)
    e.progress()
    sleep(60)
    e.progress()
    sleep(60)
    e.progress()

    return 1

rawDescription: How do you report progress from a Python UDF (for Pig)?

description: Report progress from a Python UDF (for Pig)


code:
def calc(g):
    if g.iloc[0].lab_type == 'shot':
        return sum(g.value)
    else:
        return np.mean(g.value)
result = df.groupby(['patient_id', 'lab_type']).apply(calc)

rawDescription: Pandas: Aggregate differently based on group


code: rev_key = ndb.Key('Account', 'Sandy', 'Message', 'greeting', 'Revision', '2')

rawDescription: GAE Implications of NDB hierarchy and entity groups


rawDescription: How to change default path for "save the figure" in python?

description: Change default path for "save the figure" in python


code: all(isinstance(e, int) and e > 0 for e in [1,2,'joe'])

rawDescription: any() function in Python with a callback

description: Any() function in Python with a callback


rawDescription: Difference between np.random.seed() and np.random.RandomState()


code:
a = np.random.normal(1,.5,20)
np.percentile(a, (10, 90))
a.clip(*np.percentile(a, (10,90)))

rawDescription: Creating a normal with limits with variable standard deviation