code: d2 = dict((k, f(v)) for k, v in d1.items())

rawDescription: Applying a function to values in dict

description: Applying a function to values in dict


code:
import glob, os

filelist = glob.glob("*.bak")
for f in filelist:
    os.remove(f)

rawDescription: Deleting all files in a directory with Python


code:
nice
sorted(nice.items(), key=lambda itm: list(map(int,itm[::-1])),reverse=True)

rawDescription: Python : Displaying a sorted dictionary by more than one condition


code:
# Example: File: imagediff.py

import ImageChops
import math, operator

def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add,
        map(lambda h, i: h*(i**2), h, range(256))
    ) / (float(im1.size[0]) * im1.size[1]))

rawDescription: python code to compare images in python

description: Python code to compare images in python


code:
def playerMove(board, symbol):

    validMove = False
    while not validMove:
        col = input("You are the {} player. What column would you like to play? :".format(symbol))
        for row in range (6,0,-1):
            if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "):
                board[int(row)-1][int(col)-1] = symbol
                validMove = True
                break
        else:
            print ("Invalid input. Please try again!\n")

rawDescription: Edit: Python - Going from 1 Player to Two Player Game Using Functions


code: df['time since'] = df['datetime_column'].apply(lambda x: (x.name.to_datetime() - basedate).days)

rawDescription: Pandas: number of days elapsed since a certain date


rawDescription: Checking if a certain dictionary is in a list


code: ['', 'Some information.', 'Other information', 'Some more information.', 'Some information here....\nanother line of information', 'More info', 'The last bit of information']

rawDescription: Storing multiple lines from a file to a variable using a delimiter


code:
s = 'banana'

for i,c in enumerate(s):
    print(s[i:])

banana
anana
nana
ana
na
a

rawDescription: Iterating over strings in python

description: Iterating over strings in python


code:
from collections import defaultdict
newdic = defaultdict(set)
for k,v in items.items():
    for i in v:
        newdic[i].add(k)

dict(newdic)

rawDescription: Reversing logic of a product-country mapping


code:
def getWindowText(hwnd):
    buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
    buf = win32gui.PyMakeBuffer(buf_size)
    win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
    return str(buf)

rawDescription: How do I get the URL of the active Google Chrome tab in Windows?

description: Get the URL of the active Google Chrome tab in Windows


rawDescription: How to remove first 4 bytes from s string in python

description: Remove first 4 bytes from s string in python


code: df.apply(lambda x : x/x.sum(), axis=0)

rawDescription: pandas - percentage of matr

description: Pandas - percentage of matr


code:
yourDict = {'a':1, 'b':{'c':1, 'd': {'b':1}}}
indexList = ['b','d','b']
reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"
yourDict

rawDescription: Python change an array's value from array index


code:
for index, number in enumerate(list1):
    print("index :", index, number, list2[index])

rawDescription: List indexing in Python with duplicates

description: List indexing in Python with duplicates


code:
filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
mydict={}
for i,j in zip(filtered_symbolic_path,filtered_symbolic_path_times):
    if not mydict.has_key(i):
        mydict[i]=j
    else:
        mydict[i]=j+mydict[i]

rawDescription: How to add repeating occurences of elements in two lists in python

description: Add repeating occurences of elements in two lists in python


code:
replacewith = {'<':'lt;', '>':'gt;'}
for w in replacewith:
        word = word.replace(w,replacewith[w])

In [407]: word
Out[407]: 'lt;pgt;Santa is fatlt;/pgt;'

rawDescription: Replacing characters in a string and returning in python


code:
import hashlib
getattr(hashlib, 'md5')()
getattr(hashlib, 'sha1')()

rawDescription: Pythonic way to import module whose name is only known at runtime?


code:
d = {}
for f in os.listdir('mutation_directory'):
    gene, uniprot, suffix = f.split('_')
    d[uniprot] = f

rawDescription: How to find a specific file in Python

description: Find a specific file in Python


code:
foo = None
result = operator.boolean_and(foo, foo(bar))  # hypothetical and implementation

rawDescription: python or on operator module

description: Python or on operator module


rawDescription: Parsing bits from a 128 byte block of hex in Python


code: df

rawDescription: pandas multiindex assignment from another dataframe

description: Pandas multiindex assignment from another dataframe


code:
h = Hand()
self.bob = h
self.larry = h

rawDescription: Python: how to refer to an instance name?


code:
def func(a, b, *args):
    print(args)
func(1, 2, 3, 4, 5)
a, b, *rest = [1, 2, 3, 4, 5]
rest
func(1, *rest)

rawDescription: python - create a dynamic list of parameter for a method

description: Python - create a dynamic list of parameter for a method


code:
class ComplexQuestion(Question):
    def __init__(self, label, parent=None):
        super(ComplexQuestion, self).__init__(parent)
        # do additional initialization...

rawDescription: How do I show a Test_Question (String) per page?? (PyQt/Python)

description: Show a Test_Question (String) per page?? (PyQt/Python)


code:
x_lst = [' '] * size
lst = []
for y in range(size):
    lst.append(x_lst)

rawDescription: Python - Random output has a structure

description: Python - Random output has a structure


code:
from lxml import etree
from lxml.builder import ElementMaker

E = ElementMaker()

format = E.format(
    E.type("video"),
    E.channelsDepth("16", type="uint"),
    # create more elements here

    type="format",
    uid="BEAUTY:MasterBeauty"
)
root = E.XML(
    format,

    type="formats",
    version="4"
)

print(etree.tostring(root, xml_declaration=True, encoding='utf-8', pretty_print=True))

rawDescription: Can I create this XML file with lxml?

description: Create this XML file with lxml


code:
from Tkinter import *
root = Tk()
root.wm_iconbitmap('myicon.ico')
root.wm_title('Title')
root.mainloop()

rawDescription: How can change the logo of Tkinter GUI screen


rawDescription: How to set first N elements of array to zero?

description: Set first N elements of array to zero


code:
main_batch = pyglet.graphics.Batch()
background = pyglet.graphics.OrderedGroup(0)
monster_image = pyglet.image.load('./roar.png')
self.blocks['monster001'] = baseSprite(monster_image, 10, 50, main_batch, background)
self.blocks['monster002'] = baseSprite(monster_image, 70, 20, main_batch, background)

...
main_batch.draw()

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
ii = dat[:,1].astype( np.int )  # this is the F column as ints
jj = dat[:,2].astype( np.int )  # this is the T column as ints

nx = max(ii) + 1
ny = max(jj) + 1
d = np.zeros( (nx,ny) )

n = 0
for i,j in zip(ii,jj):
    d[i,j] = dat[n,3]
    n += 1

rawDescription: 2D Array from a columned text file in python


code: sdb = Button(..., command=functools.partial(runscript, "shutdown.sh"))

rawDescription: python interpreter running shutdown code when I don't want it to

description: Python interpreter running shutdown code when I don't want it to


code:
self.currEntry2.delete(0, tk.END)
self.currEntry2.insert(tk.END, final)

rawDescription: Problems with tk entry and optionmenu widget in currency converter


code:
class GalleryAdmin(admin.ModelAdmin):

    form = GalleryForm

    def __init__(self, model, admin_site):
        self.form.admin_site = admin_site
        super(GalleryAdmin, self).__init__(model, admin_site)

rawDescription: Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form


code:
display(
        my_var
       )

rawDescription: retrieving a variable's name in python at runtime?

description: Retrieving a variable's name in python at runtime


code:
command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=5)

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


code:
from urllib2 import urlopen
from simplejson import loads
content = loads(urlopen('http://graph.facebook.com/2439131959').read())

rawDescription: Facebook Graph API and Django

description: Facebook Graph API and Django


rawDescription: Assign new values to slice from MultiIndex DataFrame


code:
class SetQueue(Queue):

    def _init(self, maxsize):
        Queue._init(self, maxsize)
        self.all_items = set()

    def _put(self, item):
        if item not in self.all_items:
            Queue._put(self, item)
            self.all_items.add(item)

rawDescription: How check if a task is already in python Queue?


code:
page = render_template('email/activate.html', confirmURL=confirmURL)
msg = Message('Please confirm your email', html=page, sender='pavsidhu98@gmail.com', recipients=[email])
mail.send(msg)

rawDescription: HTML email appears as plain text?

description: HTML email appears as plain text


code:
arglist = [query, values]
cursor.execute(*arglist)
cursor2.execute(*arglist)

rawDescription: Python MySQLdb placeholders syntax

description: Python MySQLdb placeholders syntax


code: form = my_form(create_items())

rawDescription: Proper way to create a RadioField with a dynamic default value?


code:
lst = [None] * len(fields)
for k, v in values.iteritems():
    lst[idx[k]] = v

rawDescription: Fastest way to build a list from a sparse dictionary and a list of keys


code:
def index_type(s):
    try:
        return int(s)
    except ValueError:
        try:
            return map(int, s.split(".."))
        except:
            raise ArgumentTypeError("Invalid index: %s" % (s,))

p = ArgumentParser()
p.add_argument("-h")
p.add_argument("-v")
p.add_argument("inputfile", nargs="?")
p.add_argument("indices", nargs="*", type=index_type)
args = p.parse_args()

if not (args.inputfile is None or os.path.exists(args.inputfile)):
    sys.exit("Invalid file name: %s" % (args.inputfile,))

rawDescription: Declaring a positional argument inside a group of optional arguments in Python


code:
import redis
r = redis.Redis()
r.publish('text_channel', 'oh hai!')

rawDescription: python Socket.IO client for sending broadcast messages to TornadIO2 server

description: Python Socket.IO client for sending broadcast messages to TornadIO2 server


code:
# (!) resolve() use current language
#     -> try to guess language then activate BEFORE resolve()
lg_curr = translation.get_language()
lg_url = get_language_from_path(url) or lg_curr
translation.activate(lg_url)
try:
    resolve(url)
    req.session['url_back'] = url  # no error -> ok, remember this
except Resolver404:
    pass
translation.activate(lg_curr)

rawDescription: Django i18n_patterns: resolve() doesnt work as expected


code:
Arguments: ('1st Process...',)
Arguments: ('2nd Process...',)
Arguments: ('3rd Process...',)
Arguments: ('4th Process...',)

rawDescription: Need of running the same python file in parallel


rawDescription: Create a New Command or Macro in Komodo 7.1 IDE to save and run a python file


code:
cook, chef, fireman
cook, chef, fireman
cook, chef, fireman
cook, chef, fireman
house, farm, road

rawDescription: Change case of first letter in every cell in spreadsheet


code:
import os

try:
    approot = os.path.dirname(os.path.abspath(__file__))
except NameError:  # We are the main py2exe script, not a module
    import sys
    approot = os.path.dirname(os.path.abspath(sys.argv[0]))

rawDescription: Making a standalone .exe file of a python script


code:
#!/usr/bin/env python
import os
import b
os.environ['var_name'] = 'value'
b.echo()

rawDescription: python global parameters file

description: Python global parameters file


code:
import functools

...

self.option1 = Button(frame, text="1842", command=functools.partial(self.checkAnswer, question=3, answer=2))

rawDescription: Python - Store function with parameters

description: Python - Store function with parameters


code:
data = []
for y in xrange(H):
    data.append([])
    for x in xrange(W):
        data[y].append(0)

rawDescription: How correctly draw boxes in pyprocessing?


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

rawDescription: Pandas DataFrame groupby two columns and get first and last


code:
results = DBSession.query(model.Articles).all()
return dict(status=True, results=results)

rawDescription: SqlAlchemy query in a template page

description: SqlAlchemy query in a template page


code: scipy.optimize.minimize(f, x0, args=(M,), constraints=cons)

rawDescription: I'm having difficulty understanding the syntax of scipy.optimize


code:
N=3
sublists_names = [reso_names[x:x+N] for x in range(0, len(reso_names), N)]
sublists_values = [reso_values[x:x+N] for x in range(0, len(reso_values), N)]

rawDescription: Python Matplotlib: Splitting one Large Graph into several Sub-Graphs (Subplot)


code:
extensions = [
    'sphinx.ext.autodoc',
    'rst2pdf.pdfbuilder'
]

rawDescription: sphinx not to include source code during build

description: Sphinx not to include source code during build


rawDescription: Using Xpath in Scrapy to select any text below paragraph


rawDescription: Find row corresponding to timestamp in pandas DataFrame


code:
import mechanize
import shutil

br = mechanize.Browser()
br.open('http://stackoverflow.com/')
br.select_form(predicate=lambda form: form.attrs.get('id') == 'search')
br['q'] = '[python-mechanize]'
with open('search results.html', 'wb') as f:
    shutil.copyfileobj(br.submit(), f)

rawDescription: Mechanize submit a form that creates a dynamic flie that needs to be downloaded


rawDescription: Insert field into structured array at a specific column index


code:
if getargspec(g).defaults:
    ...

rawDescription: Why is inspect.getargspec() return unsized objects?


rawDescription: is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc?

description: Is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc


code:
import cmd

class MyCmd(cmd.Cmd):
    def do_cmd1(self): pass
    def do_cmd2(self): pass
    def do_cmd3(self): pass

d = MyCmd()
d.doc_header = '(use Ctrl+l to clear screen, Ctrl+a ...)'  # <---
d.cmdloop()

rawDescription: Augment Python cmd module "help" printout


code:
for i in xrange(1, flux.shape[0]):
    for j in xrange(1, flux.shape[1]):
        flux[i,j] = 0.5*(flux[i-1,j] + bz[i-1,j]*dx) + 0.5*(flux[i,j-1] - bx[i,j-1]*dz)

rawDescription: nested loop with array indexing in numpy

description: Nested loop with array indexing in numpy


code:
import itertools

str1 = "ABC"
lst = list(str1)
for n in range(len(str1)):
    for idxs in itertools.combinations_with_replacement(range(len(str1)), n):
        xs = lst[:]
        for i in reversed(idxs): # Use reversed, otherwise index become invald
            xs.insert(i, 'x')
        print(''.join(xs))

rawDescription: Generating combinations of two strings using Python


code:
__del_attr__
_del_x

rawDescription: A property's `fdel` method is not invoked when `__delattr__` is overridden


rawDescription: How to detect a shift between images

description: Detect a shift between images


code:
df = pd.concat([dfN13, dfM13], axis=1)
df

rawDescription: Commodity Futures Hierarchical Data Structure


code:
timeit.timeit('''numpy.random.choice([-1, 0, 1],
                                     size=1000,
                                     p=[0.25, 0.5, 0.25])''',
              'import numpy', number=10000)
timeit.timeit('''
var = []
for i in xrange(1000):
    tmp = rand.rand()
    if tmp < 0.25:
        var.append(1)
    elif tmp < 0.5:
        var.append(-1)
    else:
        var.append(0)''',
setup='import numpy.random as rand', number=10000)

rawDescription: Why is random.choice so slow?

description: Why is random.choice so slow


code:
from bottle import route, run,app,template
from itertools import cycle
docs_exclude = "/api-doc","/api-map"

@route('/api-doc',method=['GET'])
def api_doc():
    colors = cycle('#FFFFFF #CCCFDF'.split())
    routes = filter(lambda x:x.rule not in docs_exclude,app[0].routes)
    return template("bottle0_template",colors=colors,routes=routes)

@route('/token')
def token():
    '''
    grant api token

    params:
      username: string,username of user
      password: string, password of user
    '''
    return "ASD!@#!#!@#"

@route('/userinfo')
def userinfo():
    '''
    grant api token

    params:
      - username: string,username of user to retrieve data for
      - code: string, api access token
    '''
    return json.dumps({"name":"bob"})

#print app[0].routes[1].callback.__doc__#api-doc
run(host='localhost', port=8080, debug=True)

rawDescription: Documenting Python Bottle API With Custom Decorators/Attributes


code: string = string.partition(',')[0]

rawDescription: How to delete some characters from a string by matching certain character in python

description: Delete some characters from a string by matching certain character in python


code: employee_expenses = Expense.objects.filter(employee__name="John Doe")

rawDescription: django model foreignkeys question

description: Django model foreignkeys question


code:
#I want all columns except two
cols = df.columns.tolist()
mycols = [x for x in cols if not x in ['a','f']]
df_view = df[mycols]

rawDescription: How to df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled?

description: Df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled


code:
with open(logfilePath) as f:
    contents = f.read()  # warning: bad with big files; see below
    ...

rawDescription: How to cut short a long 'if' statement with multiple logical AND in Python?

description: Cut short a long 'if' statement with multiple logical AND in Python


rawDescription: Transform string in a list with elements separated on Python


code:
import hmac, hashlib
hmac.new('key', 'msg').hexdigest()
hmac.new('key2', 'msg').hexdigest()
hmac.new('key', 'msg', hashlib.sha256).hexdigest()

rawDescription: How to set the crypto key for Python's MD5 module?

description: Set the crypto key for Python's MD5 module


code: repr(['bar', Foo()])

rawDescription: Python __repr__ and None

description: Python __repr__ and None


code:
from re import sub
import sys
sys.modules['re'] = {}
from re import sub

rawDescription: I want to cause an ImportError

description: I want to cause an ImportError


rawDescription: Python:Ascii character<->decimal representation conversion


code: spl[4] = spl[4].replace("A", "B")

rawDescription: Replacing strings in specific positions into a text and then rewriting all the text


code:
"""
'Proof of concept' for a new reStructuredText directive *mathmacro*.

Use for example with::

  python mathmacro.py example.rst example.html

"""

import re

from docutils.parsers.rst.directives.misc import Replace

from docutils.parsers.rst.directives.body import MathBlock
from docutils.parsers.rst.roles import math_role

def multiple_replacer(replace_dict):
    """Return a function replacing doing multiple replacements.

    The produced function replace `replace_dict.keys()` by
    `replace_dict.values`, respectively.

    """
    def replacement_function(match):
        s = match.group(0)
        end = s[-1]
        if re.match(r'[\W_]', end):
            return replace_dict[s[:-1]]+end
        else:
            return replace_dict[s]

    pattern = re.compile("|".join([re.escape(k)+r'[\W_\Z]|'+re.escape(k)+r'\Z'
                                   for k in replace_dict.keys()]),
                         re.M)
    return lambda string: pattern.sub(replacement_function, string)

class MathMacro(Replace):
    """Directive defining a math macro."""
    def run(self):
        if not hasattr(self.state.document, 'math_macros'):
            self.state.document.math_macros = {}

        latex_key = '\\'+self.state.parent.rawsource.split('|')[1]
        self.state.document.math_macros[latex_key] = ''.join(self.content)

        self.state.document.math_macros_replace = \
            multiple_replacer(self.state.document.math_macros)

        self.content[0] = ':math:`'+self.content[0]
        self.content[-1] = self.content[-1]+'`'

        return super(MathMacro, self).run()

class NewMathBlock(MathBlock):
    """New math block directive parsing the latex code."""
    def run(self):
        try:
            multiple_replace = self.state.document.math_macros_replace
        except AttributeError:
            pass
        else:
            if self.state.document.math_macros:
                for i, c in enumerate(self.content):
                    self.content[i] = multiple_replace(c)
        return super(NewMathBlock, self).run()

def new_math_role(role, rawtext, text, lineno, inliner,
                  options={}, content=[]):
    """New math role parsing the latex code."""
    try:
        multiple_replace = inliner.document.math_macros_replace
    except AttributeError:
        pass
    else:
        if inliner.document.math_macros:
            rawtext = multiple_replace(rawtext)

    return math_role(role, rawtext, text, lineno, inliner,
                     options=options, content=content)

if __name__ == '__main__':

    from docutils.parsers.rst.directives import register_directive
    from docutils.parsers.rst.roles import register_canonical_role

    register_directive('mathmacro', MathMacro)
    register_directive('math', NewMathBlock)
    register_canonical_role('math', new_math_role)

    from docutils.core import publish_cmdline, default_description
    description = ('Generates (X)HTML documents '
                   'from standalone reStructuredText sources. '
                   +default_description)
    publish_cmdline(writer_name='html', description=description)

rawDescription: Math Latex macros in reStructuredText and Sphinx


code:
def func(idx, number):
  return lambda arg: arg[idx] == number

rawDescription: How to pick lines containg numbers in given positions on the line with python

description: Pick lines containg numbers in given positions on the line with python


code:
from __future__ import unicode_literals

my_string = b"This is a bytestring"
my_unicode = "This is an Unicode string"

rawDescription: Unicode in python with Django and MongoEngine


code: col2num = lambda col: reduce(lambda x, y: x*26 + y, [ord(c.upper()) - ord('A') + 1 for c in col])

rawDescription: Convert an excel or spreadsheet column letter to its number in Pythonic fashion


code:
import unicodedata
import sys

tbl = dict.fromkeys(i for i in xrange(sys.maxunicode)
                      if unicodedata.category(unichr(i)).startswith('P'))
def remove_punctuation(text):
    return text.translate(tbl)

rawDescription: Remove punctuation from Unicode formatted strings


code: R,C

rawDescription: How can I check if one two-dimensional NumPy array contains a specific pattern of values inside it?

description: Check if one two-dimensional NumPy array contains a specific pattern of values inside it


code:
for x,y in indices:
    i = grid[x][y]
    # do stuff with i

rawDescription: Indexing a list using the values in a tuple in python


code:
def second_largest(numbers):
    count = 0
    m1 = m2 = float('-inf')
    for x in numbers:
        count += 1
        if x > m2:
            if x >= m1:
                m1, m2 = x, m1
            else:
                m2 = x
    return m2 if count >= 2 else None

rawDescription: Get the second largest number in a list in linear time


code:
# If you want *all* your responses to be text/plain
# then this is what you want
@app.after_request
def treat_as_plain_text(response):
    response.headers["content-type"] = "text/plain"
    return response

# If you want only *this* route to respond
# with Content-Type=text/plain
@app.route("/plain-text")
def a_plain_text_route():
    response = make_response(getKickstartFile())
    response.headers["content-type"] = "text/plain"
    return response

rawDescription: Output Multi-line strings with Python Flask or other framework


code:
df = pd.read_csv(filename, header=None, names=['col1','col2','col3'],
                 skiprows=2, nrows=100)

rawDescription: Pandas: read_csv (read multiple tables in a single file)


code:
def foo3():
    data=[(a,b) for a in (i*i for i in range(1,101)) for b in [1,2,3,4,5] if a+b > 40]
    return data

rawDescription: How fast are nested python generators?

description: How fast are nested python generators


code: mock_func.__iter__.return_value = itertools.cycle([1, 2])

rawDescription: Mock infinite generator in Python

description: Mock infinite generator in Python


code:
res = json.loads(json_value)
res = {k: v for k, v in res.iteritems() if v is not None}

rawDescription: is there a way to config python json library to ignore fields that has null values when calling json.loads?

description: Is there a way to config python json library to ignore fields that has null values when calling json.loads


code:
def is_lambda_function(obj):
    return isinstance(obj, types.LambdaType) and obj.__name__ == "<lambda>"

rawDescription: How to check that variable is a lambda function

description: Check that variable is a lambda function


code:
from lxml import etree
import requests
r = requests.get('https://en.wikipedia.org/wiki/3M')
doc = etree.fromstring(r.text)
e = doc.xpath('//table[@class="infobox vcard"]/tr[th/div/text()="Number of employees"]/td')
e[0].text

rawDescription: Extracting data from a wikipedia page

description: Extracting data from a wikipedia page


rawDescription: Django access data passed to form

description: Django access data passed to form


code:
from matplotlib import pyplot as pp
from scipy.misc import lena

matrix = lena()
mask = sector_mask(matrix.shape,(200,100),300,(0,50))
matrix[~mask] = 0
pp.imshow(matrix)
pp.show()

rawDescription: Mask a circular sector in a numpy array

description: Mask a circular sector in a numpy array


rawDescription: How do you implement token authentication in Flask?

description: Implement token authentication in Flask


rawDescription: Pandas: apply a function to a multiindexed series


code:
import wx

class MainFrame ( wx.Frame ):
    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 800,600 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
        bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.SetSizer( bSizer1 )
        self.Layout()

        # self.panelOne = panel_one(self)
        # self.panelTwo = panel_two(self)
        # self.panelTwo.Hide()
        self.Centre( wx.BOTH )
    def __del__( self ):
        pass

class panel_one ( wx.Panel ):
    def __init__( self, parent ):
        wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( 800,600 ), style = wx.TAB_TRAVERSAL )
        bSizer5 = wx.BoxSizer( wx.VERTICAL )
        self.m_button2 = wx.Button( self, wx.ID_ANY, u"panel 1 button", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer5.Add( self.m_button2, 0, wx.ALL, 5 )
        self.SetSizer( bSizer5 )
        self.Layout()
        # Connect Events
        self.m_button2.Bind( wx.EVT_BUTTON, self.changeIntroPanel )
    def __del__( self ):
        pass
    # Virtual event handlers, overide them in your derived class
    def changeIntroPanel( self, event ):
        event.Skip()

class panel_two ( wx.Panel ):
    def __init__( self, parent ):
        wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( 800,600 ), style = wx.TAB_TRAVERSAL )
        bSizer5 = wx.BoxSizer( wx.VERTICAL )
        self.m_button2 = wx.Button( self, wx.ID_ANY, u"panel 2 button ", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer5.Add( self.m_button2, 0, wx.ALL, 5 )
        self.SetSizer( bSizer5 )
        self.Layout()
        # Connect Events
        self.m_button2.Bind( wx.EVT_BUTTON, self.changeIntroPanel )

    def __del__( self ):
        pass
        # Virtual event handlers, overide them in your derived class
    def changeIntroPanel( self, event ):
        event.Skip()

rawDescription: wxpython - One Frame, Multiple Panels, Modularized Code

description: Wxpython - One Frame, Multiple Panels, Modularized Code


rawDescription: python replace multiple elements in string with str methods

description: Python replace multiple elements in string with str methods


code:
for short_tuple in mylist:
    short_tuple_set = set(short_tuple)

    remainder = (i for i in range(1, 50) if i not in short_tuple_set)
    for combo in itertools.combinations(remainder, 5 - len(short_tuple)):
        combo = sorted(combo + short_tuple)

rawDescription: How do I find out if a combination of numbers are in another combination of numbers?

description: Find out if a combination of numbers are in another combination of numbers


code: output = fun(other_func())[0]

rawDescription: How to return a single value instead of a tuple?

description: Return a single value instead of a tuple


code:
def fib_aux(n):
    global recAdd
    recAdd = 0
    fibonacciRecursive(5)
    print(recAdd)

rawDescription: I cannot print the final value of a variable


code: arr.reshape((arr.shape[0], -1))

rawDescription: Convert 3d Numpy array to 2d

description: Convert 3d Numpy array to 2d


rawDescription: Python value conversion to string representation of postgres procedure parameter including type casting


code:
for node in (a, b, c, d):
    print(node.name, node.value)

rawDescription: Mapping a list of inputs to the lowest level of nested lists


code:
def function(stuff):
    NotImplemented

def setup():
    NotImplemented

setup_code = """
from __main__ import function, setup
data = setup()
"""
func_code = "function(data)"

result = timeit.timeit(func_code,setup_code)

rawDescription: How to use timeit for multiple values

description: Use timeit for multiple values


code:
a.append(str(b))
a

rawDescription: Add Integer into existing list

description: Add Integer into existing list


code: np.asarray(np.rec.fromarrays(t.T, dt))

rawDescription: ValueError while trying to convert an array of strings to an array with mixed given dtypes


code:
import mylib

c2 = mylib.Foo(1,2)
Foo(int, int)

c3 = mylib.Foo(1,1,1)
Foo(int, int, int)

mylib.test(c2)
0x1521df0

mylib.test(c3)
0x1314370

c2a = c2
mylib.test(c2a)
0x1521df0 # the object has the same address of c2

rawDescription: boost python make_constructor with default arguments

description: Boost python make_constructor with default arguments


code:
from lxml.html.clean import clean_html
clean_html(page)

rawDescription: Python how to search and correct html tags and attributes?


code: kelime = content[0]  # As opposed to content[0:1]

rawDescription: Python reading from file into list then use line as list too and reach each char


code:
destroyedStatus = Status.objects.get(description="destroyed")
clients_destroyed_items = StorageItem.objects.filter(client=client,
    itemstatushistory__status=destroyedStatus)

rawDescription: Query for items using filter for most recent entry in a related table


code:
list_of_all = [instruction_reader(item) for item in line1]
opcodes = [op[0] for op in list_of_all]
dests = [dest[1] for dest in list_of_all]
srcs = [src[2] for src in list_of_all]

rawDescription: Python: Script to detect data Hazards

description: Python: Script to detect data Hazards


rawDescription: Converting Python (PyKinect) Skeleton data to Points (X,Y)


code:
from twisted.python.reflect import fullyQualifiedName
fullyQualifiedName(fullyQualifiedName)

rawDescription: Send method to subprocess

description: Send method to subprocess


rawDescription: How to sort a matrix in the ascending order by the sum of its row in Python?

description: Sort a matrix in the ascending order by the sum of its row in Python


code:
import example
spam = example.Spam()
assert(0 == example.get_count())
example.func(spam)
assert(1 == example.get_count())
try:
    example.func(1)
    assert(False)
except TypeError:
    pass

assert(1 == example.get_count())

rawDescription: Can not access destructor from python C++ wrapper


code:
class CustomRenameTemplate(Template):
    def __init__(self, *args, **kws):
        super(CustomRenameTemplate, self).__init__(*args, **kws)
        self.orig_template = self.template
        self.template = self.template.lower()

    def do_template_based_capitalization(self, mapping):
        matches = self.pattern.findall(self.orig_template)
        for match in matches:
            keyword = match[self.pattern.groupindex['braced']-1]
            if keyword[0] in uppercase:  # First letter is CAPITALIZED
                if keyword == keyword.upper():  # Condition for full capitalization
                    mapping[keyword.lower()] = mapping[keyword.lower()].upper()
                else:  # Condition for only first letter capitalization
                    mapping[keyword.lower()] = mapping[keyword.lower()].capitalize()

    def safe_substitute(self, *args, **kws):
        mapping = get_mapping_from_args(*args, **kws)
        self.do_template_based_capitalization(mapping)
        return super(CustomRenameTemplate, self).safe_substitute(mapping)

    def substitute(self, *args, **kws):
        mapping = get_mapping_from_args(*args, **kws)
        self.do_template_based_capitalization(mapping)
        return super(CustomRenameTemplate, self).substitute(mapping)

rawDescription: Python String Templating with Case Sensitivity


code:
from statsmodels.nonparametric.smoothers_lowess import lowess
filtered = lowess(pressure, time, is_sorted=True, frac=0.025, it=0)
plot(time, pressure, 'r')
plot(filtered[:,0], filtered[:,1], 'b')

rawDescription: How to filter/smooth with SciPy/Numpy?

description: Filter/smooth with SciPy/Numpy


code:
def change_Title(self, title, *args):
    main = MainApp()  # !
    main.change_curr_title(title)

rawDescription: Kivy - Why Label does not update?

description: Kivy - Why Label does not update


rawDescription: how to return dynamic json as response from google cloud endpoint python

description: Return dynamic json as response from google cloud endpoint python


code:
def is_palindrome(text):
    return text[:len(text)//2] == text[:(len(text)-1)//2:-1]

rawDescription: Palindromes function does not work

description: Palindromes function does not work


code: command = 'echo python foo.py %s %s | at %s' % (arg1, arg2, starttime)

rawDescription: Creating A Linux at Job (scheduling) in Python


code:
nsmap = {'phylo': 'http://www.phyloxml.org'}
tree.xpath('//phylo:name[text()="Espresso"]', namespaces=nsmap)

rawDescription: how to add an xml node based on the value of a text node

description: Add an xml node based on the value of a text node


rawDescription: Grouping items in two lists

description: Grouping items in two lists


rawDescription: What is the fastest way to convert string to array in python?


code:
from math import exp
exp(x)

rawDescription: Python: Questions about math and negative power


code:
tmp = "a,b,cde"
tmp2 = tmp.split(',')
tmp2.reverse()
"".join(tmp2)

rawDescription: Python: How exactly can you take a string, split it, reverse it and join it back together again?


code:
a = object()
a.b = 'c'

rawDescription: Python create list of objects from list of 2 elements lists


code:
class MonatlicherVerbrauch(models.Model):
    ...
    def get_absolute_url(self):
        return reverse('messstellen:messtelle_detail', args=[self.pk])

rawDescription: Sucess_url based on pk in GenericView from urls.py


code:
from collections import OrderedDict
[set(i) for i in OrderedDict.fromkeys(frozenset(item) for item in L)]

rawDescription: removing duplicates of a list of sets

description: Removing duplicates of a list of sets


code:
d2
np.dtype(d2)
desired_type

rawDescription: Best Way to Resize Numpy Dtype for Structured data


code: first5 = itertools.combinations(range(1, 59+1), 5)

rawDescription: Generating Combinations NOT Permutations. How?


rawDescription: How can I tranform this (100, 100) numpy array into a grayscale sprite in pygame?

description: Tranform this (100, 100) numpy array into a grayscale sprite in pygame


rawDescription: Open source language/library/representation format that allows treating numeric formulas as objects?


code:
google_news_articles.push(JSON.stringify({
    date:           each_article.find('.date').text(),
    outlet_domain:  strip(each_article.find('.outlet_domain').text()),
    title:          each_article.find('.title').text(),
    link:           each_article.find('.title').attr('href')
}));

rawDescription: Send JSON list from Javascript to Django Backend and parsing it properly


rawDescription: How to convert an array of 27 bytes where each 3 bytes is a 2's complement number into its numeric equivalent?

description: Convert an array of 27 bytes where each 3 bytes is a 2's complement number into its numeric equivalent


rawDescription: Python - Finding each occurrence of a value in a mixed array (integers, lists)


code:
chunks = [
    {
        'offset': struct.unpack('<I', stream_file.read(int_length))[0],
        'length': struct.unpack('<I', stream_file.read(int_length))[0]
    }
    for _ in xrange(chunks_count)
]

rawDescription: Python Out of memory in range

description: Python Out of memory in range


code:
sys.modules['os.path'] = path
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
    devnull)

rawDescription: How does os.path map to posixpath.pyc and not os/path.py?


code:
import sys
a = 'hello'
sys.getsizeof(a)
b = {'foo': 'bar'}
sys.getsizeof(b)
sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())

rawDescription: How can I copy a Python string?

description: Copy a Python string


code:
m=mdb.models['Model'].rootAssembly
inst=m.instances['instance']
mask=inst.cells.getMask()
partinstance_obj1=inst.cells.getSequenceFromMask(mask=mask)
prop1=mdb.models['Model'].rootAssembly.getMassProperties(regions=(partinstance_obj1,)) #Regions here will accept only a sequence of part instance obj

rawDescription: How do i query the parts' volume information with abaqus python script in abaqus/cae and abaqus/viewer mode?

description: Query the parts' volume information with abaqus python script in abaqus/cae and abaqus/viewer mode


code: lis = [u'File:Saddam Hussein (107).jpg', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'File:AlBakr.jpg', u'Template:Fn (page does not exist)', u'File:Chiracsaddam.jpg', u'File:Donald saddam.jpg', u'Template:Fn (page does not exist)', u'File:SaddamandCuellar.jpg.jpg', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'File:SaddamBaghdadwalkabout.jpg', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fn (page does not exist)', u'Kurdish Patriotic Front (page does not exist)', u'File:TrialSaddam.jpg', u'Mohammad Rashdan (page does not exist)', u'Emmanuel Ludot (page does not exist)', u'Marc Henzelin (page does not exist)', u'Adnan Khairallah Tuffah (page does not exist)', u'Nidal al-Hamdani (page does not exist)', u'Ali Hussein (page does not exist)', u'File:SaddamandRana.jpg.jpg', u'Saddam Kamel Majid (page does not exist)', u'Template:Fn (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)', u'Template:Fnb (page does not exist)']

rawDescription: Deleting elements with specific substring in python


code: now_playing_object = None

rawDescription: How can one object instance stop sound that other instance is playing?


code:
mytext = "this is my/string"
mytext = s[:s.rindex('/')] + '/text'

rawDescription: Python: Replace a string starting from a charecter


code:
exitFlag = False
for i in range(1,100):
    for j in range(1,100):
        exitFlag = True
        break
    if exitFlag:
        break

rawDescription: break two for loops

description: Break two for loops


code:
from weakref import WeakValueDictionary

_handle_dict = WeakValueDictionary()
def cache(filename):
    def decorating_function(user_function):
        def wrapper(*args, **kwds):
            args_key = str(hash(functools._make_key(args, kwds, typed=False)))
            func_key = '.'.join([user_function.__module__, user_function.__name__])
            key = func_key + args_key
            handle_name = "{}_handle".format(filename)
            if handle_name in _handle_dict:
                print("Using open handle")
                return _check_cache(_handle_dict[handle_name], key,
                                    user_function, args, kwds)
            else:
                print("Opening handle")
                with shelve.open(filename, writeback=True) as c:
                    _handle_dict[handle_name] = c
                    return _check_cache(c, key, user_function, args, kwds)

        return functools.update_wrapper(wrapper, user_function)
    return decorating_function

rawDescription: Can Python's shelve.open be called in a nested fashion?


code:
with open('data.txt') as f:
    lines=[x.strip() for x in f]
    spaces=lines.count('')   #count the number of empty lines
    odd_spaces=spaces//2+1   #odd lines 1,3,5,7...
    even_spaces=spaces-odd_spaces #even lines 2,4,6,...

    it=iter(range(1,spaces+1)) #create an iterable
    try:
        lines=[x if x!='' else next(it) for x in lines]  #if line is empty then call next(it)
    except StopIteration:
        pass
    for x in lines:
        print(x)

    fil=[4*x+1 for x in range(0,spaces+1) if 4*x+1<spaces] #4x+1
    print(fil)
    row=[lines[lines.index(x)-1] for x in fil]
    print(row)

    fil=[2*x+1 for x in range(0,spaces+1) if 2*x+1<spaces] #2x+1
    print(fil)
    row=[lines[lines.index(x)-1] for x in fil]
    print(row)

rawDescription: auto increment numbering of multi line which are blank

description: Auto increment numbering of multi line which are blank


rawDescription: Consuming from queues based upon external event (event queues)


code:
def insert_names(self, names):
    # `names` is a list of dicts

    inserted_ids = []

    for name in names:
        name['created'] = datetime.datetime.now()
        _id = self.myorders.insert(name)
        inserted_ids.append(_id)

    return inserted_ids

rawDescription: MongoDB data Posting

description: MongoDB data Posting


code:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
b1 = BitArray.from_array([i >= 3 for i in arr])
print(b1)
new_int = 9
b1 <<= 1
b1 |= (new_int >= 3)
b1.ltrim(1)
print(b1)

rawDescription: Python dynamic bit manipulation example

description: Python dynamic bit manipulation example


code:
all = sum([ list(set(x)) for x in (l1,l2,l3,l4,l5) ],[])
c = [[x,all.count(x)] for x in set(all)]
[x[0] for x in c if x[1] > 2]

rawDescription: Finding common elements in a few lists out of all lists in python


code:
for el in range(10):
  print(el)

rawDescription: 2to3 range(...) -> list(range(...))

description: 2to3 range(...) -> list(range(...))


code:
for i in content[:]:
    m=re.match(r'.*[\t\n\r\f\v]+',i)
    if m:
       content.remove(i)

content

rawDescription: Regex not matching \t\n\r\f\v in Python

description: Regex not matching \t\n\r\f\v in Python


code:
def is_instance_userdefined_and_newclass(inst):
    cls = inst.__class__
    if hasattr(cls, '__class__'):
        return ('__dict__' in dir(cls) or hasattr(cls, '__slots__'))
    return False

rawDescription: How to check if object is instance of new-style user-defined class?

description: Check if object is instance of new-style user-defined class


code:
A=np.matrix([1,2,3])
A.shape
A[0]
A[0].shape

rawDescription: Matrix indexing in Numpy

description: Matrix indexing in Numpy


rawDescription: xtick max value setup with panda and matplotlib

description: Xtick max value setup with panda and matplotlib


code:
mapping = ['name', 'email', 'lastlogon', 'more_fields', 'again_more_fields', 'and_so_on']
for row in results:
   readable_row = dict(zip(mapping, row))
   print(readable_row)
   # will print something like {'name': '...', 'email': '...', ...}

rawDescription: python copy to multiple variables

description: Python copy to multiple variables


code: return (account for account in self.accounts if account.type == 'equity').next()

rawDescription: Get specific object from a list with a certain parameter


rawDescription: Computing an md5 hash of a data structure


rawDescription: Confusion with properties

description: Confusion with properties


code:
def clickedTree1(self,index):
    node = index.internalPointer()
    print("You select item in treeView1 " + node.name())

def clickedTree2(self,index):
    node = index.internalPointer()
    print("You select item in treeView2 " + node.name())

rawDescription: PyQt 2 trees and button

description: PyQt 2 trees and button


code:
foo = np.array([[1, 2], [3, 4]])
mask = np.array([[True, False], [False, True]])
foo[mask]

rawDescription: Adding elements in arrays that fall within a criteria in Python


code: sentence

rawDescription: python: open and read a file containing germanic umlaut as unicode

description: Python: open and read a file containing germanic umlaut as unicode


code:
# pylung.py
import sys

def deutsch():
    import os
    os.durchlaufe = os.walk
    # etc...
    import collections
    sys.modules['kollektionen'] = sys.modules['collections']

rawDescription: Replace object with another in the entire process / become in Python


code: import copy

rawDescription: Python stack contents are overwritten when passed to a function


code:
df["PROFIT"] = np.where((df[TARGET_NAME] == df["PREDICTED"]) & (df["PREDICTED"].isin([0])),
                                  df['MATCH_HOME'] * df['HOME_STAKE'],
                                  np.where((dfml[TARGET_NAME] == df["PREDICTED"]) & (df["PREDICTED"].isin([1])),
                                           df['MATCH_DRAW'] * df['DRAW_STAKE'],
                                           np.where((df[TARGET_NAME] == df["PREDICTED"]) & (df["PREDICTED"].isin([2])),
                                                    df['MATCH_AWAY'] * df['AWAY_STAKE'],
                                                    0))).astype(float)

rawDescription: Pythonic way to simplify multiply 2 pandas columns with condition


rawDescription: what's the inverse of the quantile function on a pandas Series?

description: What's the inverse of the quantile function on a pandas Series


code:
rfft = np.fft.rfft(y)
np.mean((rfft * rfft.conj()).real)
rfft /= np.sqrt(len(rfft))
np.mean((rfft * rfft.conj()).real)
np.mean((rfft * rfft.conj()).real) / len(rfft)

rawDescription: (numpy) Wrong amplitude(?) of FFT'd array?


code:
def del_endpoint(dictionary, path):
    parent_path, last = path[:-1], path[-1]
    parent = resolve_path(dictionary, parent_path)
    del parent[last]

rawDescription: How to delete object in a dict by reference from another variable

description: Delete object in a dict by reference from another variable


code: a

rawDescription: Using bool array mask, replace False values with NaN


rawDescription: Python: split float after 3rd decimal place


rawDescription: Calculate the euclidean distance in scipy csr matrix


code:
class A:
   def __str__(self):
      return "Something useless"

class B(A):
   def __str__(self):
      return object.__str__(self)

rawDescription: Python : Revert to base __str__ behavior


code:
col_prefix = "Base (MW) "
for col in ['Allocated', 'Bought', 'Sold', 'Remaining']:
    treatment = None if col != 'Bought' else boughtColClipper
    df[col] = baseMultiply(df, col_prefix + col, preTreat=treatment)

rawDescription: Refactoring a bad 'code smell' in multiplication of columns in a dataframe


code:
import cmath
def point_pos(p, d, theta):
    return p + cmath.rect(d, pi/2-radians(theta))

rawDescription: Python: find a x,y coordinate for a given point B using the distance from the point A (x0, y0) and the angle


rawDescription: analyzing a txt file in python by jumping the n_th element of a list

description: Analyzing a txt file in python by jumping the n_th element of a list


code:
import itertools as it

colors = ('b','g','r',)
sessions = (sess1, sess2, sess3, sess4, sess5, sess6)
for sess, color in zip(sessions, it.cycle(colors)):
    ax.plot(sess.x, sess.y, color=color)

rawDescription: matplotlib - runtime adding multiple lines without knowing in advance

description: Matplotlib - runtime adding multiple lines without knowing in advance


code: getter = operator.itemgetter(2, 3, 4, 5, -4)

rawDescription: Slices with several intervals?

description: Slices with several intervals


code: matrix = [[1 if i == j else 0 for j in content2] for i in content1]

rawDescription: What is the easier way to initialize a matrix in Python?


rawDescription: How to find two consecutive positive-negative values in an array?

description: Find two consecutive positive-negative values in an array


code:
script = 'echo {}'.format(shlex.quote(jj['pp']))
subprocess.call(script, shell=True)

rawDescription: Execute the shell script by passing certain parameters to it using Python?


rawDescription: Create New Columns in dataFrame using existing columns in Panda


code:
p = (db.session.query(Person)
     .options(db.eagerload(Person.region))
     .get(1)
     )

print(p)
# below will not trigger any more SQL, because `p.region` is already loaded
print(p.region.name)

rawDescription: setup relationship one-to-one in Flask + SQLAlchemy

description: Setup relationship one-to-one in Flask + SQLAlchemy


rawDescription: How to hide _id from find_and_modify() - MongoDB?

description: Hide _id from find_and_modify() - MongoDB


code:
A = 'xyz'
B = 'pdq'
d = {A:B, B:A}
x = A
x = d[x]         # toggle
x
x = d[x]         # toggle
x
x = d[x]         # toggle
x

rawDescription: toggle a value in Python

description: Toggle a value in Python


code:
counter = Counter({'dlr': 21, 'said': 18, 'total': 17, 'bankamerica': 13, 'bank': 11, 'analyst': 9, 'prev': 9, 'februari': 8, 'york': 8, 'would': 8, 'price': 8, 'time': 8, 'wheat': 7})
counter2 = Counter({k:v/2 for k,v in counter.items()})
counter2

rawDescription: How to concatenate String count and Int

description: Concatenate String count and Int


code: colors = ['red', 'green', 'blue']

rawDescription: Labelling and coloring plots inside loop - matplotlib


code: newID = db.insert_id()

rawDescription: How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?

description: Safely and efficiently get the row id after an insert with mysql using MySQLdb in python


rawDescription: Groupby in pandas timeseries dataframe choosing most recent event


code:
def calculate(inputs):
    if not inputs:
        return
    s = make_empty_stack()
    for item in inputs:
        if item in ops:
            op2, op1 = pop_stack(s), pop_stack(s)
            res = ops[item](op1, op2)
            push_stack(s, res)
        else:
            push_stack(s, item)
    return pop_stack(s)

rawDescription: Stack, Pop and Add

description: Stack, Pop and Add


rawDescription: Inexpensive way to add time series intensity in python pandas dataframe


code:
grammar = pyparsing.Combine(Literal("from") + Literal(":") + Word(pyparsing.alphas))
grammar.parseString('from : mary')
grammar.parseString('from:mary')

rawDescription: How to disallow spaces in between literals in pyparsing?

description: Disallow spaces in between literals in pyparsing


rawDescription: How do I parse out the following HTML in python beautifulsoup?

description: Parse out the following HTML in python beautifulsoup


rawDescription: Display the date, like "May 5th", using pythons strftime?


code:
box1 = first.boxplot(ax=ax,notch=False,widths=0.20,sym='',rot=-45, positions=np.arange(0.0,4.0,1.0))
box2 = second.boxplot(ax=ax,notch=False,widths=0.20,sym='',rot=-45, positions=np.arange(0.3,4.3,1.0))

rawDescription: Pandas boxplot x-axis setting

description: Pandas boxplot x-axis setting


code:
#create a frame with a timeseries index and a unnamed column
rng = pd.DatetimeIndex(pd.to_datetime(['1/1/2014','1/2/2014','1/2/2014', '1/3/2014', '1/3/2014','1/4/2014','1/6/2014']))
df = pd.DataFrame({None:[5,6,7,8,2,3,6],'date':rng})
df.set_index('date', inplace=True)

# add frames to dict
frames ={}
for i in range(3):
    frames[i] = df

rawDescription: Rename Pandas column inside Python dictionary


code:
cols_string = '('
for x, i in enumerate(cols):
    if x != len(cols) - 1:
        cols_string += i + ','
    if x == len(cols) - 1:
        cols_string += i + ')'

rawDescription: Create a string for sql statement from function **keywords


rawDescription: Vector algebra in functional

description: Vector algebra in functional


code:
def some_actions(a, b):
    # some actions here
    ...
    return c

rawDescription: unittest Vs pytest

description: Unittest Vs pytest


code: flattened = data.T.flatten()

rawDescription: Flatten OpenCV/Numpy Array

description: Flatten OpenCV/Numpy Array


code: ParseResult(scheme='http', netloc='127.0.0.1:8000', path='/data/number/', params='', query='', fragment='')

rawDescription: strip string from url in Python

description: Strip string from url in Python


rawDescription: How to implement high speed, consistent sampling?

description: Implement high speed, consistent sampling


rawDescription: Longest increasing subsequence

description: Longest increasing subsequence


code: rc[:]['MyClass'] = MyClass

rawDescription: How to work with interactively-defined classes in IPython.parallel?

description: Work with interactively-defined classes in IPython.parallel


code:
def dictify(ul):
    result = {}
    for li in ul.find_all("li", recursive=False):
        key = next(li.stripped_strings)
        ul = li.find("ul")
        if ul:
            result[key] = dictify(ul)
        else:
            result[key] = None
    return result

rawDescription: Parsing nested HTML list with BeautifulSoup


rawDescription: Sublime Text 2 plugin: capture the selected text


code: monkeys_punched_yet = False

rawDescription: How to disable/restrict a line of code after it has been run? (Python)

description: Disable/restrict a line of code after it has been run? (Python)


rawDescription: Stacking and shaping slices of DataFrame (pandas) without looping


code:
import readchar

variable = ""
while len(variable) != 8:
    variable += str(readchar.readchar())

rawDescription: Python - Loop waiting for input

description: Python - Loop waiting for input


rawDescription: How to access way coordinates from a large (.json-based) list structure

description: Access way coordinates from a large (.json-based) list structure


rawDescription: Merge 2 columns in pandas into one columns that have data in python


code:
def iterate(message, app, messages):
    change(message)
    update_widget(app, messages)

def update_widget(app, messages):
    message = next(messages, None)
    if message is None: # end of the loop
        return
    delay = int(message.time * 1000) # milliseconds
    app.after(delay, iterate, message, app, messages)

update_widget(app, iter(listOfMessages))

rawDescription: time.sleep() Equivalent on Tkinter

description: Time.sleep() Equivalent on Tkinter


code:
L = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
columns = list(zip(*L))
columns
columns[1] # 2nd column

rawDescription: Appending nested list values into a new list


code:
my_values = Range('Sheet1','A1:A6').options(ndim=2).value
Range('Sheet2','A1:A6').value = my_values

rawDescription: python xlwings - copy and paste ranges

description: Python xlwings - copy and paste ranges


rawDescription: Numpy masked operations

description: Numpy masked operations


code:
input_data = np.array(inputArray)
outputlist = [] # Better position for outputList
for eqnSet in symEqns:
    for eqn in eqnSet:
        func = sp.lambdify(['R_0', 'R_1'], eqn, 'numpy')
        outputList.append(func(input_data[:,0], input_data[:,1]))

rawDescription: Improving Performance - Symbolic function applied to each row of numpy array


code:
def tabulate(function, start=0, step=1):
    "Return function(0), function(0+step), ..."
    return imap(function, count(start, step))

rawDescription: Are there already python generators that do these basic things?


code:
import os
import numpy as np
import pandas as pd

np.random.seed(2016)
df = pd.DataFrame(np.random.randint(10, size=(100, 2)), columns=list('AB'))
df.to_csv('file_csv.csv')
if os.path.exists('file_csv.hdf'): os.unlink('file_csv.hdf')
for i, df in enumerate(pd.read_csv('file_csv.csv', chunksize=50)):
    print('Saving {} chunk...'.format(i), end='')
    df.to_hdf('file_csv.hdf',
              'file_csv',
              format='table',
              data_columns=True,
              append=True)
    print('Done!')
    print(df.loc[df['A']==1])
print('-'*80)
df_hdf = pd.read_hdf('file_csv.hdf', where="A=1")
print(df_hdf)

rawDescription: Pandas HDF limiting number of rows of CSV file


code:
parentorg = Parentorgs.objects.values_list("pk", flat=True)
contracts = Contracts.objects.filter(parentorg_id__in=parentorg)

rawDescription: Odd values_list and filter behavior in Django


code:
def __init__(self, value=None, children=None):
    if not children:
        children = {}

rawDescription: class getting kwargs from enclosing scope

description: Class getting kwargs from enclosing scope


rawDescription: changing given text to list of lists

description: Changing given text to list of lists


code: inner

rawDescription: Introspection on a python decorated method


code: genres = df.Genre.str.split('|', expand=True)

rawDescription: Converting a dataframe in pandas to another one


rawDescription: String formatting of timedeltas in Pandas


rawDescription: Applying python decorators to methods in a class


code: [value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]

rawDescription: Getting all constants within a class in python


code: output_filename = "".join([x if x.isalnum() else "_" for x in required_text[:80]]).replace('__', '_').strip('_')

rawDescription: How to process the response from the server using Python?

description: Process the response from the server using Python


code:
class A(object):
    def __new__(cls, *args, **kw):
        instance = super(A, cls).__new__(cls, *args, **kw)
        return [instance]

rawDescription: (Python) __new__ method returning something other than class instance


code:
import pyfits
from scipy.io import *
M=read_array(filename)

rawDescription: How is it possible in python to convert an ascii table to a fits table?


rawDescription: Pythonic sort a list of dictionaries in a tricky order


code:
def cleanup(dirty_data):
    if isinstance(dirty_data, dict):
        for key in dirty_data:
            value = dirty_data[key]
            dirty_data[key] = cleanup(value)
        return dirty_data
    elif isinstance(dirty_data, str):
        if dirty_data in ["nan", "inf", "-inf"]:
            return float(dirty_data)
    else:
        return dirty_data

test_object = {"test": 123, "a": {"b": "nan"}}

print(cleanup(test_object))

rawDescription: python - replace value of unknown key in json

description: Python - replace value of unknown key in json


rawDescription: using an integer in a string to create a dictionary (or list) with that many numbers

description: Using an integer in a string to create a dictionary (or list) with that many numbers


rawDescription: how to find avg of column of csv file

description: Find avg of column of csv file


code: A.extend(B or ['no value'])

rawDescription: If list has values, append them to another list, else append predefined value


code:
ws = gen_ws(25)
via_slow = slow(*ws)
via_fast = fast(*ws)
np.allclose(via_slow, via_fast)

rawDescription: How can I efficiently expand a factored tensor in numpy?

description: Efficiently expand a factored tensor in numpy


code:
plt.figure()
COUNT_TO_SIZE = 1./10
plt.scatter(lat, lon, s=counts*COUNT_TO_SIZE)
plt.savefig('scatter_example2.png')

rawDescription: Python: How to plot a heatmap for coordinates with different color intensity or different radius of circles?


rawDescription: Splitting lists to make dictionary python


code: ' a '.strip()

rawDescription: Extract unicode substrings with the re module


code:
import difflib

def make_path_grouper():
    matcher = difflib.SequenceMatcher()
    def path_grouper(path):
        if not matcher.a:
            matcher.set_seq1(path)
            return path
        else:
            matcher.set_seq2(path)
            matchings = matcher.get_matching_blocks()
            # arbitrary code to decide whether we have a match
            if any(size > 14 for _,_,size in matchings):
                # we have a match
                return matcher.a
            else:
                # no match. The new path supersedes old "a"
                matcher.set_seq1(path)
                return path
    return path_grouper

rawDescription: How to cluster similar file paths?

description: Cluster similar file paths


code:
class Test:

    def __init__(self):
        self.a = 10
        self.b = 20
        self.c = 30

    def _read_vars(self):
        return self.a, self.b, self.c

    def dosomething(self):
        a, b, c = self._read_vars()
        return a + b * c

    def dosomethingelse(self):
        a, b, c = self._read_vars()
        return a - b * c

rawDescription: Python importing class attributes into method local namespace


code: tt[1].apply(lambda x: x.hour)

rawDescription: pandas warning with pd.to_datetime

description: Pandas warning with pd.to_datetime


rawDescription: eliminate text after certain character in python pipeline- with slice?

description: Eliminate text after certain character in python pipeline- with slice


rawDescription: create list using if and else condition

description: Create list using if and else condition


code: deck.append([num, suite])

rawDescription: How to approach implementing 'class Card' as required by Python textbook

description: Approach implementing 'class Card' as required by Python textbook


code:
# setup python to not import _decimal (c implementation of Decimal) if present
import sys

if "_decimal" in sys.modules or "decimal" in sys.modules:
    raise ImportError("fixedpointdecimal and the original decimal module do not work"
        " together")

import builtins
_original_import = __import__
def _import(name, *args, **kwargs):
    if name == "_decimal":
        raise ImportError
    return _original_import(name, *args, **kwargs)
builtins.__import__ = _import

# import pure-python implementation of decimal
import decimal

# clean up
builtins.__import__ = _original_import # restore original __import__
del sys, builtins, _original_import, _import # clean up namespace

rawDescription: Python decimal context for fixed point

description: Python decimal context for fixed point


code:
s='''
<root>
  <Car>
    <Color>Blue</Color>
    <Make>Chevy</Make>
    <Model/>
  </Car>
</root>'''
e = lxml.etree.fromstring(s)
carData = e.xpath('Car/node()')
carData
dict(((e.tag, e.text) for e in carData))

rawDescription: Parsing blank XML tags with LXML and Python


code:
from subprocess import check_output
def whois(k,  i):
    k = str(k[i])
    who = check_output(['whois',  k], universal_newlines=True)
    who = who.split('NetName:')[1]
    who = who.split('NetHandle')[0]
    return  who.replace(r'\n', '')

rawDescription: re.split return None in function but normaly works OK

description: Re.split return None in function but normaly works OK


code:
import ply.yacc as yacc
from h_lexer import tokens

named_structs = {}

def p_prog(p):
    'prog : named_strucs struc'
    p[0] = p[2]

def p_named_structs_empty(p):
    'named_strucs : '

def p_named_structs(p):
    'named_strucs : named_strucs named_struc'

def p_named_struct(p):
    'named_struc : NAME COLON struc'
    global named_structs
    named_structs[p[1]] = p[3]

def p_struc(p):
    'struc : BEG affects END'
    # print("STRUCT", p[2])
    p[0] = p[2]
def p_typ(p):
    'typ : TYPE'
    p[0] = p[1]

def p_pad(p):
    'pad : PAD'
    p[0] = p[1]

def p_pad_n(p):
    'pad : NUMBER PAD'
    p[0] = p[1] + p[2]

def p_affect_pad(p):
    'affect : NAME COLON pad'
    p[0] = (None, p[3])

def p_val(p):
    '''val : typ
           | struc'''
    p[0] = p[1]

def p_val_struct(p):
    'val : NAME'
    test_named_struct(p[1])
    p[0] = named_structs[p[1]]

def p_nval_single(p):
    'nval : val'
    p[0] = p[1]

def p_nval_multi(p):
    'nval : NUMBER val'
    n = int(p[1])
    if n == 0:
        raise SyntaxError
    if n == 1:
        print('WARN: array of one single element')
    p[0] = tuple([ p[2] for i in range(n) ])

def p_affect(p):
    'affect : NAME COLON nval'
    p[0] = (p[1], p[3])

def p_affects_init(p):
    'affects : affect'
    p[0] = [ p[1] ]

def p_affects_multi(p):
    'affects : affects COMMA affect'
    p[0] = p[1] + [ p[3] ]

def p_error(p):
    print ("Syntax error", p)

def test_named_struct(name):
    global named_structs
    if name not in named_structs:
        raise SyntaxError

rawDescription: Unpacking deeply nested struct with given C header into dictionary?


code:
def replacer(word, guess):
    return "".join('_' if char != guess else char for char in word)

assert(replacer("cow", "o") == "_o_")

rawDescription: Replace a certain index of a string in python 3.0


code:
import matplotlib.pyplot as plt
import pandas as pd
x = [[1.2, 2.3, 3.0, 4.5],
     [1.1, 2.2, 2.9, 5.0]]
df = pd.DataFrame(x, index=['Age of pregnant women', 'Age of pregnant men'])

df.T.boxplot(vert=False)
plt.subplots_adjust(left=0.25)
plt.show()

rawDescription: Horizontal box plots in matplotlib/Pandas


rawDescription: Python 2D table lookup by labels

description: Python 2D table lookup by labels


code:
for i in range(num_to_run):
    pool.apply_async(popen_wrapper, args=(i,), callback=log_result)

rawDescription: python multiprocessing - select-like on running processes to see which have one have finished

description: Python multiprocessing - select-like on running processes to see which have one have finished


code:
sentinel = '' # ends when this string is seen
for line in iter(raw_input, sentinel):
    pass # do things here

rawDescription: Raw input across multiple lines in Python


code:
class TaskcreateForm(forms.ModelForm):
    projects = forms.ModelChoiceField(queryset=Project.objects.none())
    class Meta:
        model = Task

rawDescription: CreateView use parameters

description: CreateView use parameters


code:
rx = re.compile(r'Process\(([^)]+)\)')
processes_filtered = set([m.group(1) \
    for process in processes \
    for m in [rx.search(process)] if m])

rawDescription: Python: Using Regex to create an array of non-duplicate entries


code:
4
instances(MyClass)

rawDescription: Python: different behavior using gc module in interactive mode


code:
from requests.auth import HTTPDigestAuth
r = requests.get(url, auth=HTTPDigestAuth('user', 'pass'))

rawDescription: How to use Python to retrieve xml page that requires http login?

description: Use Python to retrieve xml page that requires http login


code: week_matrix = ((i,j,0) for i in xrange(7) for j in xrange(n_day_cells))

rawDescription: Replace for-loop across week with list comprehension


code:
elements = driver.find_elements_by_tag_name("td")
for element in elements:
    if element.text == "Click here!":
        element.click()

rawDescription: How to click a link in WebDriver using Python?

description: Click a link in WebDriver using Python


code:
def search(request):
    query = request.POST.get('qs', '')
    results = SomeModel.objects.filter(name=query) # Your search algo goes here
    return render(request, 'search_results.html', dict(results=results))

rawDescription: Implementing Universal Search in a Django Application


code:
class EmptyClass:
    pass

x = EmptyClass()
x.data = 5
def something(ref):
    ref.data = 10
something(x)
print(x.data)    # now prints 10

rawDescription: Sharing data among instances of a mapping function in Python


code:
# Regular Python's scientific notation, split up to coefficient and exponent.
x, e = "{:1.7E}".format(timepoint).split("E")

# Format again: coefficient first, then sign, then padded "sign-less" exponent.
strTimepoint = "{}E{}{:0>3}".format(x, e[0], e[1:])

rawDescription: How does one use the format() method in python to pad numbers after the E exponent with zeros?

description: Use the format() method in python to pad numbers after the E exponent with zeros


code:
from datetime import datetime, timedelta
BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y").date()
datetime.strptime('11:00AM', '%I:%M%p').time()
datetime.combine(BoW, _)

rawDescription: Strings with start and end time to datetime


rawDescription: Comparing List and get indices in python


code:
k = x['onclick']
re.findall("'(\w+)'",k)

rawDescription: Python to get onclick values

description: Python to get onclick values


code:
def make_order_edit_form(include_fields):
    d = {}
    class Meta:
        model = Order
        fields = include_fields
        widgets = custom_widgets
    d = {'Meta':Meta}
    if 'fa_date' in include_fields:
        d['fa_date'] = CustomDateTimeField(label="first appointment time")
    return type('OrderEditForm', (forms.ModelForm,), d)

rawDescription: How to dynamically create a ModelForm based on James Bennett's article "So you want a dynamic form"?

description: Dynamically create a ModelForm based on James Bennett's article "So you want a dynamic form"


code:
import pprint

for k, v in data.items(): #data is the main dictionary
    if 'children' in v:
        for child in v['children']:
            if child in data:
                data[child].setdefault('parent', []).append(k)

pprint.pprint(data)

rawDescription: Find linked "child/parents" in pythons dictionaries


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

def main():
    tags = ['A', 'B', 'C', 'D']
    results = [('A', 'A'), ('B', 'B'), ('C', 'C'), ('A', 'D'), ('C', 'A'),
               ('B', 'B'), ('C', 'B')]
    matrix = confusion_matrix(results, tags)
    plot(matrix, tags)
    plt.show()

def confusion_matrix(results, tagset):
    output = np.zeros((len(tagset), len(tagset)), dtype=float)
    for guessed, real in results:
        output[tagset.index(guessed), tagset.index(real)] += 1
    return output / output.sum(axis=1)[:, None]

def plot(matrix, tags):
    fig, ax = plt.subplots()
    im = ax.matshow(matrix)
    cb = fig.colorbar(im)
    cb.set_label('Percentage Correct')

    ticks = range(len(tags))
    ax.set(xlabel='True Label', ylabel='Predicted Label',
           xticks=ticks, xticklabels=tags, yticks=ticks, yticklabels=tags)
    ax.xaxis.set(label_position='top')
    return fig

main()

rawDescription: White lines in confusion matrix?

description: White lines in confusion matrix


code:
df['+/-Weight'] = df['Weight'].where(df['Sex'] == 'M', -df['Weight'])
df['Wt_Diff'] = df.groupby(['City', 'Date'])['+/-Weight'].transform('sum')

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

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


code:
k = "PROTO="
keep = (ele for ele in x.split() if ele.startswith(k))
print(next(keep,"").split("=")[-1])

rawDescription: Pythonic way of getting a value from a list


code: stats = [summ for summ in data['playerStatSummaries'] if summ['wins'] == 44]

rawDescription: Python 3: Iterating over a dictionary

description: Python 3: Iterating over a dictionary


code:
def get_context_data(self, **kwargs):
    context = super(TeacherUpdate, self).get_context_data(**kwargs)
    context['user_form'] = self.second_form_class(self.request.POST or None, instance=self.object.user)
    return context

def form_valid(self, form):
    user_form = UserChangeForm(self.request.POST, instance=self.object.user)
    if user_form.is_valid():
        user_form.save()
        return super(TeacherUpdate, self).form_valid(form)

rawDescription: Django User Model one-to-one with other model and Forms


code:
parser = argparse.ArgumentParser(parents=[general_group])
subparsers=parser.add_subparsers(dest='action')
subparsers.add_parser('Restart',parents=[general_group, second_group])
subparsers.add_parser('Start', parents=[general_group])

rawDescription: How to show help for all subparsers in argparse?

description: Show help for all subparsers in argparse


code:
from itertools import product
sc.parallelize(product(xrange(10), repeat=3)).foreach(print)

rawDescription: pyspark program for nested loop

description: Pyspark program for nested loop


code:
# mymodule.py

filename = 'c:\\temp\\fileout.txt'
data = """
       This is the
       multiline string\n
       which you want to write to the file
       """
...

def write_data_to_file():
    with open(filename, 'w') as fp:
        fp.write(data)

rawDescription: Structuring of Python code

description: Structuring of Python code


code:
from collections import defaultdict

sumdict = defaultdict(float)
for name, num, val in mylist:
    sumdict[name, num] += float(val.replace(',', '.'))

# Side-note: I'd have used tuple/namedtuple for the triples here since the data likely
# shouldn't be mutable, and tuples are the "proper" type for fixed length,
# heterogeneous, immutable data, but the functional difference is minimal
summed = [[name, num, valsum] for (name, num), valsum in sorted(sumdict.items())]

rawDescription: Python list sum elements

description: Python list sum elements


code:
def format_time():
    t = datetime.datetime.now()
    s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
    tail = s[-7:]
    f = round(float(tail), 3)
    temp = "%.3f" % f
    return "%s%s" % (s[:-7], temp[1:])

rawDescription: python datetime: Round/trim number of digits in microseconds

description: Python datetime: Round/trim number of digits in microseconds


code:
# Import the C accelerators
try:
    # Element is going to be shadowed by the C implementation. We need to keep
    # the Python version of it accessible for some "creative" by external code
    # (see tests)
    _Element_Py = Element

    # Element, SubElement, ParseError, TreeBuilder, XMLParser
    from _elementtree import *
except ImportError:
    pass

rawDescription: Inherit or mock pythons etree.ElementTree.Element possible?


code:
with open(log_path, 'w') as log:
    log.write("\n*** Start ***")

# other logic (os.chdir)

for x in range(start_x, end_x + 1):
    # do stuff, possibly set download_error to False
    if not download_error:
        with open(log_path, 'a') as log:
            log.write(url)

# other logic

with open(log_path, 'a') as log:
    log.write("\n\nComplete - %r" %
               str(datetime.datetime.now().strftime('%m/%d/%Y  %H:%M:%S')))

rawDescription: Reopen file for appending

description: Reopen file for appending


code:
p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)

rawDescription: Why does `post_save` signal get emitted on object creation along with object save?


code: c = a + [e for e in b if e not in a]

rawDescription: Union of two lists in Python

description: Union of two lists in Python


code:
my_string = '''
<root>
  <address>
    <city>Anaheim</city>
    <state>California</state>
    <zip>92801</zip>
    <country>United States</country>
  </address>
  <address>
    <city>Berkley</city>
    <state>California</state>
    <zip>94705</zip>
    <country>United States</country>
  </address>
</root>
'''

from bs4 import BeautifulSoup
soup = BeautifulSoup(my_string, 'html.parser')
desired_zips = soup.findAll('zip', text="92801")
cities = []
for zip_tag in desired_zips:
    cities.append(zip_tag.findPreviousSibling('city'))

print(cities)

rawDescription: Find specific sibling of an element

description: Find specific sibling of an element


code: df2['lagged_val'] = df2_lagged

rawDescription: Use Python/Pandas to Match Sample Pairs Yearly Data


code: url(r'^product/$', product),

rawDescription: how to Pass variable in link to the django view


code:
total = 0
num = 0
for x in l:
    total = total + x
    num = num + 1
print(total/num)

rawDescription: Python HELP | Create averages from a list from .txt file?


code:
class myClass(object):
  def doAuth(self):
    callAuthProcedure()

rawDescription: Python: Store Token in Memory

description: Python: Store Token in Memory


code:
s.post('https://localhost/login.py', login_data)
#logged in! cookies saved for future requests.
r2 = s.get('https://localhost/profile_data.json', ...)
#cookies sent automatically!
#do whatever, s will keep your cookies intact :)

rawDescription: Python Requests and persistent sessions

description: Python Requests and persistent sessions


code:
SplitSegments = cut_line_at_points(MyLine, IntPoints)
gpd.GeoSeries(SplitSegments)

rawDescription: Shapely Split LineStrings at Intersections with other LineStrings


rawDescription: How can I read in a csv file as a MultiIndexed DataFrame when the spanning column header isn't repeated?

description: Read in a csv file as a MultiIndexed DataFrame when the spanning column header isn't repeated


code:
# Add the task to the 'queue1' queue and use explicit handler (/path/to/your/handler/)
taskqueue.add(queue_name='queue1', url='/path/to/your/handler/', params={'key': value})

# Add the task to the 'queue1' queue and use the default handler (/_ah/queue/queue1)
taskqueue.add(queue_name='queue1', params={'key': value})

rawDescription: How GAE detect the right handler for a task queue?


code:
bet.pop(0) # remove first
bet.pop(-1) # remove last

rawDescription: How to change a list in a for loop? Labouchere in Python

description: Change a list in a for loop? Labouchere in Python


code:
# map categories to y-values
cat_dict = dict(zip(pandas.unique(df['category']), range(1, len(categories)+1)))

# map y-values to categories
val_dict = dict(zip(range(1, len(categories)+1), pandas.unique(df['category'])))

rawDescription: Matplotlib timelines

description: Matplotlib timelines


code:
def display_text_file(self):
    with open(self.text.path) as fp:
        return fp.read().replace('\n', '
')

def display_text_file(self):
    self.text.open() # reset the pointer of file, needs if you need to read file more than once, in a request.
    return self.text.read().replace('\n', '
')

def display_text_file(self):
    self.text.open() # reset the pointer of file, needs if you need to read file more than once, in a request.
    return self.text.file.read().replace('\n', '
')

rawDescription: django - How to insert the content of uploaded file in template?

description: Django - How to insert the content of uploaded file in template


code: grouped[ grouped.groupby(level='U').transform('count') == 1 ]

rawDescription: pandas - groupby, count values and remove equal occurrences

description: Pandas - groupby, count values and remove equal occurrences


code:
class PositiveBigIntegerField(BigIntegerField):
    empty_strings_allowed = False
    description = _("Big (8 byte) positive integer")

    def db_type(self, connection):
        """
        Returns MySQL-specific column data type. Make additional checks
        to support other backends.
        """
        return 'bigint UNSIGNED'

    def formfield(self, **kwargs):
        defaults = {'min_value': 0,
                    'max_value': BigIntegerField.MAX_BIGINT * 2 - 1}
        defaults.update(kwargs)
        return super(PositiveBigIntegerField, self).formfield(**defaults)

rawDescription: Can the Django ORM store an unsigned 64-bit integer (aka ulong64 or uint64) in a reliably backend-agnostic manner?


rawDescription: Some built-in to pad a list in python

description: Some built-in to pad a list in python


rawDescription: PyBBM in Django static content

description: PyBBM in Django static content


code:
def sortable_key_from_string(value):
        version_tuple = tuple(map(int, re.compile('(\d+(?!$))').findall(value)))
        match = re.match('^(\D+)', value)
        version_name = ''
        if match:
                version_name = match.group(1)
        return (version_tuple, version_name)

rawDescription: Python3 Make tie-breaking lambda sort more pythonic?


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)
plt.plot(x, y)
plt.show()

rawDescription: how to change the shape of a contour in matplotlib

description: Change the shape of a contour in matplotlib


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

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


code:
#!/usr/bin/env python

from __future__ import print_function

from os import unlink
from tempfile import mkstemp
from subprocess import Popen

def callvim():
    fd, filename = mkstemp()

    p = Popen(["/usr/bin/vim", filename])
    p.wait()

    try:
        return open(filename, "r").read()
    finally:
        unlink(filename)

data = callvim()
print(data)

rawDescription: How can I call Vim from Python?

description: Call Vim from Python


code:
f = Foo()
f.bar = 5
f.bar
f.bar = 30
f.high = 35
f.bar = 30
f.bar

rawDescription: Access low and high settings of an ETS Range attribute?


code:
xs=[5,3,2,5,6,1,0,5]
minimum = xs[0];
for i in xs:
    if i < minimum:
        minimum = i ;
print(minimum)

rawDescription: python: How to compare elements within one list

description: Python: How to compare elements within one list


code:
for d, data in df.groupby(pd.TimeGrouper('D')):
    data.plot.line(figsize=(10, 20), sharey=True)
    plt.gcf().savefig('cats {}.png'.format(d), bbox_inches='tight')
    plt.close()

rawDescription: How to fill the indexs of dataframe & make the subplots?

description: Fill the indexs of dataframe & make the subplots


code: j = pd.merge(df,h, on=['User','DLang'])

rawDescription: pandas - unstack with most frequent values in MultiIndex DataFrame

description: Pandas - unstack with most frequent values in MultiIndex DataFrame


code:
from operator import itemgetter as i
from functools import cmp_to_key

def multikeysort(items, columns):
    comparers = [
        ((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
        for col in columns
    ]
    def comparer(left, right):
        comparer_iter = (
            cmp(fn(left), fn(right)) * mult
            for fn, mult in comparers
        )
        return next((result for result in comparer_iter if result), 0)
    return sorted(items, key=cmp_to_key(comparer))

rawDescription: Python sorting list of dictionaries by multiple keys


code: table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'})

rawDescription: Beautiful Soup [Python] and the extracting of text in a table


code:
import numpy as np
import pandas as pd

fname = 'example.txt'

full_list = []
with open(fname, "r") as f:
    for line in f:
        arr = line.strip(" \n").split(" ")
        for chunk in arr[1:]:
            # converting numbers to ints:
            int_pair = [int(x) for x in chunk.split(":")]
            full_list.append([arr[0], *int_pair])

df = pd.DataFrame(full_list)

df2 = df.pivot_table(values = 2, index = 0, columns = 1, aggfunc = np.sum, fill_value = 0)

rawDescription: Python pandas: Generate Document-Term matrix from whitespace delimited '.dat' file


code:
from collections import Counter

print(Counter(map(frozenset, y)))

rawDescription: Multiprocessing module for updating a shared dictionary in Python


code:
class Merge(object):
    def __init__(self, **extra_kws):
        self.extra_kws = extra_kws
    def __call__(self, function):
        def _wrapper(*args, **kws):
            kws.update(self.extra_kws)
            return function(*args, **kws)
        return _wrapper

rawDescription: Merge decorator function as class

description: Merge decorator function as class


code: zipped = dict(zip(labels, day0))

rawDescription: python comprehension from two list or zip

description: Python comprehension from two list or zip


code:
df = pd.DataFrame({'unique':uniq})
df.to_csv('rgdp_uniq_indstry_class.csv')

rawDescription: pandas: export ndarray to csv

description: Pandas: export ndarray to csv


code:
def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)

rawDescription: Prepend line to beginning of a file

description: Prepend line to beginning of a file


code:
class staticmethod:
    def __init__(self, thefunc): self.f = thefunc
    def __call__(self, *a, **k): return self.f(*a, **k)

rawDescription: backport function modifiers to python2.1

description: Backport function modifiers to python2.1


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import sys

# This will store the lines by tag, in order to join them
data = {}
# This will tell us how to order the columns, will be extended later
columns = ['L', 'Dr', 'Tag']
# Controls extension of the columns
maxhour = 0
# Controls the order the keys are found in the original CSV. Maybe not necessary
keys = []

with open("in.csv", 'r', newline='') as fin:
    reader = csv.DictReader(fin)
    for row in reader:
        hour = int(row['Hour'])
        # Form a unique key to match lines. Adjust to your needs
        key = (row['L'], row['Dr'], row['Tag'])
        if key not in data:
            # This is a future row, a dict with column as key, cell as value
            data[key] = {'L': row['L'], 'Dr': row['Dr'], 'Tag': row['Tag']}
            # Remember the order we've seen the keys
            keys.append(key)
        # Now, add data to the row for each minutes
        # 1 to 59
        for minute in range(1,60):
            # Copy data from column 'minute' to column 'Hour:minute'
            src_colname = str(minute)
            dest_colname = row['Hour'] + ':' + src_colname
            data[key][dest_colname] = row[src_colname]
        # There seems to be a special treatment for minute 0, at column "L 0"
        if hour == 0:
            data[key]['L 0'] = row['L 0']
        else:
            data[key][row['Hour'] + ':0'] = row['L 0']
        # Plan to generate enough columns when writing resulting file
        maxhour = max(maxhour, hour)

with open("out.csv", 'w', newline='') as fout:
    # Okay, now everything was merged into data
    # We need to tell DictWriter how to order columns
    # Treat special first column
    columns.append('L 0')
    # Then add the rest
    for hour in range(0, maxhour+1):
        # Do not include "0:0"
        for minute in range(0 if hour > 0 else 1,60):
            columns.append('{:d}:{:d}'.format(hour, minute))
    # Let's write that
    writer = csv.DictWriter(fout, columns, restval = "0")
    writer.writeheader()
    for key in keys: # or for key in data.keys(): if you don't mind the order
        writer.writerow(data[key])

rawDescription: Processing and Formatting a csv

description: Processing and Formatting a csv


code:
unqa,ID,counts = np.unique(arr[:,0],return_inverse=True,return_counts=True)
out = np.column_stack(( unqa , np.bincount(ID,arr[:,1])/counts ))

rawDescription: Average entries with duplicate first element in 2D numpy array


code: values = list(ic_next_td.strings)

rawDescription: Regex or other method for returning these values (from BeautifulSoup)


rawDescription: how to set the xaxis in time interval, say 15min using matplotlib

description: Set the xaxis in time interval, say 15min using matplotlib


rawDescription: Extracting Information from a Tuple (Python)


code:
results = {}
for k, v in data.items():
    it = iter(v[1:])
    results.update({k: dict(enumerate(zip(it, it)))})
pprint(results)

rawDescription: How to use generator expression with tuples in python

description: Use generator expression with tuples in python


code:
path = self.resource_path("logo.png")
icon = wx.Icon(path, wx.BITMAP_TYPE_PNG)
self.SetIcon(icon)

rawDescription: Add image to .spec file in Pyinstaller

description: Add image to .spec file in Pyinstaller


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

def get_coord(table, irow, icol):
    # get coordinates of a cell. This seems to work, don't ask why.
    cell = table.get_celld()[irow+1,icol] # row 0 is column headers
    box = cell.get_bbox().get_points() # [[x0, y0],[x1, y1]]
    xc, yc = box.mean(axis=0) # get center
    return xc, yc

col_labels=['G','A','T','C','C']
row_labels= ['G','T','G','C','C']
table_vals= [
    ['x','','','',''],
    ['','','x','',''],
    ['x','','','',''],
    ['','','','x','x'],
    ['','','','x','x']]
line = [(0,0), (0,1), (1,2), (2,2), (3,3), (4,4)]

# draw table
the_table = plt.table(cellText=table_vals,
    colWidths = [0.1]*len(col_labels),
    rowLabels=row_labels, colLabels=col_labels,
    cellLoc = 'center', rowLoc = 'center', bbox=[.1,.1,.8,.8])
plt.draw() # lay out table, so that cell coordinates are calculated

# look up line coordinates
x = []; y = []
for irow, icol in line:
    xc, yc = get_coord(the_table, irow, icol)
    x.append(xc)
    y.append(yc)

# draw line
plt.plot(x, y, 'r', linewidth = 5, alpha=0.5)
plt.xlim([0,1])
plt.ylim([0,1])
plt.show()

rawDescription: How to draw dynamic programming table in python

description: Draw dynamic programming table in python


code:
test_seq = itertools.izip(itertools.count(), seq(set((1, 2, 3))))
for i in range(10):
    next(test_seq)

rawDescription: Calculating the Nth Sequence of Length M in Python


code:
# Take the first `numtrain` no. of documents
# as training documents
train_docs = documents[:numtrain]
# Takes the rest of the documents as test documents.
test_docs = documents[numtrain:]
# These extract the feature sets for the classifier
# please look at the full explanation on http://stackoverflow.com/questions/20827741/nltk-naivebayesclassifier-training-for-sentiment-analysis/
train_set = [({i:(i in tokens) for i in word_features}, tag) for tokens,tag  in train_docs]

rawDescription: Testing the NLTK classifier on specific file


code:
import csv
with open('path/to/broken.csv', 'rb') as f, open('path/to/fixed.csv', 'wb') as g:
    writer = csv.writer(g, delimiter=',')
    for line in f:
        row = line.split(',', 2)
        writer.writerow(row)

rawDescription: Parsing CSV file in pandas with commas in last column


rawDescription: Cleaning text files with regex of python


code:
from __future__ import print_function
import nltk
from nltk import sent_tokenize, word_tokenize, pos_tag

f = open('file.txt')

for j in iter(f):

    toks = pos_tag(word_tokenize(j))
    print ("{0}[sentiment={1}] -> {2}".format(toks[0][1], toks[1][0], toks[0][0]))

f.close()

rawDescription: regular expressions in NLTK python

description: Regular expressions in NLTK python


code:
def check(tuple_):
    try:
        lower, upper = tuple_
        return isinstance(lower, int) and int(lower) >= 0 and \
               (upper in ('*', -1) or isinstance(upper, int) and int(lower) <= int(upper))
    except:
        return False

rawDescription: Pattern for multiplicity in python

description: Pattern for multiplicity in python


code:
newdf = df[df['id'] == "0001"]
newdf.to_csv("dataframe0001.csv", sep='\t')

rawDescription: pandas, how to filter dataframe by column value

description: Pandas, how to filter dataframe by column value


rawDescription: Automatically read configuration values in Python


code:
t = (x, y)
pix[t]

rawDescription: What does pix[x, y] mean in Python

description: What does pix[x, y] mean in Python


rawDescription: How can I "start" a bytearray in python?

description: "start" a bytearray in python


code: {{ form._meta.model.user_links_count }}

rawDescription: Django 1.6: How to print the number of objects a user uploaded?


rawDescription: Print bytes to hex

description: Print bytes to hex


code:
import itertools
list(itertools.combinations([1,2,3], 1))
list(itertools.combinations([1,2,3], 2))
list(itertools.combinations([1,2,3], 3))

rawDescription: Finding combination of elements of a list


code:
ex_str = u'Word   \n \t \r   \n\n\n word2    word3   \r\r\r\r\nword4\n    word5'
'\n'.join([' '.join(line.split()) for line in ex_str.splitlines() if line.strip(' ')])

rawDescription: Removing odd \n, \t, \r and space combinations from a given string in Python


rawDescription: Python sub-dictionary/list within a dictionary


code:
edges = []
for u, v, d in G.edges(data=True): # note that d contains each edge's data
    if u.isdigit(): # if u is numeric put it first
        edges.append( (u, v, d) )
    else:
        edges.append( (v, u, d) )

rawDescription: Read bipartite graph

description: Read bipartite graph


code:
from binascii import hexlify, unhexlify

bytes1, bytes2 = unhexlify(input1), unhexlify(input2)
xor_bytes = bytes([b1 ^ b2 for b1, b2 in zip(bytes1, bytes2)])

result = hexlify(xor_bytes).decode('ascii')

rawDescription: How to convert from binary to bytes to hex in Python 3?

description: Convert from binary to bytes to hex in Python 3


code:
def update(self, outqueue):
    try:
        msg = outqueue.get_nowait()
        if msg is not sentinel:
            self.appendLine(msg)
            root.after(250, self.update, outqueue)
        else:
            # By not calling root.after here, we allow update to
            # truly end
            pass
    except Queue.Empty:
        root.after(250, self.update, outqueue)

rawDescription: Run thread from Tkinter and wait until it's finished


rawDescription: Converting video files uploaded by user & serving it using django, python


code:
a = np.random.randint(0, 5, size=(6, 4))
b = np.random.randint(0, 5, size=(6, 4))

res1 = np.einsum('ij, ij->i', a, b)
res2 = np.sum(a*b, axis=1)

print(res1)
# [18  6 20  9 16 24]

print(np.allclose(res1, res2))
# True

rawDescription: Elegant expression for row-wise dot product of two matrices


code:
import ast

def find_parent(par):
    for par_node in mod.body:
        if isinstance(par_node, ast.FunctionDef):
            for node in par_node.body:
                if isinstance(node, ast.FunctionDef) and node.name == inner_func.func_name:
                    return eval(par_node.name)

rawDescription: Get parent function of closure

description: Get parent function of closure


rawDescription: How to reduce queries in django model has_relation method?

description: Reduce queries in django model has_relation method


rawDescription: Add and Subtract multiple element of numpy array


code: soup.findAll(href='#', title='myurl')

rawDescription: python, regex to find anchor link html

description: Python, regex to find anchor link html


code:
L = [int("%d%d%d" % (x,y,x)) for x in range(1,10) for y in range(10)]
L

rawDescription: Generate list of all palindromic numbers of 3 digits in python


code:
res = netsnmp.snmpgetbulk(oid, Version=2, DestHost='192.168.0.100',
                          Community='pub')

rawDescription: How to get data from SNMP with python?

description: Get data from SNMP with python


code:
#!/usr/bin/env python
from __future__ import print_function
from select     import select
from subprocess import Popen, PIPE

# start several subprocesses
processes = [Popen(['./child.py', str(i)], stdout=PIPE,
                   bufsize=1, close_fds=True,
                   universal_newlines=True)
             for i in range(5)]

# read output
timeout = 0.1 # seconds
while processes:
    # remove finished processes from the list (O(N**2))
    for p in processes[:]:
        if p.poll() is not None: # process ended
            print(p.stdout.read(), end='') # read the rest
            p.stdout.close()
            processes.remove(p)

    # wait until there is something to read
    rlist = select([p.stdout for p in processes], [],[], timeout)[0]

    # read a line from each process that has output ready
    for f in rlist:
        print(f.readline(), end='') #NOTE: it can block

rawDescription: Python subprocess in parallel

description: Python subprocess in parallel


code:
pdb.gimp_edit_copy (original_layer)

floating = pdb.gimp_edit_paste (target_layer)

rawDescription: Copy a layer from an image to another

description: Copy a layer from an image to another


code:
#Install signal handler
signal.signal(signal.SIGALRM, handler)

#Set alarm for 5 minutes
signal.alarm(300)

rawDescription: How can I exit a Python3 script after 5 minutes

description: Exit a Python3 script after 5 minutes


code:
lines = []
lines.append(line('Math', '3', '12', 'Hello World!'))
...

rawDescription: Python List of classes

description: Python List of classes


rawDescription: Python (football games algorithm troubles)


code:
[
    {'price': 3.87, 'link': 'http:URL-LINK'},
    {'price': 410.25, 'link': 'http:URL-LINK2'}
]

rawDescription: Beautiful Soup sorting output

description: Beautiful Soup sorting output


code:
H_coeff = np.zeros(H.shape)
for a in range(r):
    for mu in range(m):
        for i in range(n):
            H_coeff[a, mu] += W[i, a] * V[i, mu] / WH[i, mu]
        H_coeff[a, mu] /= sum(W)[a]
H = H * H_coeff

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


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

xpos = [1, 2]
ypos = [2003, 2008]
zpos = [0, 0]

dx = 1
dy = 1
dz = [2, 3]

# Move each (x, y) coordinate to center it on the tick

xpos = map(lambda x: x - 0.5, xpos)
ypos = map(lambda y: y - 0.5, ypos)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.bar3d(xpos, ypos, zpos, dx, dy, dz)

# Do not print years in exponential notation

y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
ax.yaxis.set_major_formatter(y_formatter)

plt.show()

rawDescription: How to customize axes in 3D hist python/matplotlib

description: Customize axes in 3D hist python/matplotlib


code:
print(df['col'].sub(df['col'].shift(), fill_value = 0))
# 0    0
# 1    1
# 2    1
# 3    1
# Name: col

print(df['col'].add(df['col'].shift(), fill_value = 0))
# 0    0
# 1    1
# 2    3
# 3    5
# Name: col

rawDescription: Pandas column addition/subtraction

description: Pandas column addition/subtraction