code:
import datetime as dt
from bson import ObjectId
from uuid import UUID

class UTC(dt.tzinfo):
    ZERO = dt.timedelta(0)

    def utcoffset(self, dt):
        return self.ZERO

    def tzname(self, dt):
        return 'UTC'

    def dst(self, dt):
        return self.ZERO

UTC = UTC()
UUID_1_EPOCH = dt.datetime(1582, 10, 15, tzinfo=UTC)
UUID_TICKS_PER_SECOND = 10000000

def unix_time_to_uuid_time(dt):
    return int((dt - UUID_1_EPOCH).total_seconds() * UUID_TICKS_PER_SECOND)

def object_id_to_uuid(object_id):
    """
    Converts ObjectId to UUID

    :param object_id: some ObjectId
    :return: UUID
    """

    str_object_id = str(object_id)

    b = []
    for i in [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]:
        b.append(int(str_object_id[i:i+2], 16))

    generation_time = ObjectId(str_object_id).generation_time.astimezone(UTC)
    time = unix_time_to_uuid_time(generation_time)
    time |= (b[4] >> 6) & 0x3

    most_sig_bits = str(hex(0x1000 | time >> 48 & 0x0FFF
                            | time >> 16 & 0xFFFF0000
                            | time << 32))[9:]

    least_sig_bits = str(hex(2 << 62
                             | (b[4] & 0x3F) << 56 | (b[5] & 0xFF) << 48
                             | (b[6] & 0xFF) << 40 | (b[7] & 0xFF) << 32
                             | (b[8] & 0xFF) << 24 | (b[9] & 0xFF) << 16
                             | (b[10] & 0xFF) << 8 | b[11] & 0xFF))[2:]

    return UUID('%s-%s-%s-%s-%s' % (most_sig_bits[:8], most_sig_bits[8:12], most_sig_bits[12:16],
                               least_sig_bits[0:4], least_sig_bits[4:]))

rawDescription: Find documents in MongoDB by UUID (Convert ObjectId to UUID)


code: numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)

rawDescription: python dict to numpy structured array

description: Python dict to numpy structured array


code: ['Header', 'Want This']

rawDescription: How can I parse HTML with html5lib, and query the parsed HTML with XPath?

description: Parse HTML with html5lib, and query the parsed HTML with XPath


code:
def f1(a, b):
    a[b] = (a.get(b) or 0) + 1  # increment value iff key present else value=1
    return a                    # return mutated sequence

rawDescription: What is happening in this Python function?


code:
from sqlalchemy import TypeDecorator, Text

class CleanedHtml(TypeDecorator):
    impl = Text

    def process_bind_param(self, value, dialect):
        return clean_the_data(value)

rawDescription: Flask + SQLAlchemy - custom metaclass to modify column setters (dynamic hybrid_property)


code:
# And you can even set a linear range around zero
pyplot.xscale('symlog', linthreshx=20)

rawDescription: What is the difference between 'log' and 'symlog'?


rawDescription: Python: Elementwise comparison of same shaped arrays


code: params = [{'name': xxx, 'type': yyy, 'desc': zzz} for param in functionNode]

rawDescription: Dynamically building an "array of strcuts" in Python


code:
#-------------------------------------------------------------------------------
# Name:         treeYield.py
# Purpose:      traverse a complex datastructure and yield elements
#               that fit a given criteria
#
# Authors:      Michael Scott Cuthbert
#
# Copyright:    Copyright © 2012 Michael Scott Cuthbert
# License:      CC-BY
#-------------------------------------------------------------------------------
import types

class TreeYielder(object):
    def __init__(self, yieldValue = None):
        '''
        `yieldValue` should be a lambda function that
        returns True/False or a function/method call that
        will be passed the value of a current attribute
        '''
        self.currentStack = []
        self.yieldValue = yieldValue
        self.stackVals = []
        t = types
        self.nonIterables = [t.IntType, t.StringType, t.UnicodeType, t.LongType,
                             t.FloatType, t.NoneType, t.BooleanType]

    def run(self, obj, memo = None):
        '''
        traverse all attributes of an object looking
        for subObjects that meet a certain criteria.
        yield them.

        `memo` is a dictionary to keep track of objects
        that have already been seen

        The original object is added to the memo and
        also checked for yieldValue
        '''
        if memo is None:
            memo = {}
        self.memo = memo
        if id(obj) in self.memo:
            self.memo[id(obj)] += 1
            return
        else:
            self.memo[id(obj)] = 1

        if self.yieldValue(obj) is True:
            yield obj

        ### now check for sub values...
        self.currentStack.append(obj)

        tObj = type(obj)
        if tObj in self.nonIterables:
            pass
        elif tObj == types.DictType:
            for keyX in obj:
                dictTuple = ('dict', keyX)
                self.stackVals.append(dictTuple)
                x = obj[keyX]
                for z in self.run(x, memo=memo):
                    yield z
                self.stackVals.pop()

        elif tObj in [types.ListType, types.TupleType]:
            for i,x in enumerate(obj):
                listTuple = ('listLike', i)
                self.stackVals.append(listTuple)
                for z in self.run(x, memo=memo):
                    yield z
                self.stackVals.pop()

        else: # objects or uncaught types...
            ### from http://bugs.python.org/file18699/static.py
            try:
                instance_dict = object.__getattribute__(obj, "__dict__")
            except AttributeError:
                ## probably uncaught static object
                return

            for x in instance_dict:
                try:
                    gotValue = object.__getattribute__(obj, x)
                except: # ?? property that relies on something else being set.
                    continue
                objTuple = ('getattr', x)
                self.stackVals.append(objTuple)
                try:
                    for z in self.run(gotValue, memo=memo):
                        yield z
                except RuntimeError:
                    raise Exception("Maximum recursion on:\n%s" % self.currentLevel())
                self.stackVals.pop()

        self.currentStack.pop()

    def currentLevel(self):
        currentStr = ""
        for stackType, stackValue in self.stackVals:
            if stackType == 'dict':
                if isinstance(stackValue, str):
                    currentStr += "['" + stackValue + "']"
                elif isinstance(stackValue, unicode):
                    currentStr += "[u'" + stackValue + "']"
                else: # numeric key...
                    currentStr += "[" + str(stackValue) + "]"
            elif stackType == 'listLike':
                currentStr += "[" + str(stackValue) + "]"
            elif stackType == 'getattr':
                currentStr += ".__getattribute__('" + stackValue + "')"
            else:
                raise Exception("Cannot get attribute of type %s" % stackType)
        return currentStr

rawDescription: Recursively dir() a python object to find values of a certain type or with a certain value


code:
mask = totals['dirty']+totals['swap'] > 1e3; mask
result = mask.loc[mask]; result
result.index.get_level_values('region_type').unique()

rawDescription: Is there a better way to collect unique index values in pandas?


code:
(df.shift() != df).any(axis=1)
df[(df.shift() != df).any(axis=1)]

rawDescription: How does pandas.shift really work?

description: How does pandas.shift really work


code:
from collections import defaultdict
data = (['aaron distilled ', 'alcohol', '5'],
['aaron distilled ', 'gin', '2'],
['aaron distilled ', 'beer', '6'],
['aaron distilled ', 'vodka', '9'],
['aaron evicted ', 'owner', '1'],
['aaron evicted ', 'bum', '1'],
['aaron evicted ', 'deadbeat', '1'])
result = defaultdict(list)
for key, *values in data:
   result[key].extend(values)

result

rawDescription: Merging repeated items in a list into a python dictionary


code: split_into_parts(1, 3)

rawDescription: Numpy method to split a real number into n-equal parts?


code: mongodump

rawDescription: How to share database created by MongoDB?

description: Share database created by MongoDB


code: priority = my_model.priority

rawDescription: Dynamic field calculations in Django

description: Dynamic field calculations in Django


code:
def string_distance(A, B, index_b):
    '''Count how many substitutions are required to
    change string A into the string beginning at
    index_b in string B.'''
    return 999 # FIXME

def subsequence(A, B, n):
    '''Search for the substring of B that is equal to
    A except for the minimal number of substitutions,
    and return a tuple of the index of that substring
    in B and the number of substitutions required,
    unless there is no such substring with n or fewer
    substitutions, in which case return the tuple of
    (-1, -1).'''
    answer_distance = -1
    answer_index = -1
    index = 0
    while index <= len(B) - len(A):
        substitutions_required = string_distance(A, B, index)
        # Does a match at this location need n or fewer substitutions?
        is_close_enough = False # FIXME
        # Is a match at this location better than the best match so far?
        is_better = False # FIXME
        if is_close_enough and is_better:
            answer_distance = substitutions_required
            answer_index = index
        index += 1
    return answer_index, answer_distance

rawDescription: Find Substring of A in B with n mistakes


code:
def __init__(self, *args, **kwargs):
    try:
        self.custom_name = kwargs["custom_name"]
        del kwargs["custom_name"]
    except:
        self.custom_name = None

    # do your stuff...

rawDescription: Python: passing an optional named variable with *args **kwargs


rawDescription: Memory efficient padding a list

description: Memory efficient padding a list


code:
def create_global_function():
    global foo
    def foo(): return 'bar'

foo
create_global_function()
foo
foo()
class ClassWithGlobalFunction:
    global spam
    def spam(): return 'eggs'
    def method(self):
        global monty
        def monty(): return 'python'

spam
spam()
monty
ClassWithGlobalFunction().method()
monty()

rawDescription: How to define global function in Python?

description: Define global function in Python


code:
picklevars = []
picklenames = ['object1', 'object2']
for picklename in picklenames:
    with open(pickle_name, 'r') as pickle_fp:
        picklevars.append(cPickle.load(pickle_fp))

rawDescription: how to load pickled objects into a list of empty variables?

description: Load pickled objects into a list of empty variables


code: numbers = [int(n) for n in input().split()]

rawDescription: Reading a line of integers in Python

description: Reading a line of integers in Python


code:
for n in queue_info:
      run(n['task']['name'])

rawDescription: How to fetch python output and get to dynamic massive

description: Fetch python output and get to dynamic massive


code:
x = UserDepartment(user_id=n, department_id=m, is_manager=False)
db.session.add(x)
db.session.commit()

rawDescription: How to add value to join table with SQLAlchemy?

description: Add value to join table with SQLAlchemy


rawDescription: Vectorized element assignment involving comparisons between matrices in Numpy


code:
import math
math.log(40000, 2)

rawDescription: Web scraping: Expand/contract bounding box depending on results


code:
FNV1A_64_INIT = 0xcbf29ce484222325
import pyhash
hasher = pyhash.fnv1a_64()
hasher('1', seed=FNV1A_64_INIT)
_ == 0xaf63ac4c86019afc

rawDescription: FNV1A_64 don't match

description: FNV1A_64 don't match


code:
from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Split JSON file in equal/smaller parts with Python


code:
path = os.path.dirname("/path/to/file.mp3")
target = "test.xml"
top = "/"
while True:
    if os.path.isfile(os.path.join(path,target)):
        #found
        break
    if path==top:   #alternative check for root dir: if os.path.dirname(path)==path
        #not found
        break
    path=os.path.dirname(path)

rawDescription: Pythonic way to find the file with a given name closest to a specific directory location


code: print('{0} complete (down: {1} kb/s up: {2} kb/s {3} peers: {4} {5}'.format('state.progress * 100', 'state.download_rate / 1000', 'state.upload_rate / 1000', 'state.num_peers', 'state_str[state.state]'))

rawDescription: What does tuple index out of range mean?

description: What does tuple index out of range mean


code:
im = ax_lst.imshow(T, interpolation='nearest',
                        origin='bottom',
                        aspect='auto',
                        vmin=np.min(T) + .01, # so 0 doesn't blow up the log
                        vmax=np.max(T),
                        cmap='hot',extent=[0,1,0,1],
                        norm=matplotlib.colors.LogNorm(clip=True),)

rawDescription: matplotlib imshow is not updated

description: Matplotlib imshow is not updated


code:
excludes = ['.git','.svn']
command = ['egrep','-r']
for e in excludes:
    command.append('--exclude=*%s*'%e)
command += ["text","~/directory"]
subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]

rawDescription: Python subprocess to Bash: curly braces

description: Python subprocess to Bash: curly braces


code:
if answer == "Y":
    return True
elif answer == "N":
    return False
else:
    True     # Notice that the function is NOT returning this True.

rawDescription: Function Recursion

description: Function Recursion


code:
mask = np.array(x_y_pairs_to_activate).transpose()
grid[mask] = 1

rawDescription: How can I convert a list of tuples into a mask?

description: Convert a list of tuples into a mask


code:
config = ConfigParser.RawConfigParser()
config.read('configs.ini')
items = config.items('section')
items

rawDescription: Python argparser. List of dict in INI

description: Python argparser. List of dict in INI


code: df.groupby('A').filter(lambda x: (x['B'] != 't').all())

rawDescription: gropuby and remove specified groups in pandas DataFrame

description: Gropuby and remove specified groups in pandas DataFrame


code:
class Player(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

rawDescription: Django: How to write groups and where those groups live?


code:
def _loadComplete(self):
    page = self.page()
    doc = page.currentFrame().documentElement()
    link = doc.findFirst('#link-signup')
    if link and not link.isNull():
        self.load(QUrl.fromEncoded(link.attribute('href').toAscii()))

rawDescription: PyQt4 does not redirect me to the next page


code:
import numpy as np
np.r_[np.arange(5), np.arange(1, 4)]
np.r_[1, 2, :5]
np.r_[:5]

rawDescription: Custom slicing in numpy arrays (get specific elements, then every n-th) possible?


code:
JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])

rawDescription: I want to allow html in my own text but that text is being escaped


code: cmds.xform(item, m = my_new_matrix)

rawDescription: Maya Python API Scaling a matrix about another matrix


rawDescription: Python: A complete list of modules

description: Python: A complete list of modules


code:
from collections import defaultdict
d = defaultdict(list)
d["word1"].append(1)
d["word2"].append(2)
d["word2"].append(3)
d

rawDescription: Python's append() only allows unique items in a list?


rawDescription: Python - removing xml tag in an element

description: Python - removing xml tag in an element


code:
import psutil, subprocess, random, os, zipfile, shutil, clr, sys, pandas

def initialSetup(pathPowerBI):
    sys.path.append(pathPowerBI)

    #required Analysis Services assemblies
    clr.AddReference("Microsoft.PowerBI.Amo.Core")
    clr.AddReference("Microsoft.PowerBI.Amo")
    clr.AddReference("Microsoft.PowerBI.AdomdClient")

    global AMO, ADOMD
    import Microsoft.AnalysisServices as AMO
    import Microsoft.AnalysisServices.AdomdClient as ADOMD

def restorePowerPivot(excelName, pathTarget, port, pathPowerBI):
    #create random folder
    os.chdir(pathTarget)
    folder = os.getcwd()+str(random.randrange(10**6,10**7))
    os.mkdir(folder)

    #extract PowerPivot model (abf backup)
    archive=zipfile.ZipFile(excelName)
    for member in archive.namelist():
        if ".data" in member:
            filename = os.path.basename(member)
            abfname = os.path.join(folder, filename)+".abf"
            source = archive.open(member)
            target = file(os.path.join(folder, abfname), 'wb')
            shutil.copyfileobj(source, target)
            del target
    archive.close()

    #start the cmd.exe process to get its PID
    listPIDpre = [proc for proc in psutil.process_iter()]
    process = subprocess.Popen('cmd.exe /k', stdin=subprocess.PIPE)
    listPIDpost = [proc for proc in psutil.process_iter()]
    pid = [proc for proc in listPIDpost if proc not in listPIDpre if "cmd.exe" in str(proc)][0]
    pid = str(pid).split("=")[1].split(",")[0]

    #msmdsrv.ini
    msmdsrvText='''<ConfigurationSettings>
       <DataDir>{0}</DataDir>
       <TempDir>{0}</TempDir>
       <LogDir>{0}</LogDir>
       <BackupDir>{0}</BackupDir>
       <DeploymentMode>2</DeploymentMode>
       <RecoveryModel>1</RecoveryModel>
       <DisklessModeRequested>0</DisklessModeRequested>
       <CleanDataFolderOnStartup>1</CleanDataFolderOnStartup>
       <AutoSetDefaultInitialCatalog>1</AutoSetDefaultInitialCatalog>
       <Network>
          <Requests>
             <EnableBinaryXML>1</EnableBinaryXML>
             <EnableCompression>1</EnableCompression>
          </Requests>
          <Responses>
             <EnableBinaryXML>1</EnableBinaryXML>
             <EnableCompression>1</EnableCompression>
             <CompressionLevel>9</CompressionLevel>
          </Responses>
          <ListenOnlyOnLocalConnections>1</ListenOnlyOnLocalConnections>
       </Network>
       <Port>{1}</Port>
       <PrivateProcess>{2}</PrivateProcess>
       <InstanceVisible>0</InstanceVisible>
       <Language>1033</Language>
       <Debug>
          <CallStackInError>0</CallStackInError>
       </Debug>
       <Log>
          <Exception>
             <CrashReportsFolder>{0}</CrashReportsFolder>
          </Exception>
          <FlightRecorder>
             <Enabled>0</Enabled>
          </FlightRecorder>
       </Log>
       <AllowedBrowsingFolders>{0}</AllowedBrowsingFolders>
       <ResourceGovernance>
          <GovernIMBIScheduler>0</GovernIMBIScheduler>
       </ResourceGovernance>
       <Feature>
          <ManagedCodeEnabled>1</ManagedCodeEnabled>
       </Feature>
       <VertiPaq>
          <EnableDisklessTMImageSave>0</EnableDisklessTMImageSave>
          <EnableProcessingSimplifiedLocks>1</EnableProcessingSimplifiedLocks>
       </VertiPaq>
    </ConfigurationSettings>'''

    #save ini file to disk, fill it with required parameters
    msmdsrvini = open(folder+"\\msmdsrv.ini", "w")
    msmdsrvText = msmdsrvText.format(folder, port, pid) #{0},{1},{2}
    msmdsrvini.write(msmdsrvText)
    msmdsrvini.close()

    #run AS engine inside the cmd.exe process
    initString = "\"{0}\\msmdsrv.exe\" -c -s \"{1}\""
    initString = initString.format(pathPowerBI.replace("/","\\"),folder)
    process.stdin.write(initString + " \n")

    #connect to the AS instance from Python
    AMOServer = AMO.Server()
    AMOServer.Connect("localhost:{0}".format(port))

    #restore database from PowerPivot abf backup, disconnect
    AMORestoreInfo=AMO.RestoreInfo(os.path.join(folder, abfname))
    AMOServer.Restore(AMORestoreInfo)
    AMOServer.Disconnect()

    return process

rawDescription: Extracting raw data from a PowerPivot model using Python


code:
with requests.Session() as s:
    s.post(sub_url, data=form1)
    r = (s.get("https://compare.switchon.vic.gov.au/energy_questionnaire"))
    s.post("https://compare.switchon.vic.gov.au/energy_questionnaire/submit",
           data=form2)
    r = s.get("https://compare.switchon.vic.gov.au/service/offers")
    print(r.json())

rawDescription: Multi POST query (session mode)

description: Multi POST query (session mode)


code:
message = """\
This is a multi-line message.

 + Source lines match string lines 1:1.
 + No '\\n' noise.
"""

rawDescription: Usage of """ instead of " on variables with long text inside


code:
new_l = []
for idx, ent in enumerate(l):
   if (ent > zmax) and (idx > 0):
      cnt = idx - 1
      while l[cnt] > zmax and cnt > 0:
          cnt -= 1
      new_val = l[cnt] if l[cnt] <= zmax else l[idx] # If we didn't find a good index to swap with, keep the original
      new_l.append(new_val)
   else:
      new_l.append(ent)

rawDescription: pythonic way to replace values in an array over a limit with neighbour's value

description: Pythonic way to replace values in an array over a limit with neighbour's value


code:
import numpy as np

n = input()
a = np.arange(1, n)
step = 2
while step <= len(a):
    mask = np.ones(len(a), dtype=bool)
    ind = np.arange(step-1,len(a), step)
    mask[ind] = False
    a = a[mask]
    step += 1
print(a)

rawDescription: Performance issue with Python list operations


code:
import RPi.GPIO as GPIO
from threading import Event  # We'll use it like time.sleep, but we can interrupt it.
GPIO_nek=11
GPIO_schouder=12
GPIO_rug1=8
GPIO_ONOFF=18
interval1 = 2
interval2 = 4
GPIO.setup(GPIO_ONOFF, GPIO.IN, pull_up_down=GPIO.PUD_UP)

done = False  # loop control
timer = Event()
def quit_loop():  # Called by inbuilt threaded interrupt
    global done
    done = True
    timer.set()  # Interrupt the waiting

GPIO.add_event_detect(GPIO_ONOFF, GPIO.FALLING, callback=quit_loop, bouncetime=300) # Setup interrupt to call quit_loop

rawDescription: Raspberry Pi Python pause a loop sequence, when button pushed


rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
# in my case, when it had '\n', I called it a new paragraph,
# like a collection of sentences
paragraphs = [p for p in text.split('\n') if p]
# and here, sent_tokenize each one of the paragraphs
for paragraph in paragraphs:
    sentences = tokenizer.tokenize(paragraph)

rawDescription: nltk sentence tokenizer, consider new lines as sentence boundary

description: Nltk sentence tokenizer, consider new lines as sentence boundary


code:
for i in range(1,6):  # range(a,b) gives [a,b)
    my_dict[i] = 'apple'

rawDescription: Assign a Range of Numbers to a Single Key with Dictionaries


rawDescription: Pandas - min of a column for each value in other


rawDescription: Random platform generator in pygame

description: Random platform generator in pygame


code:
from __future__ import print_function

import pandas as pd

df = pd.read_csv('data.csv', sep=',', usecols=['Sample', 'Rel. Abundance', 'Formula'])

# pivot input data
pvt = df.pivot(index='Sample', columns='Formula', values='Rel. Abundance').fillna(0).reset_index().set_index('Sample')
print(pvt)

# normalize data
norm = pvt.div(pvt.sum(axis=1), axis=0)

# check sum of rows
norm['sum'] = norm.sum(axis=1)

# output
print(norm)

rawDescription: Python Normalising a list of numbers failing/Pandas normalise row by row


code:
from collections import Counter
lst = [obj1, obj2, obj2, obj2, obj3, obj4, obj4]
counter = Counter(lst)

rawDescription: Creating a dictionary that maps an object to the amount of times it occurs in a list? In Python


code: requests.post('http://example.com/welcome', data={'password': SOME_PASSWORD, 'user': SOME_USERNAME})

rawDescription: How to send a post request with data using python requests module?

description: Send a post request with data using python requests module


code: {'version': '1.0', 'OP': 'ihuston'}

rawDescription: Can matplotlib add metadata to saved figures?


rawDescription: python shutil: only copy part of the file

description: Python shutil: only copy part of the file


rawDescription: Is there a Pythonic way to close over a loop variable?


code:
selection = raw_input("Enter your selection:")
if selection == "1":
    Random(100)
elif selection == "2":
    Random(1000)
elif selection == "3":
    Random(10000)
elif selection == "4":
    Random(100000)
elif selection == "5":
    exit()

rawDescription: Python Raspberry PI Guessing Game(Function call not working)


code:
def Mwindow_stayontop(self, event):
    CFG["AlwOnTop"] = 1 - CFG["AlwOnTop"]
    self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE | CFG["AlwOnTop"]*wx.STAY_ON_TOP)

rawDescription: Simplify the changing of this binary variable


code: [{'credit': 5, 'score': 60, 'class': 'A01', 'subject': 'math'}, {'credit': 5, 'score': 70, 'class': 'A01', 'subject': 'music'}]

rawDescription: How to compare with other json objects's value

description: Compare with other json objects's value


code:
import itertools
import pytest

numbers = [1,2,3,4,5]
vowels = ['a','e','i','o','u']
consonants = ['x','y','z']

@pytest.mark.parametrize('number,vowel,consonant',
    itertools.product(numbers, vowels, consonants)
)
def test(number, vowel, consonant):
    pass

rawDescription: pytest: parameterized test with cartesian product of arguments

description: Pytest: parameterized test with cartesian product of arguments


code:
libc.strfry
libc.strfry('hello')
libc.strfry.restype = ctypes.c_char_p
libc.strfry('hello')
libc.strfry('hello')
libc.strfry('hello')

rawDescription: C# Return Type Issue

description: C# Return Type Issue


code:
import json
json.dumps(data, indent=4)

rawDescription: Convert following data to JSON format in python


code:
#!/usr/bin/env python
import urllib2
from lxml import html

page = urllib2.urlopen('http://stackoverflow.com/q/11939631')
doc = html.parse(page).getroot()
for tr in doc.cssselect('#question table > tr'):
    for td in tr.iterchildren('td'):
        print(td.text_content()) # process td

rawDescription: Is there an easy way to parse an HTML document and remove everything except a particular table?


rawDescription: the connection between django project's urls.py and views.py

description: The connection between django project's urls.py and views.py


rawDescription: Filter not in Python

description: Filter not in Python


code:
# Take the list as an arg and pop the last element off
def bar(numbrs):  # method gets a value. In this case the value is a reference to a list
    numbrs.pop()  # call a method on that object

rawDescription: Python local variable being changed by another method


code:
from jnius import autoclass
PythonActivity = autoclass('org.renpy.android.PythonActivity')
View = autoclass('android.view.View')

rawDescription: Kivy: dimming Android navigation buttons


code:
api.add_resource(HelloWorld,
    '/',
    '/hello')

rawDescription: How to add parameters to flask-restful in python?

description: Add parameters to flask-restful in python


code: var = val

rawDescription: Counting from 1 to infinity without assignment


code:
import nt
sorted(nt.environ.keys())

rawDescription: Why python uppercases all environment variables in windows


code:
sentiment_analyzer.analyze('not the best')
Sentiment(polarity=1.0, subjectivity=0.3)

rawDescription: Why is not TextBlob using / detecting the negation?


code:
str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg"
str = str.replace("_s.jpg","_m.jpg")

rawDescription: python search and replace operation

description: Python search and replace operation


code: import string

rawDescription: python create method object for string.Method

description: Python create method object for string.Method


rawDescription: How can I solve multivariable linear equation in python?

description: Solve multivariable linear equation in python


rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function


code: order = 'x,y,t'  # this is specified outside your function

rawDescription: eval evaluates to a tuple

description: Eval evaluates to a tuple


code:
print(",".join([x.strip(",") for x in r.findall(s)]))
1,' unchanged 1'," unchanged  2 ",2.009,-2e15,3

rawDescription: python reg ex to include missing commas

description: Python reg ex to include missing commas


code:
keys = ('c', 'd', 'e')
[{k: d[k] for k in keys} for d in List]

rawDescription: How to iterate over particular keys in a dict to get values

description: Iterate over particular keys in a dict to get values


code:
words = [u'dose rate', u'object', u'dose', u'rate', u'computation']
remove_comprising(words)

rawDescription: How to remove inception words in list?

description: Remove inception words in list


code: varespec['size'] = size

rawDescription: Pandas apply with argument that varies by row


code:
FILE_NAME=0
FUNC_NAME=1
BOOL_VALUE=2

db = [
    ["file_name1", "func_name1", 0],
    ["file_name1", "func_name2", 1],
    ["file_name2", "func_name1", 0],
    ["file_name3", "func_name1", 1],
]

list_fn1 = [grp for grp in db if grp[FILE_NAME] == "file_name1"]

sum_fn1 = sum([e[BOOL_VALUE] for e in list_fn1])

rawDescription: Simple table manipulation using python

description: Simple table manipulation using python


rawDescription: How to find the set of indices where two vectors have equal elements in Python

description: Find the set of indices where two vectors have equal elements in Python


code:
import git
def lsremote(url):
    remote_refs = {}
    g = git.cmd.Git()
    for ref in g.ls_remote(url).split('\n'):
        hash_ref_list = ref.split('\t')
        remote_refs[hash_ref_list[1]] = hash_ref_list[0]
    return remote_refs

rawDescription: `git ls-remote` in GitPython

description: `git ls-remote` in GitPython


code:
import doctest
import __future__
import sys
def foo():
    """
    >>> 1 / 2
    0.5
    """
doctest.testmod(sys.modules['__main__'])
doctest.testmod(sys.modules['__main__'], extraglobs={'division': __future__.division})

rawDescription: Doctest not recognizing __future__.division


code:
def count(mylist):
    newlist = []
    for i in mylist:
        if i not in newlist:
            newlist.append(i)
    return len(newlist)

rawDescription: Count different numbers in list python

description: Count different numbers in list python


code:
d = {'A':1, 'B':2, 'C':4}

import itertools
for a, b, c in itertools.combinations_with_replacement(sorted(d, key=d.get), 3):
    if d[a] + d[b] == d[c]:
        print(a,b,c)

rawDescription: Comparing 2 values in dict to all other values


code:
config = {}
execfile("my_config", config)
myvar = config.get("myvar", "default_value")

rawDescription: python: simple way to input python data from file

description: Python: simple way to input python data from file


rawDescription: Change panel with button wxpython

description: Change panel with button wxpython


code:
parents  = [   2,     3,           1,       5,        4,          7,          8,          9,         6,        10     ]
children = [ [4,5],  [0,11],     [6,10],  [1,7],    [8,9],     [12,13],    [14,15],    [16,17],   [18,19],   [20,21]  ]

generation=(lambda c:list(map((lambda f,m={}:lambda x:m[x]if x in m else m.setdefault(x,f(f,x)))(lambda g,i:max(g(g,j)+1for j in c[i])if i in c else 0),parents)))(dict(zip(parents,children)))

print(generation)

rawDescription: list of branches sorting

description: List of branches sorting


code:
df_new2 = pd.read_sql_table("db_table",engine)
df_new2.dtypes

rawDescription: python pandas parse_dates column wildcard for sqlalchemy in pandas 0.14.1?

description: Python pandas parse_dates column wildcard for sqlalchemy in pandas 0.14.1


code:
from scipy import stats
import matplotlib.pyplot as plt

nsample=500

#create list of random variables
x=stats.t.rvs(100, size=nsample)

# Calculate quantiles and least-square-fit curve
(quantiles, values), (slope, intercept, r) = stats.probplot(x, dist='norm')

#plot results
plt.plot(values, quantiles,'ob')
plt.plot(quantiles * slope + intercept, quantiles, 'r')

#define ticks
ticks_perc=[1, 5, 10, 20, 50, 80, 90, 95, 99]

#transfrom them from precentile to cumulative density
ticks_quan=[stats.norm.ppf(i/100.) for i in ticks_perc]

#assign new ticks
plt.yticks(ticks_quan,ticks_perc)

#show plot
plt.grid()
plt.show()

rawDescription: Python equivalent for MATLAB's normplot?

description: Python equivalent for MATLAB's normplot


code: totalSeconds = sec + min*60 + hr*3600

rawDescription: Define a python function time2sec with three optional keyword arguments hour minute and second


code:
for x in a:
    x += 1

rawDescription: Grasping the basics of in-place operations


code:
def condition():
    pass # implement some condition, returning True, or False

while condition():
   a_function()

rawDescription: Repeating a part of code in python 3.4.4


code:
while not done:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:
            mousex, mousey = event.pos
            if mousex < wx_coord:
                angle += 10

rawDescription: Pygame: Mouse Specific Axis Detection

description: Pygame: Mouse Specific Axis Detection


code:
main_menu = section("Main Menu", [
    section("Product Line 1", [
        TextLink("/products/...", "A product"),
        ...
    ]),
    section(...),
])

rawDescription: Polymorphic macros in Jinja

description: Polymorphic macros in Jinja


rawDescription: arrange the elements in the sorted list so that all the redundant elements are at left/right side of the list

description: Arrange the elements in the sorted list so that all the redundant elements are at left/right side of the list


code:
filter_array = ['hi', 'friend']
col_names = ['nice', 'to', 'meet', 'you' + 'friend']
[c for c in col_names if all([f not in c for f in filter_array])]

rawDescription: Pythonic way of filtering out a list of strings from another list of strings


rawDescription: counting objects using scikit-image label

description: Counting objects using scikit-image label


rawDescription: How to find the number of days between two dates for dataframe manipulation

description: Find the number of days between two dates for dataframe manipulation


code:
list_of_strings = map(lambda l: '{}{}'.format(*l), result)
print('\n'.join(list_of_strings))

rawDescription: Prefixing the results of string.split with the substring indices of each result


code: uniform(lower_limit, upper_limit) if i > some_value else i

rawDescription: Replace values in a 2D array with different random numbers


code:
from collections import namedtuple
Pruefer = namedtuple("Pruefer", "ident maxNum name")
pr = Pruefer(1,2,3)
pr.ident
pr.maxNum
pr.name
hash(pr)

rawDescription: Python: Quick and dirty datatypes (DTO)

description: Python: Quick and dirty datatypes (DTO)


code:
for row in gp.searchcursor( fc ):
    ##grab field values
    fcValue = fields.getvalue(Atts)
    gp.AddMessage(fcValue)

rawDescription: Adding Values to an Array and getting distinct values using Python


code:
recepients = ["user1@hotmailcom", "user2@hotmail.com"]
msg['To'] = ', '.join(recepients)

rawDescription: Provide multiple email recepients in python script


code:
import settings
from retrying import retry

@retry(stop_max_attempt_number=settings.STOP_MAX_ATTEMPT_NUMBER,
       wait_fixed=settings.WAIT_FIXED)
def some_function(self):
    return True

rawDescription: Dynamic parameters with Python's retry decorator


code: df[df.Name.isin(["ALEX", "KIM"])]

rawDescription: Using 'or' in a Dataframe

description: Using 'or' in a Dataframe


code:
class Favorite(Base):
    __tablename__ = "favorites"
    user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
    restaurant_id = Column(Integer, ForeignKey("restaurants.id"), primary_key=True)

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    ...
    favorites = relationship("Restaurant", secondary=Favorite.__table__)

class Restaurant(Base):
    __tablename__ = "restaurants"
    id = Column(Integer, primary_key=True)
    ...

rawDescription: How create a favorites table that connects to a customer mysql


code:
from django.core.exceptions import PermissionDenied

def some_view(request):
    if request.REQUEST.get('key') == 'value':
        if not request.user.is_authenticated():
            raise PermissionDenied
        ...

rawDescription: Python/Django - HTTP authentication

description: Python/Django - HTTP authentication


code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException

ytlink = 'https://www.youtube.com/channel/UCUvoulvwzCnUVk7yoduI_Gw/videos'
hrefs = "a.yt-uix-sessionlink.yt-uix-tile-link.spf-link.yt-ui-ellipsis.yt-ui-ellipsis-2"
ajax= "button[data-uix-load-more-href]"
dr = webdriver.PhantomJS()
dr.get(ytlink)

while True:
    try:
        load_mode_b = dr.find_element_by_css_selector(ajax)
        load_mode_b.click()
    except StaleElementReferenceException as e:
        print(e)
    except NoSuchElementException as e:
        print(e)
        break

rawDescription: Python expanding YouTube uploads

description: Python expanding YouTube uploads


code:
def save_object(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

# sample usage
save_object(company1, 'company1.pkl')

rawDescription: Saving an Object (Data persistence in Python)


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

rawDescription: Customize the Django settings.py file depending on the OS


rawDescription: When will numpy copy the array when using reshape()


rawDescription: Django objects.all() method return my list in string format (with sqlite)


code:
square = (upper_left_x, upper_left_y, lower_right_x, lower_right_y)
center = (x, y)

if upper_left_x <= x <= lower_right_x and upper_left_y <= y <= lower_right_y:
    return 0 # point in square
elif upper_left_x <= x <= lower_right_x: # on vertical line
    return min(upper_left_y -y, lower_right_y - y)
elif upper_left_y <= y <= lower_right_y: # on horizontal line
    return min(upper_left_x -x, lower_right_x - x)
else:
    points = []
    for x in (upper_left_x, lower_right_x):
        for y in (upper_left_y, lower_right_y):
            points.append((x,y))
    return min([distance.euclidean((x,y), p) for p in points])

rawDescription: How to detect the nearest square to the image center points?

description: Detect the nearest square to the image center points


code: f = [x[2][1] for x in e]

rawDescription: How to get a vector from a list in list in python?

description: Get a vector from a list in list in python


code: import seaborn

rawDescription: Why are my python plots not styled like modern ggplots?


code:
Process.py
import subprocess
import xml.etree.ElementTree as ElementTree

hdfsCatProcess = subprocess.Popen(
        ['hdfs', 'dfs', '-cat', '/pythonAppConf.xml'],
        stdout=subprocess.PIPE)
pythonAppConfXmlTree = ElementTree.parse(hdfsCatProcess.stdout)
matchString = pythonAppConfXmlTree.find('./matchString').text.strip()

def match(key):
    return key == matchString

rawDescription: MapReduce how to allow Mapper to read an xml file for lookup


code:
import requests
from bs4 import BeautifulSoup

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.xossip.com/showthread.php?t=1384077&page=' + str(page)
        sourcecode= requests.get(url)
        plaintext = sourcecode.text
        soup = BeautifulSoup(plaintext)

        for tag in soup.findAll('img'):
            link = tag.get('src')  # get the link

            # Check if the tag is in expect format
            del tag['src']
            if tag.attrs != {';': '', 'alt': '', 'border': '0'}:
                continue

            filename = link.strip('/').rsplit('/', 1)[-1]  # to get the correct file name

            image = requests.get(link).content  # use requests to get the content of the images
            with open(filename, 'wb') as f:
                f.write(image)  # write the image into a file

        page += 1
spider(1)

rawDescription: How do I scrap specific images (excluding thumbnails,icons,etc.) from forums using Beautiful soup

description: Scrap specific images (excluding thumbnails,icons,etc.) from forums using Beautiful soup


code:
from collections import Counter
theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
newList = Counter(theList)
newList['blue']

rawDescription: Python - Access contents of list after applying Counter from collections module


code: on_release: root.current = 'game';game.serve_ball()

rawDescription: How to display game on the screen?

description: Display game on the screen


code:
import pandas as pd
df = pd.DataFrame({'count': [2, 2, 0, 2, 3, 2, 1, 0, 1]},
                  index=[u'2015-09-28', u'2015-09-29', u'2015-09-30', u'2015-10-01',
                         u'2015-10-02', u'2015-10-05', u'2015-10-06', u'2015-10-07',
                         u'2015-10-08'])

mask = (df['count'] == 0)
df['groupno'] = mask.cumsum()
# Remove the rows where the count is 0
df = df.loc[~mask]
# Make the index a column so we can use 'index':['first', 'last'] to find the
# first and last date in each group.
df = df.reset_index()
result = df.groupby('groupno').agg({'index':['first', 'last'], 'count':'sum'})
result.columns = result.columns.droplevel(0)
result = result.rename(columns={'sum':'totalcount'})

rawDescription: group data ranges by column value not zero

description: Group data ranges by column value not zero


code: print(repr({'company_code': u'ha'}))

rawDescription: Not able to parse a json post from javascript in Python


code: my_string = 'x string'

rawDescription: In programming, why are escape sequences for regex and escape sequences for string literals different?


code:
with open('myfile.txt', 'rb+') as f:
    for line_number, line in enumerate(f):
        if is_the_right_line(line):
            f.seek(FIXED_LINE_LENGTH * line_number)
            f.write(new_line)

rawDescription: python replace random line in large file

description: Python replace random line in large file


code:
from dateutil import tz
est = tz.gettz('America/New_York')
start = start.astimezone(est)
start

rawDescription: Determine start and end time of current day (UTC -> EST -> UTC) ; Python


code:
import itertools
import re
s = """hi my name is 'Ryan' and I like to 'program' in "Python" the best"""
c = itertools.count(1)
replaced = re.sub(r'([\'"])(.*?)\1', lambda m: '{0}{{{1}}}{0}'.format(m.group(1), next(c)), s)
print(replaced)

rawDescription: regex sub with pattern reference

description: Regex sub with pattern reference


code:
import threading
import queue

class Worker(threading.Thread):
    def __init__(self, q, other_arg, *args, **kwargs):
        self.q = q
        self.other_arg = other_arg
        super().__init__(*args, **kwargs)
    def run(self):
        while True:
            try:
                work = self.q.get(timeout=3)  # 3s timeout
            except queue.Empty:
                return
            # do whatever work you have to do on work
            self.q.task_done()

q = queue.Queue()
for ptf in b:
    q.put_nowait(ptf)
for _ in range(20):
    Worker(q, otherarg).start()
q.join()  # blocks until the queue is empty.

rawDescription: Threading queue working example

description: Threading queue working example


code:
my_transformed_list2 = map(lambda s: s[-1], j)
concatenated2 = ''.join(my_transformed_list2)

rawDescription: How to concatenate bytes together

description: Concatenate bytes together


code:
from Crypto.Random import random

def generate_auth_token():
    """ Generate a 32-char alnum string. 190 bits of entropy. """
    alnum = ''.join(c for c in map(chr, range(256)) if c.isalnum())
    return ''.join(random.choice(alnum) for _ in range(32))

rawDescription: How do I generate a cryptographically secure alphanumeric string in Python?

description: Generate a cryptographically secure alphanumeric string in Python


code:
def isTriangle(sides):
    smallest,medium,biggest = sorted(sides)
    return smallest+medium>=biggest and all(s>0 for s in sides)

rawDescription: Logic of triangle inequality as python conditionals?


rawDescription: How do I include an image in a window with pygtk?

description: Include an image in a window with pygtk


code: from __future__ import unicode_literals

rawDescription: Which of those encoding methods is the most reliable one?


code:
df = pd.DataFrame([["andy", "GB"], ["bob", "US"], ["chris", "GB"]], columns=["name", "country"])
df.groupby("country").size().nlargest(1)

rawDescription: Pandas - count groupBy results

description: Pandas - count groupBy results


rawDescription: How to return a number as a binary string with a set number of bits in python

description: Return a number as a binary string with a set number of bits in python


code:
plt.contour(xi, yi, F, colors='red')
plt.contour(xi, yi, F1, colors='blue')
plt.show()

rawDescription: several contour plots in the same figures

description: Several contour plots in the same figures


code: indexDict[word] = [count]

rawDescription: Creating an index of words

description: Creating an index of words


rawDescription: Markers not created after passing JSON

description: Markers not created after passing JSON


code:
import sys
sys.path.insert(0, "/opt/pillow")

rawDescription: installing Pillow and PIL

description: Installing Pillow and PIL


code:
import numpy as np

#Append zeros at the start and end of input array, x
xa = np.hstack([[0],x,[0]])

# Get an array of ones and zeros, with ones for nonzeros of x and zeros elsewhere
xa1 =(xa!=0)+0

# Find consecutive differences on xa1
xadf = np.diff(xa1)

# Find start and stop+1 indices and thus the lengths of "islands" of non-zeros
starts = np.where(xadf==1)[0]
stops_p1 = np.where(xadf==-1)[0]
lens = stops_p1 - starts

# Mark indices where "minus ones" are to be put for applying cumsum
put_m1 = stops_p1[[stops_p1 < x.size]]

# Setup vector with ones for nonzero x's, "minus lens" at stops +1 & zeros elsewhere
vec = xa1[1:-1] # Note: this will change xa1, but it's okay as not needed anymore
vec[put_m1] = -lens[0:put_m1.size]

# Perform cumsum to get the desired output
out = vec.cumsum()

rawDescription: Numpy sum running length of non-zero values


code:
import itertools
import operator

def most_common(L):
  # get an iterable of (item, iterable) pairs
  SL = sorted((x, i) for i, x in enumerate(L))
  # print 'SL:', SL
  groups = itertools.groupby(SL, key=operator.itemgetter(0))
  # auxiliary function to get "quality" for an item
  def _auxfun(g):
    item, iterable = g
    count = 0
    min_index = len(L)
    for _, where in iterable:
      count += 1
      min_index = min(min_index, where)
    # print 'item %r, count %r, minind %r' % (item, count, min_index)
    return count, -min_index
  # pick the highest-count/earliest item
  return max(groups, key=_auxfun)[0]

rawDescription: Python most common element in a list

description: Python most common element in a list


code:
df = pd.DataFrame(np.random.randint(1,6,(5,3)), columns=['Test1','Test2','Test3'])
df

rawDescription: What is the best way to create new pandas dataframe consisting of specific rows of an existing dataframe that match criteria?


code:
import itertools

def intersect(sets):
    #forms the intersection of all s in sets
    #assumes that there is at least one

    I = sets[0].copy()
    for s in sets[1:]:
        I = I & s
    return I

def largestIntersection(sets,n):
    maxSize = 0
    maxSets = [set()]
    for groupCombo in itertools.combinations(sets,n):
        I = intersect(groupCombo)
        if len(I) > maxSize:
            maxSize = len(I)
            maxSets = [I]
        elif len(I) == maxSize:
            maxSets.append(I)
    return maxSets

rawDescription: Find all subsets from list of sets that appears in at least N different sets


code:
timeit.Timer('x = 111.1').timeit()
t=timeit.Timer('x = np.array(111.1)','import numpy as np').timeit()

rawDescription: Numpy/Python performing terribly vs. Matlab


code:
r = csv.reader(tsv, dialect='excel-tab')
aps = {}
i = 0
for row in r:
    network = row[2]
    print(network)
    if network == "":
        continue
    elif "\x00" in network:
        continue
    else:
        aps["row" + str(i)] = self.APStore.append([network, "", "", ""])

rawDescription: Python ignore \x00\x00\x00\x00

description: Python ignore \x00\x00\x00\x00


code:
while True:
    pw = raw_input('Please enter a password between 6-12 characters long: ')
    if len(pw) < 6 or len(pw) > 12:
            print('Please Re-Enter your password, as it must be between 6-12 characters long')
            continue
    break

rawDescription: Restart a while loop?

description: Restart a while loop


code:
try:
    num = float(subject)
except ValueError:
    print("Illegal value")

rawDescription: Elegant way test in python if string contains nothing except 0-9,e,+,-,spaces,tabs


code:
with open(sys.argv[1]) as f:
    lst = [tuple(row) for row in csv.reader(f)]

rawDescription: Create list of tuples (in a more elegant way)


code:
from django.conf.urls import patterns, url
from .views import *

urlpatterns = patterns('',
   url(r'^add/$', PostCreateView.as_view(), name='post-add'),
   url(r'^(?P<pk>\d+)/edit/$', PostUpdateView.as_view(), name='post-edit'),
   url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='post-delete'),
)

rawDescription: Django editing and deleting, using Generic editing views or making functions in views.


code: ' \r\n\t\v'.isspace()

rawDescription: file.readlines() leaving blank lines

description: File.readlines() leaving blank lines


code:
def get_nans_blocks_length(a):
    """
    Returns 1D length of np.nan s block in sequence depth wise (last axis).
    """
    nan_mask = np.isnan(a)
    start_nans_mask = np.concatenate((np.resize(nan_mask[...,0],a.shape[:-1]+(1,)),
                                 np.logical_and(np.logical_not(nan_mask[...,:-1]), nan_mask[...,1:])
                                 ), axis=a.ndim-1)
    stop_nans_mask = np.concatenate((np.logical_and(nan_mask[...,:-1], np.logical_not(nan_mask[...,1:])),
                                np.resize(nan_mask[...,-1], a.shape[:-1]+(1,))
                                ), axis=a.ndim-1)

    start_idxs = np.where(start_nans_mask)
    stop_idxs = np.where(stop_nans_mask)
    return stop_idxs[-1] - start_idxs[-1] + 1

rawDescription: Finding start and stops of consecutive values block in Python/Numpy/Pandas


code:
def order(num):
    res = 0
    while num > 0:
        num = int(num / 10)
        res += 1
    return res

print(order(127))  # prints 3

rawDescription: Getting the number of digits (Python)

description: Getting the number of digits (Python)


code: df["Name"] = df["Infraction"] = df["Yards"] = ""

rawDescription: Trying to parse string and create new columns in data frame in Python pandas


code:
# use function to create from the raw data an interpolated datafield
xi, yi, zi = define_grid(datafield)

# rearrange those values to bring them in the form of an array with [x y z]
xyz = grid_as_array(xi, yi, zi)

# search closest values from grid for the points of the orangeline
# orangeline_xy is the array with elements [x y]
indexes = self.closest_node(orangeline_xy, xyz[:,0:2])

# take z values from the grid which we found before
orangeline_z = xyz[indexes, 2]

# add those z values to the points of the orangeline
orangeline_xyz = np.hstack((orangeline_xy,orangeline_z[:, np.newaxis]))

rawDescription: Finding nearest xy-point in numpy array and second nearest with condition


code:
err3 = np.sqrt(errfunc3(optim3, data[:,0], data[:,1])).sum()
err2 = np.sqrt(errfunc2(optim2, data[:,0], data[:,1])).sum()
print('Residual error when fitting 3 Gaussians: {}\n'
    'Residual error when fitting 2 Gaussians: {}'.format(err3, err2))
# Residual error when fitting 3 Gaussians: 3.52000910965
# Residual error when fitting 2 Gaussians: 3.82054499044

rawDescription: Python-load data and do multi Gaussian fit


code:
from collections import OrderedDict
data = {4:'str1', 19:'str2', 1:'str3', 7:'str4'}
orderedData = OrderedDict(sorted(data.items()))
orderedData

rawDescription: Sort a Dictionary in Python Based on its Keys (when all keys are ints)


code: self.path = configParser.get('your-config', 'path1')

rawDescription: How to read a config file using python

description: Read a config file using python


rawDescription: Distributing tasks to modules in python

description: Distributing tasks to modules in python


code:
from collections import Counter

d = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
substrings = ['dog', 'cat']

counter = Counter()

for substring in substrings:
    for key in d:
        if substring in key:
            counter[substring] += d[key]

print(counter.items())

rawDescription: Searching and counting dictionary key value pairs


code:
class Person(ndb.Model):
    guilds = ndb.KeyProperty(kind="Guild", repeated=True)

class Guild(ndb.Model):
    @property
    def members(self):
        return Person.query().filter(Person.guilds == self.key)

    def add_person(self, person):
        person.guilds.append(self.key)
        person.put()

rawDescription: Many-To-Many Relationship in ndb

description: Many-To-Many Relationship in ndb


code: [[a[i] for i in (0, 1, 2)] for a in matrix]

rawDescription: Extract variable number of columns for a matrix


code:
def iter_author(etree):
    for author in etree.iterfind('.//author'):
        for row in iter_docs(author):
            yield row

rawDescription: How to convert an XML file to nice pandas dataframe?

description: Convert an XML file to nice pandas dataframe


code:
#! /usr/bin/env python3
from ctypes import *
dll = cdll.LoadLibrary('./libshmem.so')

write_shmem = dll.write_shmem
write_shmem.restype = c_int

read_shmem = dll.read_shmem
read_shmem.restype = c_int

class DataBlock(Structure):
    _fields_ = [('c', c_ubyte), ('l', c_ulong),
                ('f',c_float), ('d', c_double) ]

#
# Using byref()
#
data = DataBlock(ord('A'), 123, 12.32, 1.89721)

write_shmem(b"P0W", byref(data))
read_shmem(b"P0W", byref(data))

print("{0} {1} {2} {3}".format(chr(data.c), data.l, data.f, data.d))

#
# Using pointer()
#
data = DataBlock(ord('A'), 123, 12.32, 1.89721)

write_shmem(b"P0W", pointer(data))
read_shmem(b"P0W", pointer(data))

print("{0} {1} {2} {3}".format(chr(data.c), data.l, data.f, data.d))

#
# Using cast()
#
data = DataBlock(ord('A'), 123, 12.32, 1.89721)

write_shmem(b"P0W", cast(pointer(data), c_char_p))
read_shmem(b"P0W", cast(pointer(data), c_char_p))

print("{0} {1} {2} {3}".format(chr(data.c), data.l, data.f, data.d))

rawDescription: Passing a C structure to a function in C DLL


code:
import random

def filter_shuffle(seq):
    try:
        result = list(seq)
        random.shuffle(result)
        return result
    except:
        return seq

rawDescription: Randomize elements of a list in jinja 2

description: Randomize elements of a list in jinja 2


rawDescription: using Django Rest framework to serialize custom data types and return response

description: Using Django Rest framework to serialize custom data types and return response


rawDescription: Creating a multi-index from csv census data


code: titles = soup.find_all("h1", class_="title multiline")

rawDescription: find_all() not finding any results when using Beautiful Soup + Requests

description: Find_all() not finding any results when using Beautiful Soup + Requests


code:
class Character(pygame.sprite.Sprite):
    ATTRS = ('hp', 'image', 'speed', 'x', 'y')

    def __init__(self, **kwargs):
        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()
        for attr in self.ATTRS:
            setattr(self, attr, kwargs.get(attr))  # sets to None if missing
        set_rect(...)  # do your processing of x, y

rawDescription: How to Create Instance Attributes By Lopping Over __init__ Arguments?


code:
def main(model):
    model.similarity('word1','word2')
    ...

rawDescription: Keep alive the object for using them in another program in python


code:
df = pd.DataFrame({'subscriber_id':[1,2,3,4,5]})
df
mask = df['subscriber_id'].isin([2,4,5])
mask
df.loc[~mask]

rawDescription: Filtering pandas data frame by a list of id's


code: br.select_form(nr=0) #Select the first (and only) form - it has no name so we reference by number

rawDescription: Screenscaping aspx with Python Mechanize - Javascript form submission


code:
inputlist = ['\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', u'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRs\xa021790    \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', '\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', u'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRs\xa023851\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', '\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', u'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRs\xa023905\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', '\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', u'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRs\xa026570\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']
[0 if not v.strip() else int(v.strip().split()[-1]) for v in inputlist]

rawDescription: extracting integer data from a string in list

description: Extracting integer data from a string in list


code:
from collections import OrderedDict
l = ['1:a', '2:b' '1:c', '3:d', '4:d']
list(OrderedDict.fromkeys(item.split(':')[0] for item in l).keys())

rawDescription: How can I split the strings and get only the first part of it?

description: Split the strings and get only the first part of it


code:
with open('blah.txt', 'rb') as f:
    pass

rawDescription: Can I use finally statement with def statement?

description: Use finally statement with def statement


code:
from timeit import timeit
import random
from string import ascii_lowercase
kv_pairs = [(''.join(random.sample(ascii_lowercase, random.randint(10, 20))), ''.join(random.sample(ascii_lowercase, random.randint(10, 20))))
            for _ in xrange(10000)]
len(dict(kv_pairs))  # the random keys happen to be all unique.
timeit('{k: v for k, v in kv_pairs}', 'from __main__ import kv_pairs', number=1000)
timeit('dict(kv_pairs)', 'from __main__ import kv_pairs', number=1000)
timeit('{k: v for k, v in kv_pairs}', 'from __main__ import kv_pairs; kv_pairs = kv_pairs[:3]')
timeit('dict(kv_pairs)', 'from __main__ import kv_pairs; kv_pairs = kv_pairs[:3]')

rawDescription: Dictionary comprehensions in python are too comprehensive


rawDescription: Python all combinations for multiple lists with variable k


code:
multipart = self.dealerSocket.recv_multipart()
returnRoute = multipart[:-1]
requestMsg = multipart[-1]
reply = someFunction(requestMsg)
self.dealerSocket.send_multipart(returnRoute + [reply])

rawDescription: ZMQ Python Request Reply Broker for Addressed Asynchronous Requests


rawDescription: Python: Cumulative insertion of values in a sparse matrix (lil_matrix) due to repeated indices


code:
FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
debug('Protocol problem: %s', 'connection reset', extra=d)

rawDescription: Conditionally evaluated debug statements in Python


code:
def checkpos(j):
    if j % 2:
        return lambda xs: 2 - xs[j]
    else:
        return lambda xs: 1 - xs[j]
def checkneg(j):
    if j % 2:
        return lambda xs: 2 + xs[j]
    else:
        return lambda xs: 1 + xs[j]

cons = [checkpos(j) for j in range(N)] + [checkneg(j) for j in range(N)]

rawDescription: Python: how to create many constraints for fmin_cobyla optimization using lambda functions


code:
def Sort():
    scores = []
    with open("results.txt", "r+") as x:
        for linia in x:
            name, score = linia.split(' ')
            score = int(score)
            scores.append((name, score))
        scores.sort(key=lambda sc: sc[1])

        # Go to beginning of file
        x.seek(0)

        # http://devdocs.io/python~3.5/library/io#io.IOBase.truncate
        # If no position is specified to truncate,
        # then it resizes to current position

        x.truncate()
        # note that x.truncate(0) does **not** work,
        # without an accompanying call to `seek`.
        # a number of control characters are inserted
        # for reasons unknown to me.

        for name, score in scores:
            x.write(name + ' ' + str(score) + '\n')

rawDescription: Python file read and write

description: Python file read and write


code:
from ctypes import *;
clib = cdll.LoadLibrary('/home/soltanmm/tmp/a.out');

# print should call r2() since f is a variable initialized to
# point to function r2 that returns an int. Should
# print 101
print (CFUNCTYPE(c_int).in_dll(clib,'f')())

# or call r2 directly
print(clib.r2())

# prints out the character (char *) string variable `p'
# should result in 'Hello World' being printed.
print((c_char_p).in_dll(clib,'p').value)

# call the gethw() function that returns a point to a char *
# This too should print 'Hello World'
# we must set the restype c_char_p explicitly since the default
# is to assume functions return `int`
gethw = clib.gethw
gethw.restype = c_char_p
print(gethw())

rawDescription: Using ctypes to grab a pointer from a nullary function (segfault) x64


code:
s1.isnull()
s1.isnull() == s2.isnull()

rawDescription: Comparing pandas.Series for equality when they contain nan?


code:
Views
class ProfileUpdateView(UpdateView):
    model = Profile
    form_class = UserProfileForm

    def get_object(self):
        """
        Returns the request's user.
        """
        return self.request.user.get_profile()

    # Then (unrelated, but for security)
    dispatch = login_required(UpdateView.dispatch)

rawDescription: Django UpdateView without pk in the url

description: Django UpdateView without pk in the url


code:
words = sc.textFile("README.md")
def mapper(line):
    return ((word, 1) for word in line.split())
words.flatMap(mapper).take(4)
counts = words.flatMap(mapper).reduceByKey(lambda x, y: x + y)
counts.take(5)

rawDescription: List (or iterator) of tuples returned by MAP (PySpark)


code:
def __str__(self):
     return "{0}, {1}".format(self.x, self.y)

rawDescription: What is the most pyhthonic way of printing instance variables?


code:
keys = [2,3,10]
vals = [7,9,11]
dict(zip(keys, vals))

rawDescription: array_combine() from PHP equivalent in Python?

description: Array_combine() from PHP equivalent in Python


code:
fhand = ["<abc> <abc>", "<abc>", "<d>"]

counts = {}
pattern = re.compile(r'<\w+>') # insert your own regex here

for line in fhand:
    for match in pattern.findall(line):
        # initialize the count for this match to 0 if it does not yet exist
        counts.setdefault(match, 0)
        counts[match] += 1

rawDescription: how do I create dictionary keys from a list

description: Create dictionary keys from a list


code:
for lst in lsta:
    lst.insert(0, lst.pop(4))

rawDescription: How to re-order a series of sublists?

description: Re-order a series of sublists


rawDescription: Django: Extending Querysets / Connect multiple filters with OR


code:
if args is not None:
    query = query % tuple(( get_codec(a, self.encoders)(db, a) for a in args ))

rawDescription: change paramstyle on python MySQLdb module

description: Change paramstyle on python MySQLdb module


code:
with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)

rawDescription: Reading binary file in Python and looping over each byte


code: 'os' in sys.modules

rawDescription: Python module check if

description: Python module check if


code: large_df.sort_index(by = 'time_late' , inplace=True)

rawDescription: Pandas dataframes - join on similar timestamps


code:
def move(steps,op_func,z):
    if z == "x":
        global x
        x = op_func(x, int(steps))
        print("x is now {}".format(x))
    else:
        global y
        y = op_func(y, int(steps))
        print("y is now {}".format(y))

rawDescription: global varriable doesn't change

description: Global varriable doesn't change


rawDescription: Change n-th entry of NumPy array that fulfills condition


rawDescription: Finding the consecutive zeros in a numpy array


code:
import itertools
my_list = ["{0:02x}{1:02x}{2:02x}".format(i,j,k) for i,j,k
           in itertools.product(xrange(53,256), xrange(0,208), xrange(0,208))]

rawDescription: Create a list of hex codes given an Rgb range


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-e', action='store_true')
parser.add_argument('-i', action='store_true')
parser.add_argument("arg1")
parser.add_argument("arg2")

args = parser.parse_args()
print(args)

rawDescription: python argparse: default flag

description: Python argparse: default flag


code:
matches = []
for k,v in hashdict.items():

    #see docs for extract -- 4 because you are comparing a name to itself
    top3 = process.extract(v, hashdict, limit=4)

    #remove the hashID compared to itself
    for h in top3:
        if k == h[2]:
            top3.remove(h)

    #append tuples to the list "matches" if it meets a score criteria
    [matches.append((k, v, x[2], x[0], x[1])) for x in top3 if x[1] > 60] #change score?

    #remove reciprocal pairs
    [checkpair(m[0], m[2], matches) for m in matches]

df = pd.DataFrame(matches, columns=['id1', 'name1', 'id2', 'name2', 'score'])
# write to file
writer = pd.ExcelWriter('/path/to/your/file.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()

rawDescription: How do to fuzzy matching on excel file using Pandas?


code:
from django.utils.safestring import mark_safe
from django.template import Template, Context
print(Template('{{ taggeddoc }}').render(Context({'taggeddoc': '
hello
'})))
print(Template('{{ taggeddoc }}').render(Context({'taggeddoc': mark_safe('
hello
')})))
print(Template('{{ taggeddoc|safe }}').render(Context({'taggeddoc': '
hello
'})))

rawDescription: django render_to_response how to send special characters

description: Django render_to_response how to send special characters


code: df.columns = df.iloc[1]

rawDescription: Convert row to column header for Pandas DataFrame,


code:
A = dict()
A[1] = [3]
A
A[1].append(5)  # Add a new item to the list
A

rawDescription: Add more values to same key

description: Add more values to same key


code:
import numpy as np

data = np.memmap('foo.bin', dtype='<i4', mode='r')

rawDescription: Best way to convert Hex string file to integer

description: Convert Hex string file to integer


rawDescription: make long integer in python 2 compatible in python 3

description: Make long integer in python 2 compatible in python 3


code: maxWidths = [0] * maxCols

rawDescription: How to initialize a list to a certain value in Python

description: Initialize a list to a certain value in Python


code:
try:
    testCase()
except noIdentifier:
    pass

rawDescription: Exit a Python Program (From a Function) with a Successful Run Result


code:
cache = {}

def load_cache():
    """Load hotels into {id: data} dict cache."""
    rows = db.select('hotels')
    for row in rows:
        cache[row.id] = row

def get_hotel(hotel_id):
    """Get data for hotel with given ID, or return None if not found."""
    if not cache:
        raise Exception('hotels cache not loaded')
    return cache.get(hotel_id)

rawDescription: web.py shared variables

description: Web.py shared variables


code: [xs[i][j] for i in range(len(xs)) for j in range(len(xs[0]))]

rawDescription: List Comprehension Running Sequence

description: List Comprehension Running Sequence


code: c.executemany(sql_statement, csvReader)

rawDescription: this python script can be shortened/optimized, how?

description: This python script can be shortened/optimized, how


code:
class Node(TreeModel):
    parent # foreign key to Node

class File(Model):
    node # foreign key to Node
    name # name of file
    path # path to the file on disk for example

rawDescription: How can i make the tree like menus from python list

description: Make the tree like menus from python list


rawDescription: Writing a function to convert hex to decimal


rawDescription: python matplotlib dash-dot-dot - how to?

description: Python matplotlib dash-dot-dot - how to


code:
request = tornado.httpclient.HTTPRequest(url=url, method='POST', body=body,
                                         validate_cert=False)

rawDescription: Using "tornado.httpclient" fetch "POST https" site get "HTTPError: HTTP 599"


code:
req = urllib2.Request(url)
req.headers['Range'] = 'bytes=%s-%s' % (start, end)
f = urllib2.urlopen(req)

rawDescription: Efficient large file hash over network using Python


rawDescription: Python slicing from last to first element?


rawDescription: How to do a non-greedy match

description: Do a non-greedy match


code:
from collections import namedtuple

Button = namedtuple('Button', ["title", "to_do"])

buttons_to_make = [Button("First Name", [1]),
                   Button("Last Name", [1]),
                   Button("Date of Birth", [2, '']),
                   ...]

self.buttons = {}
for button in buttons_to_make:
    for action in button.to_do:
        # your big long if/elif structure here, e.g.:
        if action == 1:
            b = QtGui.QLineEdit()
        elif action == 2:
            b = QtGui.QPushButton('Choose')
            b.clicked.connect(self.openCal)
        # etc
    self.buttons[button.title] = b

rawDescription: Pyqt4 accessing objects when creating a dynamic form


code: ts = pd.Series(1, index=datetimes)

rawDescription: matplotlib time vs date

description: Matplotlib time vs date


code:
from itertools import product

with open("result.txt", "w") as f:
    for in_pars in product(*inputs):
        res = sim(in_pars)
        f.write(",".join(str(x) for x in in_pars + res))
        f.write("\n")

rawDescription: How to prepare, populate and explore an n-dimensional numpy array?

description: Prepare, populate and explore an n-dimensional numpy array


code: sorted(dic1.iteritems(), key=lambda i: i[1][0].lower())

rawDescription: Sorting python dictionary based on value index and in alphabetical order


rawDescription: itertools dice rolls: doubles roll twice

description: Itertools dice rolls: doubles roll twice


rawDescription: Fast way to find the mean of a function?

description: Fast way to find the mean of a function


code:
execfile('other.py', blob)
print("blob %s" % blob['toto'])

rawDescription: Python 2 How to debug code injected by the exec block


code: d.groupby('Group')[["X", "Y", "Z"]].apply(lambda g: pandas.Series(distance.pdist(g), index=["D1", "D2", "D3"]))

rawDescription: Using scipy pdist on pandas data frames (and) lists


code:
import httplib
conn = httplib.HTTPConnection('bit.ly')
conn.request('HEAD', '/rgCbf')
response = conn.getresponse()
response.getheader('location')

rawDescription: Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS


code:
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt

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

wind_dirs = ['east', 'northeast', 'north', 'northwest',
             'west', 'southwest', 'south', 'southeast']
# data
speed = np.random.uniform(0,1.25,100)
temp = np.random.uniform(-10,20,100)
wind = [wind_dirs[i] for i in np.random.randint(8, size=100)]

#transform data to cartesian
angles = {'east':0, 'northeast':np.pi/4, 'north':np.pi/2, 'northwest':3*np.pi/4,
          'west':np.pi, 'southwest':5*np.pi/4, 'south':3*np.pi/2, 'southeast':7*np.pi/4}
wind_angle = np.array([angles[i] for i in wind])
X,Y = speed*np.cos(wind_angle),speed*np.sin(wind_angle)

ax.scatter3D(X, Y, temp, c = temp, cmap=cm.bwr)
ax.set_zlabel('Temp')
plt.show()

rawDescription: plot qualitative data on matplotlib

description: Plot qualitative data on matplotlib


rawDescription: Grouping daily data by month in python/pandas and then normalising


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Circle

fig = plt.figure()
ax1 = fig.add_subplot(211)
# calculate asymmetry of x and y axes:
x0, y0 = ax1.transAxes.transform((0, 0)) # lower left in pixels
x1, y1 = ax1.transAxes.transform((1, 1)) # upper right in pixes
dx = x1 - x0
dy = y1 - y0
maxd = max(dx, dy)
width = .15 * maxd / dx
height = .15 * maxd / dy

# a circle you expect to be a circle, but it is not
ax1.add_artist(Circle((.5, .5), .15))
# an ellipse you expect to be an ellipse, but it's a circle
ax1.add_artist(Ellipse((.75, .75), width, height))
ax2 = fig.add_subplot(212)

ax2.axis('equal')
# a circle you expect to be a circle, and it is
ax2.add_artist(Circle((.5, .5), .15))
# an ellipse you expect to be an ellipse, and it is
ax2.add_artist(Ellipse((.75, .75), width, height))

fig.savefig('perfectCircle1.png')

rawDescription: Why is matplotlib plotting my circles as ovals?


rawDescription: Python: Acessing index numbers within an if statement nested within a for loop


rawDescription: Transposing a multi-dimensional matrix in Python with list comprehensions


code:
from pprint import pprint
pprint(variable)

rawDescription: Python: Retrieve result from inner dictionary


rawDescription: How do I use a for loop to add new entries to a python dictionary?

description: Use a for loop to add new entries to a python dictionary


rawDescription: Remove rows from a csv file where some column matches a specific regex


rawDescription: Get parent of current directory from Python script


code:
np.vstack(np.triu_indices_from(a,k=1)).T
inds=inds[inds[:,1]>2] #Or whatever columns you want to start from.
inds
a[inds[:,0],inds[:,1]]
max_index = np.argmax(a[inds[:,0],inds[:,1]])
inds[max_index]

rawDescription: Efficient way to find the index of the max upper triangular entry in a numpy array?


code:
def __init__(self, items):
    self.items = iter(items)
    self.count = 0

rawDescription: Establishing the number of values yielded by a generator


rawDescription: pandas data frames delta (subtraction)

description: Pandas data frames delta (subtraction)


code: im = array(Image.open(path + "\\" + fname))

rawDescription: Convert a color image to input vector for libsvm


code:
d = {key:val for key,val in zip(keys,values)}
d

rawDescription: Iterate through a 3D list by column

description: Iterate through a 3D list by column


code:
from argparse import ArgumentParser, ArgumentTypeError
import re

def parseNumList(string):
    m = re.match(r'(\d+)(?:-(\d+))?$', string)
    # ^ (or use .split('-'). anyway you like.)
    if not m:
        raise ArgumentTypeError("'" + string + "' is not a range of number. Expected forms like '0-5' or '2'.")
    start = m.group(1)
    end = m.group(2) or start
    return list(range(int(start,10), int(end,10)+1))

parser = ArgumentParser()
parser.add_argument('--range', type=parseNumList)

args = parser.parse_args()
print(args)

rawDescription: Accept a range of numbers in the form of 0-5 using Python's argparse?


rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code:
from decimal import Context, MAX_EMAX
d = Context(Emax=MAX_EMAX, prec=1).create_decimal('9e'+str(MAX_EMAX))
d.is_finite()
d.next_plus()
d

rawDescription: What is the largest number the Decimal class can handle?


code:
class MyClass(object):

    def __init__(self):
        self._conn = None

    @property
    def conn(self):
        if self._conn is None:
            self._conn = ConnectToDatabase()
        return self._conn

    def do_something1(self):
        self.conn.do_something1()

    def do_something2(self):
        self.conn.do_something2()

rawDescription: Use a class decorator to implement late-initialization


rawDescription: Determining version of easy_install/setuptools


code:
if form.is_valid():
    messages.success(request, 'Success!')
    return HttpResponseRedirect('/contact/')

rawDescription: Django Form Submit Update HTML

description: Django Form Submit Update HTML


code:
dfm = df.ix[idx, ['GENE','DIRECTION','SOURCE']]
print(dfm)
#     GENE DIRECTION SOURCE
# 16  BB-2         +     C3
# 18  BB-2         -     E5
# 23  EE-3         +     G7
# 29  EE-3         -     I9
# 7   TT-1         +     A1

rawDescription: Finding and deleting repeated data entries with two identical features identified by a third unique feature


code:
getArg = lambda x: x in argv and (argv.remove(x) or True)
quiet = getArg('-d')
interactive = getArg('-i')

rawDescription: How can I do really cheap command line parsing in Python?

description: Do really cheap command line parsing in Python


code: not_matched_keys = [key for key in match if key not in order]

rawDescription: compare dict.keys() with list, bug in expression

description: Compare dict.keys() with list, bug in expression


code: my_text = re.split(r"[^\w'-]+",text)

rawDescription: Regex to ignore specific characters

description: Regex to ignore specific characters


code:
import MyPak
from MyPak import MyMod

rawDescription: how to reload a Class in python shell?

description: Reload a Class in python shell


rawDescription: Opposite of melt in python pandas

description: Opposite of melt in python pandas


code: flattenList(i)

rawDescription: Flattening a list recursively - why doesn't my code return what I want?


code: df["review_text"] = df["review_text"].map(lambda x: x.split(' '))

rawDescription: How to map the word in data frame to integer ID with python-pandas and gensim?

description: Map the word in data frame to integer ID with python-pandas and gensim


code:
def ensure_even(argnum):
  def fdec(func):
    def f(*args, **kwargs):
      assert(args[argnum] % 2 == 0)  #or assert(not args[argnum] % 2)
      return func(*args, **kwargs)
    return f
  return fdec

rawDescription: How to pass a specific argument to a decorator in python

description: Pass a specific argument to a decorator in python


code:
# Import python modules
import tkinter
import tkinter.messagebox
from collections import Counter

# Module level constants
SCORES = {'A': 1, 'C': 3, 'B': 3, 'E': 1, 'D': 2, 'G': 2, 'F': 4, 'I': 1,
          'H': 4, 'K': 5, 'J': 8, 'M': 3, 'L': 1, 'O': 1, 'N': 1, 'Q': 10,
          'P': 3, 'S': 1, 'R': 1, 'U': 1, 'T': 1, 'W': 4,  'V': 4, 'Y': 4,
          'X': 8, 'Z': 10}

class App(tkinter.Tk):

    def __init__(self, word_list, *args, **kwargs):
        # Initialize parent class by passing instance as first argument
        tkinter.Tk.__init__(self, *args, **kwargs)

        # Store values
        self.word_list = word_list

        # Setup main window
        self.title('Scrabble Solver')

        # Create widgets
        rack_label = tkinter.Label(self, text='Enter your rack')
        self.rack_entry = tkinter.Entry(self)
        rack_button = tkinter.Button(self, text='Enter', command=self.search)
        quit_button = tkinter.Button(self, text='Quit', command=self.quit)
        self.valid_list = tkinter.Listbox(self, width=40, font='Courier')

        # Place widgets
        rack_label.grid(row=0, column=0, sticky=tkinter.W)
        self.rack_entry.grid(row=1, column=0, sticky=tkinter.W)
        rack_button.grid(row=1, column=1, sticky=tkinter.W)
        quit_button.grid(row=1, column=2, sticky=tkinter.W)
        self.valid_list.grid(row=2, columnspan=3, sticky=tkinter.W)

    def run(self):
        # Enter event loop
        self.mainloop()

    def error(self):
        # Throw and error message dialog
        tkinter.messagebox.showinfo('You have entered too many letters!')

    def search(self):
        # Cleanup up valid list
        self.valid_list.delete(0, tkinter.END)
        # Get data of entry, and make them lower case
        rack = self.rack_entry.get().lower()
        # Check length of data
        if len(rack) <= 8:
            return self.find_valid_words(rack)
        self.error()

    def find_valid_words(self, rack):
        # Create a dictionary for valid words and its values
        valid = {}
        rack_chars = Counter(rack)
        for word in self.word_list:
            word_chars = Counter(word)
            if word_chars == word_chars & rack_chars:
                valid[word] = sum(SCORES[letter.upper()] for letter in word)

        # Sort the results and insert them into the list box
        if valid:
            for word, score in sorted(valid.items(), key=lambda v: v[1], reverse=True):
                self.valid_list.insert(tkinter.END, '{:<10} {}'.format(word, score))
        else:
            self.valid_list.insert(tkinter.END, 'No results found.')

if __name__ == '__main__':
    # Open dictionary file and scan for words
    with open('dictionary.dat', 'r') as f:
        all_words = [word for word in f.read().split()]
    # Create instance and call run method
    App(all_words).run()

rawDescription: tkinter and scrabble solver problems

description: Tkinter and scrabble solver problems


code:
import pygame, sys
from pygame.locals import *

try:
    import Android
except ImportError:
    Android = None

#----------------------------------------------------------------------

class Background():

    def __init__(self, screen):

        self.screen = screen

        self.x = 0
        self.y = 0

        self.r = 0

        filename = "maps.png" # "start_screen.jpg" #

        self.image = pygame.image.load(filename).convert_alpha()

    def draw(self):
        self.screen.fill((self.r,0,0))
        self.screen.blit(self.image, (self.x, self.y))

#----------------------------------------------------------------------

class Player():

    def __init__(self, screen):

        self.screen = screen

        self.x = 0
        self.y = 0
        self.movex = 0
        self.movey = 0

        filename = "boy.png" # "jar.png" #

        self.image = pygame.image.load(filename).convert_alpha()

    def move(self):
        self.x += self.movex
        self.y += self.movey

    def draw(self):
        self.screen.blit(self.image, (self.x, self.y))

    def events(self, event):

        if event.type == KEYDOWN:
            if event.key == K_a:
                self.movex = -1
            elif event.key == K_d:
                self.movex = +1
            elif event.key == K_w:
                self.movey = -1
            elif event.key == K_s:
                self.movey = +1

        if event.type==KEYUP:
            if event.key == K_a:
                self.movex = 0
            elif event.key == K_d:
                self.movex = 0
            elif event.key == K_w:
                self.movey = 0
            elif event.key == K_s:
                self.movey = 0

#----------------------------------------------------------------------

class Game():

    def __init__(self):

        pygame.init()

        if Android:
            android.init()
            android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

        self.size = self.width, self.height = 1276, 650
        self.screen = pygame.display.set_mode(self.size)

        pygame.display.set_caption("Pygame 2D RPG !")

        self.background = Background(self.screen)
        self.player = Player(self.screen)

        font = pygame.font.SysFont("serif", 72)
        self.text_paused = font.render("PAUSED", True, (255, 0, 0))

    def run(self):

        PAUSED = False

        RUNNING = True

        while RUNNING:

            # --- events ---

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False

                if event.type==KEYDOWN:
                    if event.key == K_ESCAPE:
                        RUNNING = False
                    elif event.key==K_q:
                        PAUSED = not PAUSED

                if not PAUSED:
                    self.player.events(event)

            # --- changing values ---

            if not PAUSED:
                self.player.move()

            # --- drawing ---

            self.background.draw()
            self.player.draw()

            if PAUSED:
                self.screen.blit(self.text_paused, (100, 100))

            pygame.display.update()

        pygame.quit()
        sys.exit()

#----------------------------------------------------------------------

if __name__ == '__main__':
    Game().run()

rawDescription: Pygame pause key

description: Pygame pause key


code:
from pprint import pprint
lines = ['!!!\n', '\n', '@@@\n']
pprint([list(line.rstrip()) for line in f if line.strip()])

rawDescription: Using File IO to create matrix

description: Using File IO to create matrix


code:
def replace_dupes(ax):
    result = []
    seen = set()
    for x in ax:
        if x in seen:
            result.append('')
        else:
            seen.add(x)
            result.append(x)
    return result

ax = ('0','1','1','1','2','2','2','3')
print(replace_dupes(ax))
# ['0', '1', '', '', '2', '', '', '3']

rawDescription: Remove following duplicates in a tuple

description: Remove following duplicates in a tuple


code:
import pandas as pd
levels = ('name', 'condition', 'trial')
names = ('john', 'hans')
conditions = list('ab')
trials = range(1, 3)

idx = pd.MultiIndex.from_product(
    [names, conditions, trials], names=levels)

df = pd.DataFrame(np.random.randn(len(idx), 2),
                      index=idx, columns=('accuracy', 'velocity'))

def allbut(*names):
    names = set(names)
    return [item for item in levels if item not in names]

rawDescription: Grouping by everything except for one index column in pandas


code:
def add(a, b):
    return a + b
params = { "b": 5, "a": 6}
print(add(**params))

rawDescription: Is there any benefits for using * or ** in python?


code:
import datetime as dt
df['weekday'] = df['datetime'].apply(lambda x: dt.datetime.strftime(x, '%A'))

rawDescription: Num day to Name day with Pandas

description: Num day to Name day with Pandas


code:
class NoisyDict(dict):
    def __init__(self, *args, **kwargs):
        self.handlers = {}
        #Python 3 style
        super().__init__(*args, **kwargs)

    def add_handler(self, key, callback):
        self.handlers[key] = self.handlers.get(key, [])
        self.handlers[key].append(callback)

    def __getitem__(self, key):
        for handler in self.handlers.get(key, []):
            handler('get', key, super().__getitem__(key))
        return super().__getitem__(key)

    def __setitem__(self, key, value):
        for handler in self.handlers.get(key, []):
            handler('set', key, value)
        return super().__setitem(value)

rawDescription: Pythonic way of polling a dictionary - using the key's value once it exists


code: a

rawDescription: super simple cipher function in python. comparing a list to keys in a dictionary

description: Super simple cipher function in python. comparing a list to keys in a dictionary


code: df[[isinstance(dog, list) for dog in df.dog_name]]

rawDescription: How do I subset a pandas data frame based on a list of string values?

description: Subset a pandas data frame based on a list of string values


rawDescription: Python Sqlalchemy: Filter by datediff of months


code: np.random.randint(0, len(lnz[0]))

rawDescription: index of a random choice from numpy array

description: Index of a random choice from numpy array


code:
from tkinter import *

# ---

class RedButton(Button):

    def __init__(self, parent, **options):
        Button.__init__(self, parent, **options)
        self['bg'] = 'red'
        # or
        #self.config(bg='red')

# ---

window = Tk()

RedButton(window, text="Button #1").pack()
RedButton(window, text="Button #2").pack()
RedButton(window, text="Button #3").pack()

window.mainloop()

rawDescription: Adding a hovering option to my buttons in a class


code:
for i in range(1, 6, 1):
    for c in range(1, 10, 1):
        print(c, end=" ")
    print('')

rawDescription: Aligning text in a table using string formatting with a loop inside a loop


code:
from PyQt4 import QtGui, QtCore

DEFAULT_STYLE = """
QProgressBar{
    border: 2px solid grey;
    border-radius: 5px;
    text-align: center
}

QProgressBar::chunk {
    background-color: lightblue;
    width: 10px;
    margin: 1px;
}
"""

COMPLETED_STYLE = """
QProgressBar{
    border: 2px solid grey;
    border-radius: 5px;
    text-align: center
}

QProgressBar::chunk {
    background-color: red;
    width: 10px;
    margin: 1px;
}
"""

class MyProgressBar(QtGui.QProgressBar):
    def __init__(self, parent = None):
        QtGui.QProgressBar.__init__(self, parent)
        self.setStyleSheet(DEFAULT_STYLE)

    def setValue(self, value):
        QtGui.QProgressBar.setValue(self, value)

        if value == self.maximum():
            self.setStyleSheet(COMPLETED_STYLE)

rawDescription: Changing the color of a QProgressbar()

description: Changing the color of a QProgressbar()


code:
a = [1,2,3]
b = [e for e in a]
id(a), id(b)

rawDescription: Assigning Variables in While loops

description: Assigning Variables in While loops


code:
next(my_gen)
next(my_gen)
next(my_gen)

rawDescription: Using the split function

description: Using the split function


code:
# Save the new points for x and y
x_data_plot.append(N)
y_data_plot.append(K00[i])

rawDescription: Plotting within a for loop, with 'hold on' effect in matplotlib?


code:
def search_things(things):
    names = []
    for thing in things:
        if not thing.inside:
            names.append(thing)
        else:
            names.append(search_things(thing.inside))

    return names

rawDescription: setting up iterative item query in python

description: Setting up iterative item query in python


code:
ppm.nonzero()
ppm.data

rawDescription: Transform csr_matrix into networkx graph


code:
t = pd.Timestamp.now()
(t - t.to_period("H").start_time).total_seconds()

rawDescription: Given a timestamp, get total N. of seconds in the hour


code:
from mysql.connector.cursor import MySQLCursor
getattr(MySQLCursor, 'fetchall')

rawDescription: how to call `getattr()` to get a Python MySQLCursor method?

description: Call `getattr()` to get a Python MySQLCursor method


code:
class PickDateForm(forms.Form):
    date = forms.DateField(widget=forms.DateInput(attrs={'class': 'any_custom_class_name'}))

rawDescription: Django Dynamically search item by month using datepicker


code:
liste_usager = input("Veuillez entrer la liste d'entiers:")
liste_usager = [int(n) for n in liste_usager.split(' ')]
print(liste_usager)

rawDescription: Convert this string to int list

description: Convert this string to int list


code:
import ast
ast.literal_eval('{' + s + '}')

rawDescription: Transforming the string representation of a dictionary into a real dictionary


code:
import random

def add(grid, char, count):
    while count:
        row = random.randrange(len(grid))
        column = random.randrange(len(grid[0]))
        if world[row][column] == 'g':
            world[row][column] = char
            count -= 1

rawDescription: How to create a random multidimensional array from existing variables

description: Create a random multidimensional array from existing variables


rawDescription: How to modify a Numpy array with conditional and function

description: Modify a Numpy array with conditional and function


rawDescription: Week of year calculation differences between Java and Python


code:
with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:
                f1.write(line)

rawDescription: Copying from one text file to another using Python


code:
def names(teacher):
    return {name for c in teacher['colleagues'] for name in {c['name']} | names(c)}

rawDescription: Extract set of values from nested dictionaries/lists Python


rawDescription: How to remove a string with varying numbers at the end

description: Remove a string with varying numbers at the end


code:
import numpy as np
import random
import sklearn.metrics.pairwise
import scipy.spatial.distance

r = np.array([random.randrange(1, 1000) for _ in range(0, 1000)])
c = r[:, None]

def option1(r):
    dists = np.abs(r - r[:, None])

def option2(r):
    dists = scipy.spatial.distance.pdist(r, 'cityblock')

def option3(r):
    dists = sklearn.metrics.pairwise.manhattan_distances(r)

rawDescription: Fastest pairwise distance metric in python


rawDescription: javascript comparison operators

description: Javascript comparison operators


code:
C3 = (A * B.T).T
np.allclose(C0, C3)

rawDescription: numpy array multiplication with arrays of arbitrary dimensions

description: Numpy array multiplication with arrays of arbitrary dimensions


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

fig = plt.figure()
ax = fig.add_subplot(111)

x1 = [1,2,3,4,5,6,7,8]
y1 = [20,100,50,120,55,240,50,25]
x2 = [3,4,5,6,7,8,9]
y2 = [25,35,14,67,88,44,120]

ax.plot(x1, y1, color='lightblue',linewidth=3)
ax.plot(x2, y2, color='darkgreen', marker='^')

# Plot the cross point

x3 = np.linspace(6, 7, 1000)        # (6, 7) intersection range
y1_new = np.linspace(240, 50, 1000) # (6, 7) corresponding to (240, 50) in y1
y2_new = np.linspace(67, 88, 1000)  # (6, 7) corresponding to (67, 88) in y2

idx = np.argwhere(np.isclose(y1_new, y2_new, atol=0.1)).reshape(-1)
ax.plot(x3[idx], y2_new[idx], 'ro')

plt.show()

rawDescription: Finding the point of intersection of two line graphs drawn in matplotlib


code: a.newMethod = newMethod.__get__(a, A)

rawDescription: Adding a method to a class after its creation in Python


code:
g.add_edge(1, 2, {x:2})
# or more explicitly
g.add_edge(1, 2, attr_dict={x:2})

rawDescription: Passing variables as arguments to networkx.add_edge() attributes


code:
l = []
for x in generate():
    if x < 10000:
        l.append(x)
    else:
        break

rawDescription: Python Generator Cutoff

description: Python Generator Cutoff


code:
from django import template

register = template.Library()

@register.filter
def next(some_list, current_index):
    """
    Returns the next element of the list using the current index if it exists.
    Otherwise returns an empty string.
    """
    try:
        return some_list[int(current_index) + 1] # access the next element
    except:
        return '' # return empty string in case of exception

@register.filter
def previous(some_list, current_index):
    """
    Returns the previous element of the list using the current index if it exists.
    Otherwise returns an empty string.
    """
    try:
        return some_list[int(current_index) - 1] # access the previous element
    except:
        return '' # return empty string in case of exception

rawDescription: How to access the next and the previous elements in a Django template forloop?

description: Access the next and the previous elements in a Django template forloop


rawDescription: Correct layout for dictionary literals

description: Correct layout for dictionary literals


rawDescription: Read binary file which has different datatypes


code:
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}

for i in xrange(1000000):
    if something in options:
        the_thing = options[something]
    else:
        the_thing = 4

rawDescription: Most efficient way of making an if-elif-elif-else statement when the else is done the most?


code: cmd1 | cmd2

rawDescription: Using textfile as stdin in python under windows 7


code:
class RootPage(DDTHandler):

    def get(self):
        self.view_request()

rawDescription: Header Check in Python (GAE)

description: Header Check in Python (GAE)


code:
df['record_date'] = pd.to_datetime(df.record_date)

print (df.loc[df.priority.groupby([df.userid, df.record_date.dt.date]).idxmin()])

rawDescription: How to select min record by user in a Pandas data frame while accounting for multiple matches when you only want one

description: Select min record by user in a Pandas data frame while accounting for multiple matches when you only want one


rawDescription: Move last two episodes from directory in Python?


code: purchase()

rawDescription: Python: Find an item in a list

description: Python: Find an item in a list


code:
lst = [1, 2, 3]
print(lst)  # equivalent to `print([1, 2, 3])'
print(*lst) # equivalent to `print(1, 2, 3)'
print(reversed(lst))
print(*reversed(lst))

rawDescription: Python what is '*' used for

description: Python what is '*' used for


code: [{'total': 4, 'which_group': 2}, {'total': 2, 'which_group': 1}, {'total': 1, 'which_group': 3}]

rawDescription: Highly challenging queryset filtering, sorting and annotation (in Django-based app)


code: "".join(c + ":" if i % 2 else c for i, c in enumerate(hex(address)[2:].zfill(12)))[:-1]

rawDescription: Python - Get mac address

description: Python - Get mac address


code:
class MyModel(object):
    pass # Implementation here

rawDescription: GAE, Python: How to define db object classes in only one place?


code:
import sys
levels=sys.argv[1:]

rawDescription: Using csh script to input user specified arguments into a python script


rawDescription: how to make this script a little bit faster?

description: Make this script a little bit faster


code:
import matplotlib.pyplot as plt
import pandas as pd
import time

ax = df.plot()
fig = ax.get_figure()
plt.show(block=False)
time.sleep(5)
plt.close(fig)

rawDescription: how to close pandas dataframe plot

description: Close pandas dataframe plot


rawDescription: Django Rest Framework pagination extremely slow count


rawDescription: Adding characters to certain laces in string


code:
from tastypie.resources import ModelResource, fields, ALL_WITH_RELATIONS

from fruits.models import Fruits
from origin.models import Origin

class OriginResource(ModelResource):
    class Meta:
        queryset = Origin.objects.all()
        resource_name = 'origin'
        filtering = {
            "country": ('exact',)
            }

class FruitResource(ModelResource):
    origin = fields.ForeignKey(OriginResource, 'origin', full=True)
    class Meta:
        queryset = Fruits.objects.all()
        allowed_methods = ['get']
        filtering = {
            "origin": ALL_WITH_RELATIONS,
            }

rawDescription: Django Tastypie: Filtering by ForeignKey


code:
for index, item in enumerate(myList):
    if item == something:
        doStuff(index, item)

rawDescription: Understanding pythons enumerate

description: Understanding pythons enumerate


code:
data = bytearray(2**32) # 4 GiB
n = proc.stdout.readinto(data)
if n < len(data):
    data[n:] = ''
else:
    data += proc.stdout.read()

rawDescription: How to pipe binary data into numpy arrays without tmp storage?

description: Pipe binary data into numpy arrays without tmp storage


code:
if findWholeWord('seek')(st1) == None:
    return False
else:
    return True

rawDescription: Find single or multiple words in string

description: Find single or multiple words in string


code:
class ColoredComic(Comic):
    colored = models.BooleanField(default=False)

    @staticmethod
    def create_from_Inked(**kwargs):
        inked = InkedComic.objects.get(**kwargs)
        if inked:
            colored = ColoredComic.objects.create()
            colored.__dict__.update(inked.__dict__)
            colored.__dict__.update({'id': None}) # Remove pk field value
            return colored
        else:
            # or throw an exception...
            return None

rawDescription: Populating Models from other Models in Django?