code:
message = '''
hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE
+K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA
IgDEb1NeXZ499qnSY1ZvCy/VCF1O7H71y77VQTckpfyHgWvzkaaaheMC0r+JGLZO
0w3NCTERFJ8XaXKz/+qw4gA7xxbpT9nXVXMwEwYgiAviJBJhdYw63oTlRYGgGzPh
H2YVNv2TWnpWp816xi+sbM1ZsJJERnAZSADKFYZzYw4E73VhUlrX5YBY4WN7UmQw=
'''
import base64
base64.b64decode(message)

rawDescription: Convert ASCII armored output to binary data


code:
def indexing(A, p, B=None):
    m, n = A.shape
    if B is None:
        B = np.zeros((m,n,p), dtype=int)
    for r in range (m):
        for c in range (n):
            x = np.random.randint(0, p)
            B[r, c, x] = A[r, c]
    return B
indexing(A,p,indexing(A,p))

rawDescription: Copy numpy array from one (2-D) to another (3-D)


code:
def reverse_hex(HEXDATE):
    hexVals = [HEXDATE[i:i + 2] for i in xrange(0, 16, 2)]
    reversedHexVals = hexVals[::-1]
    return ''.join(reversedHexVals)

rawDescription: Perl to Python Function translation

description: Perl to Python Function translation


code:
def remove_word2(trie, word):
    current_dict = trie
    path = [current_dict]
    for letter in word:
        current_dict = current_dict.get(letter, None)
        path.append(current_dict)
        if current_dict is None:
            # the trie doesn't contain this word.
            break
    else:
        if not path[-1].get(_end, None):
            # the trie doesn't contain this word (but a prefix of it).
            return
        deleted_branches = []
        for current_dict, letter in zip(reversed(path[:-1]), reversed(word)):
            if len(current_dict[letter]) <= 1:
                deleted_branches.append((current_dict, letter))
            else:
                break
        if len(deleted_branches) > 0:
            del deleted_branches[-1][0][deleted_branches[-1][1]]
        del path[-1][_end]

rawDescription: How to implement the remove function of a trie in python?

description: Implement the remove function of a trie in python


code:
import re

re_domain = re.compile(".*\.(.*)")
sites = {}

for index in indexes:
    match = re_domain.search(index)
    if match:
        sites.setdefault(match.group(1), []).append(index)

for site_key in sites.keys():
    devices = sites[site_key]

rawDescription: How to create a dict equivalent in Python from Perl hash?

description: Create a dict equivalent in Python from Perl hash


code:
import re

with open("myprogram.py","r",encoding='utf8') as f:
    for x in f.readlines():
        y = x   # Main code x defining as y.
        if re.findall("print",x) == ['print']: # if 'print' is found;
            x = "print(" + x.split("print")[1].strip() + ")" # strip it quotation mark and paranthesis;
            y = y.replace(y,x)  #.. replace y with x.
        print(y.strip())

rawDescription: Converting scripts to a different version of Python


code: return [diff_unique(a[key][1],b[key][1]) for key in sorted(common_keys) ]

rawDescription: comparing list of tuple elements python

description: Comparing list of tuple elements python


code:
counts_and_means = \
counts_and_means

rawDescription: Pandas: Best idioms for renaming, reordering columns while aggregating


rawDescription: How to use re.findall in a string with different patterns?

description: Use re.findall in a string with different patterns


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 10))
df[list(df.columns[:2]) + [7]]

rawDescription: keep/slice specific columns in pandas

description: Keep/slice specific columns in pandas


code:
L = []
for x in a.split(","):
    f1, f2 = x.split(":")
    L.append((f1, int(f2)))

rawDescription: Separate objects and put them into pairs


code:
for i, (image_row, data_row) in enumerate(zip(image, data)):
    image_row[i%2::2] = data_row

rawDescription: custom matplotlib plot : chess board like table with colored cells

description: Custom matplotlib plot : chess board like table with colored cells


rawDescription: Pandas reformatting multiple columns into one.


code:
import csv
a=8
mylist = [a,'2','3']
with open("myfile.csv", "wb") as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)
    mylist[0] = mylist[0] + 1  ####  here you modify a list
    wr.writerow(mylist)

rawDescription: Updating variables in a list using python's csv module


code:
#filename: /tmp/test.py
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessio

nmaker
from sqlalchemy.ext.declarative import declarative_base
import os

sqldebug=True

engine = create_engine('mysql://test:test@localhost/test1',
            convert_unicode=True,
            echo=sqldebug)

#create_engine(
#           'postgresql://user:passwd@localhost/clasificador',
#           convert_unicode=True,
#           echo=sqldebug)

db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base(bind=engine)
Base.query = db_session.query_property()

class Documento(Base):
    '''Clase definiendo los documentos'''
    __tablename__ = "documentos"

    id = Column(Integer,primary_key=True)
    nombre = Column(String(248))

    def __init__(self,nombre):
        self.nombre = nombre

    def __repr__(self):
        return '<Documento %r>' % self.nombre

Base.metadata.create_all(engine)

from sqlalchemy.orm import sessionmaker
#some other code
Session = sessionmaker(bind=engine)
session = Session()
doc = Documento(os.path.basename('/tmp/test.py'))
session.add(doc) #here fails
session.commit()

rawDescription: SQLAlchemy expects an object, but finds a Table


code:
# using a list comprehension
# make a list of the means of the windows, disregarding the Nan's
means = [window[index].mean() for window, index in zip(windows, notNan)]
new_array = np.array(means).reshape(new_shape)

# generator expression
# produces the means of the windows, disregarding the Nan's
means = (window[index].mean() for window, index in zip(windows, notNan))
new_array = np.fromiter(means, dtype = np.float32).reshape(new_shape)

rawDescription: resize a 2D numpy array excluding NaN

description: Resize a 2D numpy array excluding NaN


code:
while True:
    try:
        a,b,c,d = (int(input()) for _ in range(4))
        break
    except ValueError:
        print("Invalid input")
print(a, b, c, d)

rawDescription: Entering few integers in one line

description: Entering few integers in one line


code: a['foo']

rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


rawDescription: Efficiently creating additional columns in a pandas DataFrame using .map()


code: s = s[:-6] if s.endswith('000000') else s

rawDescription: how to trim n characters of string in python?

description: Trim n characters of string in python


code:
{'sip_domains': {'domain': [{'name': 'k200.com'},
                            {'name': 'zinga.com'},
                            {'name': 'rambo.com'}],
                 'prefix': [{'name': ''}]},
 'sip_proxy_mode': {'handle_requests': 1},
 'sip_security': {'level': 2},
 'sip_trusted_hosts': {'host': []}}

rawDescription: extracting the output using python

description: Extracting the output using python


code:
from itertools import chain
def check_valid(matrix):
   valid_set = set(range(1, len(matrix)+1))
   return all(set(row) == valid_set for row in chain(matrix, zip(*matrix)))

rawDescription: check whether an element is in list or not

description: Check whether an element is in list or not


code:
def subsets(n, modulo):
    a, b = 1, 2
    for _ in xrange(n):
        a, b = b, (a + b) % modulo
    return a

rawDescription: OverFlowError while solving "Number of subsets without consecutive numbers"


code: labels = ['[{0} - {1}]'.format(label[0], label[1]) if len(label) > 1 else '[ > {} ]'.format(label[0]) for label in labels]

rawDescription: Grouping values using pandas cut

description: Grouping values using pandas cut


code:
from a import variableName
from b import variableName
from c import variableName

rawDescription: how do I import from a file if I don't know the file name until run time?

description: Import from a file if I don't know the file name until run time


code:
def interpolate_to_distance(self, distance):
    dshape = self.dist.shape
    dist = self.dist.T.reshape(-1, dshape[-1])
    data = self.data.T.reshape(-1, dshape[-1])
    intdata = np.array([np.interp(distance, di, da)
                        for di, da in zip(dist, data)])
    return intdata.reshape(dshape[0:2]).T

rawDescription: NumPy: 1D interpolation of a 3D array

description: NumPy: 1D interpolation of a 3D array


code:
import collections
number_locations = collections.defaultdict(set)
for i, l in enumerate(a):
    for num in l:
        number_locations[num].add(i)

rawDescription: Find the index of a list which is subset in a list of list


code:
def __getattribute__(self, attr):
        obj = object.__getattribute__(self, attr)
        if hasattr(obj, '__get__'):
            return obj.__get__(self, type(self))
        return obj

rawDescription: Why is the Descriptor not getting called when defined as instance attribute?


code:
D = {}
for i, s in enumerate(strlist):
    D.setdefault(s, set()).add(i)

D

rawDescription: Generating an inverse index

description: Generating an inverse index


code:
def partition(item, filter_):
    inGroup, outGroup = [], []
    for n in items:
        if filter_(n):
            inGroup.append(n)
        else:
            outGroup.append(n)
    return inGroup, outGroup

rawDescription: python equivalent of scala partition

description: Python equivalent of scala partition


code:
from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('param1','param2')

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        param1 = cleaned_data.get("param1")
        param1 = cleaned_data.get("param2")

        if param1 and param2:
            # Only do something if both fields are valid so far.
            if param1 != param2:
                raise forms.ValidationError("param1 does not equal param2")

        return cleaned_data

rawDescription: How to control which fields from POST data in ModelForm overwrite fields from instance that is passed in?

description: Control which fields from POST data in ModelForm overwrite fields from instance that is passed in


code:
match = re.search(r"Data\s*:\s*((?:[^\n]*[\r\n]+){3})", subject)
if match:
    result = match.group(1)

rawDescription: Using regex to parse multiline string

description: Using regex to parse multiline string


rawDescription: How do you do $elemMatch in Mongokit?

description: Do $elemMatch in Mongokit


rawDescription: Python 3 - counting matches in two lists (including duplicates)


rawDescription: Field calculated from Foreign Keys, need to save twice?


code: nestedList.sort(key=lambda x: x[0])

rawDescription: Python: Sort a Nested List With Specific Criteria


code:
results = []
for i in range(len(functions)):
    results.append(functions[i](values[i]))

rawDescription: Apply a different Python function to corresponding element


code:
scipy.fftpack.fft(np.arange(8))
a = scipy.fftpack.rfft(np.arange(8))
a
a.dtype
a[1:-1].view(np.complex128) # First and last entries are real

rawDescription: How should I multiply scipy.fftpack output vectors together?


code:
class A(object):
   x = 42
   y = 43

class B(A):
   x = 11

b = B()

rawDescription: How to get an attribute just from the current class and not from possible parent classes?

description: Get an attribute just from the current class and not from possible parent classes


code: [d[element] for element in l]

rawDescription: How to do this list/dict comprehension in python

description: Do this list/dict comprehension in python


code:
def evens(n):
    return [2*n for n in range(1, n+1)]

rawDescription: Python Program that takes an integer and returns a list of n even integers


code:
cities = {'England'  : ['Manchester'],
          'Germany'  : ['Stuttgart'],
          'France'   : ['Paris', 'Lyonn'],
          'Italy'    : ['Torino']}
{key: set(value) for key, value in cities.items()}

rawDescription: Converting to a set dictionary in Python


code: sum(v1.get(k, 0) * v2.get(k, 0) for k in v1)

rawDescription: how can i get the dot product of vectors (list form) in python

description: Get the dot product of vectors (list form) in python


rawDescription: I want to be able to add function to a python class dynamically, not knowing their names in advance


code:
values = np.arange(5, 9, 0.5)
np.random.choice(values, size=3)
np.random.choice(values, size=5)

rawDescription: How to get 3 float numbers randomly with the step of 0.5 between 5.0 and 9.0 using Numpy?

description: Get 3 float numbers randomly with the step of 0.5 between 5.0 and 9.0 using Numpy


code:
import pprint

class P(pprint.PrettyPrinter):
  def _format(self, object, stream, indent, allowance, context, level):
    if isinstance(object, basestring):
      if len(object) > 20:
        object = object[:20] + '...'
    return pprint.PrettyPrinter._format(
      self, object, stream, indent, allowance, context, level)

P().pprint(range(3))
P().pprint('x' * 1000)

rawDescription: Automatically shorten long strings when dumping with pretty print


code: dict_class_copy = {k:set(v) for k,v in dict_class.items()}

rawDescription: Best way to partially deep copy a dictionary in Python?

description: Partially deep copy a dictionary in Python


code:
import json
my_data = {'id': 123, 'name': 'Test User', 'emails': ['test@example.com', 'test@hotmail.com']}
my_data_json = json.dumps(my_data)

rawDescription: Create nested JSON from CSV

description: Create nested JSON from CSV


code: words = [word for word in otherFile if word in currentFile]

rawDescription: Store value of "if any(" search

description: Store value of "if any(" search


code:
import commands
commands.getoutput('pgrep firefox')

rawDescription: How to check in Mac OSX with Python if a process is RUNNING or not

description: Check in Mac OSX with Python if a process is RUNNING or not


code:
fig, ax = plt.subplots(1, 1)

x, y = np.meshgrid(lon_grid, lat_grid)
c = np.ones_like(x)

ax.pcolor(x, y, c, facecolor='none', edgecolor='k')

ax.set_xlim(lon_grid[0], lon_grid[-1])
ax.set_ylim(lat_grid[0], lat_grid[-1])

rawDescription: How to plot the grid line only using pcolor/pcolormesh

description: Plot the grid line only using pcolor/pcolormesh


code: result = [dict(r) for r in result]

rawDescription: Sum the nested dictionary values in python


code:
def gallery_save(self, *args, **kwargs):
    return self, args, kwargs

class Gallery(object):
    save = gallery_save

class MyGallery(object):
    save = gallery_save

rawDescription: Use a method from other classes w/o inheritance


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: Python unique values in a list

description: Python unique values in a list


code:
csv.register_dialect('mycsv', delimiter='\t', quoting=csv.QUOTE_NONE)
with open(filename, 'rb') as f:
    reader = csv.reader(f, 'mycsv')

rawDescription: Python - Import file into NamedTuple

description: Python - Import file into NamedTuple


code:
def __iter__(self):
    for key in "y", "z":
        yield key, getattr(self, key)

rawDescription: How can I make a custom conversion from an object to a dict?

description: Make a custom conversion from an object to a dict


code:
import re
str = '
1. Tips and tricks
'
m = re.findall(r'((?<=>)\d+\.\s*(Tips)[^<]*)', str)
m

rawDescription: Match surrounding text around a group match


code:
self.fields['nut'].queryset = Nut.objects.exclude(
    pk__in=Bolt.objects.values('nut').query)

rawDescription: Django queryset that returns all unassigned fks


code:
for element in unpaired:
    yourDict[element] = '.'

for element in paired:
    yourDict[element[0]] = '('
    yourDict[element[1]] = ')'

rawDescription: How to store values in list based on another list and tuple

description: Store values in list based on another list and tuple


rawDescription: to slice columns in a tuple present in a numpy array

description: To slice columns in a tuple present in a numpy array


code: np.max(x[mask] + y[mask] * cm[mask])

rawDescription: Is there a better way to rewrite this NumPy Snippet


code: grid_x, grid_y = np.mgrid[0:max(Y):800j, 0:max(X):800j]

rawDescription: Plot (x, y, z) triples on 2d plane with a colormap


code:
from __future__ import print_function

import trollius as asyncio
from trollius import From

@asyncio.coroutine
def f():
    yield From(asyncio.sleep(1))
    print("world!")

@asyncio.coroutine
def g():
    asyncio.ensure_future(f())
    print("Hello, ", end='')
    yield From(asyncio.sleep(2))

loop = asyncio.get_event_loop()
loop.run_until_complete(g())

rawDescription: Fire and forget task in asyncio

description: Fire and forget task in asyncio


code:
import json

data_string = json.dumps(data) #data serialized
data_loaded = json.loads(data) #data loaded

rawDescription: Sending a Dictionary using Sockets in Python?


code:
#!/usr/bin/env python3
import sys
import time
from threading import Thread

def task(tid):
    print("P({}) sleeping".format(tid))
    time.sleep(5)
    print("P({}) entering CS".format(tid))
    # CS
    print("P({}) exiting CS".format(tid))

# Scan command line arguments
thread_count = int(sys.argv[1])

threads = [Thread(target=task, args=(tid,)) for tid in range(thread_count)]
for t in threads:
    t.daemon = True # die if the program exits
    t.start() # start the thread

# wait for completion
for t in threads: t.join()

rawDescription: Is run() method synchronous in Python 3.2?


code:
some_iterable = range(1000)
import timeit
timeit.timeit('f()', 'from __main__ import slower as f', number=10000)
timeit.timeit('f()', 'from __main__ import faster as f', number=10000)

rawDescription: What is the advantage of a list comprehension over a for loop?


code:
def foo(bar):
    return boz().addCallback(lambda result: qux(bar, result))

rawDescription: Twisted / Amp networking: Respond to all clients, not just one making a request


code:
n = type( "number", ( object, ), { "val" : 0, "__repr__" : lambda self: str(self.val) } )()
d = { 1 : n, 2 : n }
d
d[1].val = 9
d

rawDescription: How to make two directory-entries refer always to the same float-value

description: Make two directory-entries refer always to the same float-value


code:
max_columns()
import timeit
timeit.repeat(
    "max_columns()",
    setup="from __main__ import max_columns",
    number=50
)

rawDescription: Determine maximum number of columns from sqlite3


rawDescription: Credit card check exercise python

description: Credit card check exercise python


code:
import re

sen = r'this is \re\store and b\\fre'
sen1 = r'this i\s /re/store and b//fre/'
sen2 = r'this is \re\store, and b\\fre!'
sen3 = r'this i\s /re/store, and b//fre/!'

slash_back =  r'\s*(?:[\w_]*\\(?:[\w_]*\\)*[\w_]*)'
slash_fwd = r'\s*(?:[\w_]*/(?:[\w_]*/)*[\w_]*)'
slash_all = r'\s*(?:[\w_]*[/\\](?:[\w_]*[/\\])*[\w_]*)'

strt = re.sub(slash_back,"",sen)
strt1 = re.sub(slash_fwd,"",sen1)
strt2 = re.sub(slash_all,"",sen1)
strt3 = re.sub(slash_back,"",sen2)
strt4 = re.sub(slash_fwd,"",sen3)
strt5 = re.sub(slash_all,"",sen3)
print(strt)
print(strt1)
print(strt2)
print(strt3)
print(strt4)
print(strt5)

rawDescription: Removing words with special characters "\" and "/"


code:
text = '2014-04-09 16:43:15,136|PID: 1371|INFO|Test.Controller.Root|Finished processing request        in   0.003355s for https://website/heartbeat'
pattern = re.compile(r'(.*)\|(PID: .*)\|(.*)\|(.*)\|(.*)')
results = re.findall(pattern, text)
results

rawDescription: Python regex, how to capture multiple rules from 1 string


code:
from collections import Counter

def ModeList(lst):
    return Counter(lst).most_common(1)[0][0]

rawDescription: Mode of a List - Python

description: Mode of a List - Python


code:
import gzip
import ast
import json
import glob
import fileinput
from dateutil import parser
from multiprocessing import Pool

# Assuming you have a large dictionary across a multi-part gzip files.
def files_to_be_analyzed(files):
    lines = ast.literal_eval("".join([gzip.open(file).read() for file in files]))
    date = lines['created_at']
    date_converted = parser.parse(date).strftime('%Y%m%d')
    output_file = gzip.open(date_converted, "a")
    output_file.write(lines + "\n")
    output_file.close()

if __name__ == '__main__':
    pool = Pool(processes = 5) # Or what ever number of cores you have
    directories = ['/path/to/this/dire', '/path/to/another/dir']
    pool.map(files_to_be_analyzed, [glob.glob(path) for path in directories])
    pools.close()
    pools.join()

rawDescription: More Efficient Conversion of Archived Python Dict to JSON


code:
from datetime import datetime
from collections import OrderedDict
start = "09/12/2015"
end = "14/12/2015"

start = datetime.strptime(start, "%d/%m/%Y")
end = datetime.strptime(end, "%d/%m/%Y")

with open('file') as f:
    l = [i.split('|') for i in f.read().splitlines()]

d = OrderedDict()

for key, value in l:
    date = datetime.strptime(key, "%d/%m/%Y")
    if date >= start and date <= end:
        try:
            d[key] += float(value)
        except KeyError:
            d[key] = float(value)

for key, value in d.items():
    print('{} -> {}'.format(key, value))

rawDescription: Compare dates and print sum

description: Compare dates and print sum


code:
a = ['a', 'b', 'c']
e = 'd'
a.append(e)
a
flist=[]
flist.append(a)
flist
del a[-1]
a
flist

rawDescription: Python returning empty lists

description: Python returning empty lists


code:
def pick_Q(N, M, Q):
    """
    Given a deck of N cards, where M are marked,
    and Q cards are taken randomly without replacement,
    return the probability that at least one marked card is taken.
    """
    return sum(scipy.stats.hypergeom.pmf(k, N, M, Q) for k in xrange(1,Q+1))

rawDescription: Drawing cards from a deck in SciPy with scipy.stats.hypergeom


code:
b = {k:[] for k in xrange(1, 5)}
[id(x) for x in b.values()]

rawDescription: python: Why listA.append('a') affects listB?

description: Python: Why listA.append('a') affects listB


rawDescription: python split string every 3rd value but into a nested format

description: Python split string every 3rd value but into a nested format


code: from a._b import *

rawDescription: Masquerading real module of a class

description: Masquerading real module of a class


code:
a
b

rawDescription: running multiple bash commands with subprocess

description: Running multiple bash commands with subprocess


code:
st = "foobar bar"
"foo" in st
"foo" in st.split()

rawDescription: Search for few options in string (if .. in)


code:
import datetime
import calendar

today = datetime.date.today()
y = today.year
m = today.month
eom = datetime.date(y, m, calendar.monthrange(y, m)[1])

df["DATA_MM"] = eom

rawDescription: Python PANDAS: New Column, Apply Unique Value To All Rows


code: from PIL import Image, ImageTk

rawDescription: how to resize an image to fit the label size? (python)

description: Resize an image to fit the label size? (python)


code:
for i, value in enumerate(dynamic_values):
    setattr(i, 'attribute{}'.format(i), value)

rawDescription: Why use setattr() and getattr() built-ins?


code:
import os
import webkit
class FlaskAppView(webkit.WebView):
    """
    Loads pages for flask apps into a WebView.
    """
    def __init__(self, flask_app, *args, **kwargs):
        # Protocol for flask app, by default file:// is used
        # so a protocol is defined here to prevent that.
        self.PROTOCOL = 'flask://'

        super(webkit.WebView, self).__init__(*args, **kwargs)

        self._flask_app = flask_app

        # Register new navigation handler.
        self.connect(
            "navigation-policy-decision-requested",
            self._nav_request
        )

        # For navigation handler.
        self.prev_uri = None

        # Redefine open like this as when using super
        # an error like this occurs:
        #   AttributeError: 'super' object has no attribute 'open'
        self._open = self.open
        self.open = self.open_

    def _nav_request(self, view, frame, net_req, nav_act, pol_dec):
        """
        WebView navigation handler for Flask apps.
        """
        # Get the uri
        uri = net_req.get_uri()

        # In order for flask apps to use relative links
        # the protocol is removed and it is made into an absolute
        # path.
        if uri.startswith(self.PROTOCOL):
            # In this case it is not relative but
            # it needs to have it's protocol removed
            uri = uri[len(self.PROTOCOL):]

        elif not self.prev_uri.endswith(uri):
            # It is relative and self.prev_uri needs to
            # be appended.
            uri = os.path.normpath(os.path.join(self.prev_uri, uri))

        # This is used to prevent an infinite recursive loop due
        # to view.load_string running this function with the same
        # input.
        if uri == self.prev_uri:
            return False

        self.prev_uri = uri

        # Create response from Flask app.
        response = app.load_from_uri(uri) + ('utf-8', uri)

        # Load response.
        view.load_string(*response)

        # Return False to prevent additional
        # handlers from running.
        return False

    def open_(self, uri):
        """
        Prepends protocol to uri for webkit.WebView.open.
        """
        self._open(self.PROTOCOL + uri)

rawDescription: How can I load a Python flask app into a gtk webview (Webkit)

description: Load a Python flask app into a gtk webview (Webkit)


code:
class HdfWriter():
     def __init__(self,hdf_file):
         self.hdf_file=hdf_file

     def create_attrs(self,attributes):
         dset_name=attributes.keys()[0]
         attrs=attributes[dset_name]

         for key in attrs:
             self.hdf_file[dset_name].attrs[key]=attrs[key]

rawDescription: Test if some field has been initialized in python


code:
def chunk_iterator(iterable):
    chunk = []
    empty_lines = 0
    for line in iterable:
        chunk.append(line)
        if line == '\n':
            empty_lines += 1
            if empty_lines == 2:
                yield ''.join(chunk[:-2])
                empty_lines, chunk = 0, []
        else:
            empty_lines = 0

    yield ''.join(chunk)

rawDescription: file stream processing in python

description: File stream processing in python


rawDescription: How to normalize unicode encoding for iso-8859-15 conversion in python?

description: Normalize unicode encoding for iso-8859-15 conversion in python


code:
@register.filter
def get_by_index(lst, idx):
    return lst[idx]

rawDescription: Accessing list item in django template

description: Accessing list item in django template


code:
import functools
functools.partial(self.waitmuchmore, value)

rawDescription: self.after doesn't wait when passing value

description: Self.after doesn't wait when passing value


code:
bin_counts = [0 for bin in bins]
for data_point in data_points:
    bin_number = data_point // bin_width
    bin_counts[bin_number] += 1

rawDescription: How to count how many data points fall in a bin

description: Count how many data points fall in a bin


rawDescription: Making a menu in Python

description: Making a menu in Python


code:
keys = soup.findAll("h5", {"class" : "review-rating__title"})
values = soup.findAll("span", {"class" : "review-rating__score"})
for key, value in zip(keys, values):
    print(key.text + ": " + value.text)

rawDescription: Print all elements in <li> - BeautifulSoap


rawDescription: Python: Read line by line, performing an operation at each end line


code: np.random.choice(a, size=n, p=w)

rawDescription: Probabilistic selection from a numpy array


code:
def submit(self, fn, *args, **kwargs):
    with self._shutdown_lock:
        if self._shutdown:
            raise RuntimeError('cannot schedule new futures after shutdown')

        f = _base.Future()
        w = _WorkItem(f, fn, args, kwargs)

        self._work_queue.put(w)
        self._adjust_thread_count()
        return f

class _WorkItem(object):
    def __init__(self, future, fn, args, kwargs):
        self.future = future
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

    def run(self):
        if not self.future.set_running_or_notify_cancel():
            return

        try:
            result = self.fn(*self.args, **self.kwargs)  # sefl.fn is play_url in your case
        except BaseException as e:
            self.future.set_exception(e)
        else:
            self.future.set_result(result)  # The result is set on the Future

rawDescription: Python 3 concurrent.futures: How to add back failed futures to ThreadPoolExecutor?


code: df = df.unstack(['zlevel', 'lat', 'long'])

rawDescription: Python Pandas Panel4D resample

description: Python Pandas Panel4D resample


code:
def f(value):
    factors = []
    for i in range(1, int(value**0.5)+1):
        if value % i == 0:
            factors.append((i, value / i))
    return factors

rawDescription: What is the easiest way to get a list of whole factor pairs of a given integer?


code:
import pygame
import Tkinter as tk
from Tkinter import *
import os

root = tk.Tk()
embed = tk.Frame(root, width = 500, height = 500) #creates embed frame for pygame window
embed.grid(columnspan = (600), rowspan = 500) # Adds grid
embed.pack(side = LEFT) #packs window to the left
buttonwin = tk.Frame(root, width = 75, height = 500)
buttonwin.pack(side = LEFT)
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
os.environ['SDL_VIDEODRIVER'] = 'windib'
screen = pygame.display.set_mode((500,500))
screen.fill(pygame.Color(255,255,255))
pygame.display.init()
pygame.display.update()
def draw():
    pygame.draw.circle(screen, (0,0,0), (250,250), 125)
    pygame.display.update()
    button1 = Button(buttonwin,text = 'Draw',  command=draw)
    button1.pack(side=LEFT)
    root.update()

while True:
    pygame.display.update()
    root.update()

rawDescription: Embedding a Pygame window into a Tkinter or WxPython frame


rawDescription: How to check if array contains array in elegant way?

description: Check if array contains array in elegant way


rawDescription: scrapy item loader return list not single value

description: Scrapy item loader return list not single value


code:
class Item(Base):
    ...
    @property
    def total_price(self):
        return self.list_price

class KitItem(Item):
    ...
    @property
    def total_price(self):
        if self.calc_list:
            _price = 0.0
            for comp in self.components:
                _price += comp.component.list_price * comp.qty
            return _price
        else:
            # @note: again, you do not need to perform any query here at all, as *self* is that you need
            return self.list_price

rawDescription: sqlalchemy access parent class attribute

description: Sqlalchemy access parent class attribute


code:
def ensure_value(namespace, dest, default):
    stored = getattr(namespace, dest, None)
    if stored is None:
        return value
    return stored

class store_dict(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        vals = dict(ensure_value(namespace, self.dest, {}))
        k, _, v = values.partition('=')
        vals[k] = v
        setattr(namespace, self.dest, vals)

parser.add_argument('-D', default={}, action=store_dict)

rawDescription: python argparse extra args

description: Python argparse extra args


code:
from distutils.core import setup, Extension
module = Extension('_kurtosis', sources=['_kurtosismodule.c'])
setup(ext_modules=[module])

rawDescription: Implementing a "Kurtosis filter" using scipys generic_filter


code:
from django.contrib.messages import get_messages, constants as message_level

def last_message(messages, level = None):
    """Returns the last Message object in the messages with the
    specified level, or just the last message if no level is
    specified
    """

    if level is None:
        return None if not messages else messages[-1]

    level = int(level)    # Not strictly necessary, but Message object does this in its __init__()
    for message in reversed(messages):
        if message.level == level:
            return message
    return None

rawDescription: In Django, how do I display the message (using Message Framework) without looping through?


code:
import itertools
ll1i = zip(l1,itertools.repeat('l1'))
ll2i = zip(l2,itertools.repeat('l2'))

rawDescription: Merge two lists with labels

description: Merge two lists with labels


code:
class User(db.Model):

    __tablename__ = 'User'
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(80),unique=True)
    pwd_hash = db.Column(db.String(200))
    email = db.Column(db.String(256),unique=True)
    is_active = db.Column(db.Boolean,default=False)
    urole = db.Column(db.String(80))

    def __init__(self,username,pwd_hash,email,is_active,urole):
            self.username = username
            self.pwd_hash = pwd_hash
            self.email = email
            self.is_active = is_active
            self.urole = urole

    def get_id(self):
            return self.id
    def is_active(self):
            return self.is_active
    def activate_user(self):
            self.is_active = True
    def get_username(self):
            return self.username
    def get_urole(self):
            return self.urole

rawDescription: Implementing Flask-Login with multiple User Classes


code:
def decorate_all_functions(function_decorator):
    def decorator(cls):
        for name, obj in vars(cls).items():
            if callable(obj):
                try:
                    obj = obj.__func__  # unwrap Python 2 unbound method
                except AttributeError:
                    pass  # not needed in Python 3
                setattr(cls, name, function_decorator(obj))
        return cls
    return decorator

rawDescription: Catch "before/after function call" events for all functions in class


code:
class TeeFile(object):
    def __init__(self, *files):
        self.files = files
    def write(self, data):
        for f in self.files:
            f.write(data)
    def flush(self):
        for f in self.files:
            f.flush()

rawDescription: writing file & displaying result in idle

description: Writing file & displaying result in idle


rawDescription: Numpy matrix row stacking

description: Numpy matrix row stacking


code:
#!/usr/bin/env python
from optparse import OptionParser, Option, IndentedHelpFormatter

class PosOptionParser(OptionParser):
    def format_help(self, formatter=None):
        class Positional(object):
            def __init__(self, args):
                self.option_groups = []
                self.option_list = args

        positional = Positional(self.positional)
        formatter = IndentedHelpFormatter()
        formatter.store_option_strings(positional)
        output = ['\n', formatter.format_heading("Positional Arguments")]
        formatter.indent()
        pos_help = [formatter.format_option(opt) for opt in self.positional]
        pos_help = [line.replace('--','') for line in pos_help]
        output += pos_help
        return OptionParser.format_help(self, formatter) + ''.join(output)

    def add_positional_argument(self, option):
        try:
            args = self.positional
        except AttributeError:
            args = []
        args.append(option)
        self.positional = args

    def set_out(self, out):
        self.out = out
def main():
    usage = "usage: %prog [options] bar baz"
    parser = PosOptionParser(usage)
    parser.add_option('-f', '--foo', dest='foo',
                      help='Enable foo')
    parser.add_positional_argument(Option('--bar', action='store_true',
                                   help='The bar positional argument'))
    parser.add_positional_argument(Option('--baz', action='store_true',
                                   help='The baz positional argument'))
    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error("incorrect number of arguments")
    pass

if __name__ == '__main__':
    main()

rawDescription: How do I format positional argument help using Python's optparse?

description: Format positional argument help using Python's optparse


code:
def issubset(self, other):
    return self <= frozenset(other)

def issuperset(self, other):
    return self >= frozenset(other)

def union(self, *others):
    res = self
    for o in others:
        res |= frozenset(o)
    return res

def intersection(self, *others):
    res = self
    for o in others:
        res &= frozenset(o)
    return res

def difference(self, *others):
    res = self
    for o in others:
        res -= frozenset(o)
    return res

def symmetric_difference(self, other):
    return self ^ frozenset(other)

rawDescription: reload subclass of frozenset

description: Reload subclass of frozenset


code:
the_list = ['a', 'b', 'c']

with open('myFile.txt', 'w') as f:
    for num in range(4):
        for letter in the_list:
            f.write("%s%s\n" % (letter, num))

rawDescription: Pythonic way to modify all items in a list, and save list to .txt file


rawDescription: Using objectify to get items with a different namespace prefix


rawDescription: Pandas writing dataframe to other postgresql schema


rawDescription: Find shortest matches between two strings


rawDescription: selecting numpy array axis by int

description: Selecting numpy array axis by int


code:
class SurfaceCapsule (object):

    def __init__(self, resource_manager, key):
        self._res = resource_manager
        self._key = key

    def __call__(self):
        return self._res[self._key]

rawDescription: How should I serialize game objects containing pygame surfaces?


code:
for t in timeseq(start,stop,interval):
    table.objects.filter(t)

rawDescription: Get Intervals Between Two Times

description: Get Intervals Between Two Times


code:
{"username":username,
"password":password,
"next": '/users/',}

rawDescription: Redirecting Django built-in login View to a URL taking user's pk as argument


code:
import numpy as np; import matplotlib.pyplot as plt
y = np.arange(10) # points to plot
x=np.arange(10)
labels = np.arange(10) # labels of the points
fig, ax = plt.subplots(nrows=1, ncols=1)
for x_,y_,label in zip(x,y,labels):
    ax.scatter([x_], [y_], label=label, picker=3)

rawDescription: Matplotlib : how to label points individually?


code:
def got_a(*_):
    k = ndb.Key('AndGate', users.get_user().userid())
    ag = k.get()
    if ag is None:
        AndGate(a_received=True, b_received=False, key=k).put()
        return
    if ag.b_received:
        k.delete()
        signal('C').send('')
    else:
        ag.a_received = True
        ag.put()

rawDescription: Some events completed make another event in python


code:
local_namespace = locals()
name = "myVarName"
local_namespace[name] = 'VarData'
myVarName

rawDescription: Equivalent of "genvarname" in Python

description: Equivalent of "genvarname" in Python


code:
class ValidateProperty:

    def __init__(self, exception, arg_type):
        # called on the @ValidateProperty(...) line
        #
        # save the exception to raise and the expected argument type
        self.exception = exception
        self.arg_type = arg_type
        self.validator = None

    def __call__(self, func_or_value):
        # on the first call, func_or_value is the function to use
        # as the validator
        if self.validator is None:
            self.validator = func_or_value
            return self
        # every subsequent call will be to do the validation
        if (
                not isinstance(func_or_value, self.arg_type) or
                not self.validator(None, func_or_value)
                ):
            raise self.exception(
                '%r is either not a type of %r or is outside '
                'argument range' %
                (func_or_value, type(func_or_value))
                )

rawDescription: How to provide value validation at abstract class level?

description: Provide value validation at abstract class level


rawDescription: changing only numerical data in pandas DataFrame

description: Changing only numerical data in pandas DataFrame


code:
def custom_implimentation_a(**context_args):
    return render_template("template_a.jinja", **context_args)

def custom_implimentation_b(**context_args):
    return render_template("template_b.jinja", **context_args)

@app.route("/some-route")
def some_route():
    if condition:
        provider = custom_implimentation_a  # Note, no parenthesis
    else:
        provider = custom_implimentation_b

    return render_template("some_page.jinja", provider=provider)

rawDescription: Flask - SubViews

description: Flask - SubViews


code:
with io.open(filename, 'w', encoding=sys.getfilesystemencoding()) as f:
    f.write(contents.decode('utf-8'))

rawDescription: Python: Upload huge amount of files via FTP


code: df.loc[df.company_name.isin(all_companies), "instrumentclass"] = "Equity"

rawDescription: Python str.contains from two or more dictionaries


code:
# one time precalculation
cache_N = 16  # or much bigger?!
cache = {
   tuple(x): int("".join([digits[y] for y in x]),2)
   for x in itertools.product((0,1), repeat=cache_N)
}

rawDescription: Fastest way to convert a binary list(or array) into an integer in Python


code:
print('x\by')
print(r'x\by')

rawDescription: Python Regex Word Boundaries not working as expected


code:
ids = sorted(range(g.vcount()), key=igraph_eg.__getitem__, reverse=True)
names = g.vs[ids]["name"]

rawDescription: How to get name property out of the result of eigenvalue in igraph?

description: Get name property out of the result of eigenvalue in igraph


code:
labels = 'ABC' #each label corresponds to one array in x
x = [[1,3,2,8,9], [4,1,3,9,7], [2,1,3,10,8]]
y = np.array(x)
y.argmax(axis=0)
[labels[i] for i in y.argmax(axis=0)]

rawDescription: Cascading numpy logical_and leads to memory error


code:
#column names from 2 rows to 1
df.iloc[1, 3:11] = df.iloc[0, 3:11] + ' ' + df.iloc[1, 3:11]

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

#data are from 2 rows (1,2 rows is header)
df1 = df.iloc[2:,:].reset_index(drop=True)
df1.columns.name = None

df1.iloc[:, 3] = pd.to_numeric( df1.iloc[:, 3])
df1.iloc[:, 4] = pd.to_numeric( df1.iloc[:, 4])
df1.iloc[:, 9] = pd.to_numeric( df1.iloc[:, 9])
df1.iloc[:, 10] = pd.to_numeric( df1.iloc[:, 10])

rawDescription: reading text into a dataframe

description: Reading text into a dataframe


code: r'FIRMWARE_VERSION ="([\d.]+)"'

rawDescription: Find string in log files and return extra characters


code:
# some code
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "[project name].settings")
import startup
# the rest of the code

rawDescription: django + uwsgi, where to place my startup code?

description: Django + uwsgi, where to place my startup code


code:
from application.login import blueprint

application =- Flask(__name__)
application.register_blueprint(blueprint)

rawDescription: Can multiple webpages be implemented using a single Flask app?


code:
acceptableChars = ['a', 'b', 'c']
string1 = 'bacca'
string2 = 'barca'
set(string1)
set(string2)
set(string1).issubset(set(acceptableChars))
set(string2).issubset(set(acceptableChars))

rawDescription: String composed of only acceptable characters


rawDescription: Python: Unable to start file with os.startfile


code:
class AppCosts(models.Model):
    app = models.OneToOneField('AppDefs', primary_key=True, db_field='id')
    cost = models.DecimalField()

class AppDefs(models.Model):
    id = models.CharField(primary_key=True)
    data = models.TextField()

class JobHistory(models.Model):
    job_name = models.CharField(primary_key=True)
    app = models.ForeignKey(AppDefs, db_column='job_application')

rawDescription: Error saving django model with OneToOne field - Column specified twice


code: max(Image.open(f, 'r').size for f in filenames)

rawDescription: Find the largest image dimensions from list of images


code:
import re

x = raw_input("Enter word: ").strip()
with open('d.txt') as file:
    data = '\n\n' + file.read() + '\n\n'

pattern = r'\n\n(' + x + r' .*?)\n\n'
pattern_compiled = re.compile(pattern, re.DOTALL)

res = pattern_compiled.search(data)
if res:
    print(res.group(1))
else:
    print('Not found')

rawDescription: Reading a text file which contains an English dictionary to print the matching word meaning in python


code:
l = [['a','b','c'], ['d','e'], [], ['f','g','h','i']]
import itertools
list(itertools.izip_longest(*l, fillvalue=""))

rawDescription: Python: transposing uneven rows into columns


code:
{'childProj': [{'childProj': [{'childProj': [],
                               'description': u'desc 0 0',
                               'name': u'0 0',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5251250308251648)},
                              {'childProj': [],
                               'description': u'desc 0 1',
                               'name': u'0 1',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5245618633048064)},
                              {'childProj': [],
                               'description': u'desc 0 2',
                               'name': u'0 2',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5793979555643392)},
                              {'childProj': [],
                               'description': u'desc 0 3',
                               'name': u'0 3',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 6371518539890688)},
                              {'childProj': [],
                               'description': u'desc 0 4',
                               'name': u'0 4',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5208529711398912)}],
                'description': u'desc 0',
                'name': u'0',
                'parentProj': None,
                'urlSafe': Key('ndb_Project', 6460121467060224)},
               {'childProj': [{'childProj': [],
                               'description': u'desc 1 0',
                               'name': u'1 0',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 6334429618241536)},
                              {'childProj': [],
                               'description': u'desc 1 1',
                               'name': u'1 1',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 6344957925261312)},
                              {'childProj': [],
                               'description': u'desc 1 2',
                               'name': u'1 2',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 6448551898906624)},
                              {'childProj': [],
                               'description': u'desc 1 3',
                               'name': u'1 3',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5286432096649216)},
                              {'childProj': [],
                               'description': u'desc 1 4',
                               'name': u'1 4',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5808107145920512)}],
                'description': u'desc 1',
                'name': u'1',
                'parentProj': None,
                'urlSafe': Key('ndb_Project', 5282008817205248)},
               {'childProj': [{'childProj': [],
                               'description': u'desc 2 0',
                               'name': u'2 0',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5808889098403840)},
                              {'childProj': [],
                               'description': u'desc 2 1',
                               'name': u'2 1',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5035775120900096)},
                              {'childProj': [],
                               'description': u'desc 2 2',
                               'name': u'2 2',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5881052870475776)},
                              {'childProj': [],
                               'description': u'desc 2 3',
                               'name': u'2 3',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5850614068150272)},
                              {'childProj': [],
                               'description': u'desc 2 4',
                               'name': u'2 4',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5215350924771328)}],
                'description': u'desc 2',
                'name': u'2',
                'parentProj': None,
                'urlSafe': Key('ndb_Project', 5811114428334080)},
               {'childProj': [{'childProj': [],
                               'description': u'desc 3 0',
                               'name': u'3 0',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 6368218830602240)},
                              {'childProj': [],
                               'description': u'desc 3 1',
                               'name': u'3 1',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5287664114728960)},
                              {'childProj': [],
                               'description': u'desc 3 2',
                               'name': u'3 2',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5041177015353344)},
                              {'childProj': [],
                               'description': u'desc 3 3',
                               'name': u'3 3',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 6412332003491840)},
                              {'childProj': [],
                               'description': u'desc 3 4',
                               'name': u'3 4',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5231029602222080)}],
                'description': u'desc 3',
                'name': u'3',
                'parentProj': None,
                'urlSafe': Key('ndb_Project', 5245939144982528)},
               {'childProj': [{'childProj': [],
                               'description': u'desc 4 0',
                               'name': u'4 0',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 4964143656337408)},
                              {'childProj': [],
                               'description': u'desc 4 1',
                               'name': u'4 1',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 4927054734688256)},
                              {'childProj': [],
                               'description': u'desc 4 2',
                               'name': u'4 2',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 6348349238149120)},
                              {'childProj': [],
                               'description': u'desc 4 3',
                               'name': u'4 3',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 5004957119938560)},
                              {'childProj': [],
                               'description': u'desc 4 4',
                               'name': u'4 4',
                               'parentProj': None,
                               'urlSafe': Key('ndb_Project', 4960843947048960)}],
                'description': u'desc 4',
                'name': u'4',
                'parentProj': None,
                'urlSafe': Key('ndb_Project', 5250989925859328)}],
 'description': u'first entity',
 'name': u'first',
 'parentProj': None,
 'urlSafe': Key('ndb_Project', 5208229332123648)}

rawDescription: GAE Recursive Query

description: GAE Recursive Query


code:
import xlwt
import xlrd
import sys
#Create workbook and worksheet

wbk = xlwt.Workbook()
dest_sheet = wbk.add_sheet('Data_1')

for sheet_idx in range(1, 3):
  sheet = xlrd.open_workbook('Data_%d.xls' % sheet_idx).sheet_by_index(0)

  for i in range(5):
    values = sheet.row_values(i)
    for idx, element in enumerate(values):
      dest_sheet.write(i, sheet_idx+idx, element)

wbk.save('DATA.xls')

rawDescription: Merged xls output different

description: Merged xls output different


rawDescription: Difference between .score() and .predict in the sklearn library?


code:
sorted_B = [list(value) for key, value in
                groupby(sorted(B_dict.values()), key=itemgetter(2,3))]

rawDescription: Help with speeding up dictionary sort loop in Python?


code: b = np.lib.stride_tricks.as_strided(a, (1000, a.size), (0, a.itemsize))

rawDescription: Repeat NumPy array without replicating data?


rawDescription: Checking where 1 occurs in a Binary Number


code:
from collections import defaultdict
scores = defaultdict(list)

with open('ClassA.txt') as f:
    for score, name in zip(f, f):
        scores[name.strip()].append(int(score))

scores

rawDescription: Read two consecutive lines from a file into a dictionary as value, key pairs


rawDescription: adding columns to dataframe based on values (time stamps)

description: Adding columns to dataframe based on values (time stamps)


code:
import string

table = string.maketrans(string.ascii_letters, '^'*len(string.ascii_letters))

def blah(r):
    return r.translate(table)

rawDescription: Replacing only the alphabetical letters in a string


rawDescription: Apply same permutation for every row in a 2D numpy array


code: {x**2 for x in xrange(100)}

rawDescription: Is there a Python dict without values?

description: Is there a Python dict without values


rawDescription: How can I print the raw unicode in python?

description: Print the raw unicode in python


code:
def execute_some_query(query):
    code_here()
    some_code()

def close_database():
    proceed_to_close()
import atexit ; atexit.register(close_database)

rawDescription: Method that gets called on module deletion in Python


code:
M = ast.parse(''.join(open('test.py')))
ast.get_docstring(M)

rawDescription: Parsing Python Module Docstrings

description: Parsing Python Module Docstrings


code:
import itertools

with open('permutations.txt', 'wb') as f:
    f.writelines(''.join(xs) + '\n' for xs in itertools.permutations('abcdefghijkl'))

rawDescription: What hardware is required to run this program?


code: y[tuple(np.rollaxis(x, -1))]

rawDescription: Slice numpy array with other array

description: Slice numpy array with other array


code:
from io import StringIO

try:
    print('', end='', flush=False, file=StringIO())
    print_supports_flush = True
except TypeError:
    print_supports_flush = False

rawDescription: Getting parameter names for __future__ functions in python


code:
myurls = {}
for x in range(1, 15):
    for y in range(1, 87):

        strvar1 = "%s" % (x) # you can omit these.
        strvar2 = "%s" % (y)

        with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f: # This is NOT the right place to put an application-specific config file.
            myurls[x,y] = f.read().replace('\n', '')
            print("myurls[%d,%d] = %s" % (x, y, myurls[x,y]))

            def myglob(): # this function is completely pointless.
                global myurls

# Construct your urls list only after you have everything that belongs in it, i. e. on the correct indentation level:
urls = [myurls[1,1], myurls[1,2], myurls[1,3], myurls[1,4], ...]

rawDescription: How to globally declare this Python list

description: Globally declare this Python list


code: mask = (df1['ORDER_FAILED'] == True) and (df1['ORDER_FAILED'].shift(-1) == True) and ...

rawDescription: GroupBy - Datetime diff() combining additional criteria


rawDescription: begginer Python -Trouble with concatenating an array of 4 binary ints

description: Begginer Python -Trouble with concatenating an array of 4 binary ints


code:
import pandas as pd
from IPython import display
df = pd.DataFrame(...)
display.HTML(df.to_html())

rawDescription: IPython Notebook & Pandas: How does pandas produce html table?


rawDescription: Nested, infinite dictionary in python

description: Nested, infinite dictionary in python


code:
def notimplemented(*args, **kwargs):
    raise NotImplementedError
fn1 = fn2 = fn3 = notimplemented

rawDescription: Importing in functions instead of at the beginning or the script?


code:
class Foo(object):
    @staticmethod
    def cmp_absoluteOrder(self, other):
        return (self.c, self.a, self.b) < (other.c, other.a, other.b)

    @staticmethod
    def cmp_otherOrder(self, other):
        return ...

    @staticmethod
    def cmp_combinedSort(cmpA, cmpB, cmpC):
        return lambda self, other: (0, 0, 0) < (cmpA(self.c, other.c), cmpA(self.a, other.a), cmpA(self.b, other.b), )

    def __hash__(self):
        return hash(self.c) ^ hashA(self.a) ^ hash(self.b)

...
list.sort(cmp = Foo.cmp_absoluteSorting)
list.sort(cmp = Foo.cmp_combinedSort(cmp, (lambda a1, a2: ...), cmp))

hashA = hash # or replace it if important # but the same a will retunrn the same hash

rawDescription: In Python how would I compare with multiple values using custom keys?


code:
from wtforms.fields import StringField
from wtforms.widgets import TextInput

class ClassedWidgetMixin(object):
    """Adds the field's name as a class
    when subclassed with any WTForms Field type.

    Has not been tested - may not work."""
    def __init__(self, *args, **kwargs):
        super(ClassedWidgetMixin, self).__init__(*args, **kwargs)

    def __call__(self, field, **kwargs):
        c = kwargs.pop('class', '') or kwargs.pop('class_', '')
        kwargs['class'] = u'%s %s' % (field.short_name, c)
        return super(ClassedWidgetMixin, self).__call__(field, **kwargs)

# An example
class ClassedTextInput(ClassedWidgetMixin, TextInput):
    pass

class Company(Form):
    company_name = StringField('Company Name', widget=ClassedTextInput)

rawDescription: Wtforms, add a class to a form dynamically


code:
[id(x) for x in li]
[id(x) for x in li2]

rawDescription: Is a variable the name, the value, or the memory location?


code: cur.execute("SELECT name, highest FROM scores WHERE class="+str(whichclass)+" ORDER BY highest DESC")

rawDescription: SQlite3 fetching data in order with a paramter


code:
#!/usr/bin/python3

import socket
import sys
from builtins import input

def main():

    try:
        serverHostNumber = input("Please enter the ip address of the server: \n")
        serverPortNumber = input("Please enter the port of the server: \n")

        # create a socket object
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # connection to hostname on the port.
        sock.connect((serverHostNumber, int(serverPortNumber)))
        TcpSocket = socket.ssl(sock)

        while True:
            data = TcpSocket.recv(1024)
            print("Server : ", data)
            sendData = input("Client : ")

            if sendData == "exit":
                    TcpSocket.close()
                    sys.exit()

            TcpSocket.send(sendData.encode(encoding='ascii', errors='strict'))

    except Exception as e:
        print("The error: ", e)
        sys.exit()

if __name__ == "__main__" : main()

rawDescription: Encoded Communication

description: Encoded Communication


code: [[' '.join(p) for p in zip(d, c)] for d, c in zip(dates, comments)]

rawDescription: Combine two lists of lists - bitwise

description: Combine two lists of lists - bitwise


code:
from collections import Counter

d = Counter(i for nested in list_of_lists for i in nested)

rawDescription: Fast dictionary population with list of keys


code:
result = session.query(Table1.field1, Table1.field2, field1_count).filter(
    Table1.user_id == self.user_id).filter(Table1.timestamp > self.from_ts).group_by(
    Table1.field1, Travelog.field2).order_by(desc(field1_count.name)).first()

rawDescription: how use alias in sqlachemy

description: How use alias in sqlachemy


code: video_length = lambda video: re.compile(r'length_seconds=(.*?)\\', re.S).search(urllib2.urlopen(video).read()).group(1).strip()

rawDescription: Generating Links to Youtube Audio

description: Generating Links to Youtube Audio


code: x = lambda y=y: ...

rawDescription: How do you use the same function as the command for multiple buttons created in a loop?

description: Use the same function as the command for multiple buttons created in a loop


code:
from pprint import pprint
pprint(data)

rawDescription: Decoding JSON to give me a certain variable in Python?


code:
for key, entries in myDictionary.items():
    print("Details for:", key)
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

rawDescription: Python 3 - Print Specific List Item from Dictionary


code: 'INSERT INTO home_title VALUES ({})'.format(', '.join(['%s'] * 5))

rawDescription: Dynamic length of SQL args

description: Dynamic length of SQL args


rawDescription: Parse HTML style text annotations to a list of dictionaries


code:
with open("filename", "w") as f:
    for key in dict:
        print(key, file=f)

rawDescription: writing keys of a dictionary to a text file

description: Writing keys of a dictionary to a text file


code:
DATABASE = SqliteDatabase('mydb.db') # or PostgresqlDatabase or MySQLDatabase

class BaseModel(Model):
    class Meta:
        database = DATABASE

class User(BaseModel):
    email = CharField()
    # whatever other user fields

class Language(BaseModel):
    name = CharField()
    # other fields?

class Post(BaseModel):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(User, related_name='posts')
    language = TextField()
    content = ForeignKeyField(Language, related_name='posts')

rawDescription: Relational Mapping using Peewee

description: Relational Mapping using Peewee


code: merged.to_csv("{0} {1} MRG.csv".format(month, year), index=False, sep = ",")

rawDescription: Dynamically naming edited csv, to include part of the old csv name


rawDescription: How to access a remote datastore when running dev_appserver.py?

description: Access a remote datastore when running dev_appserver.py


code:
class Something(object):

    def __init__(self):
        self._thing_id
        self._cached_thing

    def __getstate__(self):
        return self._thing_id
    def __setstate__(self, thing_id):
        self._thing_id = thing_id

    # etc.

rawDescription: Preventing fields from being pickled

description: Preventing fields from being pickled


code: find_shortest_path(graph, 'A', 'D')

rawDescription: Connecting rows in a list if they exist?

description: Connecting rows in a list if they exist


code:
def filterwords(lst):
    for word in lst:
        if len(word)>=5 and sorted(word)==list(word):
            yield word

rawDescription: making a string into a list within a list comprehension

description: Making a string into a list within a list comprehension


code:
def factorial(x):
    if x == 0:
        return 1
    else:
        return x * factorial(x-1)

rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


code:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *

class Render(QWebPage):
  def __init__(self, url):
    self.app = QApplication(sys.argv)
    QWebPage.__init__(self)
    self.loadFinished.connect(self._loadFinished)
    self.mainFrame().load(QUrl(url))
    self.app.exec_()

  def _loadFinished(self, result):
    self.frame = self.mainFrame()
    self.app.quit()

url = 'http://webscraping.com'
r = Render(url)
html = r.frame.toHtml()

rawDescription: How to get real source code of html page?

description: Get real source code of html page


code:
def test_set(xs):
    seen = set()  # O(1) lookups
    for x in xs:
        if x not in seen:
            seen.add(x)
        else:
            return x

import collections

def test_counter(xs):
    freq = collections.Counter(xs)
    for k in freq:
        if freq[k] > 1:
            return k

def test_dict(xs):
    d = {}
    for x in xs:
        if x in d:
            return x
        d[x] = 1

def test_sort(xs):
    ys = sorted(xs)

    for n in range(1, len(xs)):
        if ys[n] == ys[n-1]:
            return ys[n]

##

import sys, timeit
print (sys.version + "\n")
xs = list(range(10000)) + [999]
fns = [p for name, p in globals().items() if name.startswith('test')]
for fn in fns:
    assert fn(xs) == 999
    print ('%50s %.5f' % (fn, timeit.timeit(lambda: fn(xs), number=100)))

rawDescription: Efficiently find repeated characters in a string


code:
U.match(b/(a+s))
m = U.match(b/(a+s))

rawDescription: SymPy: How to get values from expression


code:
@app.task
def set_race_as_inactive(race_object):
    """
    This celery task sets the 'is_active' flag of the race object
    to False in the database after the race end time has elapsed.
    """

    race_object.is_active = False # set the race as not active
    race_object.save() # save the race object

rawDescription: Django: How to automatically change a field's value at the time mentioned in the same object?


rawDescription: How to remove white spaces from a string in Python?

description: Remove white spaces from a string in Python


code:
class X(object):
  def __init__(self, x):
    pass

  def doit(self, bar):
    pass

class Y(X):
  def __init__(self):
    super(Y, self).__init__(123)

  def doit(self, foo):
    return super(Y, self).doit(foo)

rawDescription: How do I initialize the base (super) class in Python?

description: Initialize the base (super) class in Python


code: df.groupby('cokey')[['A','B']].filter(lambda x: x['A'].min() <= 0)

rawDescription: Discard group in pandas groupby operation


code:
linearValues = map(lambda x:x/90,range(90,-1,-1))
blueCurveValues = map(lambda x:math.sin(x*90*math.pi/180),linearValues)
yellowCurveValues = map(lambda x,y:x-(y-x),linearValues,blueCurveValues)

rawDescription: Manipulating curves with python

description: Manipulating curves with python


code:
print(list(set(legislators.values())))
['Democratic', 'Labour', 'Economic Synergy', 'DAB']

rawDescription: Creating a list from specific elements of a dictionary


code:
h = g.sortlevel('date').head()
h
h.sum()

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


code:
im = ax.pcolormesh(data, cmap=cm.gray, edgecolors='white', linewidths=1,
                   antialiased=True)

rawDescription: Matplotlib grayscale heatmap with visually distinct "NA" squares fields


code:
print(sd.unit_price)
sd.unit_price = 500
sd.save()

rawDescription: Django - Update model field based on another field


code: winners

rawDescription: Add a Year to each item in list or Dictionary


code:
description_soup = BeautifulSoup(soup.select('description:nth-of-type(2)')[0].text)
description_soup.img

rawDescription: Why Beautiful Soup Ignoring CDATA

description: Why Beautiful Soup Ignoring CDATA


code: a = Dimarray(values, ('lat', lat), ('lon', lon))

rawDescription: How to retrieve the original order of key-word arguments passed to a function call?

description: Retrieve the original order of key-word arguments passed to a function call


rawDescription: Pandas dataframe to list of tuples

description: Pandas dataframe to list of tuples


code:
def ternary (n):
    if n == 0:
        return '0'
    nums = []
    while n:
        n, r = divmod(n, 3)
        nums.append(str(r))
    return ''.join(reversed(nums))

rawDescription: Convert decimal to ternary(base3) in python


code:
import itertools as IT
def pigeonhole(n, m):
    """
    Generate the ways n balls can placed in m slots
    """
    for choice in IT.combinations(range(n+m-1), n):
        slot = [c-i for i,c in enumerate(choice)]
        result = [0]*m
        for i in slot:
            result[i] += 1
        yield result

print(list(pigeonhole(2,3)))

rawDescription: Every way to organize N objects in M list slots


code:
def light1ON():
   GPIO.output(18,HIGH)

rawDescription: Can GPIO.output be assigned to a variable? Raspberry PI


code:
value = None
for key in keySet:
    if key in myDict:
        value = myDict[key]
        break

rawDescription: Python: How to check if keys exists and retrieve value from Dictionary in descending priority


code:
# ROMANS = ...same as above
locals().update(ROMANS)
del(ROMANS)  # optional

rawDescription: Instantiate multiple objects of a class most efficiently


code:
onemin = datetime.timedelta(minutes=1)
fivemin = datetime.timedelta(minutes=5)

if onemin < parsedelta('00:02:00') < fivemin:
    print('yep')

rawDescription: Compare if datetime.timedelta is between two values


code:
import __builtin__
__builtin__.open

rawDescription: Is it possible to access original function which has been overwritten in python


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


code:
def mutate(s, num, target):
    change_locs = sample(range(len(s)), num)
    new_s = list(s)
    for change_loc in change_locs:
        new_s[change_loc] = target
    return ''.join(new_s)

rawDescription: Randomly replace items in a list

description: Randomly replace items in a list


code:
import audiere
ds = audiere.open_device()
os = ds.open_array(input, fs)
os.play()

rawDescription: How would I play audio in Python 2.6.6 while displaying text?


code:
if form.cleaned_data["action"] == "remember":
    pass  # your code for remember action
elif form.cleaned_data["action"] == "forget":
    pass  # your code for forget action

rawDescription: How to write a function in views.py that could handle more than two button?

description: Write a function in views.py that could handle more than two button


code:
def self_referencing(gen_func):
    @functools.wraps(gen_func)
    def wrapped(*args, **kwargs):
        g = gen_func(lambda: g, *args, **kwargs)
        return g
    return wrapped

class SampleCommand(sublime_plugin.TextCommand):
    @self_referencing
    def get_things(gen_self, self):
        sublime.active_window().show_input_panel(
            'First question', '',
            gen_self().send, None, None
        )
        result_a = yield
        sublime.active_window().show_input_panel(
            'Second question', '',
            gen_self().send, None, None
        )
        result_b = yield
        sublime.active_window().show_input_panel(
            'Third question', '',
            gen_self().send, None, None
        )
        result_c = yield

rawDescription: Pythonic way to manage multiple callbacks


code:
w = Warehouse(...)
i = Item(name="kindle", price=...)
iw = ItemWarehouse(quantity=50)
iw.item = i
w.items.append(i)

rawDescription: sqlalchemy / table setup

description: Sqlalchemy / table setup


code:
def clean(self):
    cleaned_data = self.cleaned_data
    npv = cleaned_data.get("npv")
    irr = cleaned_data.get("irr")
    if npv == irr:
        raise forms.ValidationError('Must have either an NPV or IRR entry.')
    if (npv != None) and (irr != None):
        raise forms.ValidationError('Must have only one entry, either NPV or IRR.')
    return cleaned_data

rawDescription: Django model forms - multiple models

description: Django model forms - multiple models


code: out = subprocess.check_output(["/usr/bin/find", ".", "-name",  "*.pdf"]).splitlines()

rawDescription: convert output of find command into array of strings in python

description: Convert output of find command into array of strings in python


code:
import win32com.client

#Create an instance of Word.Application
wordApp = win32com.client.Dispatch('Word.Application')

#Show the application
wordApp.Visible = True

#Create a new document in the application
wordDoc = wordApp.Documents.Add()

#Set the text of the first paragraph
wordDoc.Paragraphs(1).Range.Text = "Hello, World!"

rawDescription: MS Word r/w in python, Python-docx issue and win32com references?


code:
import numpy as np
from scipy import stats
from mayavi import mlab

mu, sigma = 0, 0.1
x = 10*np.random.normal(mu, sigma, 5000)
y = 10*np.random.normal(mu, sigma, 5000)
z = 10*np.random.normal(mu, sigma, 5000)

xyz = np.vstack([x,y,z])
kde = stats.gaussian_kde(xyz)

# Evaluate kde on a grid
xmin, ymin, zmin = x.min(), y.min(), z.min()
xmax, ymax, zmax = x.max(), y.max(), z.max()
xi, yi, zi = np.mgrid[xmin:xmax:30j, ymin:ymax:30j, zmin:zmax:30j]
coords = np.vstack([item.ravel() for item in [xi, yi, zi]])
density = kde(coords).reshape(xi.shape)

# Plot scatter with mayavi
figure = mlab.figure('DensityPlot')

grid = mlab.pipeline.scalar_field(xi, yi, zi, density)
min = density.min()
max=density.max()
mlab.pipeline.volume(grid, vmin=min, vmax=min + .5*(max-min))

mlab.axes()
mlab.show()

rawDescription: How to plot a 3D density map in python with matplotlib

description: Plot a 3D density map in python with matplotlib


rawDescription: All triplet combinations, 6 values at a time


code:
import agroom1
import agroom2

print("The start of the game")

while True:
    choice = input("next? > ")
    if choice == '1':
        agroom1.main()
    if choice == '2':
        agroom2.main()
    if choice == 'quit':
        break;

rawDescription: How to move to the next file in python

description: Move to the next file in python


code:
separators = [".", "!", "?", ","]
splitpattern = '|'.join(map(re.escape, separators))
# re.escape takes a string and escapes out any characters that regex considers
#   special, for instance that . would otherwise be "any character"!
split_s = re.split(splitpattern, s)
print(split_s)
# ['Hello', ' world', " It's great that you're talking to me", ' and everything', " but I'd really rather you just split me on punctuation marks", ' Okay', '']

rawDescription: What Regex to use in this example

description: What Regex to use in this example


code:
a = [[1, 2, "hello"],[3, 5, "hi There"],[5,7,"I don't know"]]

''.join(str(r) for v in a for r in v)

rawDescription: convert list of lists into a string

description: Convert list of lists into a string


rawDescription: Is python+pandas able to handle large amounts of data?


rawDescription: What is the most pythonic way to extend a list with the reversal of another?


code:
start = 10
width = 9
for i in range(1, width+1):
    for _ in range(i):
        print (start, end=" ")
        start += 1
    print('\n')

rawDescription: How to correctly print:

description: Correctly print:


rawDescription: How does a model relate to another model via Foreignkey?


code: from module import *

rawDescription: Clone a module and make changes to the copy


code:
teams = ["team1", "team2", "team3", "team4"]
list(fixtures(teams))
teams = ["team1", "team2", "team3", "team4","team5"]
list(fixtures(teams))

rawDescription: Grouping list combinations for round-robin tournament


code:
dt = datetime.datetime.now()
dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
dt

rawDescription: Truncate Python DateTime

description: Truncate Python DateTime


code:
import skimage.io._plugins.freeimage_plugin as fi
im = fi.read('tiger-rgb-strip-contig-16.tif')
fi.write(im, 'tiger-rgb-strip-contig-16-zip.tif',
         fi.IO_FLAGS.TIFF_ADOBE_DEFLATE)

rawDescription: How convert image into 16bit zip (deflate) compressed TIF in python?


code: dct = {'Daniel': ('2', 'daniel@outlook.com'), 'Jay': ('1212', 'jay@siber.com')}

rawDescription: How do I print the following objects of a list

description: Print the following objects of a list


code:
while consecutivecount < 6:
    solution = (0,0,0)
    # ** find a solution like above
    if solution == (0,0,0):
        consecutivecount = 0      #resets consecutivecount value to zero
        savedn += [n]             #adds current value of n to list
    else:
        consecutivecount += 1
    n += 1                        #increases value of n to continue test loop

rawDescription: MIT OCW 6.00's Chicken McNugget program... again


code: yourfile.tell() - data_read.count('\r') - data_read.count('\n')

rawDescription: How to exclude \n and \r from tell() count in Python 2.7

description: Exclude \n and \r from tell() count in Python 2.7


code:
klass = my_import('my_package.my_module.my_class')
some_object = klass()

rawDescription: How to dynamically load a Python class

description: Dynamically load a Python class


rawDescription: Combining Numpy Arrays in Blockwise Form


code:
s = """ this is a very
        long string if I had the
        energy to type more and more ..."""

rawDescription: Pythonic way to create a long multi-line string


code:
def interceptor(cityname, response, host='localhost', port=8000):
    def decorator(test):
        def runtest(self):
            requests_intercept.install()
            add_wsgi_intercept(
                host, port,
                lambda: create_webservice(cityname, response))
            test(self)
            requests_intercept.uninstall()
        return runtest
    return decorator

rawDescription: Test decorators with arguments are always executed


code: [x for x in A if set(x) not in [set(y) for y in B]]

rawDescription: Python - check for combination of items in list of tuples


rawDescription: Python - Extract and reformat field names from rows of data


code:
for c in word:
     print(c)

rawDescription: How to extract the characters of a string and compare them with another string in Python?

description: Extract the characters of a string and compare them with another string in Python


code:
def flatten(data, keys):
    out = []
    values = {}
    def visit(node, id):
        if id:
            id -= 1
            for key, child in node.items():
               values[keys[id]] = key
               visit(child, id)
        else:
            out.append(merge(node, values))  # use merge instead of update
    visit(data, len(keys))
    return out

rawDescription: Flatten a nested dict structure into a dataset in Python


code:
def is_number(ln):
    try:
        int(ln)
        return True
    except ValueError:
        return False

def main():
    with open('math.txt', 'r') as f:
        lines = (line.strip() for line in f)
        lines = [line for line in lines if line]

    stack = []
    for line in lines:
        if is_number(line):
            stack.append(int(line))
        elif line in ['ADD', 'SUB', 'MUL', 'DIV']:
            if line=='ADD': result = stack.pop() + stack.pop()
            if line=='SUB': result = stack.pop() - stack.pop()
            if line=='MUL': result = stack.pop() * stack.pop()
            if line=='DIV': result = stack.pop() / stack.pop()
            print(result)
            stack.append(result)
        elif line=='PRT':
            print(stack.pop())
        elif line=='STOP':
            exit()
        else:
            raise ValueError("Unknown line: %s" % line)

# Call main function

main()

rawDescription: Reverse Polish Calculator in Python

description: Reverse Polish Calculator in Python


rawDescription: How to "extract" certain values out of an array?


code:
class CallableList(list):
    def __call__(self, item):
        return self[item]

rawDescription: How might one change the syntax of python list indexing?


code:
count = 0
for checkbox in groupbox.findChildren(QtGui.QCheckBox):
    if checkbox.isChecked():
        count += 1
print('there are %s checked' % count)

rawDescription: How to search for a specific kind of qt gui control

description: Search for a specific kind of qt gui control


rawDescription: Share class attributes among several classes in Python


code:
vect = TfidfVectorizer(min_df=1)
tfidf = vect.fit_transform(["I'd like an apple",
                            "An apple a day keeps the doctor away",
                            "Never compare an apple to an orange",
                            "I prefer scikit-learn to Orange"])
(tfidf * tfidf.T).A

rawDescription: How can I detect that these two URLs drive to the same site?

description: Detect that these two URLs drive to the same site


rawDescription: get the index of the last negative value in a 2d array per column

description: Get the index of the last negative value in a 2d array per column


code: argv = shlex.split("bash -x -c 'TRAPTOOL -a STRING \"ABC\" -o STRING \'XYZ\''")

rawDescription: python subprocess sends backslash before a quote

description: Python subprocess sends backslash before a quote


code:
j2 = [i for i in j if i >= 5]
j2.sort()

rawDescription: Return list of items in list greater than some value


code:
db.test.update(
    {'files.IyzkmGh4YGD61Tc3TJjaEY17hDldH': {'$exists': 1}},
    {'$pull': {'files': {'IyzkmGh4YGD61Tc3TJjaEY17hDldH': {'$exists': 1}}}},
    multi=True)

rawDescription: how to search through a mongodb collection for dictionary keys nested in array

description: Search through a mongodb collection for dictionary keys nested in array


code:
# lines = lines parsed out of file
line_store = {}
for line in lines:
    tokens = line.split('\t')
    if len(tokens) in line_store:
        line_store[len(tokens)].append(line)
    else:
        line_store[len(tokens)] = [line]
most = []
for line_group in line_store.values():
    if len(line_group) > len(most):
        most = line_group

rawDescription: How to remove header of unknown length using Python

description: Remove header of unknown length using Python


code:
def f(): a += x

def g(): a = a + x

import dis
dis.dis(f)
dis.dis(g)

rawDescription: Why is a += x slower than a = a+x?

description: Why is a += x slower than a = a+x


code:
class SomeClass(object):

    class_var_1 = "some value"
    class_var_2 = "some other value"

    def some_method(self):
        print("Could use all class members, but need to use special syntax:", SomeClass.class_var_1)

print("Outside class method, no instance created, still can use class member:",  SomeClass.class_var_1)
obj = SomeClass()
obj.some_method()

rawDescription: Global variables, member variables and instance variables in Python


rawDescription: trying to figure out a weird math formula

description: Trying to figure out a weird math formula


code: __all__ = ['myfunc1', 'myfunc2', ..., 'myfuncN']

rawDescription: Using pydoc on modules with imported functions


code:
new_list = []
for x, y in input_list:
    result = func(x)
    if result:
        new_list.append((result, y))

rawDescription: Python: [(x, y) for (x, y) in list_of_tuples if f(x) is not empty]


code:
tidypos
tidysd

rawDescription: Pandas Create Columns From Rows in Other Data Frame with Criteria


code:
import re

with open('data_files/states/major_cities.csv') as f_in:
    with open('output_file.csv', 'w') as f_out:
        for line in f_in:
            city = line.rstrip('\n')
            f_out.write('{}'.format(
                re.sub(r'\W+', '-', city.lower()),
                city
            ))

rawDescription: Python readlines() and append data to each line output to one line


code:
def quote_url(url, safe):
    """URL-encodes a string (either str (i.e. ASCII) or unicode);
    uses de-facto UTF-8 encoding to handle Unicode codepoints in given string.
    """
    return urllib.quote(unicode(url).encode('utf-8'), safe)

rawDescription: Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()


code:
style = ttk.Style()
style.configure("Red.TCheckbutton", foreground="red")

rawDescription: Changing ttk widget text color

description: Changing ttk widget text color


code:
ins_a()
ins_b()

rawDescription: What is difference between A.fun and A().fun?


code:
import itertools

new_lst = []
for _, g in itertools.groupby(lst, key=lambda x: x['id']):
    new_lst.extend(sorted(g, key=lambda x: x['score'], reverse=True)[:4])

rawDescription: Python Select best 4 from a JSON list

description: Python Select best 4 from a JSON list


code:
list(combinations_with_guaranteed(4, 3, 1))
list(combinations_with_guaranteed(4, 3, 1, 2))

rawDescription: Combinations Including Select Elements (Python)


code:
class Settings(object):
    def __init__(self, init_dict):
        self.__dict__.update(init_dict)

class Foobar(object):
    def __init__(self, init_dict):
        self.settings = Settings(init_dict)

rawDescription: Should I extract values from Python dictionaries into object attributes?


code:
def input_swallowing_interrupt(_input):
    def _input_swallowing_interrupt(*args):
        try:
            return _input(*args)
        except KeyboardInterrupt:
            print('^C')
            return '\n'
    return _input_swallowing_interrupt

class TestShell(cmd.Cmd):

    def cmdloop(self, *args, **kwargs):
        old_input_fn = cmd.__builtins__['input']
        cmd.__builtins__['input'] = input_swallowing_interrupt(old_input_fn)
        try:
            super().cmdloop(*args, **kwargs)
        finally:
            cmd.__builtins__['input'] = old_input_fn

    # ...

rawDescription: Handle CTRL-C in Python cmd module

description: Handle CTRL-C in Python cmd module


rawDescription: How to get turtle graphics to not show turtle while its being drawn?

description: Get turtle graphics to not show turtle while its being drawn


code:
data = {"A": 10, "B": 3, "C": 8, "D": 3, "E": 2}
s_data = sorted(data.items(), key=lambda item: item[1])
s_data

rawDescription: Ranking values in a Dictionary (and taking care of ex-aequos correctly)


code:
from operator import itemgetter as it
from itertools import repeat
n = 3

new_d = [list(zip(repeat(row["index"]), map(it(0),(row[1:].sort_values(ascending=0)[:n].iteritems()))))
                 for _, row in df.iterrows()]

rawDescription: Selecting top N columns for each row in data frame


code:
s1 = "so much depends upon {}".format("a red wheel barrow")
s2 = "glazed with {} water beside the {} chickens".format("rain", "white")

rawDescription: Are there other ways to format strings other then comma, percent, plus sign?


code:
America,Dollar,1
Argentina,Peso,8.257
Australia,Dollar,1.432
Austria,Euro,0.82

rawDescription: Begineer's sorting with tuples

description: Begineer's sorting with tuples


code:
from Tkinter import *
from urllib2 import *
import csv

root = Tk()

class Fram(Frame):

    def __init__(self,tk,width,height):
        Frame.__init__(self,tk)
        self.config(width=width)
        self.config(height=height)
        self.config(bd=1)
        self.config(relief="solid")
        self.url = "http://data.nottinghamtravelwise.org.uk/parking.csv?noLocation=true?t=635509084580321642"
        self.webpage = urlopen(self.url)
        self.datareader = csv.reader(self.webpage.read().decode('utf-8').splitlines())
        self.data = list(self.datareader)
        self.a = 1
        self.b = -6
        self.c = -5
        self.value = self.calc_x(self.a, self.data)
        self.label = Label(self, text=self.value)
        self.label.pack()

    def calc_x(self, y, data):
        x = 0
        if y == self.c:
            for i in range(1,len(data)):
                x = x + int(data[i][y])
                t = x/(len(data)-1)
            return str(t)+'%'
        else:
            for i in range(1,len(data)):
                x = x + int(data[i][y])
            return str(x)

square_frame = Fram(root,500,40).grid(row=0,column=0,padx=3,pady=3)

mainloop()

rawDescription: Run a function inside a tkinter

description: Run a function inside a tkinter


code:
if not len(logger.handlers):
    logger.addHandler(fileHandler)
    logger.addHandler(consoleHandler)

rawDescription: python logging ensure a handler is added only once

description: Python logging ensure a handler is added only once


code:
def FindOccurences(data, condition, left, right):
    func = eval( u"lambda data, i : " + condition)
    return (i for i in range(left, right) if func(data, i))

rawDescription: Get fast functor from text of expression in Python (faster than eval)


code:
def update(self,newdata):
    for key,value in newdata:
        setattr(self,key,value)

rawDescription: Python update object from dictionary

description: Python update object from dictionary


code: save('path/to/file/myfile')

rawDescription: How to change the default folder for python?

description: Change the default folder for python


code:
from six.moves.html_parser import HTMLParser
h = HTMLParser()
print(h.unescape('£682m'))

rawDescription: Decode HTML entities in Python string?

description: Decode HTML entities in Python string


rawDescription: python collecting data from dataframe at specific row location

description: Python collecting data from dataframe at specific row location


code: score += SCRABBLE_LETTER_VALUES[letter]

rawDescription: dictionaries in python: summing the values returned from searching the keys

description: Dictionaries in python: summing the values returned from searching the keys


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

fig, ax = plt.subplots()
ax2 = ax.twinx()

x = np.linspace(0, 10, 100)

ax.plot(x, np.sin(x), color='blue')
ax.set_ylabel(ylabel='Y-Value 1', color='blue')
ax.set_xlabel('Same X-values')

ax2.plot(x, x**3, color='green')
ax2.set_ylabel('Y-Value 2', color='green')

plt.show()

rawDescription: pyplot twinx() tickmark overlap

description: Pyplot twinx() tickmark overlap


code:
x = 3

data = ['Column A', 'Column B', 'Column C', 'Item A1', ... , 'Item C4']
newList = []

for i in range (x):
    newList.append(data[i::x])

print (newList)

rawDescription: How can I create a nested list from an existing one where the first x items are the outer items?

description: Create a nested list from an existing one where the first x items are the outer items


code:
import lxml.etree as et
from PyQt4.QtGui import QTreeWidgetItem

# ...

class XmlTreeWidgetItem(QTreeWidgetItem):
    def __init__( self, parent, xmlitem ):
        super(MyTreeWidgetItem, self).__init__(parent)
        self.setText(0, xmlitem.get('name'))
        self.setChildIndicatorPolicy(self.ShowIndicator)

        self._xmlitem = xmlitem
        self._loaded = False

    def loadChildren( self ):
        if ( self._loaded ):
            return

        self._loaded = True
        self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless)
        for xmlchild in self._xmlitem.getchildren():
            XmlTreeWidgetItem(self, xmlchild)

# ...

class SomeClass(QWidget):
    def __init__( self, parent = None ):
        super(SomeClass, self).__init__(parent)

        self.tree_widget = QTreeWidget(parent)

        xml = et.XML(filters.filtersxml)
        items = [XmlTreeWidgetItem(None, xchild) for xchild in xml.getchildren()]
        self.tree_widget.addTopLevelItems(items)
        if ( items ):
            self.tree_widget.setCurrentItem(items[0])

        # create connections
        self.tree_widget.itemExpanded.connect(self.loadItem)

    def loadItem( self, item ):
        item.loadChildren()

rawDescription: QTreeWidget select first item

description: QTreeWidget select first item


code:
start = datetime.time(8, 5)
stop = datetime.time(9, 12)
step = datetime.timedelta(minutes = 3, seconds = 22)
for s in ftimerange(start, stop, step): print(s)

rawDescription: Adjust start and end range for time list in Python


code:
def __setattr__(self,name,value):
    self.__dict__[name] = value
    self.__dict__['_MyType__d']['Options'][name] = value

rawDescription: Change values of internal dictionary via attributes


code:
f = input("Please enter a number: ")
if f.isdigit():
    print("That's good")
else:
    print("That isn't a number.")

rawDescription: How to print something on the basis of data (input) type?

description: Print something on the basis of data (input) type


code:
class MyList(list):
    def even(self):
        return [x for x in self if x % 2 == 0]

MyList([1,2,3,4,5]).even()

rawDescription: Creating custom "list" attributes

description: Creating custom "list" attributes


rawDescription: numpy count elements across axis 0 matching values from another array

description: Numpy count elements across axis 0 matching values from another array


code:
session.query(User, func.count(Entry.id))\
    .outerjoin((Entry, (Entry.author_id==User.id) & (Entry.date>start_date)))\
    .group_by(User.id)

rawDescription: Dynamic column_property with SQLAlchemy

description: Dynamic column_property with SQLAlchemy


code:
class DecoratedListModelMixin(object):
    """
    Apply a decorator to the list view before serializing
    """
    def list(self, request, *args, **kwargs):
        has_decorator = (hasattr(self, 'decorator') and self.decorator is not None)

        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)

        if page is not None:

            if has_decorator:
                serializer = self.get_serializer(self.decorator(page, request), many=True)
            else:
                serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        if has_decorator:
            serializer = self.get_serializer(self.decorator(queryset, request), many=True)
        else:
            serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

class DecoratedListAPIView(DecoratedListModelMixin, generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

rawDescription: How to process current page of records in Django REST?

description: Process current page of records in Django REST


code:
import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]

rawDescription: How to store the result of an executed shell command in a variable in python?

description: Store the result of an executed shell command in a variable in python


rawDescription: Python cut a string after Xth sentence

description: Python cut a string after Xth sentence


code:
import pathlib
p = pathlib.Path('/path/to/my/file')

rawDescription: How to get folder name, in which given file resides, from pathlib.path?

description: Get folder name, in which given file resides, from pathlib.path


code:
import re
from pprint import pprint

def gen():
    with open('Packages') as fp:
        for line in fp:
            if line.startswith('Package:'):
                package = line.split(':')[1].strip()
            elif line.startswith('Provides:'):
                yield package, line.split(':')[1].strip().split(',')
                package = None
            elif package and line == '\n':
                yield package, []
                package = None
        if package:
            yield package, []

data = dict(gen())

pprint(data)

rawDescription: Extracting what each package provides from a text file using regex in python


code:
OrderedDict([
('company 1', tup(price=246, year='1991', month='march')),
('company 2', tup(price=245, year='1990', month='jan')),
('company 3', tup(price=243, year='1990', month='jan')),
('company 4', tup(price=247, year='1991', month='december')),
('company 5', tup(price=245, year='1991', month='june'))])

rawDescription: getting max value from each column of the csv file

description: Getting max value from each column of the csv file


rawDescription: Python - list of dicts into function that only accepts *dicts


code: {k:v if isinstance(v, (str, int)) else str(v) for k,v in dct.items() if k != ''}

rawDescription: In Python, loop through a dict and set all values of list or dict to string


code:
import scipy as sp
import scipy.interpolate

def log_interp1d(xx, yy, kind='linear'):
    logx = np.log10(xx)
    logy = np.log10(yy)
    lin_interp = sp.interpolate.interp1d(logx, logy, kind=kind)
    log_interp = lambda zz: np.power(10.0, lin_interp(np.log10(zz)))
    return log_interp

rawDescription: Logarithmic interpolation in python

description: Logarithmic interpolation in python


rawDescription: Count the occurence of specific number from column // convert column data to list


code:
_dbh = None
def get_db():
    global _dbh
    if _dbh is None:
        _dbh = pyodbc.connect(db_credentials)
    return _dbh

rawDescription: Mocking pyodbc module calls for django unit tests


code:
class B(object):
    _a = None

    @property
    def a(self):
        if self._a is None:
            self._a = A()
        return self._a

rawDescription: Dynamically adding class instance to Python instance à la __setattr__


code: ref + alt

rawDescription: How to merge cells in python3

description: Merge cells in python3


rawDescription: Python/Numpy subarray selection

description: Python/Numpy subarray selection


code:
import sys
from pyspark.sql.window import Window
from pyspark.sql.functions import exp, log, sum, first, col, coalesce

# Base window
w = Window.partitionBy("city").orderBy("year")

# ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
wr = w.rowsBetween(-sys.maxsize, -1)

rawDescription: How to calculate a column in a Row using two columns of the previous Row in Spark Data Frame?

description: Calculate a column in a Row using two columns of the previous Row in Spark Data Frame


rawDescription: filter text file based on multiple columns

description: Filter text file based on multiple columns


rawDescription: Intersection of 2d and 1d Numpy array

description: Intersection of 2d and 1d Numpy array