code:
from tkinter import *
import pickle
import os
import __main__

class Drag_Shape:
    filename = os.path.basename(__main__.__file__)
    filename = filename[:filename.index('.')]+'_coords.py'
    print(__main__.__file__)

    if os.path.isfile(filename) == False:
        foorbar = open(filename, 'w')
        foorbar.close()

    if os.path.getsize(filename) == 0: coords_dict = {}
    else:
        with open(filename, 'rb') as shape_cords:
            coords_dict = pickle.load(shape_cords)
    data = {'x': 0, 'y': 0}

    def __init__(self, canvas, *coords, shape = 'rect', fill = 'white', outline = 'black', width = 1, activefill = '',
        activeoutline = 'black', activewidth = 1, disabledfill = '', disabledoutline = 'black', disabledwidth = 1,
        state = ''):

        self.canvas = canvas
        self.shape = shape.lower()
        print(shape)
        print(coords)
        for i in self.coords_dict.keys():
            if shape.lower() in i: shape = i.lower()

        if coords != (): self.coords_dict.update({shape:coords})
        else: coords = self.coords_dict[shape]

        if shape in 'line':
            tag = 'line'
            ID = canvas.create_line(coords, tags = tag, fill = fill, width = width,
            activefill = activefill, activewidth = activewidth, disabledfill = disabledfill,
            disabledwidth = disabledwidth, state = '')

        elif shape in 'rectangle':
            tag = 'rect'
            ID = canvas.create_rectangle(coords, tags = tag, fill = fill, outline = outline, width = width,
            activefill = activefill, activeoutline = activeoutline, activewidth = activewidth, disabledfill = disabledfill,
            disabledoutline = disabledoutline, disabledwidth = disabledwidth, state = '')

        elif shape in 'oval':
            tag = 'oval'
            ID = canvas.create_oval(coords, tags = tag, fill = fill, outline = outline, width = width,
            activefill = activefill, activeoutline = activeoutline, activewidth = activewidth, disabledfill = disabledfill,
            disabledoutline = disabledoutline, disabledwidth = disabledwidth, state = '')

        elif shape in 'arc':
            tag = 'arc'
            ID = canvas.create_arc(coords, tags = tag, fill = fill, outline = outline, width = width,
            activefill = activefill, activeoutline = activeoutline, activewidth = activewidth, disabledfill = disabledfill,
            disabledoutline = disabledoutline, disabledwidth = disabledwidth, state = '')

        elif shape in 'polygon':
            tag = 'poly'
            ID = canvas.create_polygon(coords, tags = tag, fill = fill, outline = outline, width = width,
            activefill = activefill, activeoutline = activeoutline, activewidth = activewidth, disabledfill = disabledfill,
            disabledoutline = disabledoutline, disabledwidth = disabledwidth, state = '')

        elif shape in 'window':
            tag = 'win'
            ID = canvas.create_window(coords, tags = tag, fill = fill)

        elif shape in 'text':
            tag = 'text'
            ID = canvas.create_text(coords, tags = tag, fill = fill)

        elif shape in 'image':
            tag = 'img'
            ID = canvas.create_image(coords, tags = tag, fill = fill)

        elif shape in 'bitmap':
            tag = 'bitmap'
            ID = canvas.create_bitmap(coords, tags = tag, fill = fill)

        self.ID = ID
        self.tag = tag

        with open(self.filename, 'wb') as shape_coords:
            pickle.dump(self.coords_dict, shape_coords)

        canvas.tag_bind(tag, '<Button-1>', self.click)
        canvas.tag_bind(tag, '<Button1-Motion>', self.track)
        canvas.tag_bind(tag, '<ButtonRelease-1>', self.release)

    def click(self, event):
        self.data.update({'x': event.x, 'y': event.y})
        self.item = self.canvas.find_closest(self.data['x'], self.data['y'])
        return self.item

    def track(self, event):
        x, y = event.x - self.data['x'], event.y - self.data['y']
        self.canvas.move(self.item, x, y)
        self.data.update({'x': event.x, 'y': event.y})

    def release(self, event):
        self.data.update({'x': event.x, 'y': event.y})
        coords = list(self.canvas.coords(self.item))
        self.coords_dict.update({self.shape : coords})
        with open(self.filename, 'wb') as shape_coords:
            pickle.dump(self.coords_dict, shape_coords)
        return self.ID

rawDescription: (Python-3) How do you maintain the value of a variable that was changed by the program it was ran by?


code: id_array = [x.id for x in _get_object_array() if x.id % 2 == 0]

rawDescription: Python for loop with condition

description: Python for loop with condition


rawDescription: Which encoding?

description: Which encoding


code:
...

def validate_unique(self, exclude=None):
    if not self.is_deleted and \
       LibraryEntry.objects.exclude(pk=self.pk).filter(host_lib_song_id=self.host_lib_song_id, owning_user=self.owning_user).exists():
        raise ValidationError('Some error message about uniqueness required')
    super(LibraryEntry, self).validate_unique(exclude=exclude)

rawDescription: Django conditional unique together

description: Django conditional unique together


code:
import tkinter as tk

class SimpleTableInput(tk.Frame):
    def __init__(self, parent, rows, columns):
        tk.Frame.__init__(self, parent)

        self._entry = {}
        self.rows = rows
        self.columns = columns

        # register a command to use for validation
        vcmd = (self.register(self._validate), "%P")

        # create the table of widgets
        for row in range(self.rows):
            for column in range(self.columns):
                index = (row, column)
                e = tk.Entry(self, validate="key", validatecommand=vcmd)
                e.grid(row=row, column=column, stick="nsew")
                self._entry[index] = e
        # adjust column weights so they all expand equally
        for column in range(self.columns):
            self.grid_columnconfigure(column, weight=1)
        # designate a final, empty row to fill up any extra space
        self.grid_rowconfigure(rows, weight=1)

    def get(self):
        '''Return a list of lists, containing the data in the table'''
        result = []
        for row in range(self.rows):
            current_row = []
            for column in range(self.columns):
                index = (row, column)
                current_row.append(self._entry[index].get())
            result.append(current_row)
        return result

    def _validate(self, P):
        '''Perform input validation.

        Allow only an empty value, or a value that can be converted to a float
        '''
        if P.strip() == "":
            return True

        try:
            f = float(P)
        except ValueError:
            self.bell()
            return False
        return True

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.table = SimpleTableInput(self, 3, 4)
        self.submit = tk.Button(self, text="Submit", command=self.on_submit)
        self.table.pack(side="top", fill="both", expand=True)
        self.submit.pack(side="bottom")

    def on_submit(self):
        print(self.table.get())

root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()

rawDescription: Python. GUI(input and output matrices)?

description: Python. GUI(input and output matrices)


code:
for src, dst in zip(source, destination):
    copy(src, dst)

rawDescription: Copy large list of files from one location to another


code:
def menu():

 while True:
            u_in=raw_input("Input Here:: ")
            u=u_in.lower()
            if u_in=="":
                    continue

            elif u=="i":
                     Instructions()
            elif u=="c":
                    Catering()
            elif u=="p":
                    Packages()

rawDescription: Python Selecting menu choice

description: Python Selecting menu choice


code: from sqlite import *

rawDescription: How do I extend a python module to include extra functionality? (sqlite3)

description: Extend a python module to include extra functionality? (sqlite3)


code:
with open('1000dig.txt', 'r') as f:
    num_string = ''.join((line.strip() for line in f.readlines()))

d = {i: digit for i, digit in enumerate(num_string)}

rawDescription: create a dict using numbers as keys and values from ints stored in a list in python?

description: Create a dict using numbers as keys and values from ints stored in a list in python


code:
from time import sleep
import multiprocessing

def setup(event):
    global unpaused
    unpaused = event

def myFunction(arg):
    for i in range(10):
        unpaused.wait()
        print(arg)
        sleep(1)

if __name__ == "__main__":
    event = multiprocessing.Event() # initially unset, so workers will be paused at first
    pool = multiprocessing.Pool(3, setup, (event,))
    result = pool.map_async(myFunction, ["foo", "bar", "baz"])
    event.set()   # unpause workers
    sleep(5)
    event.clear() # pause after five seconds
    sleep(5)
    event.set()   # unpause again after five more seconds
    result.wait() # wait for the rest of the work to be completed

rawDescription: How to pause multiprocessing Pool from execution

description: Pause multiprocessing Pool from execution


code:
textFile = open(filename, 'r')
#open() returns a file object
#'r' opens the file for reading. 'w' would be writing
textString = textFile.read()
#This takes the file object opened with the open() and turns it into a string which
#you can now use textString in a text widget.

rawDescription: How to open text files using a listbox in Tkinter

description: Open text files using a listbox in Tkinter


code:
from collections import Counter

def has_palindrome(string):
    return sum(v % 2 for v in Counter(string).values()) <= 1

print(has_palindrome('abcabcc'))  # True
print(has_palindrome('abc'))  # False

rawDescription: Check string to see if it is a palindrome of any of it's permutations


rawDescription: Return at least X results from split

description: Return at least X results from split


code:
client_connection.sendall(ip+":"+port)
try:
    client_connection.shutdown(socket.SHUT_WR)  # signal end of strem
    while True:  # wait for the client to close or shutdown his side
        q = client_connection.recv(1024)
        if len(q) == 0:
            break
finally:
    client_connection.close()  # close the socket only after the client has close its side

rawDescription: How to call a function after some interval in python server?

description: Call a function after some interval in python server


code:
def __onLClicked(self, event):
    linestart = self.index("@{0},{1} linestart".format(event.x, event.y))
    lineend = self.index("{} lineend".format(linestart))

    self.tag_remove("current_line", 1.0, "end")
    self.tag_add("current_line", linestart, lineend)

rawDescription: Tkinter Text widget - identify line by y-coord


rawDescription: How can I store the selected element in a dropdown menu using a Selenium/Python script?

description: Store the selected element in a dropdown menu using a Selenium/Python script


code:
class Text(pygame.sprite.Sprite):
    def __init__(self, text, size, color, width, height):
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)

        self.font = pygame.font.SysFont("Arial", size)
        self.textSurf = self.font.render(text, 1, color)
        self.Surf = pygame.Surface((width, height))
        W = self.textSurf.get_width()
        H = self.textSurf.get_height()
        self.Surf.blit(self.textSurf, width/2 - W/2, height/2 - H/2)

rawDescription: Python pygame writing text in sprite

description: Python pygame writing text in sprite


rawDescription: How to count ending 0s in binary string

description: Count ending 0s in binary string


code:
import itertools
import operator

xs = [32, 6, 12]
target = 5

next(i for i, x in enumerate(itertools.accumulate(xs, operator.add)) if x > target)

rawDescription: Find index of a list using the sum of the list elements


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

import subprocess

def detach(cmd):
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

def start_everything():

    detach('firefox http://google.com')
    detach('firefox http://yahoo.com')

    # or you can start anything the same way

    detach('audacious')
    detach('leafpad')
    detach('gimp')

start_everything()

rawDescription: How to open another tab in command line and proceed there with fabric?

description: Open another tab in command line and proceed there with fabric


code:
import random
listOne = ['Blue', 'Red', 'Green']
listTwo = [1, 2, 3]
random.shuffle(listTwo)
zip(listOne, listTwo)
random.shuffle(listTwo)
zip(listOne, listTwo)

rawDescription: Python:get a couple of values from two different list


code:
from collections import Counter
summary = Counter()
with open('report_data.csv') as f:
    f.readline()
    for line in f:
        lbl, n = line.split(",")
        n = int(n)
        summary[lbl] = summary[lbl] + n

rawDescription: Python dictionary created from CSV file should merge the value (integer) whenever the key repeats


rawDescription: Trying to use hex() without 0x

description: Trying to use hex() without 0x


code:
# Hack to find machine NIC IP
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.4.4", 80))
MACHINE_IP = s.getsockname()[0]
s.close()

rawDescription: What's the best way for a Django app to get the current IP address of eth0


code:
self.string_var = []                        # create empty list
for i in xrange(self.initial_numbers):
    self.string_var.append(StringVar())     # append to list
    self.string_var[i].set("test")          # access var at index i

rawDescription: Creating StringVar() class variables

description: Creating StringVar() class variables


code: import this

rawDescription: What is the preferred Python 3.x class definition syntax?


code:
import re
re.findall("href=([^ >]+)",x)

rawDescription: Filtering a variable so it only contains a specified string python


code:
links = [(item.css('::text').extract()[0],
          item.css('::attr(href)').extract()[0])
         for item in response.css('.foo')]
loader.add_value('links', links)

rawDescription: Is it possible to use ItemLoaders for parsing HTML nodes?


code:
''' Get windows special folders without pythonwin
    Example:
            import specialfolders
            start_programs = specialfolders.get(specialfolders.PROGRAMS)

Code is public domain, do with it what you will.

Luke Pinner - Environment.gov.au, 2010 February 10
'''

#Imports use _syntax to mask them from autocomplete IDE's
import ctypes as _ctypes
from ctypes.wintypes import HWND as _HWND, HANDLE as _HANDLE,DWORD as _DWORD,LPCWSTR as _LPCWSTR,MAX_PATH as _MAX_PATH, create_unicode_buffer as _cub
_SHGetFolderPath = _ctypes.windll.shell32.SHGetFolderPathW

#public special folder constants
DESKTOP=                             0
PROGRAMS=                            2
MYDOCUMENTS=                         5
FAVORITES=                           6
STARTUP=                             7
RECENT=                              8
SENDTO=                              9
STARTMENU=                          11
MYMUSIC=                            13
MYVIDEOS=                           14
NETHOOD=                            19
FONTS=                              20
TEMPLATES=                          21
ALLUSERSSTARTMENU=                  22
ALLUSERSPROGRAMS=                   23
ALLUSERSSTARTUP=                    24
ALLUSERSDESKTOP=                    25
APPLICATIONDATA=                    26
PRINTHOOD=                          27
LOCALSETTINGSAPPLICATIONDATA=       28
ALLUSERSFAVORITES=                  31
LOCALSETTINGSTEMPORARYINTERNETFILES=32
COOKIES=                            33
LOCALSETTINGSHISTORY=               34
ALLUSERSAPPLICATIONDATA=            35

def get(intFolder):
    _SHGetFolderPath.argtypes = [_HWND, _ctypes.c_int, _HANDLE, _DWORD, _LPCWSTR]
    auPathBuffer = _cub(_MAX_PATH)
    exit_code=_SHGetFolderPath(0, intFolder, 0, 0, auPathBuffer)
    return auPathBuffer.value

rawDescription: How to get path of Start Menu's Programs directory?

description: Get path of Start Menu's Programs directory


code: sorted(data, key=lambda entry: sum(entry[1]))

rawDescription: Ordering a list of items based on their second value


code:
import tkinter
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

def moved(event):
    canvas.itemconfigure(tag, text="(%r, %r)" % (event.x, event.y))

canvas.bind("<Motion>", moved)
tag = canvas.create_text(10, 10, text="", anchor="nw")

root.mainloop()

rawDescription: How to display canvas coordinates when hovering cursor over canvas?

description: Display canvas coordinates when hovering cursor over canvas


code:
data=[]

for x in xrange(100):
    data.append(raw_input("Your data: "))

rawDescription: Python wondering about user input

description: Python wondering about user input


code:
from Tkinter import *
import ttk

root = Tk()
root.title("This space intentionally left blank")
root.minsize(800,200)
mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)

def nextInputs(*args):
    sen.set(inputs())

inputs = open("inputs.txt").readline
sen = StringVar()
ttk.Label(mainframe, textvariable=sen).grid(column=1, row=1, columnspan=99)
Button = ttk.Button(mainframe, text = "next", command = nextInputs).grid(column=99, row=5, pady=5)
root.bind('<Return>', nextInputs)
root.mainloop()

rawDescription: TKinter Change Label with "Next" Button

description: TKinter Change Label with "Next" Button


code:
step1 = pm.NUTS(vars=[p, q])
step2 = pm.Metropolis(vars=[A])

trace = pm.sample(3000, [step1, step2], start)

rawDescription: Difficulities on pymc3 vs. pymc2 when discrete variables are involved


rawDescription: Python : comparing tuples

description: Python : comparing tuples


code:
local_data = {'batsman': 'Sangakkara', 'bowler': 'swann'}
mapped_instance_from_query._local_data = local_data

rawDescription: sqlalchemy objects as dict keys?

description: Sqlalchemy objects as dict keys


code:
from dateutil.parser import parse
date1 = 'Tue Feb 10  2015 12 52pm IST'
parse(date1)
date1_with_colon = 'Tue Feb 10  2015 12:52pm IST'
parse(date1_with_colon)
date2_with_colon = '10 February  15  08:35am'
parse(date2_with_colon)
date3_with_colon = '2015 02 10 08:24:26 UTC'
parse(date3_with_colon)

rawDescription: Parser date in Python

description: Parser date in Python


code:
count  = 0
coin=[200,100,50,20,10,5,2,1]
total=[200,0,0,0,0,0,0,0]

def func(i):
    global count,total,coin
    for x in range(total[i-1]/coin[i-1]+1):
        total[i]=total[i-1]-x*coin[i-1]
        if (i == 7):
            count += 1
        else:
            func(i+1)

rawDescription: Python: simplifying nested FOR loop?

description: Python: simplifying nested FOR loop


code:
def humanize(n):
   base=1000.0   # replace with 1024 if you want kib Mib etc
   letters=['','k','M','G','T','P','E','Z','Y']
   f=float(n)
   for x in letters:
       if f < base: break
       f /= base
   return '{:.3}{}b'.format(f,x) # change {}b to {}ib if working with kib etc.

rawDescription: Multiple bit manipulation in python

description: Multiple bit manipulation in python


code:
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from subprocess import Popen, PIPE

class CygwinFirefoxProfile(FirefoxProfile):

    @property
    def path(self):

        path = self.profile_dir

        # cygwin requires to manually specify Firefox path a below:
        # PATH=/cygdrive/c/Program\ Files\ \(x86\)/Mozilla\ Firefox/:$PATH
        try:
            proc = Popen(['cygpath','-d',path], stdout=PIPE, stderr=PIPE)
            stdout, stderr = proc.communicate()
            path = stdout.split('\n', 1)[0]

        except OSError:
            print("No cygwin path found")

        return path

class CarServiceOnlineBookingsTest(unittest.TestCase):

    def setUp(self):

        firefoxProfile = CygwinFirefoxProfile()

        ## Disable CSS
        firefoxProfile.set_preference('permissions.default.stylesheet', 2)
        ## Disable images
        firefoxProfile.set_preference('permissions.default.image', 2)
        ## Disable Flash
        firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')

        self.driver = webdriver.Firefox(firefoxProfile)

rawDescription: Allow Selenium Webdriver to find Firefox path in cygwin and standard installs


code:
from pydub import AudioSegment

sound = AudioSegment.from_mp3("test.mp3")

# sound._data is a bytestring
raw_data = sound._data

rawDescription: How to extract the raw data from a mp3 file using python?

description: Extract the raw data from a mp3 file using python


code:
from .models import Plaintext, Ciphertext

def create_plain_and_cipher_text(sender, instance, created, **kwargs):
    if created:
        Plaintext.objects.create(message=instance)
        Ciphertext.objects.create(message=instance)

rawDescription: Django - Triggering creation of other instances when one instance is created


code:
import itertools
with open(filename) as fin:
    ilines = itertools.islice(fin, 2, None) #this throws away the first 2 lines
    lines = sorted(ilines, key=lambda x: x.split()[0])  #sort lexicographically on first column

with open('header') as header, open('%s.header'%filename) as fout:
    fout.writelines(header) #write the header
    fout.writelines(lines) #write the data

rawDescription: remove header and add another one

description: Remove header and add another one


code:
import math
def hi_bit(num):
        return int(math.log(num, 2))

rawDescription: How to take inverse of 2 raise to something in python2.5 (strict)

description: Take inverse of 2 raise to something in python2.5 (strict)


code:
def weight_array(ar, weights):
     zipped = zip(ar, weights)
     weighted = []
     for i in zipped:
         for j in range(i[1]):
             weighted.append(i[0])
     return weighted

np.percentile(weight_array(ar, weights), 25)

rawDescription: Weighted percentile using numpy

description: Weighted percentile using numpy


code:
service.start()
worker_1.start()
worker_1.join()
service.terminate()

rawDescription: Run server and client in the same file - python


code:
import Tkinter as tk
root = tk.Tk()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

root.bind('<Motion>', motion)
root.mainloop()

rawDescription: Mouse Position Python Tkinter

description: Mouse Position Python Tkinter


code: [item.strip() for item in mystring.split(',') if len(item.split()) < 2]

rawDescription: python filter string only showing tags less than 2 words

description: Python filter string only showing tags less than 2 words


code: urllist = ['/myurl/%s' % the_file for the_file in mylist]

rawDescription: Python Lists Beginner

description: Python Lists Beginner


code:
from scipy import signal
cor = signal.correlate2d (im1, im2)

rawDescription: how to find the correlation between two images

description: Find the correlation between two images


code:
def create_attr_filter(request, mapped_class):
    """Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
    on the request params (``queryable``, ``eq``, ``ne``, ...).

    Arguments:

    request
        the request.

    mapped_class
        the SQLAlchemy mapped class.
    """

    mapping = {
        'eq'   : '__eq__',
        'ne'   : '__ne__',
        'lt'   : '__lt__',
        'lte'  : '__le__',
        'gt'   : '__gt__',
        'gte'  : '__ge__',
        'like' : 'like',
        'ilike': 'ilike'
    }
    filters = []
    if 'queryable' in request.params:
        queryable = request.params['queryable'].split(',')
        for k in request.params:
            if len(request.params[k]) <= 0 or '__' not in k:
                continue
            col, op = k.split("__")
            if col not in queryable or op not in mapping.keys():
                continue
            column = getattr(mapped_class, col)
            f = getattr(column, mapping[op])(request.params[k])
            filters.append(f)
    return and_(*filters) if len(filters) > 0 else None

rawDescription: Tool for generating SQLAlchemy queries from JSON-esque values?


code:
@receiver(pre_save, sender=Card)
def add_auto_pk(sender, instance, **kwargs):
    if not instance.custom_pk:
        instance.custom_pk = Card.get_id()

rawDescription: Django: Auto Instantiation of custom primary key?


code:
def clean(self):
    if self.cleaned_data['image'] is not None or self.cleaned_data['content'] != '' :
          return super().clean() #For python 3
          #return super(YourForm, self).clean() // for python 2
    raise ValidationError('Some Error')

rawDescription: Django form re-validation for null/blank fields


code:
import win32com.client

visio = win32com.client.Dispatch("Visio.Application")
doc = visio.Documents.Add("")
stn = visio.Documents.Open("BASIC_M.VSS")

page = doc.Pages.Item(1)

master = stn.Masters.Item("Rectangle")
rect = page.Drop(master, 0, 0)

doc.SaveAs("C:\\<some directory>\\file.vdx")
doc.Close()

visio.Quit()

rawDescription: Use .vss stencil file to generate shapes by python code (use .vdx?)


code:
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
    globals()[name] = value

rawDescription: How to programmatically set a global (module) variable?

description: Programmatically set a global (module) variable


code:
with open('file.csv') as fd:
    reader=csv.reader(fd)
    interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)]
# now interestingrows contains the 28th and the 62th row after the header

rawDescription: CSV read specific row

description: CSV read specific row


code:
import CGIHTTPServer

def is_cgi(self):
    if self.path.endswith('.py'):
        self.cgi_info = CGIHTTPServer._url_collapse_path_split(self.path)
        return True
    return False

CGIHTTPServer.CGIHTTPRequestHandler.is_cgi = is_cgi

rawDescription: Full fledged local CGI Server

description: Full fledged local CGI Server


code:
#To write to a file:
with open("file.txt", "w") as f:
    f.write("Data!")

#To read from a file:
with open("file.txt", "r") as f:
    print(f.read())

rawDescription: Store and recall a variable in a text file Python


code:
from concurrent.futures import ThreadPoolExecutor, Future
from itertools import permutations
from collections import namedtuple, defaultdict

Result = namedtuple('Result', ('value', 'word'))

def new_calculate_similarity(word1, word2):
    return Result(
        calculate_similarity(global_map[word1], global_map[word2]),
        word2)

with ThreadPoolExecutor(max_workers=4) as executer:
    futures = defaultdict(list)
    for word1, word2 in permutations(unique_words, r=2):
            futures[word1].append(
                executer.submit(new_calculate_similarity, word1, word2))

    for word in futures:
        # this will block until all calculations have completed for 'word'
        results = map(Future.result, futures[word])
        max_result = max(results, key=lambda r: r.value)
        print(word, max_result.word, max_result.value,
            sep='\t',
            file=file_co_occurring)

rawDescription: Parallelize a nested for loop in python for finding the max value


code:
max = 2000000    # we only need to check the first 2 million numbers
numbers = []
sum = 0

for i in range(2, max):    # 0 and 1 are not primes
    numbers.append(i)      # fill our blank list
for p in range(2, max):
    if numbers[p - 2] != -1:   # if p (our array stays at 2, not 0) is not -1
        # it is prime, so add it to our sum
        sum += numbers[p - 2]
        # now, we need to mark every multiple of p as composite, starting at 2p
        c = 2 * p
        while c < max:
            # we'll mark composite numbers as -1
            numbers[c - 2] = -1
            # increment the count to 3p, 4p, 5p, ... np
            c += p

print(sum)

rawDescription: Improving runtime on Euler #10

description: Improving runtime on Euler #10


code:
import numpy as np
from scipy.optimize import curve_fit

import matplotlib.pyplot as plt

xdata = np.array([0.1639534, 0.2411005, 0.3130353, 0.3788510,  0.4381247, 0.5373147, 0.6135673, 0.6716365, 0.7506711,  0.8000908, 0.9000000])
ydata =np.array ([7.1257999E-04,9.6610998E-04,1.1894000E-03,1.3777000E-03,1.5285000E-03,1.7297000E-03,1.8226000E-03,1.8422999E-03,1.7741000E-03,1.6574000E-03,1.1877000E-03])

def func (x,a,b,c):
    return a+b*x+c*x**3
popt, pcov = curve_fit(func,xdata,ydata,p0=(1,1,1))

# Plot your original data
plt.plot(xdata, ydata, linestyle='None', marker='x', label='Data')
# Plot your fit using the xdata as x-values and func() to generate the y-values.
plt.plot(xdata, func(xdata, *popt), label='Fit')

plt.legend()

plt.show()

plt.savefig('image.png') # Save the figure.

rawDescription: plotting function from python

description: Plotting function from python


code:
try:
    return abs(number)
except TypeError:
    return 'Nope'

rawDescription: Best practice when constructing if statement based on datatype?


code:
ngram = "good sport"
words = "good day, good night, good sport, good sport charlie"

loc = []
k = 0
while k < len(words):
    if words[k] != ngram[0]:
        k += 1
    elif words[k: k+ len(ngram)] == ngram:
        loc += [k]
        k += 1
    else:
        k += 1

rawDescription: Q How to Plot n-gram positions in text

description: Q How to Plot n-gram positions in text


code:
import wave, sys, pyaudio
sound = wave.open('Sound1.wav')
p = pyaudio.PyAudio()
chunk = 1024
stream = p.open(format =
                p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output = True)
data = wf.readframes(chunk)
while data != '':
    stream.write(data)
    data = wf.readframes(chunk)

rawDescription: Play wav file python 3

description: Play wav file python 3


code:
class Tester(BlogHandler):
    def get(self):
        global visits
        logout = users.create_logout_url(self.request.uri)
        user = users.get_current_user()

        if user:
            currentregistereduser = None
            user_db_qry = User.query(User.theid == user.federated_identity())
            user_db_list = user_db_qry.fetch(1)
            # Check to see if the query returned anything at all - if so, assign
            # the value to currentregistereduser; it not, it will remain None
            if user_db_list:
              currentregistereduser = user_db_list[0]

            if currentregistereduser:
                if not currentregistereduser.username:
                    self.redirect("/profile")
                else:
                    self.render("tester.html", user=user, logout=logout)

        # Assuming the code continues here...

rawDescription: New User with Federated Login Not being Recognized


code:
class AttributeCollection(object):
    pass
shared_settings= AttributeCollection()
# now improvise
shared_settings.temperature= 30
shared_settings.samples= []
# etc

rawDescription: How to modify variables of another scope?

description: Modify variables of another scope


code:
from scipy.cluster import hierarchy
def getNewick(node, newick, parentdist, leaf_names):
    if node.is_leaf():
        return "%s:%.2f%s" % (leaf_names[node.id], parentdist - node.dist, newick)
    else:
        if len(newick) > 0:
            newick = "):%.2f%s" % (parentdist - node.dist, newick)
        else:
            newick = ");"
        newick = getNewick(node.get_left(), newick, node.dist, leaf_names)
        newick = getNewick(node.get_right(), ",%s" % (newick), node.dist, leaf_names)
        newick = "(%s" % (newick)
        return newick

tree = hierarchy.to_tree(Z,False)
getNewick(tree, "", tree.dist, leaf_names)

rawDescription: Save dendrogram to newick format

description: Save dendrogram to newick format


code:
# Here, we mock out a future object, as per GAE docs
promise_obj_stub = ndb.Future()

a_mgr = data_manager.AchievementsHandler()
a_mgr._async_get_specialist = mock.Mock(return_value=promise_obj_stub)

# Initiate data store sync and flush async to force result
future = a_mgr.async_datastore_update()

promise_obj_stub.set_result(['list', 'of', 'results', 'i', 'needed'])  # set a result on the Future obj

future.get_result()  # Works like a charm now

# Continue testing as usual

rawDescription: Setting your own value of NDB Future object when unit testing async operations


code:
from operator import itemgetter
get1 = itemgetter(1)
get1([0,1,2,3,4,5])
get1('abcdefg')

rawDescription: Function to get item from list

description: Function to get item from list


code:
full_image=img.reshape([28,28])
left_side = full_image[:,:14]

rawDescription: Taking the left side of an image in Python


code:
soup = BeautifulSoup("""
  name
  stuff here
""")
soup.find("div", "item").find('br').nextSibling

rawDescription: Getting specific data with BeautifulSoup


code:
def validate_move_rule(from_position, to_position, position_hash):
    to_pos_x = ord(to_position[0])
    to_pos_y = int(to_position[1])
    delta_pos_x = to_pos_x - ord(from_position[0]) # x
    delta_pos_y = to_pos_y - int(from_position[1]) # y

    delta_x = 0
    delta_y = 0

    if abs(delta_pos_x) == abs(delta_pos_y):
        # diagonal
        delta_x = 1 if delta_pos_x > 0 else -1
        delta_y = 1 if delta_pos_y > 0 else -1
    elif from_position[1] == to_position[1]:
        # horizontal
        delta_x = 1 if delta_pos_x > 0 else -1
    elif from_position[0] == to_position[0]:
        # vertical
        delta_y = 1 if delta_pos_y > 0 else -1
    else:
        puts("Error: it's not a legal move(hint: must diagonal horizontal vertical)")
        return False

    new_position = chr(to_pos_x + delta_x) + str(to_pos_y + delta_y)
    return new_position in position_hash

rawDescription: Does python have a better control structure or other feature to simplify the code?


code:
bytes_obj = "FooBar".encode()
type(bytes_obj[:1])
bytes_obj[:1]

rawDescription: Retrieving a bytes object of length 1 from another bytes object


code:
def groupByPrefix(strings):
    stringsByPrefix = {}
    for string in strings:
            prefix, suffix = map(str.strip, string.split("/", 1))
            group = stringsByPrefix.setdefault(prefix, [])
            group.append(suffix)
    return stringsByPrefix

rawDescription: Finding multiple common starting strings


code:
def update(self):
    self.layout().removeWidget(self.child)
    self.child.setParent(None)
    self.child = QLabel("bar", self)
    self.layout().addWidget(self.child)

rawDescription: How to dynamically change child widgets with Python and Qt?

description: Dynamically change child widgets with Python and Qt


code:
parts = urlparse.urlparse("qqqq://base/id#hint")
fake_url = "http:" + parts[2]
parts2 = urlparse.urlparse(fake_url)

rawDescription: Parse custom URIs with urlparse (Python)


rawDescription: Print python float as single precision float


code:
test
index = c.shift(1).cumsum().add(array([selected]).T, fill_value=0)
index
test.iloc[index.values[:,0]]

rawDescription: pandas dataframe groupby and get arbitrary member of each group

description: Pandas dataframe groupby and get arbitrary member of each group


code:
fig, ax = plt.subplots(1, 1)
boxplot = sns.boxplot(x="Regularisierungsparameter", y="F1", data=data.sort("Regularisierungsparameter"), ax=ax)
labels = ['%.5f' % float(t.get_text()) for t in ax.get_xticklabels()]
ax.set_xticklabels(labels)

rawDescription: Prevent scientific notation in seaborn boxplot


code: tuple(x[1:3] for x in C)

rawDescription: How to select a row from a 2D tuple

description: Select a row from a 2D tuple


code:
@app.after_request
def add_header(r):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    r.headers['Cache-Control'] = 'public, max-age=0'
    return r

rawDescription: Disabling caching in Flask

description: Disabling caching in Flask


code:
def print_full(x):
    pd.set_option('display.max_rows', len(x))
    print(x)
    pd.reset_option('display.max_rows')

rawDescription: Is there a way to (pretty) print the entire Pandas Series / DataFrame?


code:
d = range(10)
sys.getsizeof(d)
d[0] = 'text'
sys.getsizeof(d)
d

rawDescription: Why is single int 24 bytes, but in list it tends to 8 bytes


code:
import json

json_data = '{"key1":"{0}","key2":"{1}"}'
format_args = ["value1", "value2"]

data = json.loads(json_data)
formatted_data = {key: value.format(format_args) for key, value in data.items()}

rawDescription: How to format json string in Python

description: Format json string in Python


code:
class MyViewset(ModelViewSet):
    queryset = MyThing.objects.all()
    serializer_class = MyThingSerializer

    def update(self, request, pk=None, **kwargs):
        self.permission_classes = [CustomPermission,]

        return super(MyViewset, self).update(request, pk, **kwargs)

rawDescription: Limit access api view decorator Django through post method


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

x1 = np.arange(10)
y1 = x1**2
x2 = np.arange(100,200)
y2 = x2

fig = plt.figure()

ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8], label="ax1")
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.8], label="ax2", frameon=False)

ax1.yaxis.tick_left()
ax1.xaxis.tick_bottom()

ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')

ax1.spines['right'].set_color('red')
ax1.spines['top'].set_color('red')

for ylabel, xlabel in zip(ax2.get_yticklabels(), ax2.get_xticklabels()):
     ylabel.set_color("red")
     xlabel.set_color("red")

ax1.plot(x1,y1)
ax2.plot(x2,y2, 'r')

plt.show()

rawDescription: Overlayed plots without shared axes: left-bottom vs. top-right pairs (python/matplotlib)


code:
def indices(lst, items):
    last_index = 0

    for item in items:
        last_index += lst.index(item, last_index + 1) + 1

        yield last_index

rawDescription: Python: finding the indices of a list that match the given sublist


code:
import numpy as np
import scipy.odr

n = 1000
t = np.linspace(0, 1, n)

def linfit(beta, x):
    return beta[0]*x[0] + beta[1]*x[1] + beta[2] #notice changed indices for x

x1 = 2.5*np.sin(2*np.pi*6*t)+4
x2 = 0.5*np.sin(2*np.pi*7*t + np.pi/3)+2

x = np.row_stack( (x1, x2) ) #odr doesn't seem to work with column_stack

e = 0.25*np.random.randn(n)
y = 3*x[0] + 4*x[1] + 5 + e #indices changed

linmod = scipy.odr.Model(linfit)
data = scipy.odr.Data(x, y)
odrfit = scipy.odr.ODR(data, linmod, beta0=[1., 1., 1.])
odrres = odrfit.run()
odrres.pprint()

rawDescription: Scipy.Odr multiple variable regression

description: Scipy.Odr multiple variable regression


code:
import ast
import inspect
from collections import OrderedDict

class _NodeTagger(ast.NodeVisitor):
    def __init__(self):
        self.class_attribute_names = {}

    def visit_Assign(self, node):
        for target in node.targets:
            self.class_attribute_names[target.id] = target.lineno

    # Don't visit Assign nodes inside Function Definitions.
    def visit_FunctionDef(self, unused_node):
        return None

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

class StringProp(BaseProp): pass

class EmailProp(BaseProp): pass

class _BaseSchemaType(type):
    def __init__(cls, name, bases, dct):
        cls._properties = OrderedDict()
        for b in bases:
          # if the object has a metaclass which is this
          # class (or subclass of this class...)
          # then we add it's properties to our own.
          if issubclass(type(b), _BaseSchemaType):
            cls._properties.update(b._properties)

        # Finally, we add our own properties.  We find our own source code
        # read it and tag the nodes where we find assignment.
        source = inspect.getsource(cls)
        nt = _NodeTagger()
        nt.visit(ast.parse(source))
        attr_names = nt.class_attribute_names
        properties = {n: prop for n, prop in dct.items()
                      if isinstance(prop, BaseProp)}
        sorted_attrs = sorted(properties.items(),
                             key=lambda item: attr_names[item[0]])
        cls._properties.update(sorted_attrs)

    # methods on a metaclass are basically just classmethods ...
    def as_list(cls):
      return list(cls._properties.items())

    def as_dict(cls):
      return cls._properties.copy()

class BaseSchema(object):
    __metaclass__ = _BaseSchemaType

class UserIdentSchema(BaseSchema):
    email = EmailProp('email')
    password = StringProp('password')

class UserProfileSchema(UserIdentSchema):
    name = StringProp('name')
    phone = StringProp('phone')

from pprint import pprint
pprint(UserProfileSchema.as_list())

rawDescription: how to collect class variables while preserving the order

description: Collect class variables while preserving the order


code:
d
d['items']
d['items'][0]
d['items'][0]['defaultProfileId']

rawDescription: Can't get dictionary value from key in unicode dictionary


code:
class criticalPath:

    def __init__(self):
        '''
        Initialize all the variables we're going to use to calculate the critical path
        '''
        self.id = None
        self.pred = tuple()
        self.dur = None
        self.est = None
        self.lst = None
        #list to store all the objects
        self.all_objects = list()

    def set_properties(self, name, predecessor, duration):
        self.id = name
        self.pred = tuple(predecessor)
        self.dur = duration

def main():
    #starting_nodes = list()
    object_list = list()

    A = criticalPath()
    A.set_properties('A', '0', 3)

    B = criticalPath()
    B.set_properties('B', '0', 6)

    C = criticalPath()
    C.set_properties('C', 'A', 1)

    D = criticalPath()
    D.set_properties('D', 'B', 4)

    tmp_list = list()
    tmp_list.append(A)
    tmp_list.append(C)
    object_list.append(tmp_list)

    tmp_list = list()
    tmp_list.append(B)
    tmp_list.append(D)
    object_list.append(tmp_list)

    print(object_list)

    print('The total duration of the project is {}'.format(max([sum([node.dur for node in object]) for object in object_list])))
    print([path.id for path in max(object_list, key=lambda ls: sum(obj.dur for obj in ls))])

if __name__ == '__main__': main()

rawDescription: How to print a nested list of objects with the highest sum in python

description: Print a nested list of objects with the highest sum in python


code:
docs = []
document = []
for line in file2:
    line = line.strip()
    if line == "<NEW DOCUMENT>":
        # start a new document
        document = []
        docs.append(document)
    else:
        # append to the current one
        document.append(line)

# convert lists of lines into a string
docs = ['\n'.join(document) for document in docs]

rawDescription: python adding to dictionary from external file

description: Python adding to dictionary from external file


code:
p, created = Person.objects.get_or_create(
    first_name='John', last_name='Lennon',
    defaults={'birthday': date(1940, 10, 9)})

rawDescription: How does the get_or_create function in Django return two values?


code:
class A(object):
    pass

rawDescription: User defined type checking in python: "type(A()) is A" returns false


rawDescription: Pandas groupby and Multiindex

description: Pandas groupby and Multiindex


code:
try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()
def get_request():
    return getattr(_thread_locals, 'request', None)

class ThreadLocals(object):
    def process_request(self, request):
        _thread_locals.request = request

rawDescription: How to access the request.user in a Piston classmethod

description: Access the request.user in a Piston classmethod


code:
import csv
import time
from datetime import date

year = str(date.today().year)
filename = r'output\Year\{}.csv'.format(year)
reader = csv.reader(open(r"input.csv"),delimiter=',')
filtered = filter(lambda p: year == p[7], reader)
csv.writer(open(filename, 'w', newline=''), delimiter=',').writerows(filtered)
time.sleep(0.1)

rawDescription: Filter current year from csv

description: Filter current year from csv


code:
buffer = wx.EmptyBitmap(500,500) # creating empty buffer
dc = wx.MemoryDC(buffer)  # to handle the buffer
dc = wx.GCDC(dc)

dc.SetBackground( wx.Brush("White") )  # setting background
dc.DrawCircle(50,40,100)  #drawing circle
dc.DrawCircle(200,200,100)  #drawing circle

rawDescription: Why wxwidgets draw loosely the circles or rounded polygons?


code:
def write_matrix_to_textfile(a_matrix, file_to_write):

    def compile_row_string(a_row):
        return str(a_row).strip(']').strip('[').replace(' ','')

    with open(file_to_write, 'w') as f:
        for row in a_matrix:
            f.write(compile_row_string(row)+'\n')

    return True

rawDescription: Saving a large matrix in to a .txt file in python


code: return not bool

rawDescription: what is the expression opposite of Boolean

description: What is the expression opposite of Boolean


code:
import random
while True:
    while True:
        dice_type = int(input("would you like to roll a 4,6 or 12 sided dice:"))
        if dice_type in [4, 6, 12]:
            break
        print("Sorry that is not the correct input")

    score = random.randint(1, dice_type)

    print ("You have chosen to throw a %d-sided dice" %dice_type)
    print ("You rolled a %d" %score)

rawDescription: looping a program back to the begining?

description: Looping a program back to the begining


code:
with open('myfile.chn', 'rb') as f:
    data = []
    for line in f:  # a file supports direct iteration
        data.extend(hex(int(x, 2)) for x in line.split())

rawDescription: Reading binary file (.chn) in Python

description: Reading binary file (.chn) in Python


code:
df.loc[df['DateTime'] > dateOfChange, 'FileName'] = someVal
df.loc[df['DateTime'] <= dateOfChange, 'FileName'] = otherVal

rawDescription: How to conditionally set a dataframe's value based on date

description: Conditionally set a dataframe's value based on date


code:
postdata={
    'token':token,
    'arg1':'',
    'arg2':'',
    'name[user]': user, # I think this should be : instead of ,
    'name[password]':password,
    'arg3': 'Sign in'}
headers={
    'Content-Type': 'application/x-www-form-urlencoded'
    # With this header you tell the server you're sending form params
}
postresp=requests.post(url='http://example.com', headers=headers, data=postdata)

rawDescription: Handling post data with requests in python


code:
ai = NTLMAuthenticationInfo("domain", "your host", "user", "password")
result = request101.GET('/')
result = NTLMAuthentication(result, request101, ai)

rawDescription: Using jcifs in jython in order to access site using NTLM security


rawDescription: Grouping and auto incrementing group id in pandas


code:
import zipfile
from multiprocessing import Process

def extract_file(passwords):
    with zipfile.ZipFile('evil.zip') as zipf:
        for password in passwords:
            try:
                zipf.extractall(pwd=password)
                print('[+] Found password {}\n'.format(password))
            except Exception as e:
                pass

def main():
    with open('dictionary.txt', 'rb') as pass_file:
        passwords = [i.strip() for i in pass_file]

    N_PROC = 8
    for i in range(N_PROC):
        p = Process(target=extract_file, args=[passwords[i::N_PROC]])
        p.start()

if __name__ == '__main__':
    main()

rawDescription: Multithreading in zip password cracker

description: Multithreading in zip password cracker


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
class RootWidget(BoxLayout):
    ct=0
    orientation='vertical'
    file = ['Q1','a','b','c','Q2','d','e','f','Q3','g','h','i',]
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        optct=1
        g = GridLayout(rows=1, cols=3, col_default_width=10)
        for line in self.file:
            if (self.ct%4==0):
                # question here
                f = Label(text=line, font_size=32, size_hint= (1,0.3))
                self.add_widget(f)
            else:
                g.add_widget(Button(text=line))
                if optct%3==0:
                    # add when the last(3/3) option is in the loop
                    self.add_widget(g)
                    # reset the widget
                    g = GridLayout(rows=1, cols=3, col_default_width=10)
                optct+=1
            self.ct+=1

class Random(App):
    def build(self):
        return RootWidget()
Random().run()

rawDescription: Dynamic Arrangement of Widgets using KIVY


code:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))

rawDescription: Sorting a Python list by two criteria

description: Sorting a Python list by two criteria


code:
import re
from itertools import product

def getranges(s):
    for a, b in re.findall(r"\[(\d+)-(\d+)\]", s):
        yield range(int(a), int(b)+1)

def strcombs(s):
    for r in product(*getranges(s)):
        it = iter(str(i) for i in r)
        yield re.sub(r"\[\d+-\d+\]", lambda _: next(it), s)

s = "123[4-6][1-2]"
print(list(strcombs(s)))    # ['12341', '12342', '12351', '12352', '12361', '12362']

rawDescription: Python string split combination

description: Python string split combination


code:
astr = '''(ROOT
(S
(INTJ (UH Hello))
(, ,)
(NP (PRP$ My) (NN name))
(VP (VBZ is) (ADJP (JJ Melroy)))
(. .)))
(ROOT
(SBARQ
(WHNP (WP What))
(SQ (VBZ is) (NP (PRP$ your) (NN name)))
(. ?)))'''

def get_tree(astr):
    import re
    out = []
    lines = astr.splitlines()

    for line in lines:
        pat = '\(([^\(\)]+?)( \(([^\)\(]+?) [^\(\)]+?\)).*?\)'
        res = re.search(pat, line)
        while res:
            out.append((res.group(1), res.group(3)))
            line = line.replace(res.group(2),'')
            # line = re.sub('(\([^\s\(\)]*\))', '', line)
            res = re.search(pat, line)

    return out

get_tree(aster) # returns [('INTJ', 'UH'), ('NP', 'PRP$'), ('NP', 'NN'), ('VP', 'VBZ'), ('ADJP', 'JJ'), ('WHNP', 'WP'), ('SQ', 'VBZ'), ('NP', 'PRP$'), ('NP', 'NN')]

rawDescription: Regular expression in Python Tree

description: Regular expression in Python Tree


code:
ns = range(n)
ms = ns[:k] + ns[k+1:]

rawDescription: Omit one value from a range

description: Omit one value from a range


code:
import numpy as np
import seaborn as sns
x = np.random.randn(10, 10)
sns.heatmap(x, annot=True)
sns.heatmap(x, mask=x < 1, cbar=False,
            annot=True, annot_kws={"weight": "bold"})

rawDescription: change certain squares in a seaborn heatmap

description: Change certain squares in a seaborn heatmap


code: filter(condition, map(lambda name: initial-expression, collection))

rawDescription: List comprehension : is there a concise way to refer to the initial expression in the if condition?


code:
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
conn = psycopg2.connect(conn_string)

rawDescription: equivalent connection for postgres and sqlite

description: Equivalent connection for postgres and sqlite


code:
lst = [1,2,3,4]
",".join(str(item) for item in lst)

rawDescription: Python Last Iteration in For Loop

description: Python Last Iteration in For Loop


code:
actualstdout = sys.stdout
sys.stdout = StringIO()
result = foobar()
sys.stdout = actualstdout
sys.stdout.write(str(result))
sys.stdout.flush()
sys.exit(0)

rawDescription: suppressing print as stdout python

description: Suppressing print as stdout python


rawDescription: python pyplot connecting points

description: Python pyplot connecting points


code:
from functools import wraps
import logging

class ArgLogger(object):
    """
    Singleton class -- will only be instantiated once
    because of the monkey-patching of logger.
    """

    singleton = None

    def __new__(cls):
        self = cls.singleton
        if self is not None:
            return self
        self = cls.singleton = super(ArgLogger, cls).__new__(cls)
        self.code_location = None

        # Do the monkey patch exactly one time
        def findCaller(log_self):
            self.code_location, code_location = None, self.code_location
            if code_location is not None:
                return code_location
            return old_findCaller(log_self)
        old_findCaller = logging.Logger.findCaller
        logging.Logger.findCaller = findCaller

        return self

    def log_args(self, logger, level=logging.DEBUG):
        """Decorator to log arguments passed to func."""
        def inner_func(func):
            co = func.__code__
            code_loc = (co.co_filename, co.co_firstlineno, co.co_name)

            @wraps(func)
            def return_func(*args, **kwargs):
                arg_list = list("{!r}".format(arg) for arg in args)
                arg_list.extend("{}={!r}".format(key, val)
                                for key, val in kwargs.iteritems())
                msg = "{name}({arg_str})".format(name=func.__name__,
                                        arg_str=", ".join(arg_list))
                self.code_location = code_loc
                logger.log(level, msg)
                return func(*args, **kwargs)
            return return_func

        return inner_func

log_args = ArgLogger().log_args

if __name__ == "__main__":
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    fmt = "%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)4s] %(message)s"
    handler.setFormatter(logging.Formatter(fmt))
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)

    @log_args(logger)
    def foo(x, y, z):
        pass

    class Bar(object):
        @log_args(logger)
        def baz(self, a, b, c):
            pass

    def test_regular_log():
        logger.debug("Logging without ArgLog still works fine")

    foo(1, 2, z=3)
    foo(1, 2, 3)
    foo(x=1, y=2, z=3)

    bar = Bar()
    bar.baz(1, c=3, b=2)
    test_regular_log()

rawDescription: Best way to override lineno in Python logger

description: Override lineno in Python logger


code:
from collections import Counter

with open('/tmp/myfile.txt') as f:
    d = sum((Counter({k: float(v) for k, v in [line.split(':')]}) for line in f), Counter())

d = dict(d)

rawDescription: Dictionary with multiple same keys with different values python


code:
import time

while not result_from_remote.ready():
    time.sleep(5)

return result_from_remote.get()

rawDescription: Calling async_result.get() from within a celery task


code:
dx,dy = x2-x1,y2-y1

rads = math.atan2(dx/dy)
degs = math.degrees(rads)

rawDescription: How do I find the angle between 2 points in pygame?

description: Find the angle between 2 points in pygame


code:
rect = cv2.minAreaRect(cnt)
box = cv2.cv.BoxPoints(rect)
box = np.int0(box)
cv2.drawContours(im,[box],0,(0,0,255),2)

rawDescription: OpenCV Python: Draw minAreaRect ( RotatedRect not implemented)


code:
from collections import namedtuple
TestResult = namedtuple("TestResult", "name feature passed errorMessage")
TestResult("a", "b", True, "c")

rawDescription: Type imitation in python

description: Type imitation in python


code:
import pickle

class Foo(object):
    __slots__ = ['this', 'that', 'other']

    def __init__(self):
        self.this = 1
        self.that = 2
        self.other = 3

    def __getstate__(self):
        return dict((name, getattr(self, name))
                    for name in self.__slots__)

    def __setstate__(self, state):
        for name, value in state.items():
            setattr(self, name, value)

pickle.dumps(Foo(), protocol=0)

rawDescription: python multiprocessing pickle protocol

description: Python multiprocessing pickle protocol


code:
import pyodbc
connStr = (
    r"Driver={SQL Server Native Client 10.0};"
    r"Server=(local)\SQLEXPRESS;"
    r"Trusted_connection=yes;"
)
cnxn = pyodbc.connect(connStr, autocommit=True)
crsr = cnxn.cursor()
crsr.execute("CREATE DATABASE pyodbctest")
crsr.execute("USE pyodbctest")
crsr.execute("CREATE SCHEMA myschema")
crsr.close()
cnxn.close()

rawDescription: Create a schema in SQL Server using pyodbc


code:
#basically a stripped down rewrite of Phylo.draw_graphviz
import networkx, pylab
from Bio import Phylo

#taken from draw_graphviz
def get_label_mapping(G, selection):
    for node in G.nodes():
        if (selection is None) or (node in selection):
            try:
                label = str(node)
                if label not in (None, node.__class__.__name__):
                    yield (node, label)
            except (LookupError, AttributeError, ValueError):
                pass

kwargs={}
tree = Phylo.read('tree.dnd', 'newick')
G = Phylo.to_networkx(tree)
Gi = networkx.convert_node_labels_to_integers(G, discard_old_labels=False)

node_sizes = []
labels = dict(get_label_mapping(G, None))
kwargs['nodelist'] = labels.keys()

#create our node sizes based on our labels because the labels are used for the node_list
#this way they should be correct
for label in labels.keys():
    if str(label) != "Clade":
        num = label.name.split('-')
        #the times 50 is just a guess on what would look best
        size = int(num[-1]) * 50
        node_sizes.append(size)

kwargs['node_size'] = node_sizes
posi = networkx.pygraphviz_layout(Gi, 'neato', args='')
posn = dict((n, posi[Gi.node_labels[n]]) for n in G)

networkx.draw(G, posn, labels=labels, node_color='#c0deff', **kwargs)

pylab.show()

rawDescription: Phylo BioPython building trees

description: Phylo BioPython building trees


code: from openpyxl.workbook import Workbook

rawDescription: cannot import openpyxl to python on OSX

description: Cannot import openpyxl to python on OSX


code:
def censor(text, word):
    split_string = text.split()
    replace_string = "*" * len(word)
    for i in split_string:
        if i == word:
            i = replace_string # This doesn't work*
    return " ".join(split_string)

rawDescription: Why does one function work while the other doesn't?


code:
from datetime import date, timedelta

db.collection.find({'createTime':{'$lt':datetime.datetime.now(), '$gt':datetime.datetime.now() - timedelta(hours=24)}})

rawDescription: Query DateTime with PyMongo

description: Query DateTime with PyMongo


code:
import timeit
print(timeit.timeit("search_kmp(x, p)", setup="from __main__ import search_kmp, x, p"))

rawDescription: Increase precision of Python's time.process_time()


code:
vec = CountVectorizer()
doc_term_matrix = vec.fit_transform(['toto titi', 'toto toto', 'titi tata'])
doc_term_matrix = doc_term_matrix.toarray()
term_freq_matrix = doc_term_matrix.sum(0)
min_freq = np.amin(term_freq_matrix)
indices_name_mapping = vec.get_feature_names()
feature_names = [indices_name_mapping[i] for i, x in enumerate(term_freq_matrix) if x == min_freq]

rawDescription: how to selected vocabulary in scikit CountVectorizer

description: Selected vocabulary in scikit CountVectorizer


code:
from twisted.web import server, resource
from twisted.internet import reactor

class HelloResource(resource.Resource):
    isLeaf = True
    numberRequests = 0

    def render_GET(self, request):
        self.numberRequests += 1
        request.setHeader("content-type", "text/plain")
        return "I am request #" + str(self.numberRequests) + "\n"

reactor.listenTCP(80, server.Site(HelloResource()))
reactor.run()

rawDescription: How to run the Twisted Matrix Web Server

description: Run the Twisted Matrix Web Server


code:
class MonthCalends(ListView):
    template_name='month_list.html'
    ## Sets default fieldname value
    filter_field = "defaultfieldname"

    def get(self, request, *args, **kwargs):
        try:
            # if the filter field was sent as an argument
            filter_field = self.filter_field
        except:
            # else revert to default
            filter_field = MonthCalends.filter_field
        # ...rest of code

rawDescription: How to add parameters to urls in Django?

description: Add parameters to urls in Django


code:
from win32com.client import Dispatch
import os

xl = Dispatch("Excel.Application")
xl.Visible = True # otherwise excel is hidden

# newest excel does not accept forward slash in path
wbs_path = r'C:\path\to\a\bunch\of\workbooks'

for wbname in os.listdir(wbs_path):
    if not wbname.endswith(".xlsx"):
        continue
    wb = xl.Workbooks.Open(wbs_path + '\\' + wbname)
    sh = wb.Worksheets("name of sheet")
    sh.Range("A1").Value = "some new value"
    wb.Save()
    wb.Close()
xl.Quit()

rawDescription: Overwriting existing cells in an XLSX file using Python


code:
import tokenize

def tokens_with_offset(path):
    line_offsets = []
    line_offset_accum = 0
    with open(path) as f:
        for line in f:
            line_offsets.append(line_offset_accum)
            line_offset_accum += len(line)

    with open(path) as f:
        for ttype, tstring, tbegin, tend, tline in tokenize.generate_tokens(f.readline):
            offset_begin = line_offsets[tbegin[0]] + tbegin[1]
            offset_end = line_offsets[tend[0]] + tend[1]
            yield ttype, tstring, offset_begin, offset_end, tline

rawDescription: Python tokenize: token position

description: Python tokenize: token position


code:
# Simple request-reply broker
#
# Author: Lev Givon <lev(at)columbia(dot)edu>

import zmq

# Prepare our context and sockets
context = zmq.Context()
frontend = context.socket(zmq.ROUTER)
backend = context.socket(zmq.DEALER)
frontend.bind("tcp://*:5559")
backend.bind("tcp://*:5560")

# Initialize poll set
poller = zmq.Poller()
poller.register(frontend, zmq.POLLIN)
poller.register(backend, zmq.POLLIN)

# Switch messages between sockets
while True:
  socks = dict(poller.poll())

  if socks.get(frontend) == zmq.POLLIN:
    message = frontend.recv_multipart()
    backend.send_multipart(message)

  if socks.get(backend) == zmq.POLLIN:
    message = backend.recv_multipart()
    frontend.send_multipart(message)

rawDescription: What is zmq.ROUTER and zmq.DEALER in python zeromq?


code:
f = open("C:/CDRH3.txt", "r")
from collections import Counter
grab = 1
AminoAcidsFirst = []
AminoAcidsLast = []
for line in f:
   line=line.rstrip()
   left,sep,right=line.partition(" H3 ")
   if sep:
         AminoAcidsFirst.append(right[:grab])
         AminoAcidsLast.append(right[-grab:])
print ("first ",Counter(line[:] for line in AminoAcidsFirst))
print ("last ",Counter(line[:] for line in AminoAcidsLast))
f.close()

rawDescription: How do I count the occurences of characters of a partition in python?

description: Count the occurences of characters of a partition in python


rawDescription: Is there any way to see the codes of functions you've typed in your Python CMD


code:
import StringIO
import ConfigParser
f = StringIO.StringIO("[sec1]\npwd=foo;\n")
p = ConfigParser.ConfigParser()
p.readfp(f)
p.items('sec1')

rawDescription: How do I put a semicolon in a value in python configparser?

description: Put a semicolon in a value in python configparser


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

class MyWebView(QWebView):
    def __init__(self):
        QWebView.__init__(self)
        QObject.connect(self,SIGNAL('loadFinished(bool)'),self.showelements)

    def showelements(self):
        html=self.page().currentFrame().documentElement()
        for link in html.findAll('a'):
            print(link.toInnerXml(),str(link.geometry())[18:])

if __name__=='__main__':
    app = QApplication(sys.argv)

    web = MyWebView()
    web.load(QUrl("http://www.google.com"))
    web.show()

    sys.exit(app.exec_())

rawDescription: Html element position in Python

description: Html element position in Python


rawDescription: PyQt Button Selection

description: PyQt Button Selection


code:
def groupDataOnTimeBlock(data, timeBlock_type, timeBlock_factor):
    '''
    Filter Dataframe to merge lines which are within the same time block.
    i.e. being part of the same x number of seconds, weeks, months...

    data:
        Dataframe to filter.

    timeBlock_type:
        Time period with which to group data rows. This can be data per:
            SECONDS, DAYS, MILLISECONDS

    timeBlock_factor:
        Number of timeBlock types to group on.
    '''

    pd.options.mode.chained_assignment = None  # default='warn'

    tBt = timeBlock_type.upper()
    tBf = timeBlock_factor

    if tBt == 'SEC' or tBt == 'SECOND' or tBt == 'SECONDS':
        roundType = 'SECONDS'
    elif tBt == 'MINS' or tBt == 'MINUTES' or tBt == 'MIN':
        roundType = 'MINUTES'
    elif tBt == 'MILLI' or tBt == 'MILLISECONDS':
        roundType = 'MILLISECONDS'
    elif tBt == 'WEEK' or tBt == 'WEEKS':
        roundType = 'WEEKS'
    else:
        raise ValueError ('Invalid time block type entered')

    numElements = len(data.columns)
    anchorValue = timeStampReformat(data.iloc[1,len(data.columns)-7], roundType, tBf)
    delIndex = []
    mergeCount = 0
    av_agg_arr = np.zeros([1,numElements], dtype=float)

    #Cycling through dataframe to get averages and note which rows to delete
    for i, row in data.iterrows(): #i is the index value, from 0
        backDate = timeStampReformat(row['Timestamp'], roundType, tBf)
        data.loc[i,'Timestamp'] = backDate #can be done better. Not all rows need updating.

        if (backDate > anchorValue): #if data should be grouped
            delIndex.pop() #remove last index as this is the final row to use
            delIndex.append(i) #add current row so that it isnt missed.
            print('collate')
            if mergeCount != 0:
                av_agg_arr = av_agg_arr/mergeCount
                for idx in range(1,numElements-1):
                    if isinstance(row.values[idx],float):
                        data.iloc[i-1, idx] = av_agg_arr[0, idx] #configure previous (index i -1) row. This is the last of the prior datetime group

            anchorValue = backDate
            mergeCount = 0

            # Re-initialising aggregates and passing in current row values.
            av_agg_arr = av_agg_arr - av_agg_arr
            for idx in range(1,numElements-1):
                if isinstance(row.values[idx],float):
                    if not pd.isnull(row.values[idx]):
                        av_agg_arr[0,idx] += row.values[idx]
        else: #else if data is still part of same datetime group
            for idx in range(1,numElements-1):
                if isinstance(row.values[idx],float):
                    if not pd.isnull(row.values[idx]):
                        av_agg_arr[0,idx] += row.values[idx]
            mergeCount += 1
            delIndex.append(i) #picking out index value of row

    data.drop(data.index[delIndex], inplace=True) #delete all flagged rows
    data.reset_index()

    pd.options.mode.chained_assignment = 'warn'  # default='warn'
    return data

rawDescription: Merge two rows in the same Dataframe if their index is the same?


code:
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--global')
subparsers = parser.add_subparsers(dest="subparser_name") # this line changed
foo_parser = subparsers.add_parser('foo')
foo_parser.add_argument('-c', '--count')
bar_parser = subparsers.add_parser('bar')
args = parser.parse_args(['-g', 'xyz', 'foo', '--count', '42'])
args

rawDescription: Get selected subcommand with argparse

description: Get selected subcommand with argparse


code:
import pygame as pg
import time

pg.mixer.init()
pg.init()

a1Note = pg.mixer.Sound("F:\Project Harpsichord\The wavs\A1.wav")
a2Note = pg.mixer.Sound("F:\Project Harpsichord\The wavs\A0.wav")

pg.mixer.set_num_channels(50)

for i in range(25):
    a1Note.play()
    time.sleep(0.3)
    a2Note.play()
    time.sleep(0.3)

rawDescription: Playing a Lot of Sounds at Once

description: Playing a Lot of Sounds at Once


code:
unsorted = [1, 2, 4, 9, 3, 7, 11, 5, 12]
pivot = 7
left, right = [list(filter(lambda n: n < pivot, unsorted)), list(filter(lambda n: n >= pivot, unsorted))]
left
right

rawDescription: Omit a Value in a Multiple-Assignment Ternary Conditional


code:
nt_seq=['CTT','CTT','CGA','CCT','CGA']
[aa_codons[codon] for codon in nt_seq]
nt_seq=['CTT','CTT','CGA','CCT','CGA']
aa_codons={'CTT':'Leu','CCT':'Pro','CGA':'Arg'}
[aa_codons[codon] for codon in nt_seq]

rawDescription: How do I convert my list of codons into the corresponding amino acids from my dictionary?

description: Convert my list of codons into the corresponding amino acids from my dictionary


code:
def toEnglish(s):
    sentence = s.split(" ")
    english = ""
    for word in sentence:
        if word[:len(word) - 4:-1] == 'yaw':
            english += word[:len(word) - 3] + " "
        else:
            noay = word[:len(word) - 2]
            firstconsonants = noay.split("a")[-1]
            consonantsremoved = noay[:len(noay) - (len(firstconsonants)+1)]
            english += firstconsonants + consonantsremoved + " "
    return english

rawDescription: Translating Pig Latin into English Using Python 3


code: product_info = magento.catalog_product.info(1234, store_id)

rawDescription: Magento API Product info for a particular Store view?


code:
#!/usr/bin/env python
import zipfile
from contextlib import closing

MiB = 2**20 # mebibyte

with closing(zipfile.ZipFile("example.zip")) as zfile:
    for info in zfile.infolist():
        if info.filename.endswith('.txt') and 0 < info.file_size <= 3*MiB:
            zfile.extract(info)

rawDescription: Python Zip-File, wildcards

description: Python Zip-File, wildcards


code:
class Board(gtk.DrawingArea):

    def show_background(self, filepath):
        pixbuf = gtk.gdk.pixbuf_new_from_file(filepath)
        self.get_window().draw_pixbuf(self.style.bg_gc[gtk.STATE_NORMAL], pixbuf, 0,0, 0,0)

    def do_expose_event(self, event):
        self.gc = self.style.fg_gc[gtk.STATE_NORMAL]
        self.show_background("image.png")
        x=20
        y=20
        points = [(x+10,y+10), (x+10,y), (x+40,y+30),(x+30,y+10), (x+50,y+10)]
        self.get_window().draw_points(self.gc, points)

    def __init__(self, parent_widget):
        self.parent_widget = parent_widget
        gtk.DrawingArea.__init__(self)
        self.parent_widget.pack_end(self, True, True, 10)
        self.show()

rawDescription: pygtk drawing area not showing

description: Pygtk drawing area not showing


code:
somevar = 3
expression = lambda: somevar < 5
while expression():
    ...
    if continue_if_even:
        expression = lambda: (somevar % 2) == 0
    ...

rawDescription: Variable as loop's expression

description: Variable as loop's expression


code:
subscription_keys = [ndb.Key(CourseSubscription, CourseSubscription.build_id(user, course))
                     for course in courses]
real_list = ndb.get_multi(subscription_keys)

rawDescription: Structured query over M to M in NDB

description: Structured query over M to M in NDB


code:
from lxml import etree
xml = etree.parse(open('1.xml'))
xml.xpath("//qtn[@state="+state+"]/text()")

rawDescription: Reading Elements by attribute Condition lxml


code:
mylist = open(sys.argv[1], "r").read()
re.findall('[\.\w]+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}', database)

rawDescription: what is ***91 / ***93 in python

description: What is ***91 / ***93 in python


code:
nf = urllib.urlopen(url)
start = time.time()
page = nf.read()
end = time.time()
nf.close()
# end - start gives you the page load time

rawDescription: Measure website load time with Python requests


code:
class User(Base):
    __tablename__ = 'users'

    id = Column('id', Integer, primary_key=True)
    addresses = relation("Address", backref="user")

class Address(Base):
    __tablename__ = 'addresses'

    id = Column('id', Integer, primary_key=True)
    user_id = Column('user_id', Integer, ForeignKey('users.id'))

rawDescription: How to specify relations using SQLAlchemy declarative syntax?

description: Specify relations using SQLAlchemy declarative syntax


code: re.findall(r'^(un|ir)(.*)$', 'undo')

rawDescription: Slicing the prefix from the stem in Python


code:
import wx

class MyPanel(wx.Panel):
    def __init__(self, parent):
        super(MyPanel, self).__init__(parent=parent)
        mygridsizer = wx.GridBagSizer()

        sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
        sizer.Add(wx.StaticText(self,label="Hello world"))
        sizer.Add(wx.Button(self, label="hello"))
        mygridsizer.Add(sizer, pos=(0,0))
        mygridsizer.Add(wx.ComboBox(self), pos=(0,1))
        self.SetSizer(mygridsizer)

class MyPanel2(wx.Panel):
    def __init__(self, parent):
        super(MyPanel2, self).__init__(parent=parent)
        sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
        t = wx.StaticText(self,label="Hello world")
        t.Hide()
        t.GetSize()
        sizer.Add(t.GetSize())
        sizer.Add(wx.Button(self, label="non-aligned button"))
        self.SetSizer(sizer)

class MainFrame(wx.Frame):
    def __init__(self, parent):
        super(MainFrame, self).__init__(None)
        sizer = wx.GridSizer(3, 1)
        panel1 = MyPanel(parent=self)
        panel2 = MyPanel2(parent=self)
        sizer.Add(panel1)
        sizer.Add(panel2)
        self.SetSizer(sizer)

if __name__ == '__main__':
    app = wx.App()
    frame = MainFrame(None)
    frame.Show()
    app.MainLoop()

rawDescription: Elements between panels are not aligned within a sizer


code:
def sortedfilter(in_fname, filter_fname, out_fname):
    with open(in_fname) as inf, open(filter_fname) as fil, open(out_fname, 'w') as outf:
        ins = inf.next()
        try:
            for fs in fil:
                while ins < fs:
                    outf.write(ins)
                    ins = inf.next()
                while ins == fs:
                    ins = inf.next()
        except StopIteration:
            # reached end of inf before end of fil
            pass
        else:
            # reached end of fil first, pass rest of inf through
            file_output.writelines(file_input.readlines())

rawDescription: Optimizing removing duplicates in large files in Python


code:
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt

def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y

# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()

# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

rawDescription: Creating lowpass filter in SciPy - understanding methods and units


code:
java_regex = re.compile(...)  # java
at_regex = re.compile(...)    # at

copy = False  # flag that control to copy or to not copy to output

for line in file_in:
   if re.search(java_regex, line):
       # start copying if "java" is in the input
       copy = True
   else:
       if copy and not re.search(at_regex, line):
           # stop copying if "at" is not in the input
           copy = False

   if copy:
       file_out.write(line)

rawDescription: Python file copying using regex

description: Python file copying using regex


code:
import decorator
import inspect
import sys

@decorator.decorator
def simple_init(func, self, *args, **kws):
    """
    @simple_init
    def __init__(self,a,b,...,z)
        dosomething()

    behaves like

    def __init__(self,a,b,...,z)
        self.a = a
        self.b = b
        ...
        self.z = z
        dosomething()
    """

    #init_argumentnames_without_self = ['a','b',...,'z']
    if sys.version_info.major == 2:
        init_argumentnames_without_self = inspect.getargspec(func).args[1:]
    else:
        init_argumentnames_without_self = tuple(inspect.signature(func).parameters.keys())[1:]

    positional_values = args
    keyword_values_in_correct_order = tuple(kws[key] for key in init_argumentnames_without_self if key in kws)
    attribute_values = positional_values + keyword_values_in_correct_order

    for attribute_name,attribute_value in zip(init_argumentnames_without_self,attribute_values):
        setattr(self,attribute_name,attribute_value)

    # call the original __init__
    func(self, *args, **kws)

class Test():
    @simple_init
    def __init__(self,a,b,c,d=4):
        print(self.a,self.b,self.c,self.d)

#prints 1 3 2 4
t = Test(1,c=2,b=3)
#keeps signature
#prints ['self', 'a', 'b', 'c', 'd']
if sys.version_info.major == 2:
    print(inspect.getargspec(Test.__init__).args)
else:
    print(inspect.signature(Test.__init__))

rawDescription: How do I avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__?

description: Avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__


rawDescription: pandas iterrows changes ints into floats

description: Pandas iterrows changes ints into floats


code:
import subprocess

subprocess.call (['wget', '-P', '/', 'http://www.ncbi.nlm.nih.gov/Traces/wgs/?download=ACHI01.1.fsa_nt.gz'])

rawDescription: Error closing wget subprocess in Python

description: Error closing wget subprocess in Python


code:
s = 'she sells sea shells by the sea shore'
# Use hashlib
import hashlib
int(hashlib.sha1(s).hexdigest(), 16) % (10 ** 8)
# Use hash()
abs(hash(s)) % (10 ** 8)

rawDescription: Python: How to hash a string into 8 digits?


code:
def first_row(a, labels):
    d = {}
    d_setdefault = d.setdefault
    len_ = len
    num_labels = len_(labels)
    for i, row in enumerate(a):
        for label in row:
            d_setdefault(label, i)
        if len_(d) == num_labels:
            break
    return d

rawDescription: How can I improve the efficiency of this numpy loop

description: Improve the efficiency of this numpy loop


rawDescription: Combine single characters with single spaces between them together


code:
count = 0

def write_stuff():
    global count

    section = "test"
    item = "oh hey there"
    conf_filename = "test.conf"

    conf = ConfigParser.ConfigParser()
    conf.readfp(open(conf_filename, 'r', 0))

    timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")+ "_%s" % count
    count += 1

    conf.set(section, timestamp, item)

    with open(conf_filename, "w", 0) as conf_file:
        conf.write(conf_file)

rawDescription: Why does ConfigParser not write to disk immediately?


code: values = struct.unpack('!7h', data)

rawDescription: How to switch byte order of binary data

description: Switch byte order of binary data


code:
def palindrom(word):
    if len(word) == 1 or len(word) == 0:
        return 0
    if word[0] == word[-1]:
        print(word[0], word[-1])
        return palindrom(word[1:-1])
    else:
        return 1

rawDescription: Python. Making a function that tests if a word is a palindrome recursively


code:
import random
print(''.join(random.choice(original_text) for _ in range(500)))

rawDescription: How to make a random text python

description: Make a random text python


rawDescription: Unicode in Python - just UTF-16?

description: Unicode in Python - just UTF-16


code:
import Tkinter as tk
import random

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.ticker = tk.Text(height=1, wrap="none")
        self.ticker.pack(side="top", fill="x")

        self.ticker.tag_configure("up", foreground="green")
        self.ticker.tag_configure("down", foreground="red")
        self.ticker.tag_configure("event", foreground="black")

        self.data = ["AAPL", "GOOG", "MSFT"]
        self.after_idle(self.tick)

    def tick(self):
        symbol = self.data.pop(0)
        self.data.append(symbol)

        n = random.randint(-1,1)
        tag = {-1: "down", 0: "even", 1: "up"}[n]

        self.ticker.configure(state="normal")
        self.ticker.insert("end", " %s %s" % (symbol, n), tag)
        self.ticker.see("end")
        self.ticker.configure(state="disabled")
        self.after(1000, self.tick)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How merge text in a tkinter label with diferent colors


code:
doc_name = input("Document Name: ") # don't need to cast to str
end = ""
result = [] # I recommend initializing a list for the lines
for line in iter(input, end): # you only need this single input call
    result.append(line) # add each line to the list
try:
    # using "with" in this manner is guaranteed to close the file at the end
    with open("/home/" +doc_name+ ".txt", "w") as savefile:
        for line in result: # go through the list of lines
            # write each one, ending with a newline character
            savefile.write(line + '\n')
except IOError:
    print("An error occurred.\nUnable to save document.\n\n")
else: # print this if save succeeded, but it's not something we want to "try"
    print("Document - " +doc_name+ "\nSuccessfully saved.\n\n")

rawDescription: Unsure how to get user input from a multiple line loop - Python


code:
import csv

with open("organizationTest.txt","rU") as f:
        reader = csv.reader(f)
        for row in reader:
            _, created = Company.objects.get_or_create(
                Name=row[0].decode('latin-1').encode('utf8'),
                Site=row[1].decode('latin-1').encode('utf8'),
                )

rawDescription: Switch Application to Unicode

description: Switch Application to Unicode


code:
with open('file.txt','r') as f:
    #file is opened and accessible via f
    pass
#file will be closed before here

rawDescription: Python read/write file without closing

description: Python read/write file without closing


code:
for row in mult_table:
    print(" | ".join([str(cell) for cell in row]))

rawDescription: Printing 2 dimension list by row and column


code:
import base64
img_tag = "<img src='data:image/png;base64," + base64.b64encode(img_buffer.getvalue()) + "'/>"

rawDescription: python: Given a BytesIO buffer, generate img tag in html?

description: Python: Given a BytesIO buffer, generate img tag in html


code:
import sympy as sym
import pickle
import dill
a, b = symbols("a, b")
a, b = sym.symbols("a, b")
expr = sym.sin(a) + sym.cos(b)
lambdified_expr = sym.lambdify((a, b), expr, modules="numpy")

dill.settings
dill.settings['recurse'] = True
dill.dumps(lambdified_expr)

rawDescription: How to serialize sympy lambdified function?

description: Serialize sympy lambdified function


code:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

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

rawDescription: Options for building a python web based application


code:
def check_auth(email, password):
    em_login_provider = ndb.Key('AuthProvider', get_provider_id(constants.EMAIL, email)).get()
    if em_login_provider and em_login_provider.active:
        user = em_login_provider.user
        if user and verify_password(password, user.password_hash, user.password_hash_version):
            return True
    return False

rawDescription: flask-httpauth: How is get_password decorator meant to work for basic-auth?

description: Flask-httpauth: How is get_password decorator meant to work for basic-auth


code:
import ttk
s=ttk.Style()
s.theme_names()
s.theme_use()
s.theme_use('alt')
s.theme_use()

rawDescription: How do I change the tkinter overall theme to make my app have the clam theme

description: Change the tkinter overall theme to make my app have the clam theme


rawDescription: Python irc bot+sqlalchemy, track users in multiple channels


rawDescription: Finding the location of a character in a string


rawDescription: Parsing unique values in a CSV where the primary key is not unique


rawDescription: Floating point numbers of Python "float" and PostgreSQL "double precision"


code:
import matplotlib as mpl
import matplotlib.pyplot as plt

plt.style.use('ggplot')
import pandas as pd
import numpy as np
from datetime import datetime

n = 100
idx = pd.date_range(start=datetime(2016, 1, 1, 10), freq='10Min', periods=n)
data = pd.DataFrame(data={'price': np.cumsum([0.0001] * n + np.random.random(n)),
                          'volume': np.random.randint(low=100, high=10000, size=n)}, index=idx)

fig, ax = plt.subplots(nrows=2, sharex=True, figsize=(15,8))

ax[0].plot(data.index, data.price)
ax[1].bar(data.index, data.volume, width=1/(5*len(data.index)))

xfmt = mpl.dates.DateFormatter('%H:%M')
ax[1].xaxis.set_major_locator(mpl.dates.HourLocator(interval=3))
ax[1].xaxis.set_major_formatter(xfmt)

ax[1].xaxis.set_minor_locator(mpl.dates.HourLocator(interval=1))
ax[1].xaxis.set_minor_formatter(xfmt)

ax[1].get_xaxis().set_tick_params(which='major', pad=25)

fig.autofmt_xdate()
plt.show()

rawDescription: How to get an intraday price - volume plot in Pandas?

description: Get an intraday price - volume plot in Pandas


code:
class RPC(object):
    def __init__(self, host):
        self._host = host
        self._kws = {}
    def doit(self, **morekws):
        return remote(self._host, **dict(self._kws, **morekws))
    def __getattr__(self, name):
        def setkw(value):
            self._kws[name] = value
            return self
        return setkw

rawDescription: How to write lazy functions which are chainable, in python?

description: Write lazy functions which are chainable, in python


code:
def My_func(x, y, size, ls):
    return analysis(ls), generate_data(size), func(x,y)

rawDescription: return Outputs of multiple function using one function

description: Return Outputs of multiple function using one function


code: grade_list, grade_count = Gather_Intel(grade_list, grade_count)

rawDescription: python local variable sent to function, modified, but was not passed back to program

description: Python local variable sent to function, modified, but was not passed back to program


rawDescription: Join string before, between, and after

description: Join string before, between, and after


code:
def quote_identifier(s, errors="strict"):
    encodable = s.encode("utf-8", errors).decode("utf-8")

    nul_index = encodable.find("\x00")

    if nul_index >= 0:
        error = UnicodeEncodeError("NUL-terminated utf-8", encodable,
                                   nul_index, nul_index + 1, "NUL not allowed")
        error_handler = codecs.lookup_error(errors)
        replacement, _ = error_handler(error)
        encodable = encodable.replace("\x00", replacement)

    return "\"" + encodable.replace("\"", "\"\"") + "\""

rawDescription: Can't escape table or column names when importing data model from XML using SQLite


rawDescription: Find common members that are in two lists of dictionaries


code:
first = [1, 2, 3, 4]
second = [3, 2, 5, 6, 7]
third = list(set(first) | set(second))      # '|' is union
third

rawDescription: How to take two lists and combine them excluding any duplicates?

description: Take two lists and combine them excluding any duplicates


rawDescription: Get elements from list in python

description: Get elements from list in python


code:
class Chaos:
    def __init__(self):
        self.list_value = []
        self.value = "default"

rawDescription: python member variable of instance works like member variable, and some works like static variable

description: Python member variable of instance works like member variable, and some works like static variable


code: '\n'.join(s[pos:pos+76] for pos in xrange(0, len(s), 76))

rawDescription: Inserting newline character after every 76 characters in a base64 string


code:
from blist import *
x = blist([0])             # x is a blist with one element
x *= 2**29                 # x is a blist with > 500 million elements
x.append(5)                # append to x
y = x[4:-234234]           # Take a 500 million element slice from x
del x[3:1024]              # Delete a few thousand elements from x

rawDescription: Anyone Know a Great Sparse One Dimensional Array Library in Python?


code:
import datetime
date_str = '20130723'
datetime.datetime.strptime(date_str, '%Y%m%d') - datetime.timedelta(days=1)

rawDescription: Python convert date string to python date and subtract


code:
from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

rawDescription: Python Flask how to get parameters from a URL?


code:
for path in files:  # path, not f; f is usually placeholder for file-like object
    filedir, filename = os.path.split(path)
    parentdir = os.path.dirname(filedir)
    # Strip parentdir name to get 'Sample_*_' per provided code; is this what you wanted?
    # Question text seems like you only wanted the '*' part.
    sample_id = parentdir.replace('results_', '').replace('hg38_hg19', '')
    # Large magic numbers are code smell; if the name is a fixed name,
    # just use it directly as a string literal
    # If the name should be "whatever the file is named", use filename unsliced
    # If you absolutely need a fixed length (to allow reruns or something)
    # you might do keepnamelen = len('NoAdapter_len25.truncated_sorted.fastq')
    # outside the loop, and do f[-keepnamelen:] inside the loop so it's not
    # just a largish magic number
    back = filename[-38:]
    new_name = sample_id + back
    new_path = os.path.join(filedir, new_name)
    rename(path, new_path)

rawDescription: Rename files in multiple directories

description: Rename files in multiple directories


code:
a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

new = [el for el in a if any(ch.isdigit() for ch in el)]
# ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

rawDescription: What is the way to delete words in Python list which does not have numbers?


code:
import os
os.system( "google-chrome & disown " )

rawDescription: Running a command completely indepenently from script


code:
from datetime import datetime
import time
import calendar
import pytz

def howLongAgo(thirdPartyString, timeFmt):
  # seconds since epoch
  thirdPartySeconds = calendar.timegm(time.strptime(thirdPartyString, timeFmt))
  nowSecondsUTC = time.time()

  # hour difference with DST
  nowEastern = datetime.now(pytz.timezone('US/Eastern'))
  nowUTC = datetime.now(pytz.timezone('UTC'))
  timezoneOffset = (nowEastern.day - nowUTC.day)*24 + (nowEastern.hour - nowUTC.hour) + (nowEastern.minute - nowUTC.minute)/60.0

  thirdPartySecondsUTC = thirdPartySeconds - (timezoneOffset * 60 * 60)
  return nowSecondsUTC - thirdPartySecondsUTC

howLongAgo('June 09, 2016 at 06:22PM', '%B %d, %Y at %I:%M%p')
# first argument always provided in ET, either EDT or EST

rawDescription: Compare time with timezone to now

description: Compare time with timezone to now


code:
table = soup.find("table", class_ = "infobox")
name = table.find("th").text
country = table.find("th",text="Country").parent.find("td").text
table = soup.find("table", class_ = "infobox")
name = table.find("th").text
country = table.find("th",text="Country").parent.find("td").text
country = table.find("th",text="Country").find_next_sibling().text #also works
location =  table.find("th",text="Location").parent.find("td").text
location = table.find("th",text="Location").find_next_sibling().text #also works

rawDescription: Retrieve location data using BeautifulSoup


code:
def special_pattern(A, x=2, y=-1):
    B = []
    temp = []
    flag = 0
    for elem in A:
        if elem == x and flag == 0:
            flag = 1
        elif elem == y and flag == 1:
            temp.extend([x, y])
            flag = 0
        else:
            if temp != []:
                B.append(temp)
                temp = []
            if not(elem == x and flag == 1):
                flag = 0
    if temp != []:
        B.append(temp)
    return B

rawDescription: How could I find patterns of repeating pairs of integers in an array or list of integers?


rawDescription: Scrapy: parse a div from a list of divs

description: Scrapy: parse a div from a list of divs


code:
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):              # __str__ on Python 3
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200, default="")
    votes = models.IntegerField(default=0)

    def __unicode__(self):              # __str__ on Python 3
        return self.choice_text

rawDescription: Issue Setting Up Django Database Access API Using SQLite


code:
class MARGINS(ctypes.Structure):
  _fields_ = [("cxLeftWidth", c_int),
              ("cxRightWidth", c_int),
              ("cyTopHeight", c_int),
              ("cyBottomHeight", c_int)
             ]
margins = MARGINS(1, 2, 1, 1)

dwm.DwmExtendFrameIntoClientArea(handel, ctypes.byref(margins))

rawDescription: Windows 7 MARGINS structure in Python

description: Windows 7 MARGINS structure in Python


code:
qry = session.query(Usuario).filter(Usuario.id==1)

# join using the aliased. Use *outerjoin* in order to still get the result for those without a parent
res = aliased(Usuario)
qry = qry.outerjoin((res, Usuario.reseller))

# specify which table/alias represents the *contained* relationship
qry = qry.options(contains_eager(Usuario.reseller, alias=res))

rawDescription: No way to populate self eager-loaded relation


code: [i for i in xrange(no_jobs) for x in xrange(T)]

rawDescription: Quick checkup on python list comprehension


code:
testobj = type('testclass', (object,),
                 {'test':[a1,a2,b2], 'test2':'something else', 'test3':1})()

rawDescription: How to create objects on the fly in python?

description: Create objects on the fly in python


rawDescription: How to concatenate two arbitrary long hex values?

description: Concatenate two arbitrary long hex values


code:
import collections

def maptype(keys, values):
    forward = collections.defaultdict(set)
    backward = collections.defaultdict(set)
    for key, value in zip(keys, values):
        forward[key].add(value)
        backward[value].add(key)

    one_to_m = any(len(l) > 1 for l in forward.values())
    m_to_one = any(len(l) > 1 for l in backward.values())
    return one_to_m, m_to_one

rawDescription: Python, maps between 2 lists

description: Python, maps between 2 lists


code: vm_obj.set_config_x = new.instancemethod(callableFunction, vm_obj, vm_obj.__class__)

rawDescription: Add methods to a third party library class in Python


code:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

b = firefox_binary=FirefoxBinary('/usr/bin/firefox')
b.add_command_line_options("-private")
dr = webdriver.Firefox(firefox_binary=b)

rawDescription: How to open a private firefox window - selenium

description: Open a private firefox window - selenium


code:
child = pexpect.spawn('my-process -v')
child.expect('Please enter your name:')
child.sendline(user_name)

rawDescription: python how to know if subprocess is waiting for input

description: Python how to know if subprocess is waiting for input


code: grid = gs.GridSpec(2,1 , height_ratios=[2,1])

rawDescription: Python/Gridspec height_ratio issue

description: Python/Gridspec height_ratio issue


code:
def inner_html(el):
    return (el.text or '') + ''.join(tostring(child) for child in el)

rawDescription: In Python, how do I remove the "root" tag in an HTML snippet?


code:
import datetime
datetime.datetime.strptime('2014-02-13 11:55:00 -0800', '%Y-%m-%d %H:%M:%S %z')
_.tzinfo

rawDescription: Why %z is not supported by python's strptime?


code:
pd.options.display.max_seq_items
pd.options.display.max_seq_items = 4
pd.Index(range(1000))

rawDescription: printing pandas Index in full

description: Printing pandas Index in full


code:
price_subtotal = fields.Float(string='Amount', digits= dp.get_precision('Account'),
    store=True, readonly=True, compute='_compute_price')

rawDescription: How subtotal rounding works in quotation for Odoo 8?


code:
with open("film.txt", "w") as f:
    for root, _, files in os.walk(os.getcwd()):
        for file in files:
            if file.endswith((".avi", ".mp4")):
                f.write(file)

rawDescription: Python search for file ending

description: Python search for file ending


code:
import logging
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('/var/tmp/myapp.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.WARNING)

rawDescription: How to get full output of python program?

description: Get full output of python program