code:
from tkinter import *
import tkinter.simpledialog as simpledialog

def add_users():
    n = simpledialog.askinteger('', 'How many users are you going to put in?', initialvalue=1, minvalue=1, maxvalue=10)
    if not n: # 'Cancel'
        return
    for i in range(n):
        user = simpledialog.askstring('', 'User #%s from #%s' % (i+1, n))
        if user is None: # 'Cancel'
            return
        # Do something useful
        print(user)

root = Tk()
Button(root, text='Add users', command=add_users).pack(padx=50, pady=50)
Button(root, text='Quit', command=root.destroy).pack(pady=30)
root.mainloop()

rawDescription: Get the same input multiple times in python tkinter?


code:
def f(*args, **kw): return (args, kw)

f('foo', 'bar', spam='eggs', monty='python')

rawDescription: Is there a standard Python function that takes any number of arguments and does nothing?


code:
from pyspark.sql.functions import col, lit, size
from functools import reduce
from operator import and_

def array_equal(c, an_array):
    same_size = size(c) == len(an_array)  # Check if the same size
    # Check if all items equal
    same_items = reduce(
        and_,
        (c.getItem(i) == an_array[i] for i in range(len(an_array)))
    )
    return and_(same_size, same_items)

rawDescription: Filter by whether column value equals a list in spark


code:
import win32com.client
app = win32com.client.Dispatch("Excel.Application")
sheet = app.ActiveSheet

# rang is an object representing the cells A1, A2, A3
rang = sheet.Range("A1","A3")

# names is a tuple of length 3 containing tuples of length 2
names = rang.Value

#nameLst is a list of all values in names
nameLst = [name[0] for name in names]

rawDescription: In excel with python, how do you find words, from an entire column, in a cell containing multiple words?


rawDescription: Convert triplets to matrix/dataframe in python


code: set(x for x in [1, 2, 3])

rawDescription: Python: what does a comprehension in a set() mean?


rawDescription: Help on my django models for my shoe review website


code:
class MyClass(object):

    def __init__(self):
        self.data = {'a': 'v1', 'b': 'v2'}

    def __getattr__(self, attr):
        return self.data[attr]

rawDescription: Python: how to implement __getattr__()?

description: Python: how to implement __getattr__()


rawDescription: Pandas accessing last non-null value

description: Pandas accessing last non-null value


code:
import zlib

def stream_gzip_decompress(stream):
    dec = zlib.decompressobj(32 + zlib.MAX_WBITS)  # offset 32 to skip the header
    for chunk in stream:
        rv = dec.decompress(chunk)
        if rv:
            yield rv

rawDescription: Python unzipping stream of bytes?

description: Python unzipping stream of bytes


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

def unrank(S, k, i):
    n = len(S)
    nb = factorial(n) // factorial(n-k)
    if i >= nb:
        raise IndexError
    res = []
    while k > 0:
        nb = nb // n
        pos = i // nb   # the factoradic digits
        i = i % nb      # the remaining digits
        res.append(S[pos])
        del S[pos]
        k = k-1
        n = n-1
    return res

rawDescription: Computing the nth 6 character permutation of an alphabet


rawDescription: Proper way to bulk update with different IDs in Django


code:
self.__dict__.update((key, kwargs[key])
                     for key in ('log', 'bin', 'pid', 'conf')
                     if key in kwargs)

rawDescription: kwargs parsing best practice

description: Kwargs parsing best practice


code:
arr = np.genfromtxt(input_file, delimiter=';', dtype=np.float64)
arr

rawDescription: Read data with NAs into python and calculate mean row-wise


code:
import io

with io.open(fn, 'rt', newline='') as f:
    lines = f.readlines()

rawDescription: Python, read CRLF text file as is, with CRLF


code:
# Five failed attempts
for attempt in range(5):
    password = input("Password: ")
    if password == "changeme":
        print("Thou Shall Pass Into Mordor")
        break
else:
    print("Thou Shall Not Pass Into Mordor")

# Successful attempt after one failure
for attempt in range(5):
    password = input("Password: ")
    if password == "changeme":
        print("Thou Shall Pass Into Mordor")
        break
else:
    print("Thou Shall Not Pass Into Mordor")

rawDescription: Need help putting the else into the while with a counter


code:
commands = [
    Install(),
    Remove(),
]
def main():
    parser= optparse.OptionParser()
    for c in commands:
        c.setup_opts( parser )
    options, args = parser.parse()
    command= None
    for c in commands:
        if c.name.startswith(args[0].lower()):
            command= c
            break
    if command:
        status= command.execute( context, options, args[1:] )
    else:
        logger.error( "Command %r is unknown", args[0] )
        status= 2
    sys.exit( status )

rawDescription: command line arg parsing through introspection

description: Command line arg parsing through introspection


code:
# part2.py

def scream():
 print(sound)

# part1.py
import part2

if __name__=="__main__":
    part2.sound = "Yoooo"
    part2.scream()

#Output:
Yoooo

rawDescription: Python 3.x.x one variable spread across multiple .py files


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

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def index():
  return render_template('football.html')

@app.route('/bpl/')
def bplLink():
  teamName = ['AFC Bournemouth', 'Arsenal', 'Aston Villa', 'Chelsea',
  'Crystal Palace', 'Everton', 'Leicester City', 'Liverpool', 'Manchester City',
  'Manchester United', 'Newcastle United', 'Norwich City', 'Southampton',
  'Stoke City', 'Sunderland', 'Swansea City', 'Tottenham Hotspur',
  'Watford', 'West Bromwich Albion', 'West Ham United']
  return render_template('bplteams.html', teamName=teamName)

@app.route('/bpl/<team>')
def team(team):
  index = int(request.args.get('index', 0))
  stadium = ['Dean Court', 'Emirates Stadium', 'Villa Park', 'Stamford Bridge',
  'Selhurst Park', 'Goodison Park', 'King Power Stadium', 'Anfield',
  'Etihad Stadium', 'Old Trafford', 'St James Park', 'Carrow Road',
  'St Marys Stadium', 'Britannia Stadium', 'Stadium of Light',
  'Liberty Stadium', 'White Hart Lane', 'Vicarage Road', 'The Hawthorns',
  'Boleyn Ground']
  badge = ['bournemouth.png', 'arsenal.png', 'aston-villa.png', 'chelsea.png',
  'crystal-palace.png', 'everton.png', 'leicester.png', 'liverpool',
  'man-city.png', 'man-united.png', 'newcastle.png', 'norwich.png',
  'southampton.png', 'stoke.png', 'sunderland.png', 'swansea.png',
  'tottenham.png', 'watford.png', 'west-brom.png', 'west-ham.png']
  capacity = ['11,464', '60,260', '42,660', '41,798', '25,073', '39,571',
  '32,312', '44,742', '55,097', '75,653', '52,338', '27,010', '32,505',
  '27,740', '48,707', '20,909', '36,284', '21,500', '26,850', '35,345']
  manager = ['Eddie Howe', 'Arsene Wenger', 'Kevin MacDonald (caretaker)',
  'Jose Mourinho', 'Alan Pardew', 'Roberto Martinez', 'Claudio Ranieri',
  'Jurgen Klopp', 'Manuel Pellegrini', 'Louis van Gaal', 'Steve McClaren',
  'Alex Neil', 'Ronald Koeman', 'Mark Hughes', 'Sam Allardyce', 'Garry Monk',
  'Mauricio Pochettino', 'Quique Flores', 'Tony Pulis', 'Slaven Bilic']
  nickname = ['Cherries', 'Gunners', 'Villans', 'Blues', 'Eagles', 'Toffees',
  'Foxes', 'Reds', 'City', 'Red Devils', 'Magpies', 'Canaries', 'Saints',
  'Potters', 'Black Cats', 'Swans', 'Spurs', 'Hornets', 'Baggies', 'Irons']
  return render_template('details.html', team=team, stadium=stadium,
                         badge=badge, capacity=capacity, manager=manager,
                         nickname=nickname, index=index)

rawDescription: Linking multiple lists in flask

description: Linking multiple lists in flask


code: args = Namespace(bar=12, foo='ha', lol='huhu', rofl='haha')

rawDescription: argparse - Arbitrary optional arguments

description: Argparse - Arbitrary optional arguments


code:
#just use all the imports/locals from __init__.py as if they already existed
#this will be hellish if you use an IDE that checks for errors for you
class Model1(Base):
      id = Column(Integer,primary_key=True)
      ...

rawDescription: common import statement for similar classes

description: Common import statement for similar classes


code: ( len( set( a ) ) == len( a ) == max( a ) ) and min( a ) == 1

rawDescription: How to check whether elements appears in the list only once in python?

description: Check whether elements appears in the list only once in python


code:
def minimum(pNum1, pNum2):
    if pNum1 < pNum2:
        return pNum1
    else:
        return pNum2

rawDescription: Implementation of a function that finds the minimum of two values


code:
f = fred()
f.method()
f.method(2)
f.method(2, b=3)
f.method(5, b=None)
f.method(2, b=3, c=19)
help(f.method)

rawDescription: Pythonic way of getting method arguments into a dict


code:
class Foo:
    def __init__(self, value=0):
        self.value = value
    def __hash__(self):
        return self.value
    def __eq__(self, other):
        return isinstance(other, Foo) and self.value == other.value

rawDescription: What is the correct way to implement a set that checks type in the add method in python 2.7?


code:
s = "sin( 1 + 2 * x ) + tan( 2.123 * x "
import tokenize
from StringIO import StringIO
tokenize.tokenize(StringIO(s).readline)

rawDescription: Tokenize a mathematical expression in Python


code:
def __iter__(self):
   return node_depth_first_iter(self)

rawDescription: Implementing a depth-first tree iterator in Python


code:
devices = usb.core.find(find_all=1, backend=libusb1.get_backend() )
devices = usb.core.find(find_all=1, backend=libusb0.get_backend() )
devices = usb.core.find(find_all=1, backend=openusb.get_backend() )

rawDescription: How do I switch backends in libusb for python?

description: Switch backends in libusb for python


code:
c = tornadoredis.Client()
c.connect()

def on_set(result):
    log.debug("set result: %s" % result)

c.set('foo', 'Lorem ipsum #1', on_set)
c.set('bar', 'Lorem ipsum #2', on_set)
c.set('zar', 'Lorem ipsum #3', on_set)

rawDescription: how to do asynchronous writes to redis in tornado

description: Do asynchronous writes to redis in tornado


code:
success = {k:(v if v in data.get(k, []) else '') for (k,v) in client_order.items()}
success

rawDescription: Comparing the keys and values of multiple dictionaries using python


rawDescription: Grouping tuple columns so their sum is less than 1


rawDescription: How to connect the list to get ip address with port?

description: Connect the list to get ip address with port


code:
def mylist():
    for i in range(5):
        elem = myobject(i)
        yield elem

rawDescription: iterate over a list as iterator in python

description: Iterate over a list as iterator in python


code: z = map(int, x[0].split(", "))

rawDescription: Python - Convert String into Iterable Integer List


code:
import re
data1 = []
data2 = []
data3 = []
data4 = []
data5 = []
data6 = []
text="The most affordable prices\nD&G,Chanel,Hermes,Miu Miu,Balmain,Dior\nDelivery 2 weeks\n✈Woldwide shipping\n+16166350689; +998909729723"
pattern=r'(?i)([\w.]+@[\w.]+)|(?:(?:\b|[,/]\s*)(?:whatsapp|whats app|viber|wechat|we/chat))+\b\s*[:：]?\s*([()+\d -]+)|\bline(?:\sid)?\s*(?:[:：]\s*)?(@\w+)|((?:\+\d+)?[ -]?(?:\(\d+\)[ -]?)?[\d -]{6,}\d)'
if re.search(pattern, text):
    for mobj in re.finditer(pattern,text):
        if mobj.group(1):
            data1.append(mobj.group(1))
        else:
            if 'N/A' not in data1:
                data1.append('N/A')
        if mobj.group(2):
            t= mobj.group().lower()
            if 'whatsapp' in t:
                data2.append(mobj.group(2))
            if 'viber' in t:
                data3.append(mobj.group(2))
            if 'wechat' in t:
                data4.append(mobj.group(2))
            if 'whats app' in t:
                data2.append(mobj.group(2))
            if 'we/chat' in t:
                data4.append(mobj.group(2))
            else:
                if 'N/A' not in data2:
                    data2.append('N/A')
                if 'N/A' not in data3:
                    data3.append('N/A')
                if 'N/A' not in data4:
                    data4.append('N/A')
            if mobj.group(3):
                data5.append(mobj.group(3))
            else:
                if 'N/A' not in data5:
                    data5.append('N/A')
            if mobj.group(4):
                data6.append(mobj.group(4))
                print(data6)
            else:
                if 'N/A' not in data6:
                    data6.append('N/A')
print(data1)
print(data2)
print(data3)
print(data4)
print(data5)
print(data6)

rawDescription: how does the re.finditer loop work?

description: How does the re.finditer loop work


rawDescription: numerical sort a column containing numbers and strings (pandas/python)

description: Numerical sort a column containing numbers and strings (pandas/python)


rawDescription: Is it safe to make an old-style class into a new-style class using Multiple Inheritance?


code:
def num_check(n, min, max):
    n = int(n)
    if n < 1:
        return False
    if n in range(min, max+1):
        return True
    return False

rawDescription: checking if a string input lies between a range

description: Checking if a string input lies between a range


code: [('Mainsection1', '\nSome text here\n===Subsection1.1===\nOther text here\n\n'), ('Mainsection2', '\nText goes here\n===Subsecttion2.1===\nOther text goes here. ')]

rawDescription: python regex mediawiki section parsing

description: Python regex mediawiki section parsing


code:
from keyword import kwlist

def bad_name(name):
    return name in dir(__builtins__) + kwlist

rawDescription: Comprehensive overview of strings I should NOT use for local variables?


rawDescription: Extend and forward fill numpy array

description: Extend and forward fill numpy array


code:
from kivy.metrics import dp
Button(size_hint_y=None, height=dp(50))

rawDescription: Size_hint and pos_hint of kivy not working when adding buttons programmatically in python


code:
b_reader = []

for row in a_reader():
    trueOrFalse = point_in_polygon(float(row[2]), float(row[1]),polygon)
    if trueOrFalse == True:
        trueNum = trueNum + 1
        b_reader.append( row.append('Inside'))
    else:
        falseNum = falseNum + 1
        b_reader.append( row.append('Outside'))

rawDescription: Append new column to csv after reading and outputting true or false


code:
def is_boid_colliding_with_obstacles(self, boid):
    return any(colliding(boid.pos[0], boid.pos[1], boid.radius,
                         obstacle[0][0], obstacle[0][1], obstacle[1])
               for obstacle in self.obstacles)

def create_boid(self):
    while True:
        boid = Boid(random.randint(self.region[0], self.region[2]),
                    random.randint(self.region[1], self.region[3]))
        if not self.is_boid_colliding_with_obstacles(boid):
            return boid

def create_boids(self):
    self.boids.extend(self.create_boid() for _ in range(self.flock_number))

rawDescription: Checking all items in a list simultaneously in Python


rawDescription: Copy all values in a column to a new column in a pandas dataframe


code:
def some_calculation(a_dict):
    # MATH!
    return {'new_key': a_number}

rawDescription: Trouble with Flask Requests - returns GET before any actions


code: lookup = {v:i for i,v in enumerate(step1,1)}

rawDescription: Python reduce a list by order

description: Python reduce a list by order


code:
df = pd.DataFrame(np.random.random_integers(1,200,135), columns=['heights'])
bins = np.linspace(df.heights.min(), df.heights.max(), 21)
grp = df.groupby(np.digitize(df.heights, bins))
sizes = grp.size()

def f(vals, max):
    sum = 0
    group = 1
    for v in vals:
        sum += v
        if sum <= max:
            yield group
        else:
            group +=1
            sum = v
            yield group

#I've changed 6 by 30 for the example cause I don't have your original dataset
grp.size().groupby([g for g in f(sizes, 30)])

rawDescription: Binning values into groups with a minimum size using pandas


code: soFar[index] = char

rawDescription: use .replace() on only one character of a string with repetitive characters

description: Use .replace() on only one character of a string with repetitive characters


code:
mode_function2([1, 2, 2])
mode_function2([1, 2, 2, 1])
mode_function2([1, 2, 3])

rawDescription: Finding multiple modes in a tuple list - python


rawDescription: python 3.4 multiprocessing does not work with unittest

description: Python 3.4 multiprocessing does not work with unittest


code:
from lxml import etree
tree = etree.parse('xmlfile')
for tag in tree.iter():
    if not len(tag):
        print (tag.tag, tag.text)

rawDescription: python lxml loop through all tags

description: Python lxml loop through all tags


code:
from collections import OrderedDict
orig = [(1,2),(1,3),(2,3),(3,3)]
new = list(OrderedDict(orig[::-1]).items())[::-1]

rawDescription: Most pythonic way to remove tuples from a list if first element is a duplicate


code:
path = 'C:/Python27/aisources/'
sfile = raw_input("What is your filename to check? ")
if os.path.exists(os.path.join(path,sfile)):   #-->sfile is user input to check file present / not
     with open(os.path.join(path,sfile),'r') as f:
         print('its present')
else:
    print('not there')

rawDescription: access all files in a directory

description: Access all files in a directory


code:
questor = open(questfile,'wb')
q = pickle.dump(nodes,questor)

rawDescription: Saving dict with nested class instances in Python 2.7


code:
import re

VOWELS = "aeiou"
RE_VOWEL = re.compile("[%s]" % VOWELS)

def helper(parts):
    if len(parts) == 1:
        yield parts[0]
    else:
        for vowel in VOWELS:
            for item in helper([vowel.join(parts[:2])] + parts[2:]):
                yield item

def vowels(word):
    parts = re.split(RE_VOWEL, word)
    return list(helper(parts))

rawDescription: Finding all combinations of vowel replacements


code:
categories_opt = parser.add_option(..., nargs=4)

# ...

if not options.categories:
    options.categories = [raw_input('Enter input: ') for _ in range(categories_opt.nargs)]

rawDescription: how to access nargs of optparse-add_action?

description: Access nargs of optparse-add_action


rawDescription: Two Raspberries communicating each other


rawDescription: Nested regular expression

description: Nested regular expression


code: {(frozenset(item)) for item in a}

rawDescription: Assert list of list equality without order in Python


code:
import Image
from subprocess import Popen, PIPE

fps, duration = 24, 100
p = Popen(['ffmpeg', '-y', '-f', 'image2pipe', '-vcodec', 'mjpeg', '-r', '24', '-i', '-', '-vcodec', 'mpeg4', '-qscale', '5', '-r', '24', 'video.avi'], stdin=PIPE)
for i in range(fps * duration):
    im = Image.new("RGB", (300, 300), (i, 1, 1))
    im.save(p.stdin, 'JPEG')
p.stdin.close()
p.wait()

rawDescription: Can you "stream" images to ffmpeg to construct a video, instead of saving them to disk?


code: request.session.get('account', None)

rawDescription: Persisting user selected data in Django application


rawDescription: Python nltk: Find collocations without dot-separated words


code:
def get_queryset(self, request):
    qs = self.model._default_manager.get_queryset()
    order = ['yes', 'no', 'not_sure']
    return sorted(qs, key=lambda x: order.index(x.status))

rawDescription: Sort a Django queryset based on the values in the choice field


code:
def f(row):
    return "c{}n{}".format(row["condition"], row["no"])

dfTrials["r3"] = dfTrials.apply(f, axis=1)
dfTrials

rawDescription: Edit pandas dataframe row-by-row

description: Edit pandas dataframe row-by-row


code:
import pandas as pd
import json
import os

os.chdir('/Users/nicolas/Downloads')

# Reading the json as a dict
with open('json_example.json') as json_data:
    data = json.load(json_data)

# using the from_dict load function. Note that the 'orient' parameter
#is not using the default value (or it will give the same error than you had)
# We transpose the resulting df and set index column as its index to get this result
pd.DataFrame.from_dict(data, orient='index').T.set_index('index')

rawDescription: How to read a json-dictionary type file with pandas?

description: Read a json-dictionary type file with pandas


rawDescription: Writing both float and integer on a text file from one numpy array


code:
def awesome(input_string):
    functions_dict = {
        ('AB', 'CD', 'EF'): do_something,
        ('12', '34', '56'): do_something_else,
        ('!@', '@#', '#$'): do_another_thing
    }
    for sub_strings, function in functions_dict.items():
        if any(s in input_string for s in sub_strings):
            x = function() + complicated_thing()
            return x + ("Hello" if some_condition(x) else "World")

rawDescription: What's the most pythonic way (if any) to refactor these nested for/else loops?


rawDescription: Python - best way to set a column in a 2d array to a specific value


code:
#!/usr/bin/env python
import unittest
import sys
import os

unit_dir = sys.argv[1] if len(sys.argv) > 1 else '.'
os.chdir(unit_dir)
suite = unittest.TestSuite()
for filename in os.listdir('.'):
    if filename.endswith('.py') and filename.startswith('test_'):
        modname = filename[:-2]
        module = __import__(modname)
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: Running Tests From a Module

description: Running Tests From a Module


code:
e = ["2311","1441","31","233122"]
r = ["asasa2311","dadewr1441","app"]
[eelem for relem in r for eelem in e if relem.endswith(eelem)]

rawDescription: Cross Matching in python

description: Cross Matching in python


code:
words = line.split()
key = words[0]
a_objects[key] = A(words)

rawDescription: How to create objects for a class automatically?

description: Create objects for a class automatically


code:
n=nodes[:,0].astype(int)
n

rawDescription: Python - Replace data of an array by 2 values of a second array


rawDescription: How to merge and convert list of tuples to Dict

description: Merge and convert list of tuples to Dict


code:
from collections import defaultdict
d = defaultdict(list)
for item in my_list:
    d[item].append(whatever_value)

rawDescription: How do I create a dictionary with keys from a list and values separate empty lists?

description: Create a dictionary with keys from a list and values separate empty lists


code:
def PositiveValuedProperty():
    def getter(obj):
        return obj.__value

    def setter(obj, new_value):
        if new_value < 1:
            new_value = 1
        obj.__value = new_value

    return property(getter, setter)

rawDescription: Python 3.4 - How to create a template property for many classes


code:
import csv
print([l for l in csv.reader(open("file.csv"), delimiter=',') if 'DEFAULT' not in l])

rawDescription: How do I put lines into a list from CSV using python

description: Put lines into a list from CSV using python


rawDescription: How to put timedelta in django model?

description: Put timedelta in django model


rawDescription: Get index where both rows are not NaN

description: Get index where both rows are not NaN


code:
from __future__ import print_function

import re
import operator
import collections
import pprint as pp

importance = {
    'CRITICAL': 0,
    'ERROR': 100,
    'INFO': 200,
    'DEBUG': 300
}

with open('log.log', 'r') as f:
    data = f.read().splitlines()

parsed = collections.OrderedDict()

for line in data:
    cols = re.split(r'\s+\-\s+', line)
    parsed[cols[2]] = importance[cols[0]]

for k,v in sorted(parsed.items(), key=operator.itemgetter(1)):
    print(k)

rawDescription: Sort strings by splitted words

description: Sort strings by splitted words


code:
total_size(k)  #from recursive sizeof recipe
sum(y.__sizeof__() for x in k for y in x)

rawDescription: Approximately how much memory would a list of 80000 items consume in python?


rawDescription: Variable Datetime Records and how to convert all into one format


code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from itertools import groupby

alpha_grades = ('A','B','C','D','E','F','G')

color_scheme = {'A':'b','B':'g','C':'r','D':'c','E':'m','F':'y','G':'k'}

fig1, ax1 = plt.subplots(figsize=(12,9)) # same as plt.subplots(1, 1)
fig2, ax2 = plt.subplots(figsize=(12,9))

for term, ax in zip([36,60], [ax1, ax2]):
    ax.hold(True)
    for grade, color in color_scheme.items():
        df2 = df[(df['grade'] == grade) & (df['term']==term)]
        df3 = groupby('issue_date')['ROI'].mean()
        df3.plot(ax=ax, color=color,
                 label=("Grade: %s" % grade))
    ax.hold(False)
    ax.legend(loc=2)
    ax.set_title("%i Mo Lending Rate by Rating" % term)

fig1.show()
fig2.show()

rawDescription: Two graphs, two axis, one figure....stumped.


code:
def get_path(data, section_id):
    path = []
    while section_id is not None:
        section = next(s for s in data["sections"] if s["id"] == section_id)
        path.append(section["name"])
        section_id = section["parent_id"]
    return ", ".join(path)

rawDescription: Creating a hierarchy path from JSON

description: Creating a hierarchy path from JSON


rawDescription: Python -- Search Subsrtring Full Word(s)


code:
from collections import Counter
c = Counter(items + elems)
print(c.most_common()[-1][0]) # b

rawDescription: Python: Find the list element that is contained least times in another list


code:
import pandas as pd
import io
data = io.BytesIO("""    ID RT
0  foo  1
1  foo  2
2  bar  3
3  bar  4
4  foo  1
5  foo  2
6  bar  3
7  bar  4
8  bar  4""")

df = pd.read_csv(data, delim_whitespace=True)
df.groupby("ID").RT.apply(pd.Series.reset_index, drop=True).unstack()

rawDescription: make 2d array from pandas dataframe

description: Make 2d array from pandas dataframe


code:
def createEditor(self, parent, option, index):
    editor = QComboBox(parent)
    li = []
    li.append("closed")
    li.append("expired")
    li.append("cancelled")
    li.append("waiting")
    editor.addItems(li)
    return editor

rawDescription: How to restore the index of a QComboBox delegate in a QTableView?

description: Restore the index of a QComboBox delegate in a QTableView


code:
LR_Multi = LinearRegression_Multi()
LR_Multi.fit(X_stack[:,:half], y_stack[:,:half])
y_stack_pred = LR_Multi.predict(X_stack[:,half:])
R2 = LR_Multi.scores(y_stack_pred, y_stack[:,half:])

rawDescription: How to solve several independent time series at the same time using scikit linear regression model

description: Solve several independent time series at the same time using scikit linear regression model


rawDescription: Digit Sum in Python with user input

description: Digit Sum in Python with user input


code: data = list(csv.reader(f))

rawDescription: any() function with csv file in python not behaving how I'm expecting it to

description: Any() function with csv file in python not behaving how I'm expecting it to


code: outfile = open(os.path.join(path_to_script_dir, name), 'w')

rawDescription: Make python save to a folder created in the directory of the py file being run


rawDescription: sorted on basis of two keys, descending order sort for first and ascending for second

description: Sorted on basis of two keys, descending order sort for first and ascending for second


code:
def get_fresh_tokens(func_to_call, *args, **kw):
    # gets new token called accesstoken
    func_to_call(new_accesstoken, *args, **kw)

rawDescription: Calling a function with all the original parameters


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

cmap = plt.get_cmap('rainbow')
cmap.set_bad('black')

data = np.random.normal(0, 1, (10, 10))
data[3:5, 7:] = 0

data = np.ma.masked_equal(data, 0)

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', cmap=cmap)
fig.colorbar(im)
plt.show()

rawDescription: How to create matplotlib colormap that treats one value specially?

description: Create matplotlib colormap that treats one value specially


rawDescription: At what part does the iris data receive a labeled cluster?


code:
import sys
sys.stdout.write(b'\33]0;title you want\a')

rawDescription: Set GNOME terminal window title in Python?


code:
new_func = g(f)  # your original f(x)
print(new_func(1))

rawDescription: is there a way to change the return value of a function without changing the function's body?

description: Is there a way to change the return value of a function without changing the function's body


rawDescription: pythonic method to find the inner value of a list

description: Pythonic method to find the inner value of a list


code:
import scrapy
from quonde.items import QuondeItem, QuondeItemLoader

class MySpider(scrapy.Spider):
    name = "quonde"
    allowed_domains = ["quonde.com.br"]
    start_urls = [
        "http://quonde.com.br/quadras/516-515/",
    ]

    def parse(self, response):
        div = response.xpath('//div[@class="caixanorm"]')
        location = response.xpath('.//h1[@class="inline"]/span/text()').extract()[0]
        for sel in div:
            loader = QuondeItemLoader(QuondeItem(), selector=sel)

            loader.add_value("localizacao", location)
            loader.add_xpath("titulo", './/div[@id="titulo"]/a/h2/text()')
            loader.add_xpath("subtitulo", './/div[@id="titulo"]/a/h3/text()')
            loader.add_xpath("telefone", './/div[@id="endereco"]/text()[1]')
            loader.add_xpath("endereco", './/div[@id="endereco"]/text()[2]')
            loader.add_xpath("categoria", './/div[@id="servecat"]/a[1]/text()')
            loader.add_xpath("quadra", './/div[@id="servecat"]/a[@rel="tag"]/text()')

            yield loader.load_item()

rawDescription: Extract information from a div and make some field parent of others


code:
d = df.index.day - np.clip((df.index.day-1) // 10, 0, 2)*10 - 1
date = df.index.values - np.array(d, dtype="timedelta64[D]")
df.groupby(date).mean()

rawDescription: Resampling with custom periods

description: Resampling with custom periods


code: onsubmit="writeToStorage()"

rawDescription: How do I cancel action of a form after an alert?

description: Cancel action of a form after an alert


code:
@property
def _y(self):
    return self._reshape_yi(self.y)

rawDescription: scipy 0.11.0 to 0.12.0 changes a linear scipy.interpolate.interp1d, breaks my constantly updated interpolator

description: Scipy 0.11.0 to 0.12.0 changes a linear scipy.interpolate.interp1d, breaks my constantly updated interpolator


code:
def my_test_input(message):
  return 7

rawDescription: Python 3 unittest simulate user input

description: Python 3 unittest simulate user input


code:
import zipfile
z = zipfile.ZipFile("yourDocInDocx.docx")
"someText" in z.read("word/document.xml")
"random other string" in z.read("word/document.xml")
z.close()

rawDescription: Make simple edits on Word document programmatically


code:
def any(S):
    for x in S:
        if x:
            return True
    return False

def all(S):
    for x in S:
        if not x:
            return False
    return True

rawDescription: How do you apply 'or' to all values of a list in Python?

description: Apply 'or' to all values of a list in Python


rawDescription: Split Pandas Dataframe into separate pieces based on column values


rawDescription: In a python script, how can I save the contents of a string to file, and the file is in current directory?


code:
['There is a vast field of fascinating human interest, lying only just outside our doors, which as yet has been but little explored. It is the Field of Animal Intelligence.\n']
['What I am trying to do here is, find the uppercase lines, and put them all in an array. Then, using the index method, I will find the first and last paragraphs of each section by comparing the indexes of these elements of this array I created.']

rawDescription: print first paragraph in python

description: Print first paragraph in python


code:
sequence = np.array([])
for note in scale:
    sequence = np.append(sequence, waveform(note, sec))
Audio(sequence,rate=sample_rate,autoplay=True)

rawDescription: Generate series of audio tones using iPython.display.Audio


rawDescription: Random's randint won't work in a for-loop


code:
def __init__(self,*args, **kwargs):
    self.user = kwargs.pop('user') # this line added
    super(AlbumCreateForm, self).__init__(*args, **kwargs)
    self.fields['name'].widget = forms.TextInput(
       attrs={'placeholder': 'name'})

def clean(self):
    if Album.objects.filter(user=self.user).exists():
        raise forms.ValidationError('Error description')

rawDescription: django - prevent duplicates for users

description: Django - prevent duplicates for users


code:
v = v.toarray()
vi = np.argsort(v, axis=0)[::-1]
vs = v[vi]

rawDescription: Reverse sort and argsort in python

description: Reverse sort and argsort in python


code:
detect_runs_in_dict(uuids)
Out[28]: ['a']

detect_runs_in_dict(uuids,n=2)
Out[29]: ['a', 'b']

rawDescription: Detect consecutive identical values in list


code: list = sorted(list2, key=lambda element: element[1], reverse = True)

rawDescription: Paste list to an Excel file

description: Paste list to an Excel file


rawDescription: Can I delete an item of a queryset in python but without deleting that item on the database?

description: Delete an item of a queryset in python but without deleting that item on the database


code: sorted(pairs, key=lambda x: (x[0], -x[1]))

rawDescription: Double sort with reverse

description: Double sort with reverse


code:
###############################################################################
#
# Example 10.
#
#
caption = ('Rows with odd numbers are in light red. '
           'Rows with even numbers are in light green.')
#
# Write the data.
worksheet10.write('A1', caption)
##
for row, row_data in enumerate(data):
    worksheet10.write_row(row + 2, 1, row_data)
##
# Write a conditional format over a range.
for row, row_data in enumerate(data):
    if row%2 == 0:
        worksheet10.set_row(row + 2, None, format1)
    else:
        worksheet10.set_row(row + 2, None, format2)

rawDescription: Applying formatting row by row in addition to column formatting with xlsxwriter


code:
cls = np.array([0, 0, 1, 0, 1])
x[cls]  #Not what you want
x[cls.astype(bool)]  #what you want.

rawDescription: Selecting rows from numpy ndarray when groups are known


code:
def distutils_dir_name(dname):
    """Returns the name of a distutils build directory"""
    f = "{dirname}.{platform}-{version[0]}.{version[1]}"
    return f.format(dirname=dname,
                    platform=sysconfig.get_platform(),
                    version=sys.version_info)

rawDescription: Testing Python C libraries - get build path


code:
import functools
outer_merge = functools.partial(pd.merge, how="outer")
reduce(outer_merge, tmp)

rawDescription: How to pass keyword arguments in reduce over Pandas merge function

description: Pass keyword arguments in reduce over Pandas merge function


code:
parts = ['ssh', 'ubuntu@192.168.56.101', '`sed -i -e s/property=\"true\"/property=\"false\"/g ~/cfg.cfg`']
subprocess.call(parts)

rawDescription: How to transport " for remote execution?

description: Transport " for remote execution


code:
lst.sort(key=lambda d: datetime.strptime(d, "%d/%m/%Y, %H:%M") if ':' in d else datetime.strptime(d, "%d/%m/%Y"))
lst

rawDescription: Python 3 - sorting list of dates in string format in different form (with time and without)


code: df.groupby('nr').agg({'name': lambda x: x.nunique()})

rawDescription: python pandas: Simplest way to perform group by and extract count of unique entities?

description: Python pandas: Simplest way to perform group by and extract count of unique entities


code:
def deploy():
    execute(migrate)
    execute(update)

rawDescription: Migrate django app to multiple servers

description: Migrate django app to multiple servers


code:
mycolors = np.array([ 'g', 'm', 'c' ])
ax.scatter(x, y, c=mycolors[c], lw=0)

rawDescription: Plot data point according to their class labels in Python


code:
# My Imports
from requests_toolbelt import MultipartEncoder
from webob import Request
import io

# Create a buffer object that can be read by the MultipartEncoder class
# This works just like an open file object
file = io.BytesIO()

# The file content will be simple for my test.
# But you could just as easily have a multi-megabyte mpg file
# Write the contents to the file
file.write(b'test mpg content')

# Then seek to the beginning of the file so that the
# MultipartEncoder can read it from the beginning
file.seek(0)

# Create the payload
payload = MultipartEncoder(
    {

        # The name of the file upload field... Not the file name
        'uploadedFile': (

            # This would be the name of the file
            'This is my file.mpg',

            # The file handle that is ready to be read from
            file,

            # The content type of the file
            'application/octet-stream'
        )
    }
)

# To send the file, you would use the requests.post method
# But the content type is not application-octet-stream
# The content type is multipart/form-data; with a boundary string
# Without the proper header type, your server would not be able to
# figure out where the file begins and ends and would think the
# entire post content is the file, which it is not. The post content
# might even contain multiple files
# So, to send your file, you would use:
#
# response = requests.post(url, data=payload, headers={'Content-Type': payload.content_type})

# Instead of sending the payload to the server,
# I am just going to grab the output as it would be sent
# This is because I don't have a server, but I can easily
# re-create the object using this output
postData = payload.to_string()

# Create an input buffer object
# This will be read by our server (our webob.Request object)
inputBuffer = io.BytesIO()

# Write the post data to the input buffer so that the webob.Request object can read it
inputBuffer.write(postData)

# And, once again, seek to 0
inputBuffer.seek(0)

# Create an error buffer so that errors can be written to it if there are any
errorBuffer = io.BytesIO()

# Setup our wsgi environment just like the server would give us
environment = {
    'HTTP_HOST': 'localhost:80',
    'PATH_INFO': '/index.py',
    'QUERY_STRING': '',
    'REQUEST_METHOD': 'POST',
    'SCRIPT_NAME': '',
    'SERVER_NAME': 'localhost',
    'SERVER_PORT': '80',
    'SERVER_PROTOCOL': 'HTTP/1.0',
    'CONTENT_TYPE': payload.content_type,
    'wsgi.errors': errorBuffer,
    'wsgi.input': inputBuffer,
    'wsgi.multiprocess': False,
    'wsgi.multithread': False,
    'wsgi.run_once': False,
    'wsgi.url_scheme': 'http',
    'wsgi.version': (1, 0)
}

# Create our request object
# This is the same as your request object and should have all our info for reading
# the file content as well as the file name
request = Request(environment)

# At this point, the request object is the same as what you get on your server
# So, from this point on, you can use the following code to get
# your actual file content as well as your file name from the object

# Our uploaded file is in the POST. And the POST field name is 'uploadedFile'
# Grab our file so that it can be read
uploadedFile = request.POST['uploadedFile']

# To read our content, you can use uploadedFile.file.read()
print(uploadedFile.file.read())

# And to get the file name, you can use uploadedFile.filename
print(uploadedFile.filename)

rawDescription: Python requests_toolbelt MultipartEncoder filename


code:
class PersonneEnums(object):
    SEXE_HOMME = u'0'
    SEXE_FEMME = u'1'
    TAB_SEXE = {SEXE_HOMME: _(u'Male'),
                SEXE_FEMME: _(u'Female'), }

    EST_NON_FUMEUR = u'0'
    EST_FUMEUR = u'1'
    EST_FUMEUR_OCCASIONNEL = u'2'
    EST_FUMEUR_AUTRE = u'3'
    TAB_EST_FUMEUR = {EST_NON_FUMEUR: _(u'Non-smoker'),
                      EST_FUMEUR: _(u'Smoker'),
                      EST_FUMEUR_OCCASIONNEL: _(u'Social smoker'),
                      EST_FUMEUR_AUTRE: _(u'Other'),
                      }

rawDescription: What is the good way to organize a long list in a model?


code:
import csv

dics = [{'Color':'Red', 'Age':29, 'Date':'October 2nd', 'Time':'4pm'},
        {'Color':'Blue', 'Age':32, 'Date':'December 5th', 'Time':'6pm'},
        {'Color':'Green', 'Age':12, 'Date':'January 10th', 'Time':'2pm'}]

with open("file.csv",'wb') as f:
   # Using dictionary keys as fieldnames for the CSV file header
   writer = csv.DictWriter(f, dics[0].keys())
   writer.writeheader()
   for d in dics:
      writer.writerow(d)

rawDescription: Writing to a CSV file with dict keys as column names


code:
math6 = ['chapter1', 'chapter2', 'chapter3', 'chapter1-3test']
math6 = iter(math6)
next(math6)
next(math6)

rawDescription: regex replace from a list

description: Regex replace from a list


code:
def names(self, section):
    return (m[0] for m in self.items(section))

rawDescription: Python: Return tuple or list?

description: Python: Return tuple or list


code: xml.xpath("//ns:title[text()='dive into mark']", namespaces=ns)

rawDescription: remove newline and whitespace parse XML with python Xpath

description: Remove newline and whitespace parse XML with python Xpath


code:
def calculate_winner(d):
    scores = {}
    high_score = 0
    for key, value in d.items():
        scores.setdefault(value, []).append(key)
        if value > high_score:
            high_score = value
    results = scores[high_score]
    if len(results) == 1:
        return results[0]
    else:
        return 'TIE', results

rawDescription: Python max on potential same values

description: Python max on potential same values


code:
func = receive()
result = eval(func, {x: 1})

rawDescription: I want to send a function through serial to python on a RPi


rawDescription: How to delete from an arbitrarilly deeply nested dictionary

description: Delete from an arbitrarilly deeply nested dictionary


code: pascalVals = [int(x) for x in raw_input('...').split()]

rawDescription: How do I separate a space-delimited string into multiple variables?

description: Separate a space-delimited string into multiple variables


code:
kv = '''
#:set default_font_size "36sp"
<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"
            font_size: default_font_size
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"
            font_size: default_font_size
'''
Builder.load_string(kv)

rawDescription: Setting global font size in kivy

description: Setting global font size in kivy


code:
INPUT = "toto.txt"
OUTPUT = "titi.txt"

def col3_fn(columns):
    """ Just sum column 1 and 2. Used as generator of column 3 content """
    return int(columns[0]) + int(columns[1])

def col4_fn(columns):
    """ Difference between column 2 and 3. Used as generator of column 4 content """
    return int(columns[1]) - int(columns[2])

# List of functions used for column generation.
# You can add as much as you want.
functions = [col3_fn, col4_fn]

with open(INPUT, "r") as inp, open(OUTPUT, "w") as out:
    for line in inp.readlines():
        splited = line[:-1].split()

        for f in functions:
            splited.append(str(f(splited)))

        out.write("\t".join(splited) + "\n")

rawDescription: Python - Convert a 2-column file into 10-column


rawDescription: Display function definition in interactive shell


code: [[processPair(*pair) for pair in pairs] for pairs in l]

rawDescription: Iterate over Python list, preserving structure of embedded lists


rawDescription: Run certain no. of threads/processes simultaneously


rawDescription: reading json wrapped status report from tinyG

description: Reading json wrapped status report from tinyG


code:
import re

import pandas

COMMENT_CHAR = '#'
columns = []
with open('test.dat', 'r') as td:
    for line in td:

        # find the commented lines
        if line[0] == COMMENT_CHAR:
            info = re.split(' +', line)
            columns.append(info[2])

        # when we seethe first line that doesn't start with
        # COMMENT_CHAR, we pass the remaining lines of the
        # file to pandas.read_table and break our loop
        else:
            _dfs = [
                pandas.DataFrame([line.split(' ')], columns=columns, dtype=float),
                pandas.read_table(td, sep='\s', header=None, names=columns)
            ]
            df = pandas.concat(_dfs, ignore_index=True)

rawDescription: reading an ascii file with headers given in the first rows into a pandas dataframe

description: Reading an ascii file with headers given in the first rows into a pandas dataframe


code:
dict = {'ARS' : ([1500],[350])}
x = input('Home Team: ')
print(x)
print(dict[x])

rawDescription: Variable returning string as opposed to defined parameter


code: res = minimize(f, x0, args=(a,), method='SLSQP', constraints=con)

rawDescription: Scipy, optimize a function with argument dependent constraints


code:
args = ActiveWorkbook.Path & "\CreateVolsurface.py -d ""10 Sep 12"""
ret_val = Shell("C:\python27\python.exe " & args)

rawDescription: Running python script from excel vba using Shell does nothing


rawDescription: matlab find() for nonzero element in python

description: Matlab find() for nonzero element in python


rawDescription: adding list value into dictionary after appending new value into list during each iteration

description: Adding list value into dictionary after appending new value into list during each iteration


code: help(re.match) #help on method

rawDescription: Using python help to get help on MatchObject


rawDescription: Getting specific field from chosen Row in Pyspark DataFrame


rawDescription: django: exclude certain form elements based on a condition

description: Django: exclude certain form elements based on a condition


code:
def closeEvent(self, event):
    for so in self.soTab:
        if so:
            so.close()
    event.accept()

rawDescription: Python crash when closing qmainwindow with qdialog open


code:
class myBot(JabberBot):
  def start(self):
    threading.Thread(target=self.autoNotifyLoop).start()

  def autoNotifyLoop(self):
    while True:
      self.autoNotify()
      time.sleep(5) # wait 4 seconds

  def autoNotify(self):
    self.send('someuser@jabber.example.com','cooool message text!')

rawDescription: Execute Function Every X Seconds On Class Init


code:
import time
time.strftime('%H:%M:%S', time.gmtime(12345))

rawDescription: Python: convert seconds to hh:mm:ss

description: Python: convert seconds to hh:mm:ss


code:
from django.core.validators import URLValidator
from django.core.files.base import ContentFile

from rest_framework import serializers

from urllib.request import urlretrieve

class FileUrlField(serializers.FileField):
    def to_internal_value(self, data):
        try:
            URLValidator()(data)
        except ValidationError as e:
            raise ValidationError('Invalid Url')

        # download the contents from the URL
        file, http_message = urlretrieve(data)
        file = File(open(file, 'rb'))
        return super(FileUrlField, self).to_internal_value(ContentFile(file.read(), name=file.name))

rawDescription: Django Rest Framework - Downloading files on server


code:
def to_class(func):
    """ returns a decorator
    aimed to force the result to be of class cls. """
    def wrapper(cls, *args, **kwargs):
        return cls(func(*args, **kwargs))
    return classmethod(wrapper)

rawDescription: Trying to program a "to_class" general decorator


code:
import inspect, gc

def giveupthefunc():
    frame = inspect.currentframe(1)
    code  = frame.f_code
    globs = frame.f_globals
    functype = type(lambda: 0)
    funcs = []
    for func in gc.get_referrers(code):
        if type(func) is functype:
            if getattr(func, "func_code", None) is code:
                if getattr(func, "func_globals", None) is globs:
                    funcs.append(func)
                    if len(funcs) > 1:
                        return None
    return funcs[0] if funcs else None

rawDescription: Python code to get current function into a variable?


code:
imx = im * x
d2_0 = ndimage.gaussian_filter1d(imx, axis=0, sigma=5, order=2, mode='wrap')
d2_1 = ndimage.gaussian_filter1d(imx, axis=1, sigma=5, order=2, mode='wrap')

plt.figure()
plt.subplot(131)
plt.imshow(imx)
plt.title('original')
plt.subplot(132)
plt.imshow(d2_0)
plt.title('derivative along axis 0')
plt.subplot(133)
plt.imshow(d2_1)
plt.title('along axis 1')

rawDescription: Python finite difference functions?

description: Python finite difference functions


rawDescription: Verify IP string is greater or less than another IP string in python


code:
match_list = []
match = re.findall('\n(\w+)\s+(\d*)\s+(\d*)', output)
for k in match:
    #k will be a tuple like this: ('frank', '114', '0')
    match_list.append(list(k))

rawDescription: Python - Getting user data using regex

description: Python - Getting user data using regex


rawDescription: functions depending on iterables

description: Functions depending on iterables


code:
from string import punctuation
lis = ["hel?llo","intro"]
[ x.translate(None, punctuation) for x in lis]
strs = "5,6!7,8"
strs.translate(None, punctuation)

rawDescription: How to remove the punctuation in the middle of a word or numbers?

description: Remove the punctuation in the middle of a word or numbers


rawDescription: Inserting a variable in MongoDB specifying _id field


rawDescription: Update values in list of list of tuples

description: Update values in list of list of tuples


code:
import easygui
import random
AdditionAnswers = 0
IncorrectAnswers = 0
SubtractionAnswers = 0
Subject = easygui.buttonbox ("What maths subject would you like to test?", choices = ["Addition","Subtraction","Multiplication","Division"])
if Subject == "Addition":
    easygui.msgbox ("Please enter the correct answer to earn a point,there are 10 questions in this quiz")
    for number in range(0,10):
        Figure1 = random.randrange(0,11)
        Figure2 = random.randrange(0,11)
        PlayerAnswer = easygui.enterbox ("What is " +str(Figure1)+ " + " +str(Figure2)+ "?")
        if int(PlayerAnswer) == Figure1 + Figure2:
            AdditionAnswers += 1
            easygui.msgbox ("Correct! Your score is "+str(AdditionAnswers))
            print(AdditionAnswers)#To see if game is keeping count of questions asked
        else:
            AdditionAnswers += 0
            IncorrectAnswers += 1
            easygui.msgbox ("Sorry, incorrect! Your score is still "+str(AdditionAnswers))
        print(AdditionAnswers)#To see if game is keeping count of questions asked

    easygui.msgbox ("You scored " +str(AdditionAnswers)+ " out of 10")
    print(AdditionAnswers) #To check if programme is calculating score correctly
    print(IncorrectAnswers)

elif Subject == "Subtraction":
    easygui.msgbox ("Please enter the correct answer to earn a point, there are 10 questions in this quiz")
    for number in range(0,10):
        Figure1 = random.randrange(0,11)
        Figure2 = random.randrange(0,11)
        PlayerAnswer = easygui.enterbox ("What is " +str(Figure1)+ " - " +str(Figure2)+ "?")

        if int(PlayerAnswer) == Figure1 - Figure2:
            SubtractionAnswers += 1
            easygui.msgbox ("Correct! Your score is "+str(SubtractionAnswers))
            print(SubtractionAnswers)#To see if game is keeping count of questions asked
        else:
            SubtractionAnswers+= 0
            IncorrectAnswers += 1
            easygui.msgbox ("Sorry, incorrect! Your score is still "+str(SubtractionAnswers))
            print(SubtractionAnswers)#To see if game is keeping count of questions asked

    easygui.msgbox ("You scored " +str(SubtractionAnswers)+ " out of 10")
    print(SubtractionAnswers) #To check if programme is calculating score correctly
    print(IncorrectAnswers)

rawDescription: Multi choice, easygui buttonbox

description: Multi choice, easygui buttonbox


code:
def resize(event):
    print("New size is: {}x{}".format(event.width, event.height))

root.bind("<Configure>", resize)

rawDescription: tkinter python maximize window

description: Tkinter python maximize window


code: b = subprocess.Popen("ovs-vsctl add-br '{}'".format(BR_EX), ...)

rawDescription: how to give raw_input to subprocess

description: Give raw_input to subprocess


rawDescription: Converting from hexadecimal to binary values


code:
def save(self, *args, **kwargs):
    self.content = process_image_tags(self.pre_content, ContentImage)
    super(CustomFlatPage, self).save(*args, **kwargs)

rawDescription: Performing text processing on flatpage content to include handling of custom tag


code:
def index_default(line, char):
    """Returns the index of a character in a line, or the length of the string
    if the character does not appear.
    """
    try:
        retval = line.index(char)
    except ValueError:
        retval = len(line)
    return retval

def split_log_line(line):
    """Splits a line at either a period or a colon, depending on which appears
    first in the line.
    """
    if index_default(line, ".") < index_default(line, ":"):
        return line.split(".")
    else:
        return line.split(":")

rawDescription: Split by the delimiter that comes first, Python


code:
variables = {k: xr.DataArray(v, dims=['month', 'attribute'])
             for k, v in D_patient_DF.items()}
combined = xr.Dataset(variables).to_array(dim='patient')
print(combined)

rawDescription: Create DataArray from Dict of 2D DataFrames/Arrays


code:
yourdict = {}
# ...
items = yourdict.items()

rawDescription: Tuple list from dict in Python

description: Tuple list from dict in Python


code:
from module_a import log as a_log
from module_b import log as b_log

rawDescription: Most pythonic way to treat imported function override conflict


code:
def prime_factor(n):
    list = []
    if n==1:
        return [1] #or []?
    else:
        for i in range(2,n+1): #additional improvement could be made here
            if n %i ==0:
                b = prime_factor(n/i)
                list.append(i) #i is always prime in here, you return once first i is found
                list.extend(b)
                return list

rawDescription: Prime Factor Implementation

description: Prime Factor Implementation


code: tag = soup.find("div", class_="desired_div")

rawDescription: Beautiful Soup - inserting before extracted portion of parse tree


code:
# coding: utf-8
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

def process_value(v):
    v1 = v.split()[-1]
    if v1.startswith('http'):
        v = v1
    return v

class MySpider(CrawlSpider):
    name = 'spider'
    start_urls = [
        'http://task.zhubajie.com/success/?kw=%E7%99%BE%E5%BA%A6%E7%9F%A5%E9%81%93'
    ]
    rules = [
        Rule(LinkExtractor(restrict_xpaths=('//div[@class="pagination"]'),
                           process_value=process_value), follow=True)
    ]

rawDescription: scrapy LinkExtractor doesn't extract corect url

description: Scrapy LinkExtractor doesn't extract corect url


rawDescription: Regex - matching all text between two strings


code: np.argmax(mask, 2)

rawDescription: Getting the first occurrence of a value in an N-dimensional numpy array


rawDescription: Split string by two conditions - wildcard


rawDescription: Reorganize Dictionary

description: Reorganize Dictionary


code:
@classmethod
def cf_connect(cls, column_family):
    cf = pycassa.ColumnFamily(cls.pool, column_family)
    return cf

rawDescription: python static class with static method that uses self?

description: Python static class with static method that uses self


code:
def query_dicts(query_string, *query_args):
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute(query_string, query_args)
    col_names = [desc[0] for desc in cursor.description]
    while True:
        row = cursor.fetchone()
        if row is None:
            break
        row_dict = dict(izip(col_names, row))
        yield row_dict
    return
posts = query_dicts('SELECT * FROM tablename WHERE DAY(publish_date)<=%s AND MONTH(publish_date)=%s', now.day, now.month)

rawDescription: Django date filter by day of month

description: Django date filter by day of month


rawDescription: Apply non-linear regression for multi dimension data samples in Python


code:
#!/usr/bin/env python3
from subprocess import check_output

ans = check_output(['java', '-jar', 'myjarfile.jar'], input=b'haha')

rawDescription: subprocess python Popen to open java jar

description: Subprocess python Popen to open java jar


code: ax.set_ylim(-1, 1)

rawDescription: Animating plots on ipython 2 for mac os

description: Animating plots on ipython 2 for mac os


code:
hover.tooltips=[
        ("grade", "$y"),
        ("date", "@dates"),
        ("items", "@items"),
    ]

rawDescription: Bokeh HoverTool custom font and newlines from Python


code: n_items = take(n, d.iteritems())

rawDescription: Python - Return first N key:value pairs from dict


code:
# Split setences
split_sentences = [sentence.split(" ") for sentence in sentences]

# Get group lengths
grplens = np.array([len(item) for item in split_sentences])

# ID each word
unq_words,ID = np.unique(np.concatenate((split_sentences)),return_inverse=True)

# Get lengths
N = len(ID)
Nunq = len(unq_words)
Nsent = len(sentences)

# Get ID shift positions and thus row shifts for final 2D array output
row_shifts = np.zeros(N,dtype=int)
row_shifts[grplens.cumsum()[:-1]] = 1

# Finally get output boolean array using ID and row_shift IDs
out = np.zeros((Nsent,Nunq),dtype=bool)
out[row_shifts.cumsum(),ID] = 1

rawDescription: Efficiently testing if strings are present in 2D numpy arrays


code: {words[0]:words[1:] for words in lst}

rawDescription: Get first element of sublist as dictionary key in python


code: sorted_wordscount = sorted(wordscount.iteritems(), key=operator.itemgetter(1),reverse=True)

rawDescription: How to build a clean word cloud using pytagcloud without a crowded image - Python

description: Build a clean word cloud using pytagcloud without a crowded image - Python


code:
ids_new = df.ix[date_new]['ID']
ids_old = df.ix[date_old]['ID']

rawDescription: Pandas Dataframe Groupby Determine Values in 1 group vs. another group


code:
from ctypes import *
from ctypes.wintypes import BOOL, HMONITOR, HDC, RECT, LPARAM, DWORD, BYTE, WCHAR, HANDLE

import win32api  # http://sourceforge.net/projects/pywin32/files/pywin32/

_MONITORENUMPROC = WINFUNCTYPE(BOOL, HMONITOR, HDC, POINTER(RECT), LPARAM)

class _PHYSICAL_MONITOR(Structure):
    _fields_ = [('handle', HANDLE),
                ('description', WCHAR * 128)]

def _iter_physical_monitors(close_handles=True):
    """Iterates physical monitors.

    The handles are closed automatically whenever the iterator is advanced.
    This means that the iterator should always be fully exhausted!

    If you want to keep handles e.g. because you need to store all of them and
    use them later, set `close_handles` to False and close them manually."""

    def callback(hmonitor, hdc, lprect, lparam):
        monitors.append(hmonitor)
        return True

    monitors = []
    if not windll.user32.EnumDisplayMonitors(None, None, _MONITORENUMPROC(callback), None):
        raise WinError('EnumDisplayMonitors failed')

    for monitor in monitors:
        # Get physical monitor count
        count = DWORD()
        if not windll.dxva2.GetNumberOfPhysicalMonitorsFromHMONITOR(monitor, byref(count)):
            raise WinError()
        # Get physical monitor handles
        physical_array = (_PHYSICAL_MONITOR * count.value)()
        if not windll.dxva2.GetPhysicalMonitorsFromHMONITOR(monitor, count.value, physical_array):
            raise WinError()
        for physical in physical_array:
            yield physical.handle
            if close_handles:
                if not windll.dxva2.DestroyPhysicalMonitor(physical.handle):
                    raise WinError()

mons = [m for m in _iter_physical_monitors(False)]

#for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)):
#   print(hMon.handle)  # or int(hMon)

temps = (
    'UNKNOWN',
    '4000K',
    '5000K',
    '6500K',
    '7500K',
    '8200K',
    '9300K',
    '10000K',
    '11500K'
)
class MyEnum(c_int):
    MC_COLOR_TEMPERATURE_UNKNOWN = 0
    MC_COLOR_TEMPERATURE_4000K = 1
    MC_COLOR_TEMPERATURE_5000K = 2
    MC_COLOR_TEMPERATURE_6500K = 3
    MC_COLOR_TEMPERATURE_7500K = 4
    MC_COLOR_TEMPERATURE_8200K = 5
    MC_COLOR_TEMPERATURE_9300K = 6
    MC_COLOR_TEMPERATURE_10000K = 7
    MC_COLOR_TEMPERATURE_11500K = 8

o = MyEnum()
print(o)
po = pointer(o)

pm = mons[0]
print("physical %r" % pm)
t = windll.dxva2.GetMonitorColorTemperature(pm, po)  #byref(o))
if t:
    #print(o)
    #print(dir(po.contents))
    print(temps[po.contents.value])

else:
    print("Err: %s" % windll.kernel32.GetLastError())  # ERROR_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE = -1071241844 # Variable c_long '-0x03fd9da74'

rawDescription: ctypes: passing and reading an enum pointer

description: Ctypes: passing and reading an enum pointer


code:
import pandas as pd
import datetime as DT

values_a = range(16)
values_b = range(10, 26)
states = ['Georgia']*8 + ['Alabama']*8
cities = ['Atlanta']*4 + ['Savanna']*4 + ['Mobile']*4 + ['Montgomery']*4
dates = pd.DatetimeIndex([DT.date(2012,1,1)+DT.timedelta(days = i) for i in range(4)]*4)
df = pd.DataFrame(
    {'value_a': values_a, 'value_b': values_b},
    index = [states, cities, dates])
df.index.names = ['State', 'City', 'Date']
df = df.reset_index(level=[0, 1])

print(df.groupby(['State','City']).resample('2D', how='sum'))

rawDescription: Resampling Within a Pandas MultiIndex

description: Resampling Within a Pandas MultiIndex


code:
v1='dd';
v2=32;
v4=12;

import re
re_p = re.compile('^v\d+')

var_list = vars().copy()

for a_var in (v for v in var_list if re_p.match(v)):
    print(a_var, var_list[a_var])

rawDescription: loop multiple variables in python

description: Loop multiple variables in python


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)

        self.list = wx.ListCtrl(self.panel, style=wx.LC_REPORT)
        self.list.InsertColumn(0, "Date")
        self.list.InsertColumn(1, "Action")
        self.list.InsertColumn(2, "Result")

        for a in range(5):
            self.list.Append(["Date %d" % a, "Action %d" % a, "Result %d" % a])

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.list, proportion=1, flag=wx.EXPAND)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

        # Save
        for row in range(self.list.GetItemCount()):
            print(", ".join([self.list.GetItem(row, col).GetText() for col in range(self.list.GetColumnCount())]))

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: python print contents from wx.ListCtrl

description: Python print contents from wx.ListCtrl


rawDescription: Borda Count using python?

description: Borda Count using python


code:
import threading

def tryfinally(finallyf):
  u"returns a decorator that adds try/finally behavior with given no-argument call in the finally"
  def decorator(callable):
    def execute(*args, **kwargs):
      try: result = callable(*args, **kwargs)
      finally: finallyf()
      return result
    return execute
  return decorator

def usinglock(lock):
  u"returns a decorator whose argument will acquire the given lock while executing"
  def decorator(function):
    body = tryfinally(lock.release)(function)
    def execute(*args, **kwargs):
      lock.acquire()
      return body(*args, **kwargs)
    return execute
  return decorator

def synchronized(function):
  u"decorator; only one thread can enter the decorated function at a time; recursion is OK"
  return usinglock(threading.RLock())(function)

rawDescription: Thead-safe object and dict types in python


code:
import numpy as np
import datetime

# date field conversion function
dateconv = lambda s: datetime.strptime(s, '%Y-%M-%D %H:%M:%S:.%f')

col_names = ["Timestamp", "val1", "val2", "val3", "val4", "val5"]
dtypes = ["object", "uint8", "uint8", "uint8", "uint8", "float"]
mydata = np.genfromtxt("myfile.csv", delimiter=',', names=col_names, dtype=dtypes, converters={"Time": dateconv})

rawDescription: How to plot data with Python from text file

description: Plot data with Python from text file


rawDescription: using variables in class functions in another class (python)

description: Using variables in class functions in another class (python)


rawDescription: Howto NOT escape a string function parameter in python


code:
def get_dist(row):
    lat1 = row['EQP_GPS_SPEC_LAT_CORD']
    long1 = row['EQP_GPS_SPEC_LONG_CORD']
    lat2 = row['EQP_GPS_SPEC_LAT_CORD_2']
    long2 = row['EQP_GPS_SPEC_LONG_CORD_2']
    return haversine(lat1, long1, lat2, long2)

# Find consecutive rows with matching ser_no, and get coordinates.
coord_cols = ['EQP_GPS_SPEC_LAT_CORD', 'EQP_GPS_SPEC_LONG_CORD']
matching_ser = mttt_pings['ser_no'] == mttt_pings['ser_no'].shift(1)
shift_coords = mttt_pings.shift(1).loc[matching_ser, coord_cols]

# Join shifted coordinates and compute distances.
mttt_pings_shift = mttt_pings.join(shift_coords, how='inner', rsuffix='_2')
mttt_pings['hdist'] = mttt_pings_shift.apply(get_dist, axis=1)

rawDescription: Python: simplifying code by writing it in a more Pandas specific way


code:
import pandas as pd
import re

data = pd.DataFrame(data={'ID':['1','1','2','2','2','3','3','3','3'],
                    'Text1':['Apple','','','Laptop','','Pens','','Ruler',''],
                    'Text2': ['Bananas','Grape','Mouse','','DVD Player','','Pencils','',''],
                    'Text3':['Cherry','','','Headphones','','','','','Eraser'],
                    'Text4':['Mango','Strawberries','','','Cell phone','','Sticky Notes','','']
                    })

cols = [x for x in data.columns if re.search("^Text", x)] # list of all columns
                                                          # that start with "Text"

# function to be applied that takes a row and a list of columns
# to concatenate
def concat_text(row, cols):
    # The real work is done here
    return ";".join([";".join([str(x) for x in y if x]) for y in row[cols].values])

result = data.groupby("ID").apply(concat_text, cols) # groupby and apply

rawDescription: Concatenate Text on Pandas Dataframe in Python


code:
import profile
import dis

def callee():
    for x in range(10000):
        x += x
    print("let's have some tea now")

def caller():
    callee()

profile.run('caller()')

rawDescription: Performance of inline Python function definitions


code: board[y][x] = 'X'

rawDescription: Displaying a moveable character inside of a grid


rawDescription: extra empty element when removing an element from a tuple

description: Extra empty element when removing an element from a tuple


code:
from django.contrib.auth.models import User
user = ForeignKey(User)

rawDescription: ForeignKey to a Model field?

description: ForeignKey to a Model field


code:
from bson.objectid import ObjectId
from pymongo import Connection
connection = Connection()
db = connection['lenin']
collection = db.document
collection.find_one({'_id': '51e35ee82e3817732b7bf3c1'}) # returns None
collection.find_one({'_id': ObjectId('51e35ee82e3817732b7bf3c1')}) # returns the object

rawDescription: How to find by _id in ming?

description: Find by _id in ming


rawDescription: A-z Index Django

description: A-z Index Django


code:
mod = __import__(testName)
mod.HelloWorld()

rawDescription: Import file using string as name

description: Import file using string as name


code:
{'ARRAY05-2NODE-128k-0': ['C:\\Test3\\ARRAY05-2NODE-RAID1-12disk-128k-0-segmented.xlsx',
                          'C:\\Test1\\ARRAY05-2NODE-RAID1-17disk-128k-0-segmented.xlsx',
                          'C:\\Test4\\ARRAY05-2NODE-RAID1-25disk-128k-0-segmented.xlsx',
                          'C:\\Test2\\ARRAY05-2NODE-RAID1-18disk-128k-0-segmented.xlsx'],
 'ARRAY05-2NODE-32k-0': ['C:\\Test1\\ARRAY05-2NODE-RAID1-12disk-32k-0-segmented.xlsx',
                         'C:\\Test6\\ARRAY05-2NODE-RAID1-25disk-32k-0-segmented.xlsx'],
 'ARRAY05-2NODE-64k-0': ['C:\\Test2\\ARRAY05-2NODE-RAID1-12disk-64k-0-segmented.xlsx'],
 'ARRAY05-2NODE-64k-100': ['C:\\Test5\\ARRAY05-2NODE-RAID1-12disk-64k-100-segmented.xlsx']}

rawDescription: Sorting and Matching a Python list

description: Sorting and Matching a Python list


code:
def int1(kernel, x1, y1):
    # Sample KDE distribution
    sample = kernel.resample(size=100)

    include = (sample < np.repeat([[x1],[y1]],sample.shape[1],axis=1)).all(axis=0)
    integral = include.sum() / float(sample.shape[1])
    return integral

rawDescription: Different integration results using Monte Carlo vs scipy.integrate.nquad


code:
w = (np.arange(N) - N /2.) / T + 0.00000001 # slightly shifted
# integration
fourier =  ifft(ifftshift(1./ ( 2 * np.pi * 1j * w) * fftshift(fft(ys)) )  )

rawDescription: numerical integration in Fourier space with numpy.fft

description: Numerical integration in Fourier space with numpy.fft


code:
g = foo_like(d) # you'll need to write this function!
np.multiply(d, d, out=g)
g += e * e
g += f * f
np.sqrt(g, out=g)
g += b
g += a

rawDescription: Transfer ownership of numpy data

description: Transfer ownership of numpy data


code:
inputString = "my_item = ['maria','jose']"

# value is a list type
value = eval(inputString.split("=")[1])
# key is a string type
key = inputString.split("=")[0].strip()

# I don't think you can define a variable name while the script is running.
# but you can use dictionary type to call it.
mydict = {}
mydict[key] = value

rawDescription: Python: how to turn string into a list?

description: Python: how to turn string into a list


code:
def max_gap(prime_list):
    gaps = reduce(helper_to_subtract_pairs, prime_list, [0])[1:-1]
    max_idx = argmax(gaps)
    return gaps[max_idx], prime_list[max_idx:max_idx + 2]

rawDescription: Calculating the gap between pairs of twin primes in python


code:
if __name__ == "__main__":
    dir_path = "subdir"
    ids_list = ["1", "2"]
    file_extension = ".txt"

    cntr = FilesLineCounter()
    # goint to use the callback magic
    process_ids(dir_path, ids_list, file_extension, cntr.count_file_lines)
    process_ids(dir_path, ids_list, file_extension, read_file_content)

    # time to show our results
    for path, numoflines in cntr.items():
        print("File {} has {} lines".format(path, numoflines))

    for i, content in enumerate(GLOB_CONTENT):
        print("File # {} last 3 bytes are {}".format(i, content[-3:]))

rawDescription: Python statement as method's argument

description: Python statement as method's argument


rawDescription: Calculating combinations of subsets of given size leading up to the set


code:
def generate_key(password, salt, iterations):
    assert iterations > 0

    key = password + salt

    for i in range(iterations):
        key = hashlib.sha256(key).digest()

    return key

rawDescription: Encrypt / decrypt data in python with salt


code:
isinstance(type, object)
isinstance(object, type)
issubclass(type, object)
issubclass(object, type)
type.mro(object)
type.mro(type)

rawDescription: Get complete list of all possible Class Attributes


code:
def get_derivative_matrix(X):

    # Setup output array, equivalent to A
    out = np.zeros((m,3+m-2))

    # Setup the triplets in each row as [1,-2,1]
    out[:,:3] = 1
    out[:,1] = -2

    # Slice and perform matrix-multiplication
    return np.dot(out.ravel()[:m*(m-2)].reshape(m-2,-1)/(h**2), f(X))

rawDescription: Numerical Differenciation as Matrix-Vector Product


code:
OBJECT_LIBRARY = {'A': A, 'B': B, 'C': C}

OBJECT_LIBRARY['A']()

rawDescription: Python: Dictionary: Based on the key provided return an initialized class object variable


code:
from scipy.spatial.distance import cdist

C = cdist(A.reshape(A.shape[0],-1),B.reshape(B.shape[0],-1),'sqeuclidean')

rawDescription: numpy - Computing "element-wise" difference between two arrays along first axis

description: Numpy - Computing "element-wise" difference between two arrays along first axis


code: fg1 = bg1.apply(frame, learningRate=0.001)

rawDescription: OpenCV Python cv2.BackgroundSubtractor parameters


code:
def get_songs(requested_username):
    songs = Song.all()
    songs.filter('username =', requested_username).order('-created')
    return songs

rawDescription: Python Queries - Web Apps, etc

description: Python Queries - Web Apps, etc


code:
ITEMS = {
    'John greased ': ['axle', 'wheel', 'wheels', 'wheel', 'engine', ''],
    'Paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''],
    'Tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'],
    'Lisa plowed ': ['field', 'field', '', '', '', ''],
}

for key, value in ITEMS.items():
    #print value
    print(key, len([item for item in value if item]))

rawDescription: Counting how many values were attributed to a key an a python (3.2) dictionary


code:
unhandled = True
if a > 1:
  if b == 2:
    doSomething()
    unhandled = False
  if unhandled and b == 3:
    doSomethingElse()
    unhandled = False
if unhandled and a == 2: # Note: NO elif!
  doDefaultForA2()
  unhandled = False
if unhandled:
  showError("Unknown command")

rawDescription: Continue to elif after a nested if-statement?


code:
data = '''"this","is","a","test"'''

for quote in data.split(','):
    word = quote.strip('"')
    print(word)

rawDescription: python advance for loop

description: Python advance for loop


code: from my_modules import Stuff

rawDescription: Python: how to import from all modules in dir?


code:
foo, _ = find_text(x,y)
_, bar = find_text(x,y)

rawDescription: How to return elements of a list as variables?

description: Return elements of a list as variables


rawDescription: difficulty in selecting elements in a python list

description: Difficulty in selecting elements in a python list


code:
from operator import contains
v_in = np.vectorize(lambda x,y: contains(y, x), excluded={1,})

rawDescription: Numpy search for elements of an array in a subset


code:
def one(valid, data):
    valid[ data[ index[valid[:,0],0] ] == 0, 1] = False

def two(valid, data):
    valid_index = index[valid[:,0],0]
    invalid_index = (data[ valid_index ] == 0)
    valid[ invalid_index, 1 ] = False

rawDescription: efficiency vs. readability: obfuscation when using nested boolean index arrays

description: Efficiency vs. readability: obfuscation when using nested boolean index arrays


code:
THRESHOLD = 1000

class Small(object):
    def __init__(self, n):
        if n < THRESHOLD:
            self.n = n
        else:
            self.__class__ = Big
            self.__init__(n)

class Big(object):
    def __init__(self, n):
        if n < THRESHOLD:
            self.__class__ = Small
            self.__init__(n)
        else:
            self.n = n

rawDescription: Changing the class type of a class after inserted data


code: fast_colors[pix[j,i]][j,i] = pix[j,i]

rawDescription: PIL? Extract all pixels of a given RGB value


code:
a = conn.list_topics()
a_arn = a['ListTopicsResponse']['ListTopicsResult']['Topics'][0]['TopicArn']

rawDescription: Boto - AWS SNS how to extract topic's ARN number


rawDescription: Python - comparing elements of list with 'neighbour' elements


code:
import pandas as pd
import io

temp=u"""CALENDAR_DATE   ORDER_NUMBER    INVOICE_NUMBER  TRANSACTION_TYPE    CUSTOMER_NUMBER   CUSTOMER_NAME
5/13/2016 0:00    13867666       6892372              S                 2026            CUSTOMER 1"""

rawDescription: Pandas read_table error

description: Pandas read_table error


rawDescription: List slicing and finding second highest value python


code:
send(IP(dst="1.2.3.4")/ICMP())
send(IP(dst="1.2.3.4")/ICMP(), verbose=0)
send(IP(dst="1.2.3.4")/ICMP(), verbose=False)

rawDescription: Scapy send function without output

description: Scapy send function without output


rawDescription: What is the difference between a function, an unbound method and a bound method?


code:
cmd = """echo $(date) HELLO $(date);
   sleep 1;
   echo $(date)
"""
subprocess.Popen(cmd, shell=True)

rawDescription: Passing a "shell script" as a string to Python subprocess.Popen


code:
def convert_list(l):
    return dict((sublist[0], set(sublist[1:])) for sublist in l)

rawDescription: Merge two lists based on condition

description: Merge two lists based on condition


code:
quadrant = [lambda x, y: (sign[0] * x, sign[1] * y, id (sign) )
    for sign in ((1, -1), (1, 1), (-1, 1), (-1, -1))]

for q in quadrant:
    print (id (q) )

rawDescription: For Python 3.3, how can I make a list of functions using one lambda statement?


rawDescription: Python decorating functions before call

description: Python decorating functions before call


code:
class A(object): __slots__='a'

class AB(A): __slots__='b'

ab=AB()
ab.a = ab.b = 23

rawDescription: Python: How does inheritance of __slots__ in subclasses actually work?


code:
def getIndex():
    for index, item in enumerate(thelist):
       if item[0] == "332":
          return index

rawDescription: What's the fastest way to locate a list element within a list in python?


code:
from Tkinter import *
import Tkinter
top = Tkinter.Tk()
top.grid()
def OnButtonClick(self):
    print( "You clicked the button" )
B1 = Tkinter.Button(top, text ="circle", relief=RAISED,\
                         cursor="circle")
B2 = Tkinter.Button(top, text ="plus", relief=RAISED,\
                         cursor="plus")
B3 = Tkinter.Button(top, text=u"good !",relief=RAISED,\
                         cursor="plus")
B4 = Tkinter.Button(top,text=u"Click me !",
                                command=OnButtonClick(top))
B4.grid(column=1,row=0)

B1.pack()
B2.pack()
B3.pack()
B4.pack()
top.mainloop()

rawDescription: python:Merging button yields "not defined"

description: Python:Merging button yields "not defined"


code:
class B(A, autosuper):
    def rec(self):
        return self.super() + 1

rawDescription: Making a class method recognize which class context it's running in


code:
c = d.cursor()

c.execute(query)    # selected rows stored in cursor memory

rows = c.fetchall()    # get all selected rows, as Barmar mentioned
for r in rows:
    print(r)

rawDescription: Why would MySQL execute return None?

description: Why would MySQL execute return None


code:
import new
new.module('foo')

rawDescription: Python package without __init__

description: Python package without __init__


code:
from itertools import islice, izip, chain

star_list = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
sl_shift = chain(islice(star_list, 1, None), [None])
star_list = [i for i, next_i in izip(star_list, sl_shift)
             if (i, next_i) != ('**', '**')]

rawDescription: Remove certain consecutive duplicates in list


code:
import pandas as pd
import numpy as np

x = pd.DataFrame(np.arange(9).reshape((3, 3)), columns=[1, 2, 3], index=['a', 'b', 'c'])
arr = x.values
print(arr)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]

index1 = slice(0,2)
index2 = slice(1,3)
arr[index1, 2] = arr[index2, 1]
print(arr)
# [[0 1 4]
#  [3 4 7]
#  [6 7 8]]

# Instead of x.loc[index1, 3] = x.loc[index2, 2]+2
arr[index1, 2] = arr[index2, 1] + 2
print(arr)
# [[0 1 6]
#  [3 4 9]
#  [6 7 8]]

# Instead of x.loc[index1, 3] = x.loc[index1, 3] + x.loc[index2, 2]
arr[index1, 2] += arr[index2, 1]
print(arr)
# [[ 0  1 10]
#  [ 3  4 16]
#  [ 6  7  8]]

x.loc[:,:] = arr
print(x)
#    1  2   3
# a  0  1  10
# b  3  4  16
# c  6  7   8

rawDescription: Editing values in a pandas dataframe using data from another part of the dataframe


rawDescription: Linear Regression with 3 input vectors and 4 output vectors?


code:
class BaseDatabaseWrapper(object):
    # [...]
    def cursor(self):
        self.validate_thread_sharing()
        if (self.use_debug_cursor or
            (self.use_debug_cursor is None and settings.DEBUG)):
            cursor = self.make_debug_cursor(self._cursor())
        else:
            cursor = util.CursorWrapper(self._cursor(), self)
        return cursor

    def make_debug_cursor(self, cursor):
        return util.CursorDebugWrapper(cursor, self)

rawDescription: See django.db.backends logs in stdout on pycharm


code: print (lambda f: lambda x: f(f,x))(lambda f, x: x if str(x) == str(x)[::-1] else f(f, x + int(str(x)[::-1])))(29)

rawDescription: Generating list until certain condition is met using a single line


rawDescription: Writing a numpy array to binary file with variable integer precision


code:
plt.matshow(data)
plt.show()

rawDescription: Scatter a 2D numpy array in matplotlib

description: Scatter a 2D numpy array in matplotlib


code:
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA

message = 'To be encrypted'
h = SHA.new(message)

key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_v1_5.new(key)
ciphertext = cipher.encrypt(message+h.digest())

rawDescription: RSA communication between Javascript and Python


code:
for top in glob.glob('./*/www/[pP]3*'):
    for root, dirnames, filenames in os.walk(top):
        for filename in fnmatch.filter(filenames, '*.php'):
                matches.append(os.path.join(root, filename))

rawDescription: Crawling Unix for All .php Files in Specific Subdirectories


rawDescription: Writing a list with nested tuples to a csv file


code: cur.execute("SELECT COUNT(*) FROM test WHERE unit_id IN %s", (('0A1',),))

rawDescription: How can I prevent extra quotations being inserted into MySQLdb statement from Python?

description: Prevent extra quotations being inserted into MySQLdb statement from Python


code:
for name in self._fields:  # go through recorded field names
    # get method with name validate_<field name> or None
    inline = getattr(self.__class__, 'validate_%s' % name, None)
    if inline is not None:  # if there is such a method record it
        extra[name] = [inline]

rawDescription: How does WTForms know to use validate_<field name> if it is defined to validate a field?


code:
[mr + [row[-1] for row in matrix[min(i+1, last):min(i+1+grab, last)]]
 for (i, mr) in enumerate(matrix)]

rawDescription: Transpose and copy column data to each row


code:
txt = "mydrive/projects/test/version01"
txt.rfind('/')

rawDescription: RegEx - Find Position of last found symbol in String


rawDescription: Python recursion not returning value

description: Python recursion not returning value


code:
def rad_type(particle):

   my_dict = {}

   for (k, v) in particle.items():
        if (k[0] in my_dict):
            my_dict[k[0]] += v
        else:
            my_dict[k[0]] = v

   return my_dict

rawDescription: How to remove duplicate items in multiple tuples of a dictionary?

description: Remove duplicate items in multiple tuples of a dictionary


code:
import Cookie
import cookielib
cookiejar =cookielib.LWPCookieJar()

br = mechanize.Browser()
br.set_cookiejar(cookiejar)
cookie = cookielib.Cookie('ASPSESSIONIDAEBDRQRT=HBODDIACJNHNMHNHBBIHOEGO; ASPSESSIONIDCEAATTSQ=ECNDDBKCJBMAHBIJOCJAEPEO')
cookiejar.set_cookie(cookie)

rawDescription: Adding new cookies with Mechanize Python


code:
dd['date'] = pd.to_datetime(dd['date'])
dd

rawDescription: Dataframe groupby - return delta time for log entries


code:
import datetime

def time_slots(start_time, end_time):
    t = start_time
    while t <= end_time:
        yield t.strftime('%H:%M')
        t = (datetime.datetime.combine(datetime.date.today(), t) +
             datetime.timedelta(minutes=15)).time()

rawDescription: Create 15-min slots between two hours in Django


code: s = 'Hello. %s' % var

rawDescription: Python print_r which returns value instead of printing it


rawDescription: Python make more scalable of a given list products


code: y = np.maximum(np.minimum(y, 10.), 0.)

rawDescription: Capping linear regression prediction values using scikit


code:
def is_palindrome(my_str):
    letters = [c.casefold() for c in my_str if c.isalpha()]
    return letters == letters[::-1]

rawDescription: Can I make a code in python that ignores special characters such as commas, spaces, exclamation points, etc?

description: Make a code in python that ignores special characters such as commas, spaces, exclamation points, etc


code:
background_image = """\
019248a8b2f129d    # obviously not real data  ;)
c12e0284a8172f0
""".strip()

rawDescription: How to convert a string to an image to make a single executable

description: Convert a string to an image to make a single executable


rawDescription: Can we change background color of checkbox text in WxPython?


code:
import time
import subprocess

tasks = ["task1.py", "task2.py", ..., "task64.py"]
for t in tasks:
    subprocess.call(["python", task], shell=True)
    time.sleep(4)

rawDescription: Staggering tasks using Crontab

description: Staggering tasks using Crontab


rawDescription: Python Selenium: 2 buttons with same class?


code:
class SortedDict(dict):
    def __iter__(self):
        return iter(sorted(super(SortedDict, self).__iter__()))

    def items(self):
        return iter((k, self[k]) for k in self)

    def keys(self):
        return list(self)

    def values(self):
        return [self[k] for k in self]

rawDescription: How to make a sorted dictionary class?

description: Make a sorted dictionary class


code:
search_set = set().union(searchlst1, searchlst2, searchlst3)
mainlst = [x for x in mainlst if x not in search_set]

rawDescription: Check list item against multiple lists and remove if present in any of them. Python


code:
i = np.array(range(4)[::-1]*6).reshape(a.shape)
i

rawDescription: Numpy: Sorting a multidimensional array by a multidimensional array


code:
from PyQt4 import QtCore, QtGui

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(277, 244)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.show()

class MyWindow(QtGui.QMainWindow):
    def closeEvent(self,event):
        result = QtGui.QMessageBox.question(self,
                      "Confirm Exit...",
                      "Are you sure you want to exit ?",
                      QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)
        event.ignore()

        if result == QtGui.QMessageBox.Yes:
            event.accept()

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = MyWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    sys.exit(app.exec_())

rawDescription: PyQt's QMainWindow closeEvent is never called


code:
from PIL import Image

col = Image.open("cat-tied-icon.png")
gray = col.convert('L')
bw = gray.point(lambda x: 0 if x<128 else 255, '1')
bw.save("result_bw.png")

rawDescription: Convert RGB to black OR white

description: Convert RGB to black OR white


code:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
damn = '{0} Dmn'.format(locale.format('%d', self.damn, True))

rawDescription: python locale currency to 0 decimals

description: Python locale currency to 0 decimals


rawDescription: Creating tables in matplotlib

description: Creating tables in matplotlib


code:
def helloGalaxy(original_function):
    def new_function(*args, **kwargs):
        original_function(*args, **kwargs)   <-- (2)
        print("Hello, galaxy!")
    return new_function

rawDescription: Explain how Python decorator works

description: Explain how Python decorator works


code:
#test2.py
if __name__ == "__main__" and not __package__:
    print("idle trick")
    from relative_import_helper import relative_import_helper
    __package__ = relative_import_helper(__file__,2)

from .. import A
...

rawDescription: How to use relative import without doing python -m?

description: Use relative import without doing python -m


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

    def __lt__(self, other):
        return [self.name, '<', other]

def myfunc(arg):
    print(arg)

myage = col('myage')
myfunc(myage < 10)

rawDescription: Take logic operation it self not only the boolean result as a input of function in PYTHON


code:
A[-1] += B[0]  # update the last element of A to tag on contents of B[0]
A.extend(B[1:])  # extend A with B but exclude the first element

rawDescription: Joining two list whereby the last element of list "A" and first element of list "B" are concatenated


code:
HeaderTable = doc.Sections(1).Headers(1).Range.Tables(1)
FooterTable = doc.Sections(1).Footers(1).Range.Tables(1)

rawDescription: Reading Table Contet In Header And Footer In MS-Word File Using Python


rawDescription: Numpy: given a vector of 0s and 1s, how to efficiently use Numpy functions manipulate values in another array, based on 0/1 value of first array?


rawDescription: numpy - how to outer join arrays

description: Numpy - how to outer join arrays


code:
a = Rectangle(3.2,5.1)
a.area
a.perimeter
a.length=2
a.area
a.perimeter
a.length

rawDescription: Rectangle OOP/classes

description: Rectangle OOP/classes


code: getattr(self, func)(*args)

rawDescription: How to pass list elements as arguments

description: Pass list elements as arguments


code:
Counter("foos") - Counter("foo")
Counter("foo") - Counter("foos")
Counter("pauls") - Counter("paul")
Counter("paul") - Counter("paul")

rawDescription: sets operations on lists

description: Sets operations on lists


code:
solution = defaultdict(list)
for first,*rest in my_problem:
    solution[first].append(rest)

rawDescription: List of three-tuples to a dictionary of list of lists


code: file --mime-type --mime-encoding

rawDescription: Processing (binary?) file in python and linux shell


code:
import glob
glob.glob("mytest.*")

rawDescription: Python check all file with a specific name in a directory


code:
stty -F /dev/ttyAMA0 -isig
stty -F /dev/ttyAMA0 -icanon

rawDescription: Serial Port Reading with PHP weirdness

description: Serial Port Reading with PHP weirdness


code:
def newFunct(str, test):
    return (lambda x: str if test(x) else "")
is_even = newFunct("even", lambda x: x % 2 == 0)

rawDescription: Add a variable test to a function

description: Add a variable test to a function


code: data = json.load(outfile)

rawDescription: Is there an easy way to edit a json file with python


code: primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

rawDescription: Python Set Comprehension

description: Python Set Comprehension


code:
class Collection():
    def __init__(self, db, collection_name):
        self.db = db
        self.collection_name = collection_name

        if not hasattr(self.__class__, 'client'):
            self.__class__.client = MongoClient()

        database = getattr(self.client, self.db)
        self.collection = getattr(database, self.collection_name)

rawDescription: can I have a mongodb collection as a class attribute in python

description: Have a mongodb collection as a class attribute in python


code: re.sub('[:\s+]', '', soup.find('strong', text=re.compile('Date')).next_sibling)

rawDescription: Finding end tag content in HTML with BeautifulSoup


code:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

class EmailUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(email=self.normalize_email(email),)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        user = self.create_user(email, password=password,)
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

class EmailUser(AbstractBaseUser, PermissionsMixin):
    email = EmailField(
        verbose_name='email',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    objects = EmailUserManager()

    USERNAME_FIELD = 'email'

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def __str__(self):
        return self.email

    @property
    def is_staff(self):
        return self.is_admin

rawDescription: Django registration redux registration only with email (no password)


rawDescription: Ipython notebook align Latex equations in Ipython.Display module


code:
p = re.compile(r'\\\*')
assert p.search(r'\*')

rawDescription: why \* escapes even when it is a raw string?

description: Why \* escapes even when it is a raw string


rawDescription: Convert a file into a matrix, replace each character with a number in Python


code: dfs = {m: df.loc[df.month == m, :] for m in df.month.unique()}

rawDescription: calculate standard deviation and plot the curving fit using Python 2.7

description: Calculate standard deviation and plot the curving fit using Python 2.7


code: info = LAPACKE_dgtsv(LAPACK_COL_MAJOR, ...)

rawDescription: Wrapping a LAPACKE function using Cython


code:
import operator as op
from functools import reduce

def get_num_divisors(factorization):
    return reduce(op.mul, (e+1 for _, e in factorization), 1)

rawDescription: Find the number of divisors of (N!)^2

description: Find the number of divisors of (N!)^2


code:
def import_progress():
    """
    Just a small example
    """
    for number in range(1, 101):
        sse_id = str(number)
        sse_data = str(number)
        sse_event = 'import-progress'

        if number == 100:
            sse_event = 'last-item'
            sse_data = url_for('product_list')

        yield "id:{_id}\nevent:{event}\ndata:{data}\n\n".format(
            _id=sse_id, event=sse_event, data=sse_data)

rawDescription: How to redirect when server-sent-event is finished in Flask on server side?

description: Redirect when server-sent-event is finished in Flask on server side


rawDescription: How to associate multiple things using dictionary?

description: Associate multiple things using dictionary


code:
def cap(iterable, maximum):
    for n in iterable:
        if n > maximum:
            break

        yield n

pages = list(cap(parse_ranges('1, 3, 4-7, 9-'), 20))

rawDescription: How to represent a dynamic list of ranges?

description: Represent a dynamic list of ranges


code: a = map(hex, xrange(pow(2,16) - 1))

rawDescription: Generate a list of hexadecimal numbers in python


rawDescription: Numpy: Rearrange array based upon index array


code:
def make_comp_func(i, j):
    return lambda: nodes[i].value() == nodes[j].value()

for i in [0, 1, 2]:
    j = i + 3
    results.append(make_comp_func(i, j))

rawDescription: Deferred evaluation with lambda in Python


code:
del L[:]
L.append(L1)

rawDescription: Filtering a list of strings in python

description: Filtering a list of strings in python


code:
import subprocess
# You may want to set some options in the following line ...
p = subprocess.Popen(['my_command'] + counters[:1])
p.communicate()

rawDescription: Python: Combining string and lists

description: Python: Combining string and lists


rawDescription: How to Read Reg_Binary type values in string format from Registry in python


code: df = df['uids'].apply(set) # great thanks to EdChum

rawDescription: How to convert list into set in pandas?

description: Convert list into set in pandas


code:
import numpy as np
from sklearn.preprocessing import LabelBinarizer
lb = LabelBinarizer()
label = lb.fit_transform(['yes', 'no', 'no', 'yes'])
label = np.hstack((label, 1 - label))
label

rawDescription: sklearn LabelBinarizer returns vector when there are 2 classes

description: Sklearn LabelBinarizer returns vector when there are 2 classes


code:
import sys
class Quitter(object):
    def __repr__(self):
        sys.exit()

exit = Quitter()

rawDescription: exit from ipython

description: Exit from ipython


code:
def save(self, commit=True):
    # Call save of the super of your own class,
    # which is UserCreationForm.save() which calls user.set_password()
    user = super(RegistrationForm, self).save(commit=False)

    # Add the things your super doesn't do for you
    user.email = self.cleaned_data['email']
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']

    if commit:
        user.save()

    return user

rawDescription: Extending UserCreationForm: password not saved


code: Animal = namedtuple('Animal', 'number_of_legs favourite_food')

rawDescription: Grouping constants in python

description: Grouping constants in python


code:
data_out = [
    {
        'address': u'2a00:2384:0:208f::13',
        'hostname': u'static.bt.com',
        'ports': {
            80: {
                'state': u'open',
                'reason': u'syn-ack'
            },
            443: {
                'ssl_cert': u'place   holder',
                'state': u'open',
                'reason': u'syn-ack'
            }
        }
    }
]

rawDescription: Python - Iterating lists and dictionaries


code:
uid = re.compile(r"uid=(\d*)")
uids = [match.group(1) for match in filter(None, map(uid.search, list_of_urls))]

rawDescription: Python extract value beautifulsoup regex


code: from all_my_imports import *

rawDescription: Globally loading classes or functions for any file in an application in Python


code:
idx = df.category == 'Random'
xs = df.category[~idx].unique()  # all other categories

# randomly assign to categories which are 'Random'
df.category[idx] = np.random.choice(xs, idx.sum())

rawDescription: Distributing a pandas DataFrame feature at random


code:
t1 = MyTime(5,5,5)
t1.hours
t1.hours()
t1.seconds
t1.totalsecs
t1.increment(10)
t1.seconds
t1.totalsecs

rawDescription: Python3/Classes/OOP/ How do you change a objects self values with a method?