code:
def splitpoint(a):
    a = np.asarray(a)
    c1 = a.cumsum()
    c2 = a[::-1].cumsum()[::-1]
    if a.dtype.kind == 'u':
        # np.abs(c1-c2) doesn't work on unsigned ints
        absdiffs = np.where(c1>c2, c1-c2, c2-c1)
    else:
        # c1>c2 doesn't work on complex input.
        # We also use this case for other dtypes, since it's
        # probably faster.
        absdiffs = np.abs(c1-c2)
    return np.argmin(absdiffs)

rawDescription: Find the equilibrium point in a numpy array


code:
class State(object):
    on_enter = CallList()
    def enter(self):
        self.on_enter()

rawDescription: Class variables and inheritance in Python


code:
print('description', customer, '<MPID={0}>'.format(mpid))
print('description {0} <MPID={1}>'.format(customer, mpid))

rawDescription: Python Newbie Combine Text

description: Python Newbie Combine Text


code:
a=[5,4,3,2,1]
def eleMax(items, start=0, end=None):
    return max(items[start:end])
eleMax(a,2)   # a[2:] == [3,2,1]

rawDescription: How to return the maximum element of a list in Python?

description: Return the maximum element of a list in Python


code:
from PIL import ImageGrab
screenshot = ImageGrab.grab()
screenshot.save('wham.png')

rawDescription: screenshot not showing all windows in python screenshot imagegrab

description: Screenshot not showing all windows in python screenshot imagegrab


code:
from collections import defaultdict

data = defaultdict(  # State
    lambda: defaultdict(  # City
        lambda: defaultdict(list)  # Area
    )
)

data['State']['City']['Area'].append('area 1')
data['State']['City']['Area'].append('area 2')
data['State']['City']['Area'].append('area 2')

areas = data['State']['City']['Area']
print(areas)  # ['area 1', 'area 2', 'area 2']

total = len(areas)
print(total)  # 3

rawDescription: How to create nested dictionaries with duplicate keys in python

description: Create nested dictionaries with duplicate keys in python


code: rev_list = original[::-len('1')]

rawDescription: Reversing order of a list using only the len() function


rawDescription: Group list by values and keep both

description: Group list by values and keep both


code:
from compiler.misc import mangle
mangle('__some_such', 'Foo')

rawDescription: Python name mangling function

description: Python name mangling function


code:
def removeLine():
    with open(path, 'rU') as file:
        next(file, None)  # skip a line *if present*
        lines = list(file)
    with open(path, 'w') as file:
        file.writelines(lines)

rawDescription: Most efficient way to "nibble" the first line of text from a text document then resave it in python


code:
def __getattr__(self, name):
    if name in self.varMap:
        return self.varMap[name]
    raise AttributeError

rawDescription: Natural Naming Scheme for a dynamic set of members


code:
items = ['Tag1','Tag2']
for tag in items:
    for value in xml_file.getElementsByTagName(tag):
        project[tag].append(value.firstChild.data)

rawDescription: Getting list of tags from Python minidom XML


code:
"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(player1.games)  # 'games: 123'
"games: {:>3}".format(player2.games)  # 'games:   4'
"games: {:0>3}".format(player2.games) # 'games: 004'

rawDescription: String Formatting in Python 3

description: String Formatting in Python 3


code:
message = "sometext"
lista = ["a","b","c"]
any(a in message for a in lista)
lista = ["a","b","e"]
any(a in message for a in lista)

rawDescription: Fastest way to check does string contain any word from list


code:
_mystring()
u = uppercase()
u.str = 'a'
u.str

rawDescription: Inheriting setter, overwriting getter in python abstract class


code:
for res in results:
    category = res.find(attrs={'class': "category"}) or res.find(attrs={'class': "categories"})
    category.b.decompose()
    print(category)

rawDescription: Python - BeautifulSoup4 decompose() isn't working


code: any(v in (a, b, c) for v in X)

rawDescription: python membership testing order by rarity

description: Python membership testing order by rarity


code:
# method definition
def start_workouts(total_days, init_workout, workout_increase):
    workouts = [(init_workout + day * workout_increase) for day in range(total_days)]
    return workouts

# method execution (3 days, starting at 100, increasing 20 each day)
my_workouts = start_workouts(3, 100, 20)
# my_workouts == [100, 120, 140]
# my_workouts[0] is "Day1"
# my_workouts[1] is "Day2"
# my_workouts[2] is "Day3"

rawDescription: Simple Python loop counter issue

description: Simple Python loop counter issue


rawDescription: Converting to json re-orders objects in python


code:
h = """

            Some text

foo bar!

"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(h)

td = soup.select_one("#bar")
td.br.replace_with("\n")

td.replace_with(td.text)

print(repr(soup))

rawDescription: Python simplify HTML table

description: Python simplify HTML table


code:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

rawDescription: Where to implement python classes in Django?


code:
for index, item in enumerate(values):
    if not selectors[index]:
        continue
    ...
# where selectors is a truth array like nodeSet_IDs_TF

rawDescription: Skipping a pattern of elements using itertools and accompanying list


code:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def read(logfile):
    with open(logfile) as f:
        data = []
        while True:
            line = f.readline()
            time.sleep(0.1)
            if line:
                data.append(float(line.split(',')[1][:-2]))
                yield data

def animate(values):
    x = list(range(len(values)))
    line.set_data(x, values)
    ax.set_xlim(x[0], x[-1])
    ax.set_ylim(min(values), max(values))
    return line,

fig, ax = plt.subplots()
line, = ax.plot([])

ani = FuncAnimation(fig, animate, frames=read('log.txt'), interval=10)
plt.show()

rawDescription: How to chart live updates to logfile using matplotlib?

description: Chart live updates to logfile using matplotlib


rawDescription: Python webscraper outputs brackets with the number


code: 'has_deposit' in test_data.keys()

rawDescription: Python advice with some code

description: Python advice with some code


code: any(t.lower()==w.lower() for w in L)

rawDescription: Project Gutenberg Python problem?

description: Project Gutenberg Python problem


code: a, b = np.linalg.lstsq(A, B)[0].reshape(2)

rawDescription: Loops to minimize function of arrays in python


rawDescription: Keep other columns when using min() with groupby


code:
finder = BigramCollocationFinder.from_words(tweet_phrases.split(), window_size = 3)
finder1 = BigramCollocationFinder.from_words(tweet_phrases.split(), window_size = 3)

rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
def __init__( self, von=None, bis=None, somemore=something ):
    if von is None:
        von = _today()
    if bis is None:
        bis = _today()

rawDescription: python: datetime within module always provides date of first call

description: Python: datetime within module always provides date of first call


rawDescription: Convert empty dictionary to empty string


code:
class MyTable(tables.Table):
  tr_class=tables.Column(visible=False)
  ... # other columns

rawDescription: django-tables2 specify different properties for different rows

description: Django-tables2 specify different properties for different rows


code:
data = ['**','***','.param','+foo = bar','+foofoo = barbar','+foofoofoo = barbarbar',
     '.model','+spam = eggs','+spamspam = eggseggs','+spamspamspam = eggseggseggs']

# First get the interesting positions.
param_tag_pos = data.index('.param')
model_tag_pos = data.index('.model')
# Get all elements between tags.
params =  [param for param in data[param_tag_pos + 1: model_tag_pos] if param.startswith('+')]
models =  [model for model in data[model_tag_pos + 1: -1] if model.startswith('+')]

print(params)
print(models)

rawDescription: Split list based on first character - Python


rawDescription: Get only those elements of array that match all elements of test array?


code:
data = json.loads(JSON_Object)
self.attrA = data['attrA']
self.attrB = data['attrB']
...

rawDescription: Parameterizing Python's json.loads() object_hook to a Factory Method


code: from ordereddict import OrderedDict

rawDescription: Recursive sorting function for list in Python


code:
def GetWindowSize(self):
    """ Returns the associated window size. """
    wnd = self._wnd
    if wnd.GetSizer():      # the window is a complex one hold by a sizer
        size = wnd.GetBestSize()
    else:                   # simple window, without sizers
        size = wnd.GetSize()
    print(size)
    return size

rawDescription: Widget Windows in UltimateListCtrl Won't Resize/Refresh


code:
game=quietCraps()
for x in range(n):
    game

rawDescription: Python calling a function with another function


code:
def multi_product(lists, repeats):
    producted = [ product(lst, repeat) for lst, repeat in zip(lists, repeats) ]
    return product(*producted)

rawDescription: Can itertools allow for list to be created from multiple lists where I set a limit to how many selections per list?


rawDescription: Using df.apply() with a Pandas MuliIndex / carrying out operations on hierarchical index rows?


code:
import numpy as np

def clipped_zoom(img, zoom_factor, **kwargs):

    h, w = img.shape[:2]

    # size of the zoomed array
    zh = int(np.round(zoom_factor * h))
    zw = int(np.round(zoom_factor * w))

    # we're zooming out
    if zoom_factor < 1:

        # bounding box of the clip region within the output array
        top = (h - zh) // 2
        left = (w - zw) // 2

        # zero-padding
        out = np.zeros_like(img)
        out[top:top+zh, left:left+zw] = zoom(img, zoom_factor, **kwargs)

    # we're zooming in
    elif zoom_factor > 1:

        # bounding box of the clip region within the input array
        top = (zh - h) // 2
        left = (zw - w) // 2

        out = zoom(img[top:top+zh, left:left+zw], zoom_factor, **kwargs)

        # `out` might still be slightly larger than `img` due to rounding, so trim
        # off any extra pixels at the edges
        trim_top = ((out.shape[0] - h) // 2)
        trim_left = ((out.shape[1] - w) // 2)
        out = out[trim_top:trim_top+h, trim_left:trim_left+w]

    # if zoom_factor == 1, just return the input array
    else:
        out = img

    return out

rawDescription: Scipy rotate and zoom an image without changing its dimensions


rawDescription: Stuck with Number Float format in Python Decimal


code:
'hello\r\n'.encode('unicode_escape').decode() == 'hello\\r\\n'
'hello\r\n' == 'hello\\r\\n'.encode().decode('unicode_escape')

rawDescription: python compare "\n" escape chars with "\\n"

description: Python compare "\n" escape chars with "\\n"


code:
re.sub(r"^(.*?)\.(.*)", lambda m: m.group(1)[0] + '.' + m.group(2), string_test)
re.sub(r"^(.*?)(\..*)", lambda m: m.group(1)[0] + m.group(2), string_test)

rawDescription: How can I index group elements in re.sub?

description: Index group elements in re.sub


code:
s.index = np.arange(6)
s.index
s.index.get_indexer([0,4])
s.index.values

rawDescription: Series.index versus Series.index.values

description: Series.index versus Series.index.values


code:
from module import logImports
logImports()

import math

rawDescription: How to measure Python import loading times/latencies in AppEngine

description: Measure Python import loading times/latencies in AppEngine


code:
def find_location_fast(location_name):
    try: return loc2reg[location_name]
    except KeyError:
        raise ValueError('Location {!r} unknown'.format(location_name))

rawDescription: Set player's main region depending on location - Python


code:
import urllib
from bs4 import BeautifulSoup

def worldnews():
    count = 0
    html = urllib.urlopen("https://www.reddit.com/r/worldnews/")
    soup = BeautifulSoup(html,"lxml")
    titles = soup.find_all('p',{'class':'title'})
    for i in titles:
        print(i.text)

worldnews()

rawDescription: Readin information in reddit with urllib


code: df.loc[df['float_col'] > 5, 'int_col'] = df['int_col'] * 2

rawDescription: Applying Operation to Pandas column if other column meets criteria


rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


rawDescription: What's the logic behind Python's hash function order?


rawDescription: Setting object owner with generic create_object view in django


code:
def get_or_create(session, model, defaults=None, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
    else:
        params = dict((k, v) for k, v in kwargs.iteritems() if not isinstance(v, ClauseElement))
        if defaults:
            params.update(defaults)
        instance = model(**params)
        return instance

rawDescription: SQLAlchemy ON DUPLICATE KEY UPDATE

description: SQLAlchemy ON DUPLICATE KEY UPDATE


code:
list_filter = [('legs__depart_date', DateRangeListFilter),]

def lookup_allowed(self, key, value):
    if key in ('legs__depart_date__gte', 'legs__depart_date__lt'):
        return True
    return super(RequestAdmin, self).lookup_allowed(key, value)

rawDescription: Date Range List filter for foreign key Django admin


rawDescription: Python: Regex v. BeautifulSoup to remove from text <TYPE>


code: ms in layouts

rawDescription: Check regex result in a list ,if-else python


code: log.warning("OnKeyDown event %s" % (event))

rawDescription: wxpython capture keyboard events in a wx.Frame

description: Wxpython capture keyboard events in a wx.Frame


code:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))

rawDescription: About num1 and num2 in python calculator


code:
import pandas as pd

AvgPrice = pd.read_csv('csv/BAVERAGE-USD-Bitcoin24hPrice.csv',
                       index_col=False,
                       parse_dates=['Date'],
                       usecols=[0,1],
                       header=0,
                       names=['Date','Price'])

TransVol = pd.read_csv('csv/BCHAIN-ETRAV-BitcoinEstimatedTransactionVolume.csv',
                       index_col=False,
                       parse_dates=['Date'],
                       header=0,
                       names=['Date','TransactionVolume'])

TotalBTC = pd.read_csv('csv/BCHAIN-TOTBC-TotalBitcoins.csv',
                       index_col=False,
                       parse_dates=['Date'],
                       header=0,
                       names=['Date','TotalBTC'])

USDExchVol = pd.read_csv('csv/BCHAIN-TRVOU-BitcoinUSDExchangeTradeVolume.csv',
                       index_col=False,
                       parse_dates=['Date'],
                       header=0,
                       names=['Date','USDExchange Volume'])

rawDescription: Python Pandas - Cannot Merge Multiple DataFrame returning NaN


code:
value = raw_input('>')
contains_letters = any( c.isalpha() for c in value )

rawDescription: Python input validation -- int between 20 and 100, no letters


code:
import urllib.request # `import` statements at the top! have a look at PEP 8

def htmlfrom(website_url):
    ''' reads HTML from a website
        arg: `website_url` is the URL you wish to read '''
    response = urllib.request.urlopen(website_url)
    return response.read()

rawDescription: How do I set my own global variables using input() in python 3.3?

description: Set my own global variables using input() in python 3.3


code:
from System import Int32
Int32.TryParse('12345')
Int32.TryParse('12345x')

rawDescription: (Iron)Python - defining a variable of specific type


code: df.MIN = df.MIN.map(str_to_number)

rawDescription: Pandas: convert column from minutes (type object) to number


code:
try:
    checkout = Checkout.objects.get(item=my_item, checked_in=None)
except Checkout.DoesNotExist:
    #item isn't checked out
    checkout = None

rawDescription: Django checkout model

description: Django checkout model


code:
from flask_login import LoginManager

login_manager = LoginManager()
login_manager.init_app(app=app)

@login_manager.user_loader
def load_user(username):
    return User(username)

@login_manager.request_loader
def load_from_request(request):
    return User.auth_is_valid(request.authorization)

rawDescription: Passing POST call values using url_for in Flask


rawDescription: Including user statistics for multiple views


rawDescription: Django, Python X value in List of Dicts/Queryset


code:
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
data['sex'].replace({0:'Female',1:'Male'},inplace=True)
data

rawDescription: Pandas - replacing column values

description: Pandas - replacing column values


code:
list(mix_lists('abcdefgh', range(12)))
list(mix_lists('abcdefg', [1, 2, 3, 4]))

rawDescription: Homogeneous mix of two lists

description: Homogeneous mix of two lists


code:
for i in range(0, img_layers):
  img.seek(i)
  a = numpy.array(img.getdata(), dtype=dtype)
  a.resize(sx, sy, channels)
  z = i % sz
  frame = i // sz
  dset[..., z, frame] = a # Majority of time in this call

rawDescription: How do I fill an n-dimensional array in HDF5 from a 1D source?

description: Fill an n-dimensional array in HDF5 from a 1D source


code:
from itertools import groupby
from operator import itemgetter

rawDescription: How to add items in a list of tuples if the item is the same

description: Add items in a list of tuples if the item is the same


code:
import unittest
import calc

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.testInput = 10

    def test_first(self):
        output = calc.first(self.testInput)
        correct = 100
        assert(output == correct)

    def test_second(self):
        output = calc.second(self.testInput)
        correct = 1000
        assert(output == correct)

if __name__ == '__main__':
    unittest.main()

rawDescription: Right way to write Unit-Tests in module?

description: Right way to write Unit-Tests in module


code:
from ctypes import *

def enumProcessModules():
    # Get handle of current process
    kernel32 = windll.kernel32
    kernel32.GetCurrentProcess.restype = c_void_p
    hProcess = kernel32.GetCurrentProcess()

    # Load EnumProcessModules either from kernel32.dll or psapi.dll
    try:
        EnumProcessModulesProc = windll.psapi.EnumProcessModules
    except AttributeError:
        EnumProcessModulesProc = windll.kernel32.EnumProcessModules
    EnumProcessModulesProc.restype = c_bool
    EnumProcessModulesProc.argtypes = [c_void_p, POINTER(c_void_p), c_ulong, POINTER(c_ulong)]

    hProcess = kernel32.GetCurrentProcess()
    hMods = (c_void_p * 1024)()
    cbNeeded = c_ulong()
    if EnumProcessModulesProc(hProcess, hMods, sizeof(hMods), byref(cbNeeded)):
        return hMods
    return None

def getLoadedModule(moduleName):
    kernel32 = windll.kernel32
    kernel32.GetModuleFileNameA.restype = c_ulong
    kernel32.GetModuleFileNameA.argtypes = [c_void_p, c_char_p, c_ulong]

    modules = enumProcessModules()
    if modules is None:
        return None
    for module in modules:
        cPath = c_char_p(' ' * 1024)
        kernel32.GetModuleFileNameA(module, cPath, c_ulong(1024))
        path = cPath.value
        if path.lower().endswith(moduleName):
            return module
    return None

rawDescription: Using ctypes to load a specific runtime library (MSVCRT80)


rawDescription: How to create a keyframe with Python API for 3D Studio Max

description: Create a keyframe with Python API for 3D Studio Max


code:
import random

numcalls = 0
def bs(wordlist, word):
    # increment numcalls
    print('wordlist',wordlist)
    global numcalls
    numcalls += 1

    # base cases
    if not wordlist:
        return False
    length = len(wordlist)
    if length == 1:
        return wordlist[0] == word

    # split the list in half
    mid = int(length/2) # mid index
    leftlist = wordlist[:mid]
    rightlist = wordlist[mid:]
    print('leftlist',leftlist)
    print('rightlist',rightlist)
    print()

    # recursion
    if word < rightlist[0]:
        return bs(leftlist, word) # word can only be in left list
    return bs(rightlist, word) # word can only be in right list

alphabet = 'abcdefghijklmnopqrstuvwxyz'
wl = sorted(random.sample(alphabet, 10))
print(bs(wl, 'm'))
print(numcalls)

rawDescription: Why is my implementation of binary search very inefficient?


code: my_objects = [MyClass(0) for _ in range(100)]

rawDescription: Creating an array of objects in python without having to append in a loop


code:
def f(letter):
    return lalala
f # return f

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
class MatchForm(forms.Form):
    user1 = forms.ChoiceField(choices = [])

    def __init__(self, *args, **kwargs):
        super(MatchForm, self).__init__(*args, **kwargs)
        self.fields['user1'].choices = [(x.pk, x.get_full_name()) for x in User.objects.all()]

rawDescription: How would I use django.forms to prepopulate a choice field with rows from a model?


rawDescription: Find the area between two curves ploted in matplotlib (fill_between area)


code:
data = pd.DataFrame(np.arange(12).reshape(3,4), columns=pd.MultiIndex.from_product([['a','b'],[0,1]]))
data
data.loc[0,'a'] = data.loc[1,'b'].values
data

rawDescription: How to assign one row of a hierarchically indexed Pandas DataFrame to another row?

description: Assign one row of a hierarchically indexed Pandas DataFrame to another row


rawDescription: How to create copies of a python object that are not linked to original object?

description: Create copies of a python object that are not linked to original object


rawDescription: pandas groupby on a values based on n-1 index record

description: Pandas groupby on a values based on n-1 index record


code:
firstDict = [{'A':1 ,'B':1}, {'A':2 ,'B':2}]
secondDict = [{'A':3 ,'B':3}, {'A':2 ,'B':2}]
magicFunction(firstDict, secondDict)
magicFunction(secondDict, firstDict)

rawDescription: subtract two "lists of dictionaties"

description: Subtract two "lists of dictionaties"


rawDescription: Best way to obtain information from a dict

description: Obtain information from a dict


code:
lis = [[] for _ in xrange(6)] # don't use  [[]]*6
lis[1].append("foo")
lis[4].append("bar")
lis[1].append("py")
lis

rawDescription: python list with fixed number of elements

description: Python list with fixed number of elements


rawDescription: python & pandas: How do I split a dataframe into groups

description: Python & pandas: How do I split a dataframe into groups


code:
import cffi

ffi = cffi.FFI()
ffi.cdef('''
enum MESSAGE_TYPE
{
    SIMPLE_MESSAGE,     // short string describing error code
    VERBOSE_MESSAGE,    // long string describing error code
};

int _InitializeBIRDSystem(void);

int _GetErrorText(
    int                 errorCode,
    char                *pBuffer,
    int                 bufferSize,
    enum MESSAGE_TYPE   type
    );
''')

lib = ffi.dlopen('atc3dg.dll')
buf = ffi.new('char[100]')

err = lib._InitializeBIRDSystem()
lib._GetErrorText(err, buf, len(buf), lib.SIMPLE_MESSAGE)
print(ffi.string(buf).decode('ascii'))

# output:
# System         : No BIRDs were found anywhere

rawDescription: How to call a __cdel decorated function with cffi?

description: Call a __cdel decorated function with cffi


code:
# views.py
from app_settings import MY_SETTING

rawDescription: add variables in settings to be used in views - Django

description: Add variables in settings to be used in views - Django


code:
print(MyFloat(.4444))
print(MyFloat(-.4444))
print('some text {:.3f} some more text',format(MyFloat(.4444)))
print('some text {:+.3f} some more text',format(MyFloat(.4444)))

rawDescription: Print floating point values without leading zero


rawDescription: How to make a Python function sleep some time while the rest of the game continues?

description: Make a Python function sleep some time while the rest of the game continues


code:
entry_list = []

entry = Entry(...)
...
entry_list.append(entry)

entry = Entry(...)
...
entry_list.append(entry)

rawDescription: How do I check if any entry boxes are empty in Tkinter?

description: Check if any entry boxes are empty in Tkinter


code:
def run(self):
    # Explicit request for old-style install?  Just do it
    if self.old_and_unmanageable or self.single_version_externally_managed:
        return _install.run(self)

    # Attempt to detect whether we were called from setup() or by another
    # command.  If we were called by setup(), our caller will be the
    # 'run_command' method in 'distutils.dist', and *its* caller will be
    # the 'run_commands' method.  If we were called any other way, our
    # immediate caller *might* be 'run_command', but it won't have been
    # called by 'run_commands'.  This is slightly kludgy, but seems to
    # work.
    #
    caller = sys._getframe(2)
    caller_module = caller.f_globals.get('__name__','')
    caller_name = caller.f_code.co_name

    if caller_module != 'distutils.dist' or caller_name!='run_commands':
        # We weren't called from the command line or setup(), so we
        # should run in backward-compatibility mode to support bdist_*
        # commands.
        _install.run(self)
    else:
        self.do_egg_install()

rawDescription: python setuptools install_requires is ignored when overriding cmdclass

description: Python setuptools install_requires is ignored when overriding cmdclass


code:
try:
    checkbox = driver.find_element_by_xpath('//tr/td[1][(@class="rowodd" or @class="roweven") and text() = "%s${nbsp}"]/following-sibling::td[2]/input[starts-with(@name, "selectionIndex")]' % k)
    checkbox.click()
except NoSuchElementException:
    # question not found - need to handle it, or just move on?
    pass

rawDescription: Iterating Through a Table in Selenium Very Slow


code:
count=0
for i in range(0, len(g)-len(sub_string)):
    if g[i:i+len(sub_string)]==sub_string:
        count+=1

count

rawDescription: Counting instances a substring shows up

description: Counting instances a substring shows up


code:
from itertools import product
[x_o_r(zip(list(a), list(b))) for a, b in product(x, repeat=2)]

rawDescription: Python - Result returns generator instead of list (comprehension)


code:
def f(params):
    y_hat = params[0] * np.sin(params[1] * x + params[2])
    return np.linalg.norm(y_hat - y) + np.linalg.norm(y_hat - y2) + np.linalg.norm(y_hat - y3)

rawDescription: Trying to find a best fit line for multiple noisy sine waves


code: y = (slope * auto_data['DISPLACEMENT'] + intercept).round()

rawDescription: Correct Syntax for clearing SettingWithCopyWarning in Pandas


code:
from hurry.filesize import size
size(11000, system=mysystem)
size(198283722, system=mysystem)

rawDescription: Better way to convert file sizes in Python


code:
import struct
x_bytes = ser.read(4)  # (where ser is your Serial instance)
x = struct.unpack('<f', x_bytes)[0]
x

rawDescription: Converting a float in chars to float (PYTHON)


code: df

rawDescription: Splitting a column that contains multiple date formats


code: injuries["shoulder"]

rawDescription: Julia storing a partitioned data frame to a dictionary


code:
"""
win32_unicode_argv.py

Importing this will replace sys.argv with a full Unicode form.
Windows only.

From this site, with adaptations:
      http://code.activestate.com/recipes/572200/

Usage: simply import this module into a script. sys.argv is changed to
be a list of Unicode strings.
"""

import sys

def win32_unicode_argv():
    """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
    strings.

    Versions 2.x of Python don't support Unicode in sys.argv on
    Windows, with the underlying Windows API instead replacing multi-byte
    characters with '?'.
    """

    from ctypes import POINTER, byref, cdll, c_int, windll
    from ctypes.wintypes import LPCWSTR, LPWSTR

    GetCommandLineW = cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = LPCWSTR

    CommandLineToArgvW = windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
    CommandLineToArgvW.restype = POINTER(LPWSTR)

    cmd = GetCommandLineW()
    argc = c_int(0)
    argv = CommandLineToArgvW(cmd, byref(argc))
    if argc.value > 0:
        # Remove Python executable and commands if present
        start = argc.value - len(sys.argv)
        return [argv[i] for i in
                xrange(start, argc.value)]

sys.argv = win32_unicode_argv()

rawDescription: Read Unicode characters from command-line arguments in Python 2.x on Windows


code: points = [map(int, line.split(',')[:2]) for line in lasfile]

rawDescription: Reading all lines in a file with list comprehension


code:
# SQL Server format
cursor.execute("exec sp_dosomething(123, 'abc')")

# ODBC format
cursor.execute("{call sp_dosomething(123, 'abc')}")

rawDescription: Using stored procedures[python + ms sql]


code: names = [my_record.name for my_record in query.all()]

rawDescription: What's the pythonic idiom for making a simple list out of a list of instances?


code:
while not finished_event.wait(.1): # timeout in seconds
    pass

rawDescription: Catch Keyboard Interrupt in program that is waiting on an Event


code: LOGIN_URL = 'login' # name of url pattern

rawDescription: Django - use reverse url mapping in settings


code: next in ["left", "Left"]

rawDescription: The CLI seems to ignore my function and go to another! (Python)


code:
# __init__.py
from user import UserModel
from group import GroupModel

rawDescription: How do I separate my models out in django?

description: Separate my models out in django


rawDescription: Matplotlib: how to adjust zorder of second legend?


code:
edges, weights = zip(*dict_edges.items())
g = Graph(edges, edge_attrs={"weight": weights})

rawDescription: How to add edges in an igraph object from a dictionary

description: Add edges in an igraph object from a dictionary


code:
p1.iloc[0].dtypes
p1.iloc[:,0].dtypes
p1.iloc[:,:,0].dtypes
p1.iloc[:,:,0]

rawDescription: Pandas data types change when iterating over the major axis


code: [n.is_integer() for n in x]

rawDescription: Finding round figure

description: Finding round figure


code:
from itertools import groupby
{k:list(v) for k, v in groupby(reports, lambda x: x.status)}

rawDescription: Is there a better way to split of objects by one of its attributes?


code:
self.il = wx.ImageList(16, 16)

self.idx1 = self.il.Add(images.Smiles.GetBitmap())
self.sm_up = self.il.Add(images.SmallUpArrow.GetBitmap())
self.sm_dn = self.il.Add(images.SmallDnArrow.GetBitmap())

rawDescription: Problems with wx.ListCtrl

description: Problems with wx.ListCtrl


code:
import itertools

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

map(sum, grouper(3, interger, 0))

rawDescription: Adding up number in a list with every 3 number


code:
self.sync_trait("xmin", index_mapper.range, "_low_value")
self.sync_trait("xmax", index_mapper.range, "_high_value")
self.sync_trait("ymin", value_mapper.range, "_low_value")
self.sync_trait("ymax", value_mapper.range, "_high_value")

self.sync_trait("rangeXMin", plot2.index_mapper.range, "low", False)
self.sync_trait("rangeXMax", plot2.index_mapper.range, "high", False)

rawDescription: Chaco: Get Index and Value out of a chaco plot


rawDescription: An efficient way of making a large random bytearray


rawDescription: Python introspection

description: Python introspection


code:
import inspect

def get_unpassed_defaults(fn, args, kwargs):
        args_len = len(args) + len(kwargs)
        argspec = inspect.getargspec(fn)

        defaults = argspec.defaults
        default_names = argspec.args[-len(defaults):]

        number_of_args = len(argspec.args)
        number_of_positional_args = number_of_args - len(argspec.defaults)
        number_of_kwargs = number_of_args - number_of_positional_args
        number_of_kwargs_passed_as_positional = len(args) - number_of_positional_args

        default_values = defaults[number_of_kwargs_passed_as_positional:]
        default_names = default_names[number_of_kwargs_passed_as_positional:]
        defaults_dict = dict(zip(default_names, default_values))

        for kwarg_name in kwargs:
            if kwarg_name in defaults_dict:
                defaults_dict.pop(kwarg_name)

        return defaults_dict

rawDescription: Is python parameters' default value accepted by args or kwargs?


rawDescription: how can I get the position of the nonzero values in a numpy array?

description: Get the position of the nonzero values in a numpy array


code:
def make_elem_class(name):
    """Dynamically creates the class with a type() call."""

    def init(self, content=None, **kwargs):
        super().__init__(tag=name, content=content, **kwargs)

    __class__ = type(name, (elem,), {"__init__" : init})
    return __class__

rawDescription: Mix type(), and custom __init__() using super().__init__()


code:
for line in infile:
    data = line.rstrip("\n").split("|")
    kind = data[0]
    # start of changes
    if kind == "OBR":
        data[7] += "0000" # check that 7 is correct!
    # end of changes
    outrecord = "|".join(data)
    outfile.write(outrecord + "\n")

rawDescription: Optimal way to replace characters in large string with Python?


code:
def unique_file(file_name):
    counter = 1
    file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
    while 1:
        try:
            fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)
            return os.fdopen(fd), file_name
        except OSError:
            pass
        file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
        counter += 1

rawDescription: Is this the best way to get unique version of filename w/ Python?


code:
import tooltips
def login(): ...
def main():
    login()
    tooltips.check_tooltips()

rawDescription: Python Selenium webdriver query

description: Python Selenium webdriver query


code:
def changelist(self, request, extra_context=None):
    if request.GET['foo']:
        self.change_list_template = "students/student_change_list_other.html"

    return super(STUDENTAdmin, self).changelist_view(request, extra_context)

rawDescription: How can i change the Django admin template on the fly

description: Change the Django admin template on the fly


code:
from operator import itemgetter
bar = ['a','b','c','x','y','z']
itemgetter(0, 3, 4)(bar)

rawDescription: Compact way to assign values by slicing list in Python


rawDescription: Find all occurrences of integer within text in Python


code:
Nx1, idx1 = np.unique(data[:, 0], return_inverse=True)
Nx1 = Nx1.shape[0]
Nx2, idx2 = np.unique(data[:, 1], return_inverse=True)
Nx2 = Nx2.shape[1]
Nx3, idx3 = np.unique(data[:, 2], return_inverse=True)
Nx3 = Nx3.shape[0]

f = np.empty((Nx1, Nx2, Nx3))
f[idx1, idx2, idx3] = data[:, 3]
g = np.empty((Nx1, Nx2, Nx3))
g[idx1, idx2, idx3] = data[:, 4]
h = np.empty((Nx1, Nx2, Nx3))
h[idx1, idx2, idx3] = data[:, 5]

rawDescription: Converting coordinate tuple information to numpy arrays


code:
# initialize a variable to keep track of the total
total = 0

# Determine price per pound
# use if elif
if quantity >= 40:
    total = quantity * 7.50
elif quantity >= 20:
    total = quantity * 8.75
elif quantity >= 10:
    total = quantity * 10.00
else:
    total = quantity * 12.00

# do the tax calculations assigning it to a different variable
tax = total * 0.07

# add the tax to the total
total = total + tax

# print the tax
print('Tax $', format(tax,'.2f'), sep='')

# print the total
print('Cost of coffee $', format(total,'.2f'), sep='')

rawDescription: Python assign variable names to if else function


code:
class FilterForm(forms.Form):
    selectedplant = forms.ModelChoiceField(queryset=Plant.objects.all().order_by('IMS_plant'), required=True)

rawDescription: dropdown that filters results in django

description: Dropdown that filters results in django


rawDescription: python - intersection point of two great circles (lat/long)

description: Python - intersection point of two great circles (lat/long)


code: myfunc2(a, b, c)

rawDescription: Passing n arguments to a function in Python


code: #!/usr/bin/env python

rawDescription: Bash tab completion with argparse does not show all the files in the directory


code:
# ape bear cat dog
# ape elephant frog giraffe
# ape horse iguana jaguar

rawDescription: How to end for loop in Python?

description: End for loop in Python


code:
list2 = list1
list3 = list2

rawDescription: List Title Depends on Variable in Python


code:
file_date_string_list = ["%s %s"%(x[0],date.fromtimestamp(x[1])) \
                                             for x in file_date_tuple_list]

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

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


code: hour_sums = np.bincount(hour, weights=rentals, minlength=24)

rawDescription: Is there a way to use bincount with a clause in python?


code:
abc=['sentence1', '-1', 'sentence2', '1', 'sentence3', '0', 'sentence4']

new=[(abc[0],)]+[(''.join(i),) for i in zip(abc[1::2],abc[2::2])]

import csv
with open('test.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    a.writerows(new)

rawDescription: Python 3: write string list to csv file

description: Python 3: write string list to csv file


rawDescription: How to get a specific frame in a web page and retrieve its content

description: Get a specific frame in a web page and retrieve its content


code:
def isCyrillicOrd(filename):
    for char in filename:
        if 0x0400 <= ord(char) <= 0x04FF:    # directly checking unicode code point
            return True

    return False

rawDescription: Renaming Cyrillic file names

description: Renaming Cyrillic file names


code: re.match('(\d+)\s+(.*)', line).groups()

rawDescription: Extracting two values from python regex

description: Extracting two values from python regex


code: my_dist = np.ma.array(my_dist, mask = ~np.isfinite(my_dist))

rawDescription: specifying missing values to pdist in scipy

description: Specifying missing values to pdist in scipy


code:
for docid, termid, val in read_text(text):
    docs[docid].append((termid,val))

rawDescription: Check that matrix keys are in running order - python


code:
def weekend(day):
    if day == 'Saturday' or day == 'Sunday':
        return True
    else:
        return False

rawDescription: Return a Boolean instead of a string containing True or False in Python


code:
#!/usr/bin/python

import os

import keystoneclient.auth.identity as keystone_identity
import keystoneclient.session as keystone_session
import keystoneclient.client as keystone_client
import novaclient.client as nova_client
import glanceclient.client as glance_client

auth = keystone_identity.v2.Password(auth_url=os.environ['OS_AUTH_URL'],
                   username=os.environ['OS_USERNAME'],
                   password=os.environ['OS_PASSWORD'],
                   tenant_name=os.environ['OS_TENANT_NAME'])

# establish a keystone session
sess = keystone_session.Session(auth=auth)

# get a keystone client
kc = keystone_client.Client('2',
                            session=sess,
                            auth_url=sess.auth.auth_url)

# and authenticate it
kc.authenticate(token=sess.get_token(),
                project_id=sess.get_project_id(),
                tenant_id=sess.get_project_id())

# get a nova client
nc = nova_client.Client('2', session=sess)

# get a glance client
gc = glance_client.Client('2',
                          endpoint=kc.service_catalog.url_for(
                              service_type='image',
                              endpoint_type='publicURL'),
                          token=sess.get_token())

rawDescription: Openstack - Selectively deleting images based on some criteria?


rawDescription: Python sort CSV File

description: Python sort CSV File


code: return sum(map(doSomething, originalList), [])

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

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


code:
def addChildren(pname, pid, cloc, cstat):
    p = session.query(Parent).get(pid) # will give you either Parent or None
    if not(p):
        p = Parent(pname, pid)
        session.add(p)
    p.children.append(Child(loc=cloc, status=cstat))
    session.commit()

rawDescription: sqlalchemy add child in one-to-many relationship

description: Sqlalchemy add child in one-to-many relationship


code:
medals = df.pivot_table('no of medals', ['Year', 'Country'], 'medal')
medals

rawDescription: Python Pandas: Convert Rows as Column headers


code: {i:val for i, val in enumerate([4,6,7,21,1,7,3]) if val <= 4}

rawDescription: How to extract from a Python list while also accounting for the position of the extracted elements?

description: Extract from a Python list while also accounting for the position of the extracted elements


code:
text_list = ['help', 'me', 'solve', 'this', 'problem']
'select blah from table where blah = blahblah and ({})'.format(
    ' or '.join(['text like %s'] * len(text_list)))

rawDescription: Unpack python list to pass to a MySQL WHERE clause?


code:
# xml input file path, json output file path, custom indent for json
xml_to_json('sample.xml', 'sample.json', indent=2)

rawDescription: XML conversion fails to JSON return object


code:
def add(a, b):
    "Same as a + b."
    return a + b

def concat(a, b):
    "Same as a + b, for a and b sequences."
    if not hasattr(a, '__getitem__'):
        msg = "'%s' object can't be concatenated" % type(a).__name__
        raise TypeError(msg)
    return a + b

rawDescription: What is the difference between Python's __add__ and __concat__?


code:
num_pages = Math.Ceil( T / I ) # ceil(322/50) = 7 pages
cur_page = P # 6

start = I*P # 50 * 6 = 300
end = start + ipp # 300 + 50 = 350
if end > total: # true
  end = total # end = 322, not 350

items = allitems[start:end] # this page's items

rawDescription: Pagination in web2py with no database

description: Pagination in web2py with no database


code:
from itertools import compress
list(compress("abcdefg", [1, 1, 0, 0, 1, 1, 0]))

rawDescription: Match character from string with binary list


code:
# override Request object in order to set new authorization token into the header when the token expires
authorization_token = None

class AuthTokenRequest(Request):
    @property
    def headers(self):
        global authorization_token
        return Headers({'Authorization': 'BEARER {}'.format(authorization_token)}, encoding=self.encoding)

    @headers.setter
    def headers(self, value):
        pass

rawDescription: Scrapy - scraped website authentication token expires while scraping


code:
class SettingsView(BaseView):
     def get(request):
        return (...)

rawDescription: Django Url group only for Authenticated Users


rawDescription: Python: static variable decorator

description: Python: static variable decorator


code: res = c[:, None] ** q[None, :]

rawDescription: take different powers of a vector and save in txtfile

description: Take different powers of a vector and save in txtfile


code:
import tempfile
f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
n = f.name
f.close()
import subprocess
subprocess.call(['nano', n])

rawDescription: Start nano as a subprocess from python, capture input


rawDescription: Import Matlab Workspace variables into Spyder (Python)


code:
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk

class HelloWorld:

    def delete_event(self, widget, event, data=None):
        return False

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def __init__(self):
        # create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        self.window.set_icon_from_file('icon.png')

        self.window.connect("delete_event", self.delete_event)
        self.window.connect("destroy", self.destroy)

        # Creates a new button with the label "Hello World".
        self.button = gtk.Button("Hello World")

        self.window.add(self.button)
        self.button.show()
        self.window.show()

    def main(self):
        gtk.main()

if __name__ == "__main__":
    hello = HelloWorld()
    hello.main()

rawDescription: Adding a program icon in Python GTK

description: Adding a program icon in Python GTK


code:
m = mock.MagicMock(spec=bpgsql.Connection)
isinstance(m, bpgsql.Connection)

rawDescription: Can I fake/mock the type of my mock objects in python unittests

description: Fake/mock the type of my mock objects in python unittests


rawDescription: creating dictionaries in python

description: Creating dictionaries in python


code: data = dict((k, []) for k in range(2))

rawDescription: How do I initialize a dictionary of empty lists in Python?

description: Initialize a dictionary of empty lists in Python


code:
import csv

with open("propertyOutput.csv", "rbw") as fp:
    reader = csv.DictReader(fp, skipinitialspace=True)
    table = [row for row in reader]
    header = reader.fieldnames

rawDescription: how to write back to open csv file in python

description: Write back to open csv file in python


code:
def p(lst):
    if lst:               # at least one element
        print(lst[0])     # print first element
        if len(lst) > 1:  # if it's not the last element (which is not printed twice)
            p(lst[1:])    # recursive call with the rest of the list
            print(lst[0]) # and print first element again

rawDescription: Python Recursive Spiral List Printing

description: Python Recursive Spiral List Printing


rawDescription: Read .arrays txt files with python?

description: Read .arrays txt files with python


code:
def haslower(unicodechar):
    return unicodechar != unicodechar.lower()

def anylower(unicodestring):
    return any(haslower(c) for c in unicodestring)

rawDescription: Unicode case conversion

description: Unicode case conversion


code:
search(dfrm, lambda x: x > 0.8)
search(df, lambda x: x == 1)

rawDescription: Python pandas: Getting the locations of a value in dataframe


code:
def __iter__(self):
    yield from self._iterable

rawDescription: python make class iterable by returning embedded iterable

description: Python make class iterable by returning embedded iterable


code:
result = [first_el for first_el in first
          for second_el in second if first_el == second_el]

rawDescription: Comprehensive `for...in` different from standard loops


code:
devnull = open('/dev/null', 'w')
process = subprocess.Popen(shlex.split(command_line), stdout=devnull)
retcode = process.wait()

rawDescription: python subprocess hide stdout and wait it to complete

description: Python subprocess hide stdout and wait it to complete


code:
result = Differ().compare(s1, s2)
list(result)

rawDescription: Result of Differ.compare() vanishes after using once


code:
class Blacklist(Whitelist):
    def filter(self, record):
        return not Whitelist.filter(self, record)

rawDescription: What is a correct way to filter different loggers using python logging?


code:
import cPickle
hash(cPickle.dumps({'a': 42, 'i': 81}))
hash(cPickle.dumps({'i': 81, 'a': 42}))

rawDescription: Singleton/Borg pattern based on different parameters passed while creating the object


code:
class MyGroup(pygame.sprite.Group):
    def clear_by_class(self, cls):
        for sprite in self:
            if isinstance(sprite, cls):
                sprite.kill()

rawDescription: Pygame delete all objects in class

description: Pygame delete all objects in class


code:
import jinja2

template = jinja2.Template('''

{% for row in res %}

    {% for col in row -%}
        {{ col|replace('\s', ':1,7>') }}
    {% endfor %}

{% endfor %}

''')

rawDescription: How to display the result with temple jinjia2 or others?

description: Display the result with temple jinjia2 or others


code:
# mg.py

bar = 5

# server.py
import mg

def foo():
    mg.bar = 10

rawDescription: python: can i import the module namespace within the module itself?

description: Python: can i import the module namespace within the module itself


code:
def word_search(word, file):
    pattern = re.compile(r'\b{}\b'.format(re.escape(word)), flags=re.IGNORECASE)
    return (item for item in file if pattern.search(item))

rawDescription: wrong output in search file for word code

description: Wrong output in search file for word code


code:
import datetime

x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
z = datetime.datetime.today().strftime('%Y-%m-%d')

outfile = 'outputfile.txt'

with open(outfile, 'w') as f:
    f.write(str(x))
    f.write("\n")
    f.write(y)
    f.write("\n")
    f.write(z)
    f.write("\n")

rawDescription: redirecting python output to a log file

description: Redirecting python output to a log file


rawDescription: Implementing my own higher level test scripting language


rawDescription: Python wildcard matching

description: Python wildcard matching


code: '123'.join(['click', 'bounce'])

rawDescription: how to join various bits of string and data together using python

description: Join various bits of string and data together using python


code:
import urllib.request

your_url = "http://stackoverflow.com/"   # for example

opener = urllib.request.FancyURLopener({})
f = opener.open( your_url )
vr = f.read()
vr = vr.decode()
print( vr )

rawDescription: Regex and BeautifulSoup using Python

description: Regex and BeautifulSoup using Python


code:
splits = np.hsplit(A, [1,3]) # A split at indices 1 and 3 (gives list of three sub-arrays)
B = np.hstack((splits[0], splits[2]))
C = splits[1]

rawDescription: splitting numpy array into 2 arrays

description: Splitting numpy array into 2 arrays


rawDescription: Python: splitting on spaces, except between certain characters


code: method_object = foo_instance.descriptor

rawDescription: Why should classes with __get__ or __set__ know who uses them?


rawDescription: Converting paired table to binary table

description: Converting paired table to binary table


code:
def dot1d(a,b):
    return sum(x*y for x,y in zip(a,b))

def dot_2cmp(a):
    return [[dot1d(r,c) for c in a] for r in a]

rawDescription: Pythonic way of calculating A x A' (without numpy)


code: print(pd.read_csv(io.BytesIO(text), sep=' ', header=None))

rawDescription: Python Pandas does not read the first row of csv file


code:
product_list = [{'index': 12, 'verifier': 1}, {'index': 3, 'verifier': 0}, {'index': 9, 'verifier': 1}, {'index': 2, 'verifier': 0}]
sorted(product_list, key=lambda k: (k['verifier'] == 1, k['index']))
sorted(product_list, key=lambda k: k['index'] if k['verifier'] == 1 else None)

rawDescription: sort python list of dictionaires based on value of 2 keys

description: Sort python list of dictionaires based on value of 2 keys


code:
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['Hello World']

rawDescription: How Gunicorn forward request to flask

description: How Gunicorn forward request to flask


code: from django.db.models import Count

rawDescription: Django: Count users used in model's ManyToMany


code:
def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

rawDescription: Remove duplicate according to a callback


rawDescription: 'exportKey' function not recognized in pycrypto-2.6.1(python 2.7.6) ubuntu14.04 LTS


rawDescription: Need to add space between SubPlots for X axis label, maybe remove labelling of axis notches


code:
import time
import sys

rawDescription: User Defined Interrupt

description: User Defined Interrupt


code:
import datetime
import itertools
import random
import sys
import timeit
from collections import defaultdict

import mongoengine as db
from pycallgraph.output.graphviz import GraphvizOutput
from pycallgraph.pycallgraph import PyCallGraph

db.connect("test-dicts")

class MyModel(db.Document):
    date = db.DateTimeField(required=True, default=datetime.date.today)
    data_dict_1 = db.DictField(required=False)

MyModel.drop_collection()

data_1 = ['foo', 'bar']
data_2 = ['spam', 'eggs', 'ham']
data_3 = ["subf{}".format(f) for f in range(5)]

m = MyModel()
tree = lambda: defaultdict(tree)  # http://stackoverflow.com/a/19189366/3271558
data = tree()
for _d1, _d2, _d3 in itertools.product(data_1, data_2, data_3):
    data[_d1][_d2][_d3] = list(random.sample(range(50000), 20000))
m.data_dict_1 = data
m.save()

def pymongo_doc():
    return db.connection.get_connection()["test-dicts"]['my_model'].find_one()

def mongoengine_doc():
    return MyModel.objects.first()

if __name__ == '__main__':
    print("pymongo took {:2.2f}s".format(timeit.timeit(pymongo_doc, number=10)))
    print("mongoengine took", timeit.timeit(mongoengine_doc, number=10))
    with PyCallGraph(output=GraphvizOutput()):
        mongoengine_doc()

rawDescription: Mongoengine is very slow on large documents comapred to native pymongo usage


code:
[x for x in rt if x not in dp]
[3]

rawDescription: Most pythonic means to find out if an element from one list is not a member of another list


code: m = re.match("\W*RX packets[^:]*:(\d+)", line)

rawDescription: Extract string and assign to the variable using regex in Python


code:
...
def method1(self):
    return {"name": "method 1",
            "list": [1, 2, 3]}

rawDescription: Python, best way to return/handle complex data from a method


code: pprint([name for _0, _1, name in ephem._libastro.builtin_planets()])

rawDescription: look up planet or moon by name in pyephem?

description: Look up planet or moon by name in pyephem


code:
tuple_ = (a,b,c)
"\n".join([ str(foo(i)) for i in tuple_ ])

rawDescription: Tuple to string with a function to each element


code:
from itertools import chain, product
ABC = [ list(chain(*z)) for z in product(*SETS) ]

rawDescription: Python: Concatenate list of lists in the algebraic way


code: diffs = [nextitem-item for item,nextitem in zip(values, values[1:])]

rawDescription: Read other items in a python list while iterating through it


code: foo

rawDescription: input redirection for python 2.7

description: Input redirection for python 2.7


rawDescription: How to swap one value with next value in Python?

description: Swap one value with next value in Python


code:
from itertools import combinations
print(sum(1 for i in combinations(range(10000), 2)))

rawDescription: hashing large sequences of numbers, creating sets of hashes, storing, and comparing similarity of sets using python

description: Hashing large sequences of numbers, creating sets of hashes, storing, and comparing similarity of sets using python


rawDescription: Pythonic way to insert every 2 elements in a string


rawDescription: Rounding a sum in Python using round()

description: Rounding a sum in Python using round()


code:
def func(x,y):
    x = x+200 #this can be written x += 200
    y = y+300 #as above: y += 300
    return (x,y) #returns a tuple (x,y)

x = 2
y = 3
func(x,y) # returns (202, 303)
print(x,y) #prints 2 3

rawDescription: How to change the scope of a variable in a function? Python

description: Change the scope of a variable in a function? Python


rawDescription: Difference in regex behavior between Perl and Python?


rawDescription: Check what proxies are used in Requests module in Python3


code:
def formatTime(self, record, datefmt=None):
    ct = self.converter(record.created)
    if datefmt:
        s = time.strftime(datefmt, ct)
    else:
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        s = "%s,%03d" % (t, record.msecs)
    return s

rawDescription: Python logging: use milliseconds in time format


code:
import numpy as np

def float_to_int(array):
    int_array = array.astype(int, casting='unsafe', copy=True)
    if not np.equal(array, int_array).all():
        raise TypeError("Cannot safely convert float array to int dtype. "
                        "Array must only contain whole numbers.")
    return int_array

rawDescription: Convert float64 to int64 using "safe"

description: Convert float64 to int64 using "safe"


rawDescription: Python values of multiple lists in one list comprehension


rawDescription: Python Pandas: Find index based on value in DataFrame


code:
@timeout(timeout=2)
def return_later():
    time.sleep(3)
    return 'later'

rawDescription: Python and measuring the time in ms and aborting if threshhold is met


code: Billy

rawDescription: Python Child/Parent classes, Child Class Returning String Twice?


code:
"""I need a count of the word given by key(s) in multiple lists at the given index. So what I need is
>>> count(["a", "b", "c"], ["c", "b", "a"])
{"a": [1,0,1], "b": [0,2,0], "c": [1,0,1]}":
"""

rawDescription: Python dict count

description: Python dict count


rawDescription: Random string generation with upper case letters and digits in Python


code:
import random
for i in range(0,8):
    key = random.randint(33,126)
    key = chr(key)
    print(key, end='')

rawDescription: How can I make a string of ASCII characters from a for loop (Python 3.3)?

description: Make a string of ASCII characters from a for loop (Python 3.3)


rawDescription: Formatting text to be justified in Python 3.3 with .format() method


code:
recordslist = [["Daniel", 18], ["John", 19], ["Paul", 20], ["Jack", 44]]
a_dict = dict(recordslist)
a_dict
a_dict['Daniel']

rawDescription: Python List within List - References

description: Python List within List - References


code: return pair[0] if pair[0] != core else pair[1]

rawDescription: pythonic solution for finding the other element in a list of length two

description: Pythonic solution for finding the other element in a list of length two


code: my_lists = my_dict.values()

rawDescription: Turn list into list of lists using an object attribute


code:
def testFunc():
    for j in range(1,6):
        time.sleep(1)
        print("waiting for "+str(j) +" sec")
    print('this is a test')

for i in range(5):
    print('test')
    testFunc()
print("Have any test funcs been called")

rawDescription: Will a for loop that calls a function finish before any of the functions are called?


code:
from django.http import HttpResponse
import cv, Image

def instantPhoto(request) :
    cv_img = cv.QueryFrame( CAM[0] )
    pil_img = Image.fromstring("RGB", cv.GetSize(cv_img), cv_img.tostring())
    response = HttpResponse(mimetype="image/png")
    pil_img.save(response, "PNG")
    return response

rawDescription: Use cv.CaptureFromCAM in Django

description: Use cv.CaptureFromCAM in Django


code: setbuf(stdout, NULL)

rawDescription: subprocess stdin PIPE does not return until program terminates

description: Subprocess stdin PIPE does not return until program terminates


code:
#!/usr/bin/python
# this program is run by Python 2

rawDescription: Specifying a script is Python 2 or 3 which version of Python a program is written for


rawDescription: How to get type of multidimensional Numpy array elements in Python

description: Get type of multidimensional Numpy array elements in Python


code:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.properties import ObjectProperty
from kivy.clock import mainthread

class StudentsScreen(Screen):

    grid = ObjectProperty()

    def __init__(self, **kwargs):
        super(StudentsScreen, self).__init__(**kwargs)
        self.create_buttons()

    @mainthread  # slight delay
    def create_buttons(self):
        for i in xrange(200):
            button = StudentButton(text='student %s' % i)
            self.grid.add_widget(button)

class StudentButton(Button):
    pass

class Test(App):
    pass

if __name__ == "__main__":
    Test().run()

rawDescription: Convert Python script to KV langauge as a screen (Kivy)


rawDescription: copying functions located in instances

description: Copying functions located in instances


code:
import time
class WeatherData(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    temp_f = models.DecimalField()

    def created_at_utc(self):
        # whatever logic you need to do the conversion
        return time.mktime(self.created_at.timetuple())

rawDescription: Django views: how to modify returned queryset before rendering in template?


rawDescription: Will this cost me two queries for the same thing?


rawDescription: Grouping two lists in python

description: Grouping two lists in python


rawDescription: My Maxent Classifier works fine with gis algorithm but does not work with iis algorithm. It is not throwing any error, just some warnings


code: {{ count }}

rawDescription: Count objects with ListView

description: Count objects with ListView


code:
values=["2","3"]
content=["line1","line2","line3"]
for line in content:
    in_line = false
    for item in values:
        if item in line:
            in_line = true
            break
    if not in_line:
        print(line)

rawDescription: Applying conditional after nested loop to the parent loop


code:
for word in word_list:
    word = punctuation.sub("", word)

rawDescription: Removing punctuation/numbers from text problem


code:
for item in file_split(open('filename.txt')):
    doStuff(item)

rawDescription: Is there a way to read a file in a loop in python using a separator other than newline


code: mylist[0][0]   # get the first character from the first item in the list

rawDescription: Python: Get the first character of a the first string in a list?


code:
isOdd(5.2)
isOdd(5)
isOdd(6)

rawDescription: How would I check if a number is odd in python without using modulo or a library?


code:
from jellyfish import soundex

data = {soundex('google'): 'google.com', soundex('stackoverflow'): 'stackoverflow.com'}
print(data[soundex('gooooogle')])
# Should print `google.com`, because soundex pretty much ignores vowels

rawDescription: Python dictionary vague key search

description: Python dictionary vague key search


code:
args=['-f','--foo']
kwargs={'type':int, 'nargs':'*', 'help':'this is a help line'}

parser=argparse.ArgumentParser()
parser.add_argument(*args, **kwargs)
parser.print_help()

rawDescription: Add argparse arguments from external modules


code:
import scipy

def extrapolate_nans(x, y, v):
    '''
    Extrapolate the NaNs or masked values in a grid INPLACE using nearest
    value.

    .. warning:: Replaces the NaN or masked values of the original array!

    Parameters:

    * x, y : 1D arrays
        Arrays with the x and y coordinates of the data points.
    * v : 1D array
        Array with the scalar value assigned to the data points.

    Returns:

    * v : 1D array
        The array with NaNs or masked values extrapolated.
    '''

    if numpy.ma.is_masked(v):
        nans = v.mask
    else:
        nans = numpy.isnan(v)
    notnans = numpy.logical_not(nans)
    v[nans] = scipy.interpolate.griddata((x[notnans], y[notnans]), v[notnans],
        (x[nans], y[nans]), method='nearest').ravel()
    return v

new_reds   = extrapolate_nans(data[:, :, 0], data[:, :, 1], new_reds)
new_greens = extrapolate_nans(data[:, :, 0], data[:, :, 1], new_greens)
new_blues  = extrapolate_nans(data[:, :, 0], data[:, :, 1], new_blues)

new_colors = numpy.dstack([new_reds, new_greens, new_blues])

plt.imshow(new_colors, extent=(0, width, 0, height), origin='lower')
plt.show()

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


rawDescription: Django unique filtering

description: Django unique filtering


code:
binascii.hexlify(struct.pack('<d', 123.456)) # little-enddian
binascii.hexlify(struct.pack('>d', 123.456)) # big-endian

rawDescription: BitConverter.DoubleToInt64Bits equivalent in python


code:
class spmatrix(object):
    ...
    def __mul__(self, other):
        ...
        M,N = self.shape
        if other.__class__ is np.ndarray:
            # Fast path for the most common case
            if other.shape == (N,):
                return self._mul_vector(other)
            elif other.shape == (N, 1):
                return self._mul_vector(other.ravel()).reshape(M, 1)
            elif other.ndim == 2  and other.shape[0] == N:
                return self._mul_multivector(other)

rawDescription: Numpy/Scipy Sparse vs dense multiplication


code:
import numpy as np
np.random.seed(0)
N = 20
X = np.random.rand(N, 3)
w = np.array([1.0, 2.0, 3.0])
y = np.dot(X, w) + np.random.rand(N) * 0.1

rawDescription: Understanding scipy's least square function with IRLS


code:
func                 | x                    | time
unique_concatenate   | many_uniques         | 0.863
empty_set_union      | many_uniques         | 1.191
short_set_union_rest | many_uniques         | 1.192
long_set_union_rest  | many_uniques         | 1.194
set_chain            | many_uniques         | 1.224

func                 | x                    | time
long_set_union_rest  | many_duplicates      | 0.958
short_set_union_rest | many_duplicates      | 0.969
empty_set_union      | many_duplicates      | 0.971
set_chain            | many_duplicates      | 1.128
unique_concatenate   | many_duplicates      | 2.411

func                 | x                    | time
empty_set_union      | many_small_lists     | 1.023
long_set_union_rest  | many_small_lists     | 1.028
set_chain            | many_small_lists     | 1.032
short_set_union_rest | many_small_lists     | 1.036
unique_concatenate   | many_small_lists     | 1.351

func                 | x                    | time
long_set_union_rest  | few_large_lists      | 0.791
empty_set_union      | few_large_lists      | 0.813
unique_concatenate   | few_large_lists      | 0.814
set_chain            | few_large_lists      | 0.829
short_set_union_rest | few_large_lists      | 0.849

rawDescription: Fastest way to get union of lists - Python


code:
A = ['a', 'b', 'c']
dfA = pd.DataFrame(A)

start = datetime(year=2016, month=1, day=1)
end = datetime(year=2016, month=4, day=1)
months = pd.DatetimeIndex(start=start, end=end, freq="MS")
dfB = pd.DataFrame(months.month)

pd.DataFrame(np.array(np.meshgrid(dfA, dfB, )).T.reshape(-1, 2))

rawDescription: What is the most efficient way to create a pandas dataframe that combine two unrelated series?


rawDescription: Regexp works with sublime text search but not from python script


code:
class RegisterDescriptor(object):
    """
    A descriptor that models reading and writing to hardware registers.
    """

    def __init__(self, offset, size):
        self.offset = offset
        self.size = size

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        return hw_read(obj.base_address + self.offset, self.size)

    def __set__(self, obj, value):
        if obj is None:
            raise AttributeError("Cannot set attribute")
        hw_write(obj.base_address + self.offset, self.size, value)

rawDescription: Python - hardware handling, how to efficiently implement hardware registers as a property in an object


code:
xvfb.terminate()
# At this point, `ps -C Xvfb` may still show a running process
# (because signal delivery is asynchronous) or a zombie.
xvfb.wait()
# Now the child is dead and reaped (assuming it didn't catch SIGTERM).

rawDescription: How do I start and stop a Linux program using the subprocess module in Python?

description: Start and stop a Linux program using the subprocess module in Python


code:
maybe_c = {'c': mydict["SomeKey"]} if "SomeKey" in mydict else {}
foo( val1, val2, **maybe_c )

rawDescription: Let default value for parameter take precedence if test fails


code:
class MyTestCaseOne(unittest.TestCase):
    setup = my_setup

rawDescription: How can I define one setup function for all nosetests tests?

description: Define one setup function for all nosetests tests


rawDescription: How to extract only numbers from input file. Numbers can be float/int

description: Extract only numbers from input file. Numbers can be float/int


code: myList = list((i,r) if i != 0 else stop_iteration() for (i,r) in foo())

rawDescription: Python List Comprehension. Generating a List by repeatedly calling a function till it returns a predefined value


code:
class User(models.Model):
  ...
  friends = models.ManyToManyField(self) # self means User.

rawDescription: many to many field - django model - understanding

description: Many to many field - django model - understanding


code:
import time

def timestamp_to_ticks(t=None):
    if t is None:
        t = time.time()
    return int(t * (10**7)) + 621355968000000000

rawDescription: Time Ticks: 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001


code: plt.xticks(arange(5, 301, 29.5))

rawDescription: How can I force pyplot to show axis limits

description: Force pyplot to show axis limits


code:
reader = csv.reader(f)
headers = next(reader)
data = [row[1] for row in reader if int(row[2]) < 10]

rawDescription: manipulating TSV file

description: Manipulating TSV file


code: run_folder = os.path.join(currentwd, 'Folder_' + folder)

rawDescription: os.path.join producing an extra forward slash

description: Os.path.join producing an extra forward slash


rawDescription: launch HTML code without opening web-browser

description: Launch HTML code without opening web-browser


code: {elem.split('=', 1)[0]: elem.split('=', 1)[1].strip() for elem in x}

rawDescription: How to parse a tuple of "x=y" strings into a dictionary in python?

description: Parse a tuple of "x=y" strings into a dictionary in python


code:
n = []
for i, v in enumerate(a):
    n.append(b[i] - v)
print(n)

rawDescription: Subtract two lists in Python without using classes


code: array[i], array[j] = array[j], array[i]

rawDescription: Python implementation of Quicksort fails to sort the entire array


code:
def exists(a, b):
    """checks if b exists in a as a subsequence"""
    pos = 0
    for ch in a:
        if pos < len(b) and ch == b[pos]:
            pos += 1
    return pos == len(b)

rawDescription: Finding substring (nonconsecutive)

description: Finding substring (nonconsecutive)


code:
def fork(request):
    return myfunc1(request)

def myfunc1(request):
    return render_to_response('templates/derived/template2', {'msg': 'msg1'}, request)

rawDescription: Separating view_config routing and rendering in Pyramid


code:
import requests
prepared = requests.Request(url='http://httpbin.org/get').prepare()
prepared.url
prepared.prepare_url(prepared.url, {'foo': 'bar', 'spam': 42})
prepared.url
prepared.prepare_url(prepared.url, {'monty': 'python'})
prepared.url

rawDescription: Modify request params with custom authentication


code:
def get_serializer_class(self):
    if request.method == 'POST':
        return AnchorToUserPostSerializer
    return AnchorToUserGetSerializer

rawDescription: Only serialize on GET not POST Django REST Framework


code: text_entry.delete("2.0", "3.0")

rawDescription: Python 3.4 Tkinter - How can I just delete a string anywhere in a text widget?


code:
arr = np.array([[ch for ch in line ] for line in stg.translate(junk).split()])

arr = np.array([[ch for ch in line if ch.isdigit() or ch.isalpha()] for line in stg.split()])

rawDescription: Convert a long string into a matrix, cleaning it


code:
import yaml
yaml.load("""a: 1
b: foo
""")

rawDescription: Userfriendly way of handling config files in python?


code:
class AuthLinkBackend(object):
  def authenticate(auth_link = None):
    if auth_link:
      # validate and expire this link, return authenticated user if successful
      return user

rawDescription: Self Authenticating Links in Django

description: Self Authenticating Links in Django


code: coords = zip(indices[0], indices[1])

rawDescription: Finding the (x,y) indexes of specific (R,G,B) color values from images stored in NumPy ndarrays


code:
G= nx.Graph()
G.add_edges_from([(0,1),(0,2), (1,3), (1,4), (2,5), (2,6), (3,7)])
for node in G.nodes():
    if node%2==0:
        G.node[node]['child_status'] = 'left'  #assign even to be left
    else:
        G.node[node]['child_status'] = 'right' #and odd to be right
pos = binary_tree_layout(G,0)
nx.draw(G, pos=pos, with_labels = True)

rawDescription: preserving the left and right child while printing python graphs using networkx

description: Preserving the left and right child while printing python graphs using networkx


code: {int(d):d for d in data}.values()

rawDescription: Remove duplicate data from an array in python


code:
import numpy as np

mu_cell = X_train[:,0:channels,:,:].mean(0)
sigma_cell = X_train[:,0:channels,:,:].std(0)

rawDescription: Per-cell standardization efficiently in NumPy


rawDescription: Pyparsing problem with operators

description: Pyparsing problem with operators


code:
def setPrice(self, price):
    self._price = price

rawDescription: Calling While loop Function in __main__?

description: Calling While loop Function in __main__


rawDescription: Efficient way to apply multiple filters to pandas DataFrame or Series


code:
from sklearn.datasets import load_svmlight_file
X_train, y_train = load_svmlight_file("/path/to/train_dataset.txt")

rawDescription: Scikit SVM: create training dataset

description: Scikit SVM: create training dataset


rawDescription: Correct incantation of subprocess with shell=True to get output and not hang


code:
ax = var.total.plot(label='Variance')
ax = shares.average.plot(secondary_y=True, label='Average Age')

ax.left_ax.set_ylabel('Variance of log wages')
ax.right_ax.set_ylabel('Average age')

rawDescription: Legend only shows one label when plotting with pandas


code:
@login_required(login_url='/yourloginurl/')
def save_newfriend(request):
   owner = request.user
   # process friend_form_data
   new_friend = owner.owners_friend.create(friend=friend_form_data)

rawDescription: Django models, how to set object owner while saving


code:
from django.middleware.cache import get_cache_key as gk
help(gk)

rawDescription: Deleting a specific value from Django cache based on cookie


code:
import config
connection = MySQLdb.connect(
    host = config.HOST, user = config.USER,
    passwd = config.PASS, db = config.MYDB)

rawDescription: Connecting python program to mysql safely


code: exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)

rawDescription: Alternative to execfile in Python 3?

description: Alternative to execfile in Python 3


code: (t for t in dir(__builtins__) if type(getattr(__builtins__, t)) == type([].__class__))

rawDescription: Generate a list of objects of python builitins that can be called without arguments


code:
import os
import sys
import subprocess

for i, a in enumerate(sys.argv[1:]):
    if '=' not in a: break
    name, _, value = a.partition('=')
    os.environ[name] = value

sys.exit(subprocess.call(sys.argv[i:]))

rawDescription: Temporary PYTHONPATH in Windows

description: Temporary PYTHONPATH in Windows


code:
class Milk(object):
    def __repr__(self):
        return 'Milk()'

class ChocolateMilk(Milk):
    def __repr__(self):
        return 'ChocolateMilk()'

rawDescription: How to invoke C#/.NET namespace in IronPython?

description: Invoke C#/.NET namespace in IronPython


code:
@print_trace
def f():
    pass

rawDescription: Komodo - watch variables and execute code while on pause in the program


code:
df['Value'] = df.groupby(['station_id'])['Value'].cumsum()
df

rawDescription: Using np.cumsum on a grouped csv file

description: Using np.cumsum on a grouped csv file


code:
result = [set(x) for x in a] # start with the original list of sets
fixedPoint = False # whether we found a fixed point
while not fixedPoint:
    fixedPoint = True
    for x, y in combinations(result, 2): # search all pairs …
        if x & y: # … for a non-empty intersection
            x.update(y)
            result.remove(y)

            # since we have changed the result, we haven’t found the fixed point
            fixedPoint = False

            # abort this iteration
            break

rawDescription: Python nested list internal comparison and editing


code:
deck = [(cardval,suitval) for suitval in range(4) for cardval in range(13)]
deck.shuffle()

rawDescription: Card game framework Python 2.6 help/guidance


rawDescription: How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python?

description: Obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python


code:
import re
content = """
<title>
xxxxxxx
</title>
"""
title = re.findall('<title>(.*?)</title>', content, re.S)
title
title[0].strip()

rawDescription: Having issues with re.findall

description: Having issues with re.findall


code:
list1 = [['a', 'b', 'c', 'd']]
result = list1[0]
result

rawDescription: List in list convert to one list?

description: List in list convert to one list


code:
def findCaller(self):
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    """
    f = currentframe()
    #On some versions of IronPython, currentframe() returns None if
    #IronPython isn't run with -X:Frames.
    if f is not None:
        f = f.f_back
    rv = "(unknown file)", 0, "(unknown function)"
    while hasattr(f, "f_code"):
        co = f.f_code
        filename = os.path.normcase(co.co_filename)
        if filename == _srcfile:
            f = f.f_back
            continue
        rv = (filename, f.f_lineno, co.co_name)
        break
    return rv

rawDescription: Does using funcName when logging in Python have any performance impact?


code:
def hard_wrap(input, width, indent=' '):
   for line in input:
      indent_width = width - len(indent)
      yield line[:width]
      line = line[width:]
      while line:
         yield '\n' + indent + line[:indent_width]
         line = line[indent_width:]

rawDescription: Python Textwrap - forcing 'hard' breaks

description: Python Textwrap - forcing 'hard' breaks


code:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def CreatePagination(request, obj_list):
    # Create the pagination
    RESULTS_PER_PAGE = 10
    paginator = Paginator(obj_list, RESULTS_PER_PAGE)
    page = request.GET.get('page')  # Actual page
    try:
        page_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        page_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        page_list = paginator.page(paginator.num_pages)

    return page_list

rawDescription: Get current page of pagination in view and manually set count of page


code: col_two = [[n for n in number if n not in c1_list] for c1_list in col_one]

rawDescription: Randomizing an array into two arrays

description: Randomizing an array into two arrays


code:
import sys, os, random
from PyQt4 import QtCore, QtGui
StudentNames = []
StudentScores = []

class StartTest(QtGui.QMainWindow):
    def __init__(self, questions, parent=None):
        global StudentNames
        global StudentScores
        super(StartTest, self).__init__(parent)

        self.stack = QtGui.QStackedWidget(self)
        StudentNames.append('Hamzah Akhtar')
        StudentNames.append('Bob Marley')
        StudentNames.append('John Meadows')
        StudentScores.append(int(0))
        StudentScores.append(int(0))
        StudentScores.append(int(0))
        for index, question in enumerate(questions):
            page = Question(question, self)
            page.submit.clicked[()].connect(
                lambda index=index: self.handleSubmit(index))
            self.stack.addWidget(page)
        self.answers = []

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

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

    def handleSubmit(self, index):
        page = self.stack.widget(index)
        answer = page.answer.text()
        # validate submitted answer...
        self.answers.append(answer)
        if index < self.stack.count() - 1:
            self.stack.setCurrentIndex(index + 1)

class Question(QtGui.QWidget):
    def __init__(self, question, parent=None):
        super(Question, self).__init__(parent)
        self.question = QtGui.QLabel(question, self)
        self.answer = QtGui.QLineEdit(self)
        self.submit = QtGui.QPushButton('Submit', self)
        form = QtGui.QFormLayout(self)
        form.addRow(self.question, self.answer)
        form.addRow(self.submit)

if __name__ == '__main__':
    User = ''
    app = QtGui.QApplication([])
    questions = [
        'What is 5+5?',
        'What is 45+10?',
        'What is 28+47?',
        'What is 22+13?',
        ]
    window = StartTest(questions)
    window.show()
    # window.showFullScreen()
    app.exec_()

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


code:
class ComponentInline(admin.TabularInline):
    model = Component
    extra = 1
    formset = ComponentInlineFormSet

rawDescription: Validate inlines before saving model

description: Validate inlines before saving model


code:
if foo is None:
  foo = 42

rawDescription: Python equivalent for MySQL's IFNULL

description: Python equivalent for MySQL's IFNULL


code:
t = Test()

if 'foo' in t.commands:
    t.dispatch('foo')

for cmd in t.commands:
    # Obviously this will call each method with multiple commands dispatched to it once
    # for each command
    t.dispatch(cmd)

rawDescription: Dynamically calling nested functions based on arguments


code:
first = open('firstfile').readlines()
second = open('secondFile').readlines()

diff = [line for line in second if line not in first]

rawDescription: Python diff and get the new part

description: Python diff and get the new part


code:
class A(object):
    def __del__(self):
        print("DEL")
    def a(self):
        pass

def log_all_calls(function):
    def inner(*args, **kwargs):
        print("Calling {}".format(function))

        try:
            return function(*args, **kwargs)
        finally:
            print("Called {}".format(function))

    return inner

a = A()
a.a = log_all_calls(a.a)

a.a()

rawDescription: Why set a bound method to python object create a circular reference?


rawDescription: Special case when finding min key for dictionary in Python


code: ax.xaxis.labelpad = 20

rawDescription: Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks


code:
from nltk.corpus import brown
brown.words()[:50]
brown.tagged_words()[:50]
brown.sents()
brown.sents()[:3]
brown.tagged_sents()[:3]

rawDescription: How to tag an article with NLTK?

description: Tag an article with NLTK


code:
first_model_instance = MyFirstModel()
first_model_instance.save()

rawDescription: can I save models in this way in Django ?

description: Save models in this way in Django


code:
@jit(nopython=True)
def dot(a,b):
    res = a[0]*b[0]+a[1]*b[1]+a[2]*b[2]
    return res

@jit
def compute_stuff2(array_to_compute):
    N = array_to_compute.shape[0]
    con_mat = np.zeros((N,N))

    p0 = np.zeros(3)
    p1 = np.zeros(3)
    q0 = np.zeros(3)
    q1 = np.zeros(3)

    p0m1 = np.zeros(3)
    p1m0 = np.zeros(3)
    q0m1 = np.zeros(3)
    q1m0 = np.zeros(3)
    p0mq0 = np.zeros(3)

    for i in range(N):
        for j in range(i+1,N):

            for k in xrange(3):
                p0[k] = array_to_compute[i,k]
                p1[k] = array_to_compute[i,k+3]
                q0[k] = array_to_compute[j,k]
                q1[k] = array_to_compute[j,k+3]

                p0m1[k] = p0[k] - p1[k]
                p1m0[k] = -p0m1[k]

                q0m1[k] = q0[k] - q1[k]
                q1m0[k] = -q0m1[k]

                p0mq0[k] = p0[k] - q0[k]

            s = ( dot(p1m0, q1m0)*dot(q1m0, p0mq0) - dot(q1m0, q1m0)*dot(p1m0, p0mq0))/( dot(p1m0, p1m0)*dot(q1m0, q1m0) - dot(p1m0, q1m0)**2 )
            t = ( dot(p1m0, p1m0)*dot(q1m0, p0mq0) - dot(p1m0, q1m0)*dot(p1m0, p0mq0))/( dot(p1m0, p1m0)*dot(q1m0, q1m0) - dot(p1m0, q1m0)**2 )

            for k in xrange(3):
                con_mat[i,j] += (p0[k]+(p1[k]-p0[k])*s-(q0[k]+(q1[k]-q0[k])*t))**2

    return con_mat

rawDescription: Inter segment distance using numba jit, Python


code:
word1
word2
word3
word1word2
word1word3
word2word1
word2word3
word3word1
word3word2
word1word2word3
word1word3word2
word2word1word3
word2word3word1
word3word1word2
word3word2word1

rawDescription: Generating subsets of a permuted wordlist in Python


code:
#many imports
from theFileContainingTheLoginDialogue import DlgLogin

class MainWindow (QtGui.QMainWindow):
    def __init__ (self, parent = None):
        super (MainWindow, self).__init__ ()
        self.ui = Ui_MainWindow ()
        self.ui.setupUi (self)
        dlg = DlgLogin (self)
        if (dlg.exec_ () == DlgLogin.Accepted):
            #check here whether you accept or reject the credentials
            self.database = Database (*dlg.values)
            if not self.database.check (): sys.exit (0)
        else:
            sys.exit (0)
        self.mode = None

rawDescription: Connecting two different widgets together on qt with python through a button


rawDescription: How can I convert a bytestring array in a hex string in Python 3.4?

description: Convert a bytestring array in a hex string in Python 3.4


rawDescription: Given a list of strings, how to locate position of first string matching substring using RegEx?


code:
IMAGE_FORMAT = ('.png','.gif','.jpg','.jpeg')
'fred.gif'.endswith(IMAGE_FORMAT)

rawDescription: Python: How to test multiple values inside an if [multiple values] in list:


code:
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='u', passwd='p', db='mydb')
curs = conn.cursor()
uids = [1234,4321,1111]
qry = ("""SELECT cheese
            FROM cheeseshop
           WHERE id IN (%s)""" % ','.join(['%s']*len(uids)))
# 'SELECT cheese FROM cheeseshop WHERE id IN (%s,%s,%s)'
curs.execute(qry, uids)
curs.fetchone()
# ...

rawDescription: Fastest way to make a dict a single comma-separated string


rawDescription: How do I change my float into a two decimal number with a comma as a decimal point separator in python?

description: Change my float into a two decimal number with a comma as a decimal point separator in python


code:
for file_name in os.listdir(directory):
    name,ext = os.path.splitext(file_name)
    cashed_file_name = newest_files.get(name).file_name
    if file_name != cashed_file_name: #it's not the newest with this name
        os.remove(file_name)

rawDescription: Find duplicate filenames, and only keep newest file using python


code:
def format_args(arg1, arg2, arg3, arg4=0, arg5=0, arg6=0):
    return '{0}, {1}, {2}, {3}, {4}, {5}'.format(
      arg1, arg2, arg3, arg4, arg5, arg6)

rawDescription: Pythonic insertion of variable number of arguments into a string


code: numpy.delete(a, index)

rawDescription: How to remove specific elements in a numpy array

description: Remove specific elements in a numpy array


code:
import re
input = open('path/file').read()
result = re.search(r'.*string match\s*(.*)$', input, re.DOTALL)
print(result.group(1))

rawDescription: python return all lines after last regex match

description: Python return all lines after last regex match


code: alleles = GAllele.GAlleles()

rawDescription: How to set different parameter ranges within a real valued chromosome using Pyevolve?

description: Set different parameter ranges within a real valued chromosome using Pyevolve


rawDescription: Python: create all derivatives of string by replacing its symbols


rawDescription: Python Fuzzy Matches in two text files

description: Python Fuzzy Matches in two text files


code:
def intdict():
    return defaultdict(int)

grid = defaultdict(intdict)

rawDescription: python: representing square grid that wraps on itself (cylinder)

description: Python: representing square grid that wraps on itself (cylinder)


code:
class MyResource(ModelResource):
    class Meta:
        filtering = {
            "user": ('exact',),
            "friend": ('exact',),
            "comment": ('exact',)
        }

rawDescription: handling multiple query parameters in tastypie

description: Handling multiple query parameters in tastypie


code: d = datetime.date.today()

rawDescription: Getting the date of the last day of this [week/month/quarter/year]


code:
for line in file_in:
    items = line.split('|')
    team = items[0]
    name = items[1]
    teams[team].add(name.strip())

rawDescription: Aggregate text keys-values python defaultdict


code:
a = [0, 1, 2, 3, 5, 7, 8, 10]
it = iter(a)
start = next(it)
slices = []
for i, x in enumerate(it):
    if x - a[i] != 1:
        end = a[i]
        if start == end:
            slices.append([start])
        else:
            slices.append([start, end])
        start = x
if a[-1] == start:
    slices.append([start])
else:
    slices.append([start, a[-1]])

rawDescription: Python, converting a list of indices to slices


code:
IN_IPYNB = 'get_ipython' in vars()

if IN_IPYNB:
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    for h in logger.handlers:
        h.setFormatter(logging.Formatter(
                '(%(threadName)-0s) %(relativeCreated)d - %(message)s'))
else:
    logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-0s) %(relativeCreated)d - %(message)s')

rawDescription: Python 3 concurrent.futures and per-thread initialization


code:
plt.subplot(111)
hb = plt.hexbin(x,y, cmap=plt.cm.YlOrRd_r)
plt.axis([xmin, xmax, ymin, ymax])
cb = plt.colorbar()
cb.set_ticks(np.linspace(hb.get_array().min(), hb.get_array().max(), 6))
cb.set_ticklabels(np.linspace(0, 1., 6))

rawDescription: matplotlib hexbin normalize

description: Matplotlib hexbin normalize


rawDescription: Why are Python lambdas useful?

description: Why are Python lambdas useful


code: b = element[3](a)

rawDescription: is there a way to avoid eval() to accomplish dynamic dispatch of a function specified in a list in python

description: Is there a way to avoid eval() to accomplish dynamic dispatch of a function specified in a list in python


code:
import pandas as pd
df = pd.read_csv("cluster.csv")
df

rawDescription: Counting particular occurences in python in csv file


code:
from matplotlib.dates import date2num

# I'm assuming you have tuples, so we can't modify them in-place...
quotes = [(date2num(item[0]),) + item[1:] for item in quotes]

rawDescription: Candlestick data in list to matplotlib

description: Candlestick data in list to matplotlib


rawDescription: Add string in a certain position in Python


code:
import sys
from BeautifulSoup import BeautifulSoup

# where so_soup.txt is your html
f = open ("so_soup.txt", "r")
data = f.readlines ()
f.close ()

soup = BeautifulSoup ("".join (data))

cells = soup.findAll('td', {"class" : "lft lm"})
for cell in cells:
    # You can compare cell.string against "Accounts Payable"
    print (cell.string)

rawDescription: Using Python and Beautifulsoup how do I select the desired table in a div?


code:
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = [ line for line in iter(lambda:input("Please enter an item to add"), "nothing")]

print('There are {} items in the basket: '.format(len(basket)))
for ind,item in enumerate(basket,1):
    print("Item{}: {} ".format(ind,item))

rawDescription: Line breaks with lists

description: Line breaks with lists


code:
def unique_rows(data):
    unique = dict()
    for row in data:
        row = tuple(row)
        if row in unique:
            unique[row] += 1
        else:
            unique[row] = 1
    return unique

rawDescription: comparing row in numpy array

description: Comparing row in numpy array


rawDescription: Python MySQLdb update table from dictionary of lists


code:
from google.appengine.api import datastore
from google.appengine.api import datastore_errors

def get_entities(keys):
    rpc = datastore.GetRpcFromKwargs({})
    keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys)
    entities = None
    try:
        entities = datastore.Get(keys, rpc=rpc)
    except datastore_errors.EntityNotFoundError:
        assert not multiple

    return entities

def put_entities(entities):
    rpc = datastore.GetRpcFromKwargs({})
    keys = datastore.Put(entities, rpc=rpc)
    return keys

rawDescription: Migrating data when changing an NDB field's property type


code:
import sympy as sm
a, b, c, x = sm.symbols('a b c x')
F = sm.symbols('F', cls=sm.Function)
expr = F(a - b) - F(b**2 - c)

rawDescription: placeholder functions in sympy

description: Placeholder functions in sympy


code:
b=0
b = [sum(a[:k]) for k in range(1+len(a))]

rawDescription: incremental sum a list of numbers in Python 2.7

description: Incremental sum a list of numbers in Python 2.7


code:
for num in unsorted:
    bucketappender[(num & byte_check) >> ofs8](num)

rawDescription: Pushing Radix Sort (and python) to its limits


code:
import tkFont
helv36 = tkFont.Font(family='Helvetica',
    size=36, weight='bold')  # you don't have to use Helvetica or bold, this is just an example
button['font'] = helv36

rawDescription: How to change font and size of buttons and frame in tkinter using python?

description: Change font and size of buttons and frame in tkinter using python


rawDescription: Method that applies to instance of a class in python // Apply a method to an instance of a class in python


code:
from itertools import groupby

groupby(sl, key=lambda l:l[1])

rawDescription: Finding similar data and putting them on separate list


code:
class Pk_lookup(models.Model):
  # since we're using sha256, set the max_length of this field to 32
  hashed_pk = models.CharField(primary_key=True, max_length=32)
  key = models.IntegerField()

rawDescription: django, python and link encryption

description: Django, python and link encryption


code:
filename = "%s_%s_.exe" % (software.capitalize(),version)
if not os.path.exists(os.path.join(OUTPUT_FOLDER, filename)):
    base_url = urlJoin(LINK, + version + "_multi.exe")
    writeFile(original_filename, httpRequestFile(base_url), "wb")

rawDescription: Python skip a function if the file already exists


code:
namelist = {}

for full_subdir_name in lst_names:
    namelist[full_subdir_name] = [os.path.join(full_subdir_name, n) for n in os.listdir(full_subdir_name)]

rawDescription: Python--read files, save the file names and access to these files


rawDescription: Sequential image presentation in Pygame

description: Sequential image presentation in Pygame


code:
def compile(pattern, flags=0):
    "Compile a regular expression pattern, returning a pattern object."
    return _compile(pattern, flags)

rawDescription: How does Python's regex pattern caching work?


rawDescription: Character replacement in string: How to do it with regex?


code:
from scrapy import Item, Field
from scrapy.contrib.spiders import XMLFeedSpider

from testscraper.items import testscraperItem

class MySpider(XMLFeedSpider):
    name = "Test_scraper"
    itertag = 'item'

    allowed_domains = ["dealbook.nytimes.com"]
    start_urls = ["http://dealbook.nytimes.com/feed/"]

    def parse_nodes(self, response, nodes):
        for index, selector in enumerate(nodes, start=1):
            ret = iterate_spider_output(self.parse_node(response, selector))
            for result_item in self.process_results(response, ret):
                result_item['index'] = index
                yield result_item

    def parse_node(self, response, selector):
        struct = testscraperItem()
        title = selector.select('./title/text()').extract()
        link = selector.select('./link/@href').extract()
        pubdate = selector.select('./pubDate/text()').extract()
        topics = selector.select('./category/text()').extract()

        struct["title"] = title
        struct["link"] = link
        struct["pubdate"] = pubdate
        struct["topics"] = topics
        yield struct

rawDescription: Scrapy not scraping all HTML tags

description: Scrapy not scraping all HTML tags


code:
class rint(int):
    def __format__(self, spec):
        return int.__format__(int(round(self, -2)), spec)

raw_data = [111, 22222, 33333]
data = map(rint, raw_data)
[format(x, ',') for x in data]

rawDescription: Possible to round numbers to the hundreds, thousands, etc. using Python 3's number formatting


code:
_config = ConfigParser.ConfigParser()
with open(your_config_file) as config_file:
    _config.readfp(config_file)

rawDescription: Python - How to change the name of a section use configparser?


code: lat, long = string.split('cbll=')[1].split('&')[0].split(',')

rawDescription: Stripping an dynamic url content

description: Stripping an dynamic url content


code:
from package import *

print(example('derp'))

rawDescription: How to import members of modules within a package

description: Import members of modules within a package


code:
def quadratic(value_of_x):
    y = (value_of_x **2) + (3*value_of_x) + 5
    return y

eg_1 = quadratic(5)
print (eg_1)
eg_2 = quadratic(3)
print (eg_2)

# But this will fail
#print (y)

rawDescription: counting number with 3 csvs python

description: Counting number with 3 csvs python


rawDescription: Data Manipulation in accordance with a Pattern in Python