code:
class Camera(Node):
    def __init__(self, enabled=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # On Py2, super isn't magic, so you need to be explicit unlike Py3:
        # super(Camera, self).__init__(*args, **kwargs)
        self.enabled = enabled

rawDescription: python parent child relationship class

description: Python parent child relationship class


rawDescription: 2D Python list will have random results

description: 2D Python list will have random results


code:
children_of_name = dict([('', list())]) # Access root with empty string

def insert(name):
    parent_name = '::'.join(name.split('::')[:-1])
    dic = dict([('name', name), ('children', list())])
    children_of_name[parent_name].append(dic)
    children_of_name[name] = dic['children']

for group in ["foo", "bar", "foo::fone", "foo::ftwo", "foo::ftwo::ffone"]:
    insert(group)

rawDescription: Recursive sorting function for list in Python


code:
def naturalNumbers(n):
    return range(1, n + 1)

rawDescription: Python - Building/creating a list using for loop


code:
infile = open('hey.txt','r+')
content = infile.read()
table = str.maketrans('foo','bar')
content = content.translate(table)  #replaces 'foo' with 'bar'
infile.write(content)
infile.close()

rawDescription: I need to open and rewrite a line in a file in Python


code:
...
self.mytabs_widget = QtGui.QTabWidget(self)
...

rawDescription: PySide: How to change the status bar text from another class?


code:
coord = np.random.randint(0, 3, (10, 2))
coord
weights = np.ones(10)
uniq_coord, sums = sum_unique(coord, weights)
uniq_coord
sums
a = np.zeros((3,3))
x, y = uniq_coord.T
a[x, y] = sums
a

rawDescription: Map arrays with duplicate indexes?

description: Map arrays with duplicate indexes


rawDescription: How can I mimic a space efficient version of dict in Python?

description: Mimic a space efficient version of dict in Python


code:
import array
dat = bytearray(b'\x01\x00\x02\x00\x03\x00\x04\x00')
data = array.array('H')
data.fromstring(buffer(dat))

rawDescription: Reading binary data (image data type) from SQL database and inflate it, Matlab vs. Python


code:
list(islice(multiletters('ABC'), 20))
list(islice(multiletters(ascii_uppercase), 30))

rawDescription: Python: Pair alphabets after loop is completed


code: totalsum = np.sum(i * matrix for i in arr)

rawDescription: Make numpy.sum() return a sum of matrices instead of a single number


code:
action = run_once(my_function)
action() # run once the first time

action.has_run = False
action() # run once the second time

rawDescription: Efficient way of having a function only execute once in a loop


rawDescription: Eliminate numbers in string in Python

description: Eliminate numbers in string in Python


code:
num_lines = sum(1 for line in open('2grams.txt'))  ## in order not to print junk

count = 0
intersect = open('2grams.txt', 'r')
out_file = open("output.txt", 'w')
scores = open("2gram_glues.txt", 'r')

with open('2mwus.txt', 'r') as base:
    for line in base:

        line = line.rstrip()
        number = line[-2:]
        number = int(number.lstrip())

        line = line[:-2]
        line = line.rstrip()

        intersect.seek(0, 0)
        scores_lines=scores.readlines()
        scores.seek(0, 0)

        for i, line_intersect in enumerate(intersect):
            line_intersect= line_intersect.rstrip()
            if line == line_intersect:
                print("**The 2 Gram is: " + line.strip() + "\t The score is: " + scores_lines[i] +
                      'The number is ' + str(number))
                count += 1
                if count >= num_lines:
                    break

intersect.close()
out_file.close()
scores.close()

rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


rawDescription: NumPy: counting sizes of row-wise intersections between two arrays


code:
def noauth(username, password, pkey, key_filenames, allow_agent,
       look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host): pass
...
sshobj._auth = noauth
sshobj.connect("192.168.0.1", port=22, look_for_keys=False, timeout=None, banner_timeout=5)
...

rawDescription: Paramiko check login timeout of SSH Server


code: import matplotlib.pyplot as plt

rawDescription: How can I get pyplot images to show on a console app?

description: Get pyplot images to show on a console app


code:
import tkinter as TK
import evilOverlappingModule as evil

rawDescription: Tkinter importing without *?

description: Tkinter importing without *


rawDescription: Repeating large elements in a regular expression


code:
s = """
login url=http://demo.url.net username=test@url.net password=mytester

create-folder foldername=demo

select-folder foldername=test123

logout
"""

from collections import defaultdict
from itertools import count

result_dict = defaultdict(dict)
item = count()

# pretend you opened the file and are reading it line by line
for line in s.splitlines():
    if not line:
        continue # skip empty lines
    parts = line.split()
    result_dict[next(item)][parts[0]] = dict(p.split('=') for p in parts[1:])

rawDescription: Split dictionary key and list of values from dict


code: Counter({'baby': 4, 'hello': 3, 'this': 2})

rawDescription: Counting the Repeating of words in a list PYTHON


code:
import logging
import copy

logger=logging.getLogger(__name__)

class ColoredFormatter(logging.Formatter):
    # A variant of code found at http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored
    LEVELCOLOR = {
        'DEBUG': 'BLUE',
        'INFO': 'BLACK',
        'WARNING': 'PURPLE',
        'ERROR': 'RED',
        'CRITICAL': 'RED_BG',
        }

    def __init__(self, msg):
        logging.Formatter.__init__(self, msg)

    def format(self, record):
        record = copy.copy(record)
        levelname = record.levelname
        if levelname in self.LEVELCOLOR:
            record.levelname = colorstr(levelname,self.LEVELCOLOR[levelname])
            record.name = colorstr(record.name,'BOLD')
            record.msg = colorstr(record.msg,self.LEVELCOLOR[levelname])
        return logging.Formatter.format(self, record)

if __name__=='__main__':
    logger.setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setFormatter(
        ColoredFormatter('%(name)s: %(message)s (%(filename)s:%(lineno)d)'))
    logger.addHandler(console)
    fh = logging.FileHandler('/tmp/test.log','w')
    fh.setFormatter(logging.Formatter('%(name)s: %(message)s'))
    logger.addHandler(fh)

    logger.debug('debug')
    logger.info('info')
    logger.warning('Warning')
    logger.error('ERROR')
    logger.critical('CRITICAL!!!')

rawDescription: print colorful string out to console with python

description: Print colorful string out to console with python


rawDescription: Finding a string in a string in a list python


code: bc/ac/ab/abc

rawDescription: Combining words in Python (permutations?)


code: all(entry is None for entry in my_hash.values())

rawDescription: Find if a hash in Python has only values of None


code: block = (first_element[0], output[1:])

rawDescription: Create a Tuple from text file

description: Create a Tuple from text file


code: direction = "left"

rawDescription: How can I get my animation loop working?

description: Get my animation loop working


rawDescription: How to implement a rolling_pct_change(period) in pandas?

description: Implement a rolling_pct_change(period) in pandas


code: x = numpy.random.uniform(1.5)

rawDescription: Make a number more probable to result from random


code:
def display_path(path):
    return path.replace("\\", "/")

rawDescription: Why not os.path.join use os.path.sep or os.sep?


code:
zips = itertools.izip_longest(s1,s2, fillvalue='')
''.join(itertools.chain.from_iterable(zips))

rawDescription: recursively mix strings

description: Recursively mix strings


rawDescription: Annotate a column field from relation on django


code:
subList = []
for i, header in enumerate(colHeaders):
    text = Text(root,width=20, height=1, bg='white')
    text.grid(row=len(myTextWidgets),column=i)
    text.insert('0.0', header)
    subList.append(text)
myTextWidgets.append(subList)

rawDescription: edit entry on special position in a grid

description: Edit entry on special position in a grid


code:
class RequestHandler(SocketServer.BaseRequestHandler):
    def setup(self):
         # the socket is called request in the request handler
         self.request.settimeout(1.0)

    def handle(self):
         while True:
             try:
                 data = self.request.recv(1024)
                 if not data:
                      break # connection is closed
                 else:
                      pass  # do your thing
             except socket.timeout:
                 pass # handle timeout

rawDescription: SocketServer ThreadingTCPServer & Asyncore Dispatcher


code:
import atexit
atexit._exithandlers = []

rawDescription: Is registered atexit handler inherited by spawned child processes?


code: from __future__ import absolute_import

rawDescription: Import with files names conflict

description: Import with files names conflict


code:
from collections import defaultdict, Counter
import csv

with open('myfile.csv', 'rb') as inf:
    incsv = csv.reader(inf)
    col1, col2 = defaultdict(Counter), defaultdict(Counter)
    for c1,c2,label in incsv:
        col1[label][c1] += 1
        col2[label][c2] += 1

labels = sorted(col1)
for lbl in labels:
    print('{}:'.format(lbl))
    print('Column1:')
    for entry in ['0', '1']:
        print("No. of {}'s = {}".format(entry, col1[lbl][entry]))
    print('Column2:')
    for entry in ['0', '1']:
        print("No. of {}'s = {}".format(entry, col2[lbl][entry]))

rawDescription: Python -- Read and compare rows and columns


code:
set()
set([])

rawDescription: confused by Python set initialization

description: Confused by Python set initialization


code: [dict(t) for t in set([tuple(d.items()) for d in l])]

rawDescription: Remove duplicate dict in list in Python

description: Remove duplicate dict in list in Python


code:
def sim_time(record, datefmt=None):
    return datetime.datetime(2000,1,2,3,4,5,678).strftime('%Y-%m-%d %H:%M:%S,%f')[:-3]

formatter.formatTime = sim_time

rawDescription: Python logging: override log time

description: Python logging: override log time


code:
a1_rshifted = np.roll(a1, 1)
starts = a1 & ~a1_rshifted  # it's True but the previous isn't
ends = ~a1 & a1_rshifted

rawDescription: Find span where condition is True using NumPy


code:
a1, a2 = df1.align(df2, fill_value=0)
a1 + a2

rawDescription: Matrix addition using triples representation in Python


rawDescription: Create edges in networkx out of csv-File


code:
curs.execute("""SELECT A.x = ANY(SELECT my_col FROM my_table)
                  FROM (SELECT * FROM unnest(%s) x) A""", (vals,))

rawDescription: Checking existence of list of python values in psycopg2/postgresql


code:
from decimal import Decimal, ROUND_HALF_UP
def round_decimal(x):
  return x.quantize(Decimal(".01"), rounding=ROUND_HALF_UP)

cost = Decimal(input("Enter 12 month cost: "))
print("6 Month Cost: ", round_decimal(cost * Decimal(".6")))

rawDescription: Round an answer to 2 decimal places in Python


code:
import numpy as np
row = np.array([1,2,3,4,5])
a = np.array([1, 5])
b = np.array([10, 550])
np.in1d(row, a)
row[np.in1d(row, a)] = b
row

rawDescription: Numpy array modifying multiple elements at once


rawDescription: Variable/unknown length string/unicode dtype in numpy


code:
import cStringIO
s = cStringIO.StringIO()
img.save(s, 'png')
in_memory_file = s.getvalue()

rawDescription: Convert string to image in python

description: Convert string to image in python


code:
for i,j,k in combinations(range(n), r=ndim):
    # Do your cool stuff here
    pass

rawDescription: Triangular indices for multidimensional arrays in numpy


rawDescription: How do I clear this list at the end of every loop?

description: Clear this list at the end of every loop


code:
def validate_float(self, widget, entry):
    entry_text = entry.get_text()
    newtext = self.rx.findall(entry_text)
    if len(newtext) :
        entry.set_text(newtext[0])
    else:
        entry.set_text("")

rawDescription: How to get a pygtk entry accept only floats?

description: Get a pygtk entry accept only floats


code:
for row in self.cur:
   yield row

rawDescription: Proper way to use PyMySql in a memory efficient generator


code:
import re
from django.template import Library
from django.template.defaulttags import URLNode, url

register = Library()

class SubdomainURLNode(URLNode):
    def render(self, context):
        domain = context['request'].get_host()
        subdomain = re.sub(r'^www\.','',domain).split('.')[0]
        path = super(SubdomainURLNode, self).render(context)
        return re.sub(r'^/%s/' % subdomain, '/', path)

@register.tag
def subdomainurl(parser, token, node_cls=SubdomainURLNode):
    """Just like {% url %} but checks for a subdomain."""
    node_instance = url(parser, token)
    return node_cls(view_name=node_instance.view_name,
        args=node_instance.args,
        kwargs=node_instance.kwargs,
        asvar=node_instance.asvar)

rawDescription: Django, subdomains and mod_rewrite. URLs messing up on deployment setups


code:
# Read in csv file and convert to list of list of entries. Use with so that
# the file is automatically closed when we are done with it
csvlines = []
with open("CSV-sorted.csv") as f:
    for line in f:
        # Use strip() to clean up trailing whitespace, use split() to split
        # on commas.
        a = [entry.strip() for entry in line.split(',')]
        csvlines.append(a)

# I'll print it here so you can see what it looks like:
print(csvlines)

# Next up: converting our list of lists to a dict of sets.

# Create empty dict
sample_dict = {}

# Fill in the dict
for line in csvlines:
    gene = line[0] # gene is first entry
    samples = set(line[1:]) # rest of the entries are samples

    # If this gene is in the dict already then join the two sets of samples
    if gene in sample_dict:
        sample_dict[gene] = sample_dict[gene].union(samples)

    # otherwise just put it in
    else:
        sample_dict[gene] = samples

# Now you can print the dictionary:
print(sample_dict)

rawDescription: Python lists, csv, duplication removal

description: Python lists, csv, duplication removal


code:
indexes = [i for i, bit in enumerate(my_str) if bit == '1']
num = sum(2**i for i in indexes)

rawDescription: Binary to Decimal (mathematics way)

description: Binary to Decimal (mathematics way)


code:
urlpatterns = patterns('',
    url(r'^(?P<post_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<post_id>\d+)/remove/$', views.remove, name='remove'),
    # ...
)

rawDescription: Call an object's method from Django's Template on click


rawDescription: write matrix to image by PIL

description: Write matrix to image by PIL


code:
dfm = pd.melt(df, var_name=['items', 'labels'], id_vars=['index'], value_name='indicator')
dfm
df2m = pd.melt(df2, var_name=['labels'], id_vars=['index'], value_name='value')
df2m

rawDescription: Pandas MultiIndex Operations on Sub-Index


code:
import re
import json

class justdialdotcomSpider(BaseSpider):
    name = "justdialdotcom"
    domain_name = "www.justdial.com"
    start_urls = ["http://events.justdial.com/events/search.php"]

    # Initial request
    def parse(self, response):
        return [FormRequest(url="http://events.justdial.com/events/search.php",
                                        formdata={'fetch': 'area',
                                                  'pageNo': '1',
                                                  'city' : 'Hyderabad',
                                                  'cat' : '0',
                                                  'area' : '0',
                                                  'fromDate': '',
                                                  'toDate' : '',
                                                  'subCat' : '0'
                                                  },
                                        callback=self.area_count
                                        )]

# Get total count and paginate through events
    def area_count(self, response):
        total_count = 0
        for area in  json.loads(response.body):
            total_count += int(area["count"])

        pages_count = (total_count / 10) + 1

        page = 1
        while (page <= pages_count):
            yield FormRequest(url="http://events.justdial.com/events/search.php",
                                        formdata={'fetch': 'events',
                                                  'pageNo': str(page),
                                                  'city' : 'Hyderabad',
                                                  'cat' : '0',
                                                  'area' : '0',
                                                  'fromDate': '',
                                                  'toDate' : '',
                                                  'subCat' : '0'
                                                  },
                                        callback=self.parse_events
                                        )
            page += 1

# parse events
    def parse_events(self, response):
        events = json.loads(response.body)
        events.pop(0)

        for event_details in events:
            yield FormRequest(url="http://events.justdial.com/events/search.php",
                                        formdata={'fetch': 'event',
                                                  'eventId': str(event_details["id"]),
                                                  },
                                        callback=self.parse_event
                                        )

    def parse_event(self, response):
        event_details = json.loads(response.body)
        items = []
        #item = Product()

        items.append(item)
        return items

rawDescription: Empty list for hrefs to achieve pagination through JavaScript onclick functions


code:
def getValueForSpecificKey(self, capturedLog, key):
    '''
    Get value from log for any specific key.
    capturedLog will be searched if it is a list or dictionary.
    Returns None if the key is not found, or capturedLog is another type.
    '''

    if isinstance(capturedLog, dict):
        if key in capturedLog:                # base case #1 (found the key)
            return capturedLog[key]

        values = capturedLog.values()

    elif isinstance(capturedLog, list):
        values = capturedLog

    else:
        return None                           # base case #2 (not a list or dict)

    for value in values:
        result = self.getValueForSpecificKey(value, key)      # recursive case
        if result is not None:
            return result

    return None                               # nothing found in the recursive search

rawDescription: How to reset a global variable in python "recursive" function?

description: Reset a global variable in python "recursive" function


code: lambda x: x and x.isdigit() and int(x) or None

rawDescription: Lambda instead of "if" statement

description: Lambda instead of "if" statement


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

rawDescription: Get non-contiguous columns from a list of lists


code:
from collections import defaultdict

counts = defaultdict(set)

for mydict in li:
  for k, v in mydict.items():
    counts[k].add(v)

rawDescription: Number of different values assoicated with a key in a list of dicts


code:
from parsers.parser_a import ParserA
from parsers.parser_b import ParserB

rawDescription: Using java-like imports in a pythonic way


code:
import re
results = {}
for name, *data in map(str.splitlines, filetext2.split('\n\n')):
    if re.match('[A-Za-z]*\d{5}:', name):
        results[name[:-1]] = [x for x in data if x.endswith('.zip')]

rawDescription: Match all names with exactly 5 digits at the end


code:
import Tkinter
import tkMessageBox
WindowBox = Tkinter.Tk()
WindowBox.geometry("250x200")
WindowBox.title("Welcome to E-UPSR")

Tkinter.Label (WindowBox, text="Username:").pack()

username1 = Tkinter.Entry (WindowBox)
username1.pack()

Tkinter.Label (WindowBox, text="Password:").pack()

password1 = Tkinter.Entry (WindowBox)
password1.pack()

student=[]

def read():
    if not username1.get() or not password1.get():
        tkMessageBox.showerror('Invalid', 'Empty username or password')
    else:
        addstudent = open ("student.txt", "r")
        lines = addstudent.readlines()
        addstudent.close ()
        i = 0
        while i < len(lines) - 1:
            # username and password are saved in two line, label and value are separated by ':'.
            # to get them we need to reed two line in each iteration and split with ':' to get the value (second result of spliting) then strip to remove end line.
            user = lines[i].split(':')[1].strip()
            password = lines[i+1].split(':')[1].strip()
            # test if the user is registred
            if user == username1.get() and  password == password1.get():
                WindowBox.withdraw()
                MenuBox.deiconify()
                break
            i += 2
    return

def register():
    WindowBox.withdraw()
    RegBox.deiconify()
    return

RegBox = Tkinter.Tk()
RegBox.geometry("250x200")
RegBox.title("register")

Tkinter.Label (RegBox, text="Username:").pack()

username2 = Tkinter.Entry (RegBox)
username2.pack()

Tkinter.Label (RegBox, text="Password:").pack()
password2 = Tkinter.Entry (RegBox)
password2.pack()
RegBox.withdraw()

def back():
    RegBox.withdraw()
    WindowBox.deiconify()
    return

def save():
    if not username2.get() or not password2.get():
        tkMessageBox.showerror('Invalid', 'Empty username or password')
    else:
        addstudent = open ("student.txt", "a")
        addstudent.write('Username:' + username2.get() + '\n')
        addstudent.write('Password:' + password2.get()+'\n')
        tkMessageBox.showinfo("Writing", "Done")
    return

MenuBox = Tkinter.Tk()
MenuBox.geometry("250x200")
MenuBox.title("MainMenu")
MenuBox.withdraw()

Tkinter.Button (RegBox, text="Back", command=back).pack()
Tkinter.Button (RegBox, text="Enter", command=save).pack()
Tkinter.Button (WindowBox, text="Register", command=register).pack()
Tkinter.Button (WindowBox, text="Proceed", command=read).pack()

WindowBox.mainloop()

rawDescription: Register username and password

description: Register username and password


code:
def mock_client(dictionary):
    client = mock.MagicMock()
    client.dictionary = dictionary

    def append_dictionary(self, key, value):
        self.dictionary[key] = value

    client.append_dictionary = append_dictionary
    return client

rawDescription: Passing arguments to mock method

description: Passing arguments to mock method


code:
import re, locale
sall = ''.join(chr(i) for i in xrange(256))
len(sall)
re.sub('[\W_]+', '', sall)
re.sub('[\W_]+', '', sall, flags=re.LOCALE)
locale.setlocale(locale.LC_ALL, '')
re.sub('[\W_]+', '', sall, flags=re.LOCALE)

rawDescription: Python remove anything that is not a letter or number


rawDescription: Most efficient way to find longest incrementing subsequence in a list of lists


code: a is b

rawDescription: Sure-fire, simple way to compare two complex objects in Python?


code:
class A:
    def __init__(self, name):
        self.name = name

a = A('a')
a.name
foo = A('foo')
foo.name
bar = foo # additional references to an object will still return the original name
bar.name

rawDescription: How to get the object name from within the class?

description: Get the object name from within the class


code:
import re

data = 'var v = "this is string constant + some numbers and \" is also included "\r\nvar v = "and another \"line\" "'
matches = re.findall( r'= "(.*(?<!\\))"', data, re.I | re.M)
print(matches)

rawDescription: Extracting string constant from source code in a string using regular expressions in Python


code:
import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'submodFolder'))

import submod

rawDescription: python import from sub-directory in a git safe way

description: Python import from sub-directory in a git safe way


code:
df[["Trial","Time","Condition","Status","Q"]].set_index(
                            ["Trial","Time","Condition","Status"]).unstack("Status")

rawDescription: Inverting Rows of multiple columns to vertically concatenated columns


code: c = b[index]

rawDescription: Python: an efficient way to slice a list with a index list


code: LOGIN_REDIRECT_VIEW = 'login_success'

rawDescription: Django -- Conditional Login Redirect

description: Django -- Conditional Login Redirect


code:
def setter(fn):
    return property(
        lambda self: getattr(self, '_' + fn.__name__),
        fn)

rawDescription: Defining setter in a shorter way

description: Defining setter in a shorter way


code:
def on_keypress( event ):                          # keeping the Globals-style,
    global direction                               #         however shall be rather
    global x_vel                                   #         implemented in a Class-based
    global y_vel                                   #         manner

    direction     = dir_vel[event.keysym][0]       # ref. remark on more complex FSA
    x_vel        += dir_vel[event.keysym][1]
    y_vel        += dir_vel[event.keysym][2]

def on_keyrelease( event ):
    global direction
    global x_vel
    global y_vel
    x_vel        -= dir_vel[event.keysym][1]
    y_vel        -= dir_vel[event.keysym][2]
    if abs( x_vel * y_vel ) < 0.1:
        direction = None                          # ref. remark on more complex FSA

rawDescription: How can I program two simultaneous key press events in tkinter to move a canvas item diagonally using a dictionary of keypress events?

description: Program two simultaneous key press events in tkinter to move a canvas item diagonally using a dictionary of keypress events


code:
reports_by_status = {}
for report in reports:
    if report.status not in reports_by_status:
        reports_by_status[status] = []
    reports_by_status[status].append(report)

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


rawDescription: Mock same method with different return value called twice in a function in python


code:
import wikipedia
ny = wikipedia.page('New York')
dir(ny)

rawDescription: listing all attributes of an object

description: Listing all attributes of an object


code:
string3 = 'This is some text to introduce the bullet points:\n  - This is the first bullet points\n  - This is the second bullet point\n  - This is the third bullet point\nThis some last bit of text.'
htmlize(string3)

rawDescription: Form an unordered list with regex

description: Form an unordered list with regex


rawDescription: Test for list without duplicated elements


code:
import numpy as np
rng = np.random.RandomState(42)

n_samples_train, n_features = 40, 10
n_samples_test = 20
X_train = rng.randn(n_samples_train, n_features)
X_test = rng.randn(n_samples_test, n_features)

from sklearn.decomposition import PCA
pca = PCA(whiten=True)

pca.fit(X_train)

X_train_mean = X_train.mean(0)
X_train_centered = X_train - X_train_mean
U, S, VT = np.linalg.svd(X_train_centered, full_matrices=False)
components = VT / S[:, np.newaxis] * np.sqrt(n_samples_train)

from numpy.testing import assert_array_almost_equal
# These assertions will raise an error if the arrays aren't equal
assert_array_almost_equal(components, pca.components_)  # we have successfully
                                                        # calculated whitened components

transformed = pca.transform(X_test)
inverse_transformed = transformed.dot(S[:, np.newaxis] ** 2 * pca.components_ /
                                            n_samples_train) + X_train_mean

assert_array_almost_equal(inverse_transformed, X_test)  # We have equality

rawDescription: Inversing PCA transform with sklearn (with whiten=True)


code:
def word_from_lst(lst, word):
    if word == " " or not word:
      return True
    if word[0] in lst:
      lst_ = lst[:]
      lst_.remove(word[0])
      return word_from_lst(lst_, word[1:])
    return False

rawDescription: How to remove strings from a list in Python in a loop so it won't be used as a duplicate?

description: Remove strings from a list in Python in a loop so it won't be used as a duplicate


rawDescription: Index a list of lists

description: Index a list of lists


code:
byloc = lambda x: x['loc']

it = (
    (loc, list(user_grp))
    for loc, user_grp in itertools.groupby(
        sorted(dataset['users'], key=byloc), key=byloc
    )
)
fs_loc = [
    {'loc': loc, 'ids': [x['id'] for x in grp], 'count': len(grp)}
    for loc, grp in it
]

rawDescription: Difficulty creating new list grouping by a key using itertools in python


rawDescription: Python - How to remove similar elements from a list?


code: s.apply(lambda x: type(x))

rawDescription: Access index in pandas.Series.apply

description: Access index in pandas.Series.apply


code:
ax.xaxis.set_major_formatter(
   FuncFormatter(lambda x, pos: '{:0.1f}'.format(log10(x))))

rawDescription: What is the correct way to replace matplotlib tick labels with computed values?


rawDescription: How can I sort a 2D list?

description: Sort a 2D list


rawDescription: Collecting like term of an expression in Sympy


rawDescription: python stats models - quadratic term in regression

description: Python stats models - quadratic term in regression


code:
df['duration'] = - df.groupby('IDs')['date'].diff()
df

rawDescription: Time series analysis in pandas

description: Time series analysis in pandas


code: map(int, re.findall(r'\d+', string1))

rawDescription: How to get integer values from a string in Python?

description: Get integer values from a string in Python


code:
import re
dict(re.findall(r'(\S+)=(".*?"|\S+)', s))

rawDescription: creating dictionary from space separated key=value string in python

description: Creating dictionary from space separated key=value string in python


code:
A.func1 #GET!!!
obj = A()
obj.func1 #GET!!!
obj.func1 is obj.func1 # True
A.func1 # GET!!!
obj2 = A()
obj2.func1 is not obj.fun1 # True + GET!!!

rawDescription: Python - using decorator.py to preserve a method docstring


code:
#!/usr/bin/python
import lxml.etree as ET

dom = ET.parse('C:\\Path\\To\\MainXML.xml')
xslt = ET.parse('C:\\Path\\To\\AboveXSLT.xsl')
transform = ET.XSLT(xslt)
newdom = transform(dom)

tree_out = ET.tostring(newdom, encoding='UTF-8', pretty_print=True, xml_declaration=True)

xmlfile = open('C:\\Path\\To\\Output.xml','wb')
xmlfile.write(tree_out)
xmlfile.close()

rawDescription: Parse Two XML using Python

description: Parse Two XML using Python


code:
a3d = np.zeros((2,3,4))
ndim = 5
padded_shape = (a3d.shape + (1,)*ndim)[:ndim]
new_a3d = a3d.reshape(padded_shape)
new_a3d.shape

rawDescription: np.array ndmin argument: specify placement of added dimensions

description: Np.array ndmin argument: specify placement of added dimensions


code:
x = 4
y = 9
repeatList = []
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))

x = 3
y = 2
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))
x = 4
y = 9
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))
print(repeatList)

rawDescription: How to remove and show there were string duplicates in a list?

description: Remove and show there were string duplicates in a list


code:
from django.db import models

class Service(models.Model):
    port = models.PositiveIntegerField()

class SSHService(Service):
    username = models.CharField(max_length=64)
    pkey = models.TextField()

class TelnetService(Service):
    username = models.CharField(max_length=64)
    password = models.CharField(max_length=64)

class GenericTcpService(Service):
    pass

class GenericUDPService(Service):
    pass

class Node(models.Model):
    name = models.CharField(max_length=64)
    # various fields
    services = models.ManyToManyField(Service)

rawDescription: ForeignKey to abstract class (generic relations)


code:
v = df['Value']
v.index = pd.MultiIndex.from_arrays([df['foo'], identifier])
v

rawDescription: Pandas: Combining values in multiple columns to create a new column


code:
def clean(self):
    from django.core.exceptions import ValidationError
    if self.id1 == self.id2:
        raise ValidationError('Entries must compare different objects')

rawDescription: Django sql check

description: Django sql check


rawDescription: Remove items from a list in Python based on previous items in the same list


code: global_dict["bar"] = "hello"

rawDescription: Using a global dictionary with threads in Python


code:
# there is only one inner list
foo = [[]] * 3
foo[0].append(0)
foo
# [[0], [0], [0]]

# there are three separate inner lists
bar = [[] for _ in range(3)]
bar[0].append(0)
bar
# [[0], [], []]

rawDescription: Generating iterables of iterables with python itertools. (using the repeat function)


code: LOGIN_REDIRECT_URL = '/my_profile/'

rawDescription: django-profiles: How do I show the profile after login?

description: Django-profiles: How do I show the profile after login


code:
forms = (("_ref_ck", ref),
         ("type", "create"),
         ("selected_items[]", sel_itms[0]),
         ("selected_items[]", sel_itms[1]),
         # ...
         )
data = urllib.urlencode(forms)

rawDescription: Sending multiple values for one name urllib2


rawDescription: Python position of a character in a string in a list


code:
import inspect

defaults = inspect.getargspec(foo).defaults
foo(*(defaults + (1,2,3)))

rawDescription: Is there a way to access varargs without specifying default value arguments in Python


rawDescription: Append elements of a set to a list in Python


code:
from collections import defaultdict
d = defaultdict (int)
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
d['e'] = 5
print (d)

rawDescription: Python : Get list by index not key in defaultdict


rawDescription: pandas: calculate over multiindex

description: Pandas: calculate over multiindex


code:
df_city_sums = df_city.groupby('city').sum()
df_city_sums

rawDescription: pandas: groupby and variable weights

description: Pandas: groupby and variable weights


code:
# start of file
import myapp.logging
myapp.logging.setlevel(myapp.logging.DEBUG)

# rest of imports

# rest of main

rawDescription: Can I determine if an application is being run normally vs via a unittest in Python?

description: Determine if an application is being run normally vs via a unittest in Python


rawDescription: How does one parse a file to a 2d array whilst maintaining data types in Python?

description: Parse a file to a 2d array whilst maintaining data types in Python


code:
from jira import JIRA

jira = JIRA('https://jira.atlassian.com')
issue = jira.issue('JRA-9')
issue.fields.__getattribute__(issue.fields,'customfield_11437')

rawDescription: JIRA Python use a string to access class


code: df_new = df.resample(rule='1S')

rawDescription: pandas - resample - upsampling before downsampling

description: Pandas - resample - upsampling before downsampling


code:
import re
i = 'john(is,great),paul,school'
re.split(r',+(?=[^()]*(?:\(|$))', i)

rawDescription: Splitting a String Python within a list

description: Splitting a String Python within a list


code:
def scrambled(orig):
    dest = orig[:]
    random.shuffle(dest)
    return dest

rawDescription: Scramble Python List

description: Scramble Python List


code:
result = pd.pivot_table(melted, values='d', index=['value'], columns=['variable'],
                        aggfunc=np.median)

rawDescription: summarizing data frame in pandas - python

description: Summarizing data frame in pandas - python


code: "baz".join(s.rsplit("foo", 1))

rawDescription: Python: replacing a repeating string once in text


rawDescription: How do I take an integer from a list intending to use it?

description: Take an integer from a list intending to use it


code:
import itertools

list1 = [12,25,45]
list2 = [14,69]
list3 = [54,98,68,78,48]

for i,(a,b,c) in enumerate(itertools.product(list1,list2,list3),1):
    # Note: Computing rest this way will *not* work if there are duplicates
    #       in any of the lists.
    rest1 = [n for n in list1 if n != a]
    rest2 = [n for n in list2 if n != b]
    rest3 = [n for n in list3 if n != c]
    rest = ','.join(str(n) for n in rest1+rest2+rest3)
    print('chosen{0}=[{1},{2},{3}], rest{0}=[{4}]'.format(i,a,b,c,rest))

rawDescription: divide list and generate series of new lists. one from each list and rest into other

description: Divide list and generate series of new lists. one from each list and rest into other


code:
anomalies = x - x.mean()
signs = np.sign(anomalies).astype(np.int8)

rawDescription: Reasoning about consecutive data points without using iteration


rawDescription: How can I rotate this list of lists with python

description: Rotate this list of lists with python


code:
def __init__(self):
    window = Tk()
    window.title("Loan Calculator")

    frame = Frame(window)
    frame.pack()

    Label(frame, text="Loan Amount").grid(row=1,column=1, sticky=W)
    self.loanAmmount = StringVar()
    self.entryLoan = Entry(frame, textvariable=self.loanAmmount, justify=RIGHT)
    Label(frame, text="Years").grid(row=1, column=3,sticky=W)
    self.years = StringVar()
    self.entryYears = Entry(frame, textvariable=self.years, justify=RIGHT)
    btCalc = Button(frame, text="Calculate Loan", command=self.Calculate)
    scrollbar = Scrollbar(frame)
    self.text = Text(frame, width=60, height=10,wrap=WORD, yscrollcommand=scrollbar.set)
    scrollbar.config(command=self.text.yview)

    self.entryLoan.grid(row=1, column=2)
    self.entryYears.grid(row=1, column=4)
    btCalc.grid(row=1, column=5)
    self.text.grid(row=2,column=1,columnspan=4)
    scrollbar.grid(row=2, column=5, sticky="NSW")

rawDescription: Python Tkinter Text/Scrollbar Widget not functioning as expected


code: ']. Using this surgical technique the mesorectal compartment including the rectum and perirectal fat is completely excised by sharp dissection along the mesorectal fascia (MRF) ['

rawDescription: Extracting untagged text using beautifulsoup


rawDescription: Using metaclasses to override methods of complex builtin


rawDescription: How to use Python Lepl to parse a subset of a domain specific language?

description: Use Python Lepl to parse a subset of a domain specific language


rawDescription: Windows path in python

description: Windows path in python


code:
env['SQLITE3COMSTR'] = 'Generating $TARGET from $SOURCES with sqlite3'
...
built_database = env.Command(target, sources, Action('mySqlite3', '$SQLITE3COMSTR'))

rawDescription: How to specify a COMSTR for the Command Builder in 'scons'

description: Specify a COMSTR for the Command Builder in 'scons'


rawDescription: Create sub-lists in lists in Python

description: Create sub-lists in lists in Python


code:
import win32com.shell.shell as shell
param = '/d:"%s"' % printer
shell.ShellExecuteEx(fmask = win32com.shell.shellcon.SEE_MASK_NOASYNC, lpVerb='print', lpFile=pfile, lpParameters=param)

rawDescription: How to determine if win32api.ShellExecute was successful using hinstance?

description: Determine if win32api.ShellExecute was successful using hinstance


code:
import script2
import script3

rawDescription: How to run multiple scripts from a script in python

description: Run multiple scripts from a script in python


code:
LoT
repr(LoT)

rawDescription: Convert a tuple to a string that is that tupple


code:
array_name.shape
array_name[0, 0]
array_name[0, 1]

rawDescription: Trying to make a readable txt file from an np array, all printing on one line?


code:
for name, values in scores.items():
    print(name, 'Total: {} Average: {:5.2f} '.format(
          len(values), sum(values) / (len(values))))

rawDescription: How to sort notepad data in average order?

description: Sort notepad data in average order


code:
a = aliased(Model, name="a")
b = aliased(Model, name="b")
q = (
    session
    .query(a)
    .outerjoin(b, and_(a.pk == b.pk, b.insert_date < task_date))
    .filter(a.insert_date == task_date)
    .filter(b.pk == None)
    # or: .filter(b.pk != None)
)

rawDescription: SQLAlchemy return model from outerjoin

description: SQLAlchemy return model from outerjoin


code: dict(line.split() for line in open('path/to/input'))

rawDescription: How to add to a dictionary through a text file

description: Add to a dictionary through a text file


code:
from sys import getrefcount
lis = [1,2,3]
foo = lis       #creates a new reference to the same object [1,2,3]
lis is foo
getrefcount(lis) #number of references to the same object
foo.append(4)
lis.append(5)
foo,lis
lis = [1,2,3]
foo = lis[:]    #assigns a shallow copy of lis to foo
foo is lis
getrefcount(lis) #still 2(lis + shell_, as foo points to a different object
foo.append(4)
lis.append(5)
foo, lis

rawDescription: List being identified with another, using new items in the loop


code:
import numpy as np

def calc_combination(N1, N2, n1, n2, theta, phi):
    N1 = N1[(N1 >= 0) & (N1 <= n1)]
    N2 = N2[(N2 >= 0) & (N2 <= n2)]

    a = N2 * theta + phi
    res = N1.reshape(N1.shape[0], 1) - a.reshape(1, a.shape[0])

    indices = np.argwhere(res >= 0)
    pairs = zip(N1[indices[:,0]], N2[indices[:,1]])
    return pairs

def test_case():
    n1 = 5
    n2 = 1
    theta = 2
    phi = 2

    N1 = np.arange(n1 + 1)
    N2 = np.arange(n2 + 1)

    assert (calc_combination(N1, N2, n1, n2, theta, phi) ==
            [(2, 0), (3, 0), (4, 0), (4, 1), (5, 0), (5, 1)])

test_case()

rawDescription: Finding combinations that meet a threshold relation


rawDescription: How do I write a regular expression to replace % by function?

description: Write a regular expression to replace % by function


rawDescription: Return the row maximum in a dictionary format


code:
def printDict(myDict):
    from itertools import groupby
    def sortFunc(item):
        return len(item[0])

    sortedItems = sorted(myDict.items(), key=sortFunc)
    groups = groupby(sortedItems, sortFunc)
    for _, group in groups:
        print( ';'.join('%s:%s' % entry for entry in group))

rawDescription: printing a dictionary with specific format

description: Printing a dictionary with specific format


code:
data =  {"Title":"Un homme idÃ©al","Year":"2015","Rated":"N/A",\
         "Released":"18 Mar 2015","Runtime":"97 min","Genre":"Thriller",\
         "Director":"Yann Gozlan","Writer":"Yann Gozlan, Guillaume Lemans, GrÃ©goire Vigneron",\
         "Actors":"Pierre Niney, Ana Girardot, AndrÃ© Marcon, Valeria Cavalli",\
         "Plot":"N/A","Language":"French","Country":"France","Awards":"N/A",\
         "Poster":"N/A","Metascore":"N/A","imdbRating":"6.3","imdbVotes":"214",\
         "imdbID":"tt4058500","Type":"movie","Response":"True"}

import xlwt
book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("AssetsReport0")

colunm_count = 0
for title, value in data.iteritems():
    sheet1.write(0, colunm_count, title)
    sheet1.write(1, colunm_count, value)
    colunm_count += 1

file_name = "test.xls"%()
book.save(file_name)

rawDescription: Parse Json data to Excel

description: Parse Json data to Excel


code:
@app.route('/logout')
def logout():
    logout_user()
    session.clear()
    ...

rawDescription: Copy user session when anonymous user logs in with Flask-Login


code:
class OpenGLWidget(QtOpenGL.QGLWidget):
    def __init__(self, parent=None):
        self.parent = parent
        self.camera = camera_view.View()

rawDescription: modelview matrix not updated using pyopengl and pyqt

description: Modelview matrix not updated using pyopengl and pyqt


code: x = y = {}  # same dict object assigned to x ,y. We should not do this.

rawDescription: Python initialize multiple variables to the same initial value


code:
def put_tasks(q):
    ...

    print('put_tasks: no more tasks')
    q.put(end_of_queue)

def work(id, q):
    while True:
        task = q.get()

        if task == end_of_queue:
            q.put(task)
            print("DONE")
            return

        print('process %d: %s' % (id, task))
        time.sleep(.1)
    print('process %d: done' % id)

class Sentinel:
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        if isinstance(other, Sentinel):
            return self.id == other.id

        return NotImplemented

if __name__ == '__main__':
    q = Queue(2)
    end_of_queue = Sentinel("end of queue")
    task_gen = Process(target=put_tasks, args=(q,))
    processes = [Process(target=work, args=(id, q)) for id in range(0, 3)]
    ...

rawDescription: Tell consumers to stop waiting for queue elements


code:
u3 = u2.reindex(min_date, max_date)
u3

rawDescription: How to get an accumulative counting of rows in a data frame?

description: Get an accumulative counting of rows in a data frame


code:
try:
    import winreg
except:
    import _winreg as winreg
import win32api

def notepad_print(textfile, newset=None):
    if newset is not None:
        oldset = {}
        hkcu = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
        notepad = winreg.OpenKey(hkcu, r'Software\Microsoft\Notepad', 0,
                                 winreg.KEY_ALL_ACCESS)
        for key, item in newset.items():
            oldset[key] = winreg.QueryValueEx(notepad, key)
            winreg.SetValueEx(notepad, key, None, item[1], item[0])

    #force printing with notepad, instead of using the 'print' verb
    win32api.ShellExecute(0, 'open', 'notepad.exe', '/p ' + textfile, '.', 0)

    input('once the job is queued, hit <enter> to continue')

    if newset is not None:
        for key, item in oldset.items():
            winreg.SetValueEx(notepad, key, None, item[1], item[0])

rawDescription: hide header and footer on text files when direct print using win32 and python

description: Hide header and footer on text files when direct print using win32 and python


code: min(enumerate(a), key=lambda x: abs(x[1]-11.5))

rawDescription: finding index of an item closest to the value in a list that's not entirely sorted

description: Finding index of an item closest to the value in a list that's not entirely sorted


code:
setA = {word for word, sym in self.list if sym == "A"}
setB = {word for word, sym in self.list if sym == "B"}

AB_words = setA & setB  # Preserves only those words found in both input sets

rawDescription: comparing a list of tuples python

description: Comparing a list of tuples python


code:
class Fist(pygame.sprite.Sprite):
    """moves a clenched fist on the screen, following the mouse"""

    def update(self):
        "move the fist based on the mouse position"
        pos = pygame.mouse.get_pos()
        self.rect.midtop = pos
        if self.punching:
            self.rect.move_ip(5, 10)

rawDescription: How to make a sprite follow your mouse cursor using pygame?

description: Make a sprite follow your mouse cursor using pygame


code:
import os
os.environ['MY_DAILY_CONST_1'] = 'dailyconst1'
os.environ['MY_DAILY_CONST_2'] = 'dailyconst2'
...

rawDescription: How to efficiently define daily constant?

description: Efficiently define daily constant


code:
def test_updates(dictish):
    dictish['abc'] = 123
    dictish.update({'def': 234})
    dictish.update(red=1, blue=2)
    dictish.update([('orange', 3), ('green',4)])
    dictish.update({'hello': 'kitty'}, black='white')
    dictish.update({'yellow': 5}, yellow=6)
    dictish.setdefault('brown',7)
    dictish.setdefault('pink')
    try:
        dictish.update({'gold': 8}, [('purple', 9)], silver=10)
    except TypeError:
        pass
    else:
        raise RunTimeException("Error did not occur as planned")

python_dict = dict([('b',2),('c',3)],a=1)
test_updates(python_dict)

my_dict = MyUpdateDict([('b',2),('c',3)],a=1)
test_updates(my_dict)

rawDescription: Subclassing Python dictionary to override __setitem__


code:
import mailchimp
API_KEY = 'my-api-key'
LIST_ID = 'my-list-id'

api = mailchimp.Mailchimp(API_KEY)
api.lists.subscribe(LIST_ID, {'email': 'email@example.com'})

rawDescription: How do I subscribe someone to a list using the python mailchimp API v2.0?

description: Subscribe someone to a list using the python mailchimp API v2.0


code:
# Original rollback code:
for rlist in the_dict.itervalues():
    if not rlist: continue
    while rlist[-1][0] > target_revno:
        rlist.pop()

# New rollback code
for revno in xrange(current_revno, target_revno, -1):
    for rlist in delta_index[revno]:
        assert rlist[-1][0] == revno
        del rlist[-1] # faster than rlist.pop()
del delta_index[target_revno+1:]

rawDescription: delta-dictionary/dictionary with revision awareness in python?

description: Delta-dictionary/dictionary with revision awareness in python


code:
results = []
for i in range(1, 51):
    parameter = getattr(hdf2.root, 'OM%02d' % i)
    result = Fitter(parameter, plot=False)
    results.append(result)

rawDescription: Loop a python script

description: Loop a python script


code:
negatives = filter(lambda number: number <  0, numbers)
positives = filter(lambda number: number >= 0, numbers)

rawDescription: Is there a simple feature that builds a sublist based on value conditioning in Python?


code:
string.ascii_uppercase
string.digits
string.ascii_uppercase + string.digits

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


rawDescription: pandas merge and fill a dataframe with summary data

description: Pandas merge and fill a dataframe with summary data


code: indexes = np.zeros((a.shape[0], unique.size), dtype=np.bool)

rawDescription: List of indices of every value

description: List of indices of every value


code:
# Authors per year
authors_per_year = { year: len(authors) for year, authors in the_list }

rawDescription: Counting number of elements in nested list


code:
import re
x = soup.find(text=re.compile('Having reread this book'))

rawDescription: Extracting content of div with BeautifulSoup


code:
#data_1 is the larger dictonary

n=100000
data_1 = pd.DataFrame(np.random.randint(1,100,(n,3)),
                      index=pd.date_range('2012-01-01',periods=n, freq='1Min').date,
                      columns=['Product', 'Hub', 'Period']).drop_duplicates()
data_1.index.name='Date'

#data_2 is a random subset, w/o column Period
data_2 = data_1.ix[np.random.randint(0,len(data_1),1000), ['Product','Hub']]

rawDescription: Optimal filling of pandas DataFrame column by matching values in another DataFrame


code: print([(phrase, count) for phrase, count in all_phrases.items() if count > 1])

rawDescription: Python: Finding unknown repeated word(s) in a list of strings


code:
import heapq
heapq

rawDescription: Python heapq - Python and C implementation? Which one is used?


code: numpy.where(data < 4)[0]

rawDescription: Filter array returning arguments

description: Filter array returning arguments


code:
import collections
Action = collections.namedtuple('Action', 'name hostgroup actions operations')

rawDescription: python - elegantly handle sequence of multiple arguments

description: Python - elegantly handle sequence of multiple arguments


rawDescription: How can I parse text in Python?

description: Parse text in Python


code:
file_list = [ 'drug.resp1.17A.tag', 'drug.resp1.96A.tag', 'drug.resp1.56B.tag', 'drug.resp2.17A.tag', 'drug.resp2.56B.tag', 'drug.resp2.96A.tag']
dictonary = {}
for i in file_list:
    k = i.split('.')[-2]
    if k in dictonary:
        dictonary[k].append(i)
    else:
        dictonary[k] = [i]
dictonary

rawDescription: combine two lists into a dictionary if a pattern matches

description: Combine two lists into a dictionary if a pattern matches


code:
for val, key in zip(L1, D1):
    D1[key] = val

rawDescription: Update the value of a dictionary with elements in the lists Python


code:
def merge_lists(head1, head2):
    if head1 is None:
        return head2
    if head2 is None:
        return head1

    # create dummy node to avoid additional checks in loop
    s = t = node()
    while not (head1 is None or head2 is None):
        if head1.value < head2.value:
            # remember current low-node
            c = head1
            # follow ->next
            head1 = head1.next
        else:
            # remember current low-node
            c = head2
            # follow ->next
            head2 = head2.next

        # only mutate the node AFTER we have followed ->next
        t.next = c
        # and make sure we also advance the temp
        t = t.next

    t.next = head1 or head2

    # return tail of dummy node
    return s.next

rawDescription: merging two sorted linked lists into one linked list in python

description: Merging two sorted linked lists into one linked list in python


code:
def answer(digits, total):
    n_or_fewer = sum(npermutations(l) for l in unique_combos(digits, total))
    fewer = sum(npermutations(l) for l in unique_combos(digits-1, total))
    print("There are {} {}-digit numbers with digits summing to {}".format(
        n_or_fewer - fewer,
        digits, total))

if __name__=='__main__':
    answer(4,18)
    answer(10,39)

rawDescription: Speeding Up a Python While Loop

description: Speeding Up a Python While Loop


code:
def dfs(v,last):
    if v in vis:
        return True
    vis.append(v)
    c = False
    current_adj_list = list(adj[v])
    for el in current_adj_list:
        if el == last:
            adj[el].remove(v)
        else:
            c = c or dfs(el,v)
    return c

adj = {1: [2,4], 2:[1,5,4], 4: [1,2], 5: [2]}
vis = []

print(dfs(1,None))

rawDescription: Finding a circle in an undirected graph

description: Finding a circle in an undirected graph


rawDescription: Can I efficiently swap two class instances by swapping __dict__?

description: Efficiently swap two class instances by swapping __dict__


code:
def get_field_value(soup, field):
    field_label = soup.find('td', text=field + ':')
    return field_label.find_next_sibling('td').get_text(strip=True)

rawDescription: Trouble extracting data from html-doc with BeautifulSoup


code:
import csv
from itertools import islice,ifilter

MAINDIR = "../"
with  open(MAINDIR + "atp_players.csv") as pf,  open(MAINDIR + "atp_rankings_current.csv") as rf:
    players = list(csv.reader(pf))
    rankings = csv.reader(rf)
    # only get first ten rows using islice
    for i in islice(rankings, None, 10):
        # ifilter won't create a list, gives values in the fly
        player = next(ifilter(lambda x: x[0] == i[2], players),"")

rawDescription: Python large multi-list efficient query

description: Python large multi-list efficient query


code:
from operator import itemgetter
set(map(itemgetter("food"), orders.values()))

rawDescription: Obtaining list (or set) of unique values in nested dictionary


code: text = text.split('\n')

rawDescription: String from input is limited?

description: String from input is limited


code:
s = 'https://docs.python.org/3.4/tutorial/interpreter.html'
s.rsplit('/',1)
s.rsplit('/',1)[1]

rawDescription: Remove Part of String Before the Last Forward Slash


code:
user1, hash_pass_u1
user2, hash_pass_u2
user3, hash_pass_u3
...

rawDescription: Find password by username

description: Find password by username


code:
def insert_object(new_object: str, position: int) -> str:
    room_start = room[0:position]
    end_position = position + len(new_object)
    room_end = room[end_position:]
    new_room = room_start + new_object + room_end
    return new_room

rawDescription: How do I format code to print with the same width every time?

description: Format code to print with the same width every time


code:
# Extract features from corpus and for each document label it with the appropriate labels.
label_feats = label_feats_from_corpus(movie_reviews)

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


code:
[{'entries': [{'division': 'I',
    'isFreshBlood': False,
    'isHotStreak': False,
    'isInactive': False,
    'isVeteran': False,
    'leaguePoints': 0,
    'losses': 14,
    'playerOrTeamId': 'xxyyzz',
    'playerOrTeamName': 'xxyyzz',
    'wins': 8}],
  'name': "Talon's Army",
  'queue': 'xxyyzz',
  'tier': 'BRONZE'},
 {'entries': [{'division': 'V',
    'isFreshBlood': False,
    'isHotStreak': False,
    'isInactive': False,
    'isVeteran': False,
    'leaguePoints': 18,
    'losses': 2,
    'playerOrTeamId': 'xxyyzz',
    'playerOrTeamName': 'xxyyzz',
    'wins': 5}],
  'name': "xxyyzz",
  'queue': 'xxyyzz',
  'tier': 'SILVER'}]

rawDescription: Navigate in Dictionaries

description: Navigate in Dictionaries


rawDescription: Interleave two numpy arrays based on element distances (python)


code: x = np.random.randn(10, 10).astype('f')

rawDescription: Can I specify a numpy dtype when generating random values?

description: Specify a numpy dtype when generating random values


code:
x = json.dump(json_data,f,ensure_ascii=True)
print(type(x))

rawDescription: JSON data recognized as a string field instead of integer


code:
def decode (line):
    return ' '.join (token [:-3]
        if token.endswith ('WAY')
        else (lambda a, b: b [:-3] + a) (*token.split ('X') )
        for token in line.split () )

rawDescription: Convert piglatin to english?

description: Convert piglatin to english


code:
grouped.get_group(True)
grouped.get_group(False)
[g for k,g in list(grouped)]
dict(list(grouped))
dict(list(grouped)).values()

rawDescription: Python Pandas - Removing Rows From A DataFrame Based on a Previously Obtained Subset


rawDescription: Is this control structure a code smell?

description: Is this control structure a code smell


code:
if os.name == "posix" and sys.platform == "darwin":
    from ctypes.macholib.dyld import dyld_find as _dyld_find
    def find_library(name):
        possible = ['lib%s.dylib' % name,
                    '%s.dylib' % name,
                    '%s.framework/%s' % (name, name)]
        for name in possible:
            try:
                return _dyld_find(name)
            except ValueError:
                continue
        return None

rawDescription: Which paths does python ctypes module search for libraries on Mac OS?


code:
replacements = [('one', '1'), ('two', '2'), ('three', '3'), ...]
numbers = foo
for item in replacements:
    numbers = numbers.replace(*item)

rawDescription: Shorten method chaining in Python variable


code: birdofprey.storage_i = i

rawDescription: Python Global Variable: sharing between function class then function


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
images = [np.random.rand(40, 40) for x in range(68)]
gs = mpl.gridspec.GridSpec(17, 4)
gs.update(wspace=0.1, hspace=0.1, left=0.1, right=0.4, bottom=0.1, top=0.9)
for i in range(68):
    plt.subplot(gs[i])
    plt.imshow(images[i])
    plt.axis('off')
plt.show()

rawDescription: how to remove "empty" space between subplots?

description: Remove "empty" space between subplots


code: [word+"$" for word in words]

rawDescription: Removing last character from each element in array (Python)


code:
Definition
import random
import operator
import bisect
import itertools

# or use itertools.accumulate in python 3
def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    try:
        total = next(it)
    except StopIteration:
        return
    yield total
    for element in it:
        total = func(total, element)
        yield total

class MultiKeyMultiValNonDeterministicDict(dict):

    def key_combinations(self, keys):
        """get all combinations of keys"""
        return [frozenset(subset) for L in range(0, len(keys)+1) for subset in itertools.combinations(keys, L)]

    def multi_val_rule_prob(self, rules, rule):
        """
        assign probabilities for each value,
        spreading undefined result probabilities
        uniformly over the leftover results not defined by rule.
        """
        all_results = set([result for result_probs in rules.values() for result in result_probs])
        prob = rules[rule]
        leftover_prob = 1.0 - sum([x for x in prob.values()])
        leftover_results = len(all_results) - len(prob)
        for result in all_results:
            if result not in prob:
                # spread undefined prob uniformly over leftover results
                prob[result] = leftover_prob/leftover_results
        return prob

    def multi_key_rule_prob(self, key, val):
        """
        assign probability distributions for every combination of keys,
        using the default for combinations not defined in rule set
        """
        combo_probs = {}
        for combo in self.key_combinations(key):
            if combo in val:
                result_probs = self.multi_val_rule_prob(val, combo).items()
            else:
                result_probs = self.multi_val_rule_prob(val, frozenset([])).items()
            combo_probs[combo] = result_probs
        return combo_probs

    def weighted_random_choice(self, weighted_choices):
        """make choice from weighted distribution"""
        choices, weights = zip(*weighted_choices)
        cumdist = list(accumulate(weights))
        return choices[bisect.bisect(cumdist, random.random() * cumdist[-1])]

    def __setitem__(self, key, val):
        """
        set item in dictionary,
        assigns values to keys with precomputed probability distributions
        """

        precompute_val_probs = self.multi_key_rule_prob(key, val)
        # use to show ALL precomputed probabilities for key's rule set
        # print precompute_val_probs

        dict.__setitem__(self, frozenset(key), precompute_val_probs)

    def __getitem__(self, key):
        """
        get item from dictionary,
        randomly select value based on rule probability
        """
        key = frozenset([key]) if isinstance(key, str) else frozenset(key)
        val = None
        weighted_val = None
        if key in self.keys():
            val = dict.__getitem__(self, key)
            weighted_val = val[key]
        else:
            for k in self.keys():
                if key.issubset(k):
                    val = dict.__getitem__(self, k)
                    weighted_val = val[key]

        # used to show probabality for key
        # print weighted_val

        if weighted_val:
            prob_results = self.weighted_random_choice(weighted_val)
        else:
            prob_results = None
        return prob_results

rawDescription: Multikey Multivalue Non Deterministic python dictionary


code:
from csv import DictWriter
out_fh = StringIO()
writer = DictWriter(fh, fieldnames=dr.fieldnames)
for mapping in dr:
    writer.write(dict((k, v) for k, v in mapping.items() if v != 'null'))

rawDescription: Python strings / match case

description: Python strings / match case


code: random_word = random.choice(lst)

rawDescription: Selecting a random value from a dictionary in python


code: Number_List[1:] = [x+1 for x in Number_List[1:]]

rawDescription: More elegant way for updating a slice of a list


code:
from itertools import islice
set.intersection(set(lis[0]), *islice(lis, 1, None))

rawDescription: get intersection of list of sets

description: Get intersection of list of sets


code:
import urllib
from bs4 import BeautifulSoup

url = 'http://python-data.dr-chuck.net/comments_213060.html'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tags = soup('span')
lst = [int(tag.text) for tag in tags]
print(sum(lst))

rawDescription: Python merge lists

description: Python merge lists


code:
print(x.nmbrMovies)
# 2

rawDescription: change the superclass of object in Python

description: Change the superclass of object in Python


code:
headers = getter(next(reader))

data = []
for row in reader:
    if row[1]=="7/1/2000" or row[1]=="7/1/2010":
        data.append(getter(row))

rawDescription: manipulating TSV file

description: Manipulating TSV file


code:
glob = "global"

class ClassName:
    name = "Class Name"

rawDescription: Per-class constants in Python

description: Per-class constants in Python


code:
import wx.lib.newevent
QuantityChangedEvent, EVT_QUANTITY_CHANGED = wx.lib.newevent.NewCommandEvent()

rawDescription: Generate a custom CommandEvent in wxPython


code:
items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
sorted_items = ["".join(sorted(item)) for item in items]

rawDescription: For loop - Sorting each character alphabetically within a list of words


rawDescription: python program to replicate the given matrix

description: Python program to replicate the given matrix


code:
@classmethod
def from_float(cls, p):
    return cls(p)

rawDescription: Can I let a superclass return reference to the "actual type"?

description: Let a superclass return reference to the "actual type"


code:
import multiprocessing, os, shutil, tempfile
processes=16

def example_function(i):
    with tempfile.TemporaryDirectory() as path:
        os.chdir(path)
        print(os.getcwd())
        return i*i

if __name__ == '__main__':
    #starting pool
    pool=multiprocessing.Pool(processes)

    result=pool.map(example_function,range(1000))

rawDescription: multiprocessing change current folder for every process

description: Multiprocessing change current folder for every process


code:
df = pd.concat([df1, df2]).fillna(0)
df

rawDescription: Merge two CSV's with unique columns in python


code:
import time
time.mktime(datetime(2010, 3, 17, 10, 1, 40).timetuple())

rawDescription: In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field?


rawDescription: Convert UTF-8 octets to unicode code points


code:
# Make copy of original image
cimg2 = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

# Find contours
contours,_ = cv2.findContours(255 - img, cv2.RETR_LIST, cv.CV_CHAIN_APPROX_NONE)

# Draw all detected contours on image in green with a thickness of 1 pixel
cv2.drawContours(cimg2, contours, -1, color=(0,255,0), thickness=1)

# Show the image
cv2.imshow('detected circles', cimg2)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Circular Hough Transform misses circles

description: Circular Hough Transform misses circles


code:
test[0]   #which is 1
test[1]   #which is 2
test[2]   #which is 5
test[3]   #which is 10

rawDescription: Python: list index out of range error; certain list elements work


code:
class MyClass(object):
    def __init__(self):
        #myClassObject= MyClass() # Causes recursion error.
        #myClassObject.greet() # You should not be accessing your instance method this way
        self.greet()

    def greet(self):
        print("stackoverflow is the best !!!")

if __name__ == '__main__':
    instance = MyClass()

rawDescription: print to console in PyDev

description: Print to console in PyDev


code:
class MyHelper:
    def __init__(self, label):
        self.mylabel = label

    def getter2(self, other):
        return other.mydict[self.mylabel]

    def setter2(self, other, value):
        other.mydict[self.mylabel] = value

def makeProperty(label):
    H = MyHelper(label)
    return property(H.getter2, H.setter2)

class MyClass:
    def __init__(self, d):
        self.mydict = d

    X = makeProperty('X')
    Y = makeProperty('Y')

rawDescription: Dynamic python properties

description: Dynamic python properties


rawDescription: How to write a return value of a function into new column of a pandas dataframe

description: Write a return value of a function into new column of a pandas dataframe


code:
X = np.array([range(5),range(5)])
Y = np.array([range(5), [2,3,4,1,0]])
output = np.zeros(X.shape)
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X

rawDescription: numpy 2D array assignment with 2D value and indices arrays

description: Numpy 2D array assignment with 2D value and indices arrays


rawDescription: Django URL Config - Match filename

description: Django URL Config - Match filename


code:
def main():
    def f(x):
        x[0] = input()
        return x[0]

    x = ['']
    print("Sin(" + f(x) + ")")

rawDescription: Input between print in python

description: Input between print in python


code:
def create_shape(key, **kwargs):
    if key == 'square':
        return square(**kwargs)
    elif key == 'triangle':
        return triangle(**kwargs)

rawDescription: Cascading optional parameters in Python

description: Cascading optional parameters in Python


code:
df.sort(['item_id', 'date'], inplace = True)

def sequence_id(item):
    item['seq_id'] = range(0,len(item)-1,1)
    return item

df_with_seq_id = df.groupby(['item_id']).apply(sequence_id)
df_with_seq_id.groupby(['seq_id']).agg(np.mean)

rawDescription: Indexing by row counts in a pandas dataframe


rawDescription: Getting name of attributes with Scrapy XPATH


code:
class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

rawDescription: Tkinter adding line number to text widget


code:
import glob
for myfilename in glob.glob("*.m3u"):
  with open(myfilename, 'r+b') as file1:
    text=""
    for lines in file1:
      text=text+lines
    a=text.replace("U:\Sync", "")
    file1.write(a)

rawDescription: Get python script to repeat for all files in a directory


code:
import hdf5storage
import numpy as np

matcontent = hdf5storage.loadmat('data.mat')
matcontent[u'some_numbers'] = np.array([10, 50, 20])
hdf5storage.savemat('data.mat', matcontent)

rawDescription: Adding a new variable to a .mat file using the Python package hdf5storage


code:
poller = PricePoller(heartbeat)
poller.start()

rawDescription: Calling While loop Function in __main__?

description: Calling While loop Function in __main__


code:
lines = open("file.txt", "r").readlines()
outfile = open("file.2txt", "w")
lines.sort(key=lambda x: x.split()[5], reverse=True)
for i in lines:
    outfile.write(i)

rawDescription: Write to a file

description: Write to a file


code: start_url = str(get_url())

rawDescription: Simple scrapy spider doesn't crawl

description: Simple scrapy spider doesn't crawl


code:
for line in fn:
    line_list = line.strip().split(";")
    main_list.append(line_list)
return main_list

rawDescription: Generating a list of tuples and using it


rawDescription: Python - find average for columns with unique matching value in nested list


code: splitted_result = ['/media/My', 'Passport/fileName1']

rawDescription: Splitting line on python

description: Splitting line on python


code:
"""
    :param client_class: A subclass of `oauthlib.oauth1.Client` to use with
                         `requests_oauthlib.OAuth1` instead of the default
"""

rawDescription: Setting HTTP User-Agent header with requests-oauthlib


code:
' '.join(x.encode('hex') for x in base64.urlsafe_b64decode("49ugdj9v_3290k3r902qkf9="))
'e3 db a0 76 3f 6f ff 7d bd d2 4d eb f7 4d aa 91 ff'

rawDescription: What is the R equivalent of python base64.urlsafe_b64decode(client_secret)?


code:
from django import forms
from models import Equipment

class EquipmentModelForm(forms.ModelForm):
    class Meta:
        model = Equipment

    def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        self.fields['equipment'].queryset = Equipment.avail.all()

rawDescription: How to filter filter_horizontal in Django admin?

description: Filter filter_horizontal in Django admin


code:
from matplotlib.backends.backend_pdf import PdfPages

def write_pdf(fname, figures):
    doc = PdfPages(fname)
    for fig in figures:
        fig.savefig(doc, format='pdf')
    doc.close()

def main():
    a = fig_barh(['a','b','c'], [1, 2, 3], 'Test #1')
    b = fig_barh(['x','y','z'], [5, 3, 1], 'Test #2')
    write_pdf('test.pdf', [a, b])

if __name__=="__main__":
    main()

rawDescription: How to assign a plot to a variable and use the variable as the return value in a Python function

description: Assign a plot to a variable and use the variable as the return value in a Python function


rawDescription: string to time with decimal seconds

description: String to time with decimal seconds


rawDescription: Python Regular Expression for splitting key/value pairs separated by an equal sign when a value may or may not have quotes


code:
d = {}
for key, val in list1:
    if key not in d:
        d[key] = []
    d[key].append(val)

rawDescription: Read list of lists and output as dictionary, the count of values per key


code: lines = [[l.split() for l in z] for z in lines]

rawDescription: Python List Modifying Directly

description: Python List Modifying Directly


code:
d = DemoConcrete(5)             # Succeeds by calling a concrete __init__()
d = DemoConcrete.from_int(5)    # Succeeds by calling a concrete from_int()
DemoABC()                       # Fails because from_int() is abstract
DemoABC.from_int(5)             # Fails because from_int() is not implemented

rawDescription: Python 2.7 Combine abc.abstractmethod and classmethod


code:
import sqlite3
import numpy as np
import itertools

my_arr = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
TableNameList = 't1', 't1', 't2', 't3'

conn = sqlite3.connect(':memory:')
c = conn.cursor()

c.execute('''CREATE TABLE t1 (c1, c2, c3)''')
c.execute('''CREATE TABLE t2 (c1, c2, c3)''')
c.execute('''CREATE TABLE t3 (c1, c2, c3)''')

## Insert a row of data
#c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

for table, values in itertools.izip(TableNameList, my_arr):
    c.execute("INSERT INTO %s VALUES (?, ?, ?)"%table, values)

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

rawDescription: python sqlite3 executemany using multiple lists

description: Python sqlite3 executemany using multiple lists


code:
writer = cv2.VideoWriter(filename="my_video.avi",  #Provide a file to write the video to
fourcc=cv.CV_FOURCC('i','Y', 'U', 'V'),            #Use whichever codec works for you...
fps=15,                                        #How many frames do you want to display per second in your video?
frameSize=(width, height))                     #The size of the frames you are writing

rawDescription: How do I use the FPS argument in cv2.VideoWriter?

description: Use the FPS argument in cv2.VideoWriter


code:
from ajax_select import LookupChannel
from django.utils.html import escape
from django.db.models import Q
from yourapp.models import *

class AlphaLookup(LookupChannel):

    model = Alpha

    def get_query(self,q,request):
        # The real query
        # Here the filter will select only non-submitted entries
        return Alpha.objects.filter(Q(name__icontains = q) & Q(submitted = false)).order_by('name')

    def get_result(self,obj):
        u""" result is the simple text that is the completion of what the person typed """
        return obj.name

    def format_match(self,obj):
        """ (HTML) formatted item for display in the dropdown """
        return escape(obj.name)

    def format_item_display(self,obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        return escape(obj.name)

rawDescription: configuring ajax lookup in django ajax_lookup

description: Configuring ajax lookup in django ajax_lookup


code:
# ...
self._filter = Filter()
# adjust for your QLineEdit
self.ui.lineEdit.installEventFilter(self._filter)

rawDescription: How to connect QLineEdit focusOutEvent

description: Connect QLineEdit focusOutEvent


code:
with open(file) as f:
    for line in f:
        line = line.rstrip('\n')
        outline = parse(line, regexA, 'A') or parse(line, regexB, 'B') or parse(line, regexC, 'C') or parse(line, regexD, 'D')
        if outline:
            anOutPutFile.write(outline)

rawDescription: Slow python parsing script

description: Slow python parsing script


code:
print('| ', end='')
for i in range(4):
    print(str(i) + ' | ', end='')

rawDescription: Assigning range of numbers to a letter in python


code:
import concurrent.futures as cf
import threading
import queue

NUM_CPUS = 3
NUM_THREADS = 4
MAX_QUEUE_SIZE = 20

# Runs in worker processes.
def producer(i):
    return i + 10

def consumer(i):
    global total
    # We need to protect this with a lock because
    # multiple threads in the main program can
    # execute this function simultaneously.
    with sumlock:
        total += i

# Runs in threads in main program.
def consume_results(q):
    while True:
        future = q.get()
        if future is None:
            break
        else:
            consumer(future.result())

if __name__ == "__main__":
    sumlock = threading.Lock()
    result_queue = queue.Queue(MAX_QUEUE_SIZE)
    total = 0
    NUM_TO_DO = 1000
    with cf.ThreadPoolExecutor(NUM_THREADS) as tp:
        # start the threads running `consume_results`
        for _ in range(NUM_THREADS):
            tp.submit(consume_results, result_queue)
        # start the worker processes
        with cf.ProcessPoolExecutor(NUM_CPUS) as pp:
            for i in range(NUM_TO_DO):
                # blocks until the queue size <= MAX_QUEUE_SIZE
                result_queue.put(pp.submit(producer, i))
        # tell threads we're done
        for _ in range(NUM_THREADS):
            result_queue.put(None)
    print("got", total, "expected", (10 + NUM_TO_DO + 9) * NUM_TO_DO // 2)

rawDescription: Concurrent.futures usage guide - a simple example of using both threading and processing


code: line.strip(' \n' '\r')

rawDescription: Class and Array Problems

description: Class and Array Problems


question: what is 2+2

answer: 4

question: what is the meaning of life?

answer: pizza

rawDescription: Pythonic way to import multiple dictionaries from text file


rawDescription: find the maximum occurrence of a string in value for all keys in a dictionary

description: Find the maximum occurrence of a string in value for all keys in a dictionary


code:
ind_y_good = np.where(iy>=0) and np.where(iy<ny)
ind_x_good = np.where(ix>=0) and np.where(ix<nx)

rawDescription: Shifting data in 2d array through shifted indices


code:
def all_but_one_letter():
    with open('dictionary.txt','r') as dictionary:
        user_string = input("Please enter a string of characters: ")
        for line in dictionary:
            words = line.rstrip().split() # split into individual words
            for word in words:
                st1 = set(user_string)
                if len(st1.intersection(word)) == len(st1) - 1:
                    print(word)

rawDescription: Finding words that contain all but one letter in string


code:
DEFAULT_ESCAPES = {
    'x': 'filters.xml_escape',
    'h': 'filters.html_escape',
    'u': 'filters.url_escape',
    'trim': 'filters.trim',
    'entity': 'filters.html_entities_escape',
    'unicode': 'unicode', # str in python 3
    'decode': 'decode',
    'str': 'str',
    'n': 'n'
}

rawDescription: Lookup escape filter method

description: Lookup escape filter method


rawDescription: Missed values when creating a dictionary with two values


rawDescription: Python: RE only captures first and last match


code:
def reverseDisplay(n):
    tmp = n % 10
    print(tmp, end="")
    if n == tmp:
        print()
        return tmp
    else:
        return int(str(tmp) + str(reverseDisplay(n // 10)))

rawDescription: I am using a recursive function and need to print from within the function just once


code:
import matplotlib.pyplot as plt

thing1 = (10, [8,9,10,11,12])
thing2 = (25, [24,25,26,27])
thing3 = (30, [28,29,30,31,32,33])

thing1_y = []
for i in thing1[1]:
    thing1_y.append(i)
thing1_x = []
for i in range(len(thing1_y)):
    thing1_x.append(thing1[0])

rawDescription: Chart with lots of (but varied number of) Y values for each X value


code:
mixed_fruit = Juice([Fruit("apple", 2), Fruit("banana", 3)])
mixed_fruit.sugar_content

rawDescription: Pythonic way of inheriting many classes?

description: Pythonic way of inheriting many classes


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

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


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("https://semantria.com/demo")

item = driver.find_element_by_css_selector("form#analyze_url_form input[name=link]")
item.send_keys("http://finance.yahoo.com/news/skystar-bio-pharmaceutical-company-provides-133000048.html" + "\n")

wait = WebDriverWait(driver, 30)

sentiment_value = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "strong.sentiment_score_value")))
print(sentiment_value.text)

rawDescription: Python: Selenium send_key not working

description: Python: Selenium send_key not working


code:
val
exec('val=math.sin(1)**2')
val

rawDescription: Executing mathematical user inputed statements as code in Python 3


rawDescription: Python list comparison to create trees

description: Python list comparison to create trees


code: result = [i+j[1:] for i in list1 for j in list2 if i[0]==j[0]]

rawDescription: Numpy, 1:M joins on Arrays

description: Numpy, 1:M joins on Arrays


code: ww.write("%-12s\t%s\n" % (a[each], b[each]))

rawDescription: writing to a text file with proper allign

description: Writing to a text file with proper allign


code:
from os import makedirs, path

def create_folder_structure():
    print('--- all your instructions ---')
    driveLetter = 'D'
    limaReference = 'lima'
    rootPath = driveLetter + ':/' + limaReference + '/'
    # build exhibits here
    targetPath = rootPath + 'CaseFile/XWays/'
    _create_directory(targetPath)
    targetPath = rootPath + 'CaseFile/Encase/Temp'
    _create_directory(targetPath)

def remove_folder():
    print("in remove_folder...")

def case_backup():
    print("in case_backup...")

def _create_directory(targetPath):
    print("in create_directory...")
    if not path.exists(targetPath):
        print('now we have to create the folder')
        # makedirs(targetPath)
    else:
        print('Path ' + targetPath + ' already exists, skipping...')

rawDescription: How can I call function from an imported module and then when i return to the original module use the text menu correctly?

description: Call function from an imported module and then when i return to the original module use the text menu correctly


rawDescription: Automatically mask np.ma array when item set equal to fill_value


rawDescription: Django-Execute function after Celery job completion


code:
for (i,t) in enumerate(turtles):
  t.goto(data[2*i],data[2*i+1])

rawDescription: Can I use a variable in this context?

description: Use a variable in this context


code: [vid(*tup) for tup in itertools.product([0,1,2,3], repeat = 3)]

rawDescription: Is it possible to use iterated values as method argument values?


code:
for s in preCompiledRegexList:
    if re.search(s, parsedOutTag.text):
        # checking inner layer tags for additional content
        break

rawDescription: accessing a conditional iterate in python

description: Accessing a conditional iterate in python


code: sum(numbers)

rawDescription: extracting numbers in a string

description: Extracting numbers in a string


rawDescription: Dataframe columns from Dataframe rows in Pandas


code:
data = """

test1

test2

Here CAPTCHA is a part of a sentence

test3
"""
soup = BeautifulSoup(data)
soup.find(text=lambda x: 'CAPTCHA' in x).parent

rawDescription: Beautifulsoup: How to find a string if tag or element not known?


code: self.hello = Button(text="hello", on_press=lambda a:self.auth())

rawDescription: Bind function to Kivy button

description: Bind function to Kivy button


code:
class FruitPie(object):
    def __init__(self, same_list):
        self.same_list = same_list

    def _run_pool(self, func):
        pool = mp.Pool(processes=8)
        pool.map(func, self.same_list)
        pool.close()

    def apple(self):
        self._run_pool(func1)

    def banana(self):
        self._run_pool(func2)

    def orange(self):
        self._run_pool(func3)

# use like this...
pie = FruitPie(same_list)
pie.apple()
pie.banana()
pie.orange()

rawDescription: Python : putting functions into classes

description: Python : putting functions into classes


code:
SortInputfile=open("InterpBerg1","r")
line=SortInputfile.readlines()
line.sort(key=lambda line: int(line.split()[0]))
map(SortOutputfile.write, line)

rawDescription: sorted() only sorting by first digit

description: Sorted() only sorting by first digit


code:
a = [{"Definition": ["Hello World."], "Fast": ["10"], "Free": ["Yes"], "Name": ["Hello"], "Movement": ["Fine"]}]
b = {a[0]['Name'][0]:a[0].copy()} # copy optional
b

rawDescription: How to set key value pair of json output in scrapy?

description: Set key value pair of json output in scrapy


code:
class User(db.Model):
    "usual properties like name, etc"

class Message(db.Model):

    # list of users that have this message
    users = db.ListProperty(db.Key)

rawDescription: AppEngine data strategy to handle a large index per user?


code:
revs = [str(n)[-1::-1] for n in nums]           # nums as reversed strings
dsum = lambda *ds: sum(int(d or 0) for d in ds) # str-digits -> their sum
sums = map(dsum, *revs)[-1::-1]                 # digit sums, in order
ones = [str(s % 10) for s in sums]              # last digits of the sums
res  = int(''.join(ones))                       # result: 3960

rawDescription: Add numbers without carrying

description: Add numbers without carrying


code:
def my_func_1(x, **kwargs):
    if kwargs.get('plus_3'):
        return my_func_2(x, **kwargs) + 3
    return my_func_2(x, **kwargs)

def my_func_2(x, **kwargs):
    #Imagine that the function did more work
    if kwargs.get('square'):
        return x ** 2
    # If you decided to add cube as a parameter
    # you only need to change the code here:
    if kwargs.get('cube'):
        return x ** 3
    return x

rawDescription: difference bewteen *args and **args in python?

description: Difference bewteen *args and **args in python


code:
#views.py
def normalize_query(query_string,
    findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
    normspace=re.compile(r'\s{2,}').sub):

    '''
    Splits the query string in invidual keywords, getting rid of unecessary spaces and grouping quoted words together.
    Example:
    >>> normalize_query('  some random  words "with   quotes  " and   spaces')
        ['some', 'random', 'words', 'with quotes', 'and', 'spaces']
    '''

    return [normspace('',(t[0] or t[1]).strip()) for t in findterms(query_string)]

def get_query(query_string, search_fields):

    '''
    Returns a query, that is a combination of Q objects.
    That combination aims to search keywords within a model by testing the given search fields.
    '''

    query = None # Query to search for every search term
    terms = normalize_query(query_string)
    for term in terms:
        or_query = None # Query to search for a given term in each field
        for field_name in search_fields:
            q = Q(**{"%s__icontains" % field_name: term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query

rawDescription: How can I make Django search in multiple fields using QuerySets and MySql "Full Text Search"?

description: Make Django search in multiple fields using QuerySets and MySql "Full Text Search"


code: cache = Cache(config={'CACHE_TYPE': 'simple'})

rawDescription: Using Flask-Cache to cache a lxml.html object


code:
url = 'http://view.example.com/candidates'
cand_id = input("Enter a candidate id: ")
new_url = "{}/{}".format(url, cand_id)

rawDescription: How to embed "input(id)" into URL in GET request using Python?

description: Embed "input(id)" into URL in GET request using Python


code:
views.py
def Admin_add(request):
    if request.method == "POST":
        form = AdminSetup(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            group_name = request.POST.get('group_name')
            g = Group.objects.get(name=group_name)
            g.user_set.add(user)
            post.save()
            return redirect('admin_add.html', pk=post.pk)
    else:
        form = AdminSetup()
        groups = Group.objects.all()
    return render(request,'admin_add.html', {'form': form, 'groups': groups}, context_instance= RequestContext(request))

rawDescription: Django get User Group in template

description: Django get User Group in template


code:
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")

x = range(100)
y = [i**2 for i in x]
proxy.plot('/tmp/test.png', x, y)

rawDescription: Standard ASCII File Format For Plotting from Matplotlib


rawDescription: Using 2 Python Arrays

description: Using 2 Python Arrays


code:
from __future__ import print_function
import re
#NDoc = raw_input("Enter name of to-be-made document")
#log = open("C:\Users\XYZ\Desktop\Python\NDoc.txt", "w")
#Need help with this^ How do I make new file instead of opening a file?

#nl = list()
#file = raw_input("Enter a file to be sorted")
xfile = open("file")

line = xfile.read()
l=line.strip()
l=re.sub("\n","",l)
n=re.sub("(\B)(?=((MTH|SCN|ENG|HST)[|]))","\n\n",l)
print(n)

rawDescription: RegEx Python Find and Print to a new document


code: [].__hash__ = lambda x: 0

rawDescription: How to use a list of strings [which may contain any character] as keys?

description: Use a list of strings [which may contain any character] as keys


code:
client = input("What is your Client ID. CaSe SeNsItIvE")
file = open("clientIntensity.txt" , "r")
for line in file:
    if client in line:
        print(line[5:13])
        break

rawDescription: Reading from a .txt file and making conditions from it


code: dummy = [ ('./name[@val="1"]/Output' + str(i) ) for i in xrange(0,5)]

rawDescription: list of strings differ by suffix

description: List of strings differ by suffix


code:
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """

rawDescription: Docstrings - one line vs multiple line

description: Docstrings - one line vs multiple line


code:
class Wrapper:
    def __init__(self, value):
        self.__dict__['value'] = value

    def __setattr__(self, name, value):
        setattr(self.value, name, value)

rawDescription: Clean way to disable `__setattr__` until after initialization


code:
def Union(L):
    b = []
    [b.append(x) for c in L for x in c if x not in b]
    return set(b)

rawDescription: intersection of multiple sets in a list

description: Intersection of multiple sets in a list


rawDescription: choose numbers of different lengths

description: Choose numbers of different lengths


code:
areatable = soup.find('table',{'id':'codes'})
d = {}
def chunks(l, n):
    return [l[i:i+n] for i in range(0, len(l), n)]
dict(chunks([i.text for i in areatable.findAll('td')], 2))

rawDescription: Extracting data in table using BeautifulSoup


code:
All = []
Class1 = {"name":"A","score":[60,70,80]}
Class2 = {"naem":"B","score":[70,80,90]}
All.extend(Class1['score'])
All.extend(Class2['score'])
print(All)

rawDescription: How to put the element of a list to another list directly?

description: Put the element of a list to another list directly


code:
def show_description(self,desired_item_id):
    for i in range(self.item_info_model.rowCount()):
        if self.item_info_model.record(i).value(0) == desired_item_id:  # the field can be defined by position or by name
            self.item_info_mapper.setCurrentIndex(i)
            break

rawDescription: QDataWidgetMapper-find index for sqlite database row in pyqt


code:
def setUserData(user, form):
    user.name = form.name.data
    user.username = form.username.data
    user.password = form.password.data
    user.email = form.email.data

rawDescription: Is there a better way to write these in python?


code:
#!/usr/bin/env python
from datetime import datetime

def in_between(now, start, end):
    if start < end: # e.g., "07:00-23:00"
        return start <= now < end
    elif end < start: # e.g., "23:00-07:00"
        return start <= now or now < end
    else: # start == end
        return True # consider it 24 hour interval

now = datetime.now().time()
for date_range in ["07:00-23:00", "23:00-07:00"]:
    start, end = [datetime.strptime(s, "%H:%M").time()
                  for s in date_range.split("-")]
    not_ = '' if in_between(now, start, end) else 'not '
    print("{now:%H:%M} is {not_}in between {date_range}".format(**vars()))

rawDescription: python time range validator

description: Python time range validator


code:
updater.py
import os
import shutil

# Imported for convenience
from collections import namedtuple

# Main function, so this can act like a script
if __name__ == '__main__':
    ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))  # Root directory

    file_change_times_dest = []  # List of files from destination folder
    file_change_times_src = []  # List of files from source folder

    # Nameed tuple to ease writing code
    FileInformation = namedtuple('FileInformation', ['file_path', 'file_name', 'last_modified'])

    # Loop through files in destination folder to collect information
    for dirpath, dirs, files in os.walk(os.path.join(ROOT_DIR, 'dest')):
        for file in files:
            # getting file path
            file_path = os.path.join(dirpath, file)
            # getting file change info and casting it to FileInformation type
            file_change_times_dest.append(FileInformation(file_path, file, os.stat(file_path).st_mtime))

    # Loop through source folder, same logic
    for dirpath, dirs, files in os.walk(os.path.join(ROOT_DIR, 'src')):
        for file in files:
            file_path = os.path.join(dirpath, file)
            file_change_times_src.append(FileInformation(file_path, file,os.stat(file_path).st_mtime))

    # Comparing the two, using Zip to combine the two lists into a tuple
    for file_comp in zip(file_change_times_dest, file_change_times_src):

        # Settings variables for 0 and 1 to make writing code easier
        _DEST = 0
        _SRC = 1

        # File comparison, to see if file name is the same, since we want to update
        if file_comp[_SRC].file_name == file_comp[_DEST].file_name:
            # If the last modified is greater for source, then we copy
            if file_comp[_SRC].last_modified > file_comp[_DEST].last_modified:
                shutil.copy(file_comp[_SRC].file_path, file_comp[_DEST].file_path)
                print("File moved")  # Just for checking

rawDescription: python - how to move only updated files from folder to folder?

description: Python - how to move only updated files from folder to folder


code:
def f():
  return f.v

rawDescription: Python dynamic function attribute

description: Python dynamic function attribute


code:
l = ['2,alex', '5,james', '3,ben']
l.sort(key=lambda x: x.split(',')[1])
l

rawDescription: Python: Alphabetically sorting a list with letters and numbers in


code:
import os
import crypt

password ="testpassword"
encPass = crypt.crypt(Password,"salt")
os.system("useradd -p "+encPass+" someuser ")

rawDescription: How to create linux users via my own GUI application in Python?

description: Create linux users via my own GUI application in Python


code:
code = re.sub('(define MY_STRING\s+)0', "\\1 1", code);
## \\1 is the captured group on regex inside (...)

rawDescription: How to substitute a numeric value in a string using Python?

description: Substitute a numeric value in a string using Python


rawDescription: Numpy extract submatrix

description: Numpy extract submatrix


code:
a=[]
for element in i["counts"]:
    a.append(element["total"])

rawDescription: Colouring the area under curve of plotted list


code:
add_check = re.match(r'add (.+)', message)
if add_check:
    print(add_check.group(1))
else:
    del_check = re.match(r'del (.+)', message)
    if del_check:
        print(del_check.group(1))
    else:
        print("bar")

rawDescription: save re.match in variable to use after elif

description: Save re.match in variable to use after elif


rawDescription: Python create instance from list of classes