code:
#We must redefine it in Py3k if it's not already there
def execfile(file, glob=None, loc=None):
    if glob is None:
        glob = globals()
    if loc is None:
        loc = glob
    stream = open(file, 'rb')
    try:
        encoding = None
        #Get encoding!
        for _i in range(2):
            line = stream.readline() #Should not raise an exception even if there are no more contents
            #Must be a comment line
            if line.strip().startswith(b'#'):
                #Don't import re if there's no chance that there's an encoding in the line
                if b'coding' in line:
                    import re
                    p = re.search(br"coding[:=]\s*([-\w.]+)", line)
                    if p:
                        try:
                            encoding = p.group(1).decode('ascii')
                            break
                        except:
                            encoding = None
    finally:
        stream.close()

    if encoding:
        stream = open(file, encoding=encoding)
    else:
        stream = open(file)
    try:
        contents = stream.read()
    finally:
        stream.close()

    exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script

rawDescription: How to replace execfile() with exec() in Pydev on Ctrl+Alt+Enter key binding?

description: Replace execfile() with exec() in Pydev on Ctrl+Alt+Enter key binding


code:
MyTuple = namedtuple('MyTuple', ['attr1', 'attr2', 'attr3'])
new_tuple = nt_from_kws(MyTuple, attr1=1, attr2=2, attr3=3)

rawDescription: Is it possible to specify attribute names when creating an instance of namedtuple?


rawDescription: Gridding a numpy array

description: Gridding a numpy array


code: np.einsum('...mm->...m', arr)

rawDescription: Numpy einsum broadcasting

description: Numpy einsum broadcasting


rawDescription: Python Regular Expression to find all combinations of a Letter Number Letter Designation


code:
df.loc[(df == 0).all(1)] = np.nan
df

rawDescription: Find missing data in pandas dataframe and fill with NA


code:
class Test(object):

    def __init__(self):
        self.a = None
        self.b = None

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, val):
        # add your checking here
        self._a = val

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, val):
        # add your checking here
        self._b = val

rawDescription: Use a function to write different class attributes


code:
my_list=[10, 13, 15, 18, 20, 15]
from itertools import combinations
sum(i+j==30 for i,j in combinations(my_list,2))

rawDescription: How to iterate and sum each element in a list with another to find a number?

description: Iterate and sum each element in a list with another to find a number


code:
parse1: 1
parse1: 2
parse1: 3
parse2: 4
parse2: 5
parse2: 6
parse2: 7
parse2: 8
parse2: 9

rawDescription: Cancel last line iteration on a file

description: Cancel last line iteration on a file


code: ans = [a[0] - a[i] for i in ind]

rawDescription: Implementing np.subtract.outer for index of array([[array .... structure in python


code:
# Note you have to have NORMAL imported
t["state"] = NORMAL

rawDescription: Is there a way to make a Text widget in Tkinter non-clickable and non-editable?


code:
temp = int_list[i]
int_list[i] = int_list[i+1]
int_list[i+1] = temp

rawDescription: Sorting algorithm doesn't work

description: Sorting algorithm doesn't work


code:
import pandas as pd

def geo(x):
    return x*2, x*3

df = pd.DataFrame({'address':[1,2,3]})

output = df['address'].apply(geo)

df['a'] = [x[0] for x in output]
df['b'] = [x[1] for x in output]

rawDescription: Applying the output of a function to two columns using .apply


code:
import numpy as np

arr_a = np.random.rand(10)
arr_b = np.random.rand(10)

arr_c = np.where((abs(arr_a - arr_b)/arr_a) > 0.3, 1, 0)

rawDescription: Create numpy array based on magnitude of difference between arrays


code:
from bisect import bisect_left

def generate_time_off_paid_days_list(years, rules, default):
    r_list = sorted(rules)
    d = {y : default if y > r_list[-1] else
             rules[r_list[bisect_left(r_list, y)]] for y in years}
    return d

rawDescription: How to generate a dictionary based on a list and dictionaries

description: Generate a dictionary based on a list and dictionaries


code:
array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])
_, inv, counts = np.unique(array_, return_inverse=True, return_counts=True)
counts[inv]

rawDescription: numpy fastest way to transform an array's elements to their frequency

description: Numpy fastest way to transform an array's elements to their frequency


code: sheet.cell(row=2, column=3).value = 'hello world'

rawDescription: Writing to row using openpyxl?

description: Writing to row using openpyxl


code:
globals()['a'] = 2
a

rawDescription: How are Behave's decorators created/declared?


code:
vList = [[1],[2],[3],[4]]
vsum = 0
for x in vList:
    for y in x:
        vsum += y

vsum

rawDescription: how to convert list to number and add them up (python 2.7)

description: Convert list to number and add them up (python 2.7)


code: ['visitor', 'guest', 'object (in grammar)']

rawDescription: python regex unicode - extracting data from an utf-8 file

description: Python regex unicode - extracting data from an utf-8 file


rawDescription: Adding '0' to binary

description: Adding '0' to binary


rawDescription: Trying to get a nice format output, easy Python


code:
print ('This is a very long line of text that goes beyond the 80\n'
       'character limit.')

rawDescription: Splitting long line printed to screen the right way in python


code:
from scipy.signal import lfilter
N=3
a=np.array([1,-1])
b=np.concatenate(([1],np.zeros(N-1),[-1]))/N
x=np.arange(5)
means=lfilter(b,a,x)
# array([0.,0.3333,1.,2.,3.])

rawDescription: numpy.convolve python old numbers cant change

description: Numpy.convolve python old numbers cant change


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

x=np.linspace(0,np.pi*2,1000)

plt.plot(x,np.sin(x),hold=True)
plt.plot(x,np.sin(x)**2,hold=False)
plt.show()

rawDescription: What does the matplotlib `hold` keyword argument do?


code:
class Machine(dict):
    def __init__(self):
        dct = {'poweron':'OUTP ON', 'home' : 'MV 0, 0', 'identify': '*IDN?'}
        super(Machine, self).__init__(dct)
    def __dir__(self):
        return sorted(self)
    def __getattr__(self, k):
        if k in self:
            def getter_setter(new_value=None):
                if new_value is None:
                    return self[k]
                self[k] = new_value
            return getter_setter
        raise AttributeError(k)

m = Machine()
dir(m)
m.home
m.home()
m.home('new value')
m.home()

rawDescription: Extract methods of a class from the keys of a dictionary


code:
db.GqlQuery("SELECT * FROM Pet WHERE owner = :1 and vet = :2", owner.key(), vet.key())

Pet.all().filter("owner =", owner.key()).filter("vet =", vet.key())

rawDescription: How to query on ReferenceProperties?

description: Query on ReferenceProperties


code:
from collections import namedtuple
MyClass = namedtuple("MyClass", ["a", "b"])
ob = MyClass(a=1, b=2)
ob.a

rawDescription: Python: how to implement __getattr__()?

description: Python: how to implement __getattr__()


rawDescription: Creating array from CSV in Python while limiting columns used


rawDescription: Save email attachment (python3, pop3_ssl, gmail)


rawDescription: Override python logging for test efficiency


code: import cart

rawDescription: no module named 'cart' when i go to admin

description: No module named 'cart' when i go to admin


code:
def no_property_adaptor(obj):
    class wrapper(obj.__class__):
        def __getattr__(self, name):
            if name.startswith("get_"):
                return lambda: getattr(self, name[4:])
            elif name.startswith("set_"):
                return lambda value: setattr(self, name[4:], value)
            else:
                return super(wrapper, self).__getattr__(name)

    obj.__class__ = wrapper
    return obj

rawDescription: Python: renaming method names on-the-fly


code: pairs = IT.combinations(idx, 2)

rawDescription: Pairwise Set Intersection in Python

description: Pairwise Set Intersection in Python


rawDescription: Python mailbox encoding errors

description: Python mailbox encoding errors


code:
caller(1,2,3, arg=True)
caller.assert_called_with(*[Any(int)]*3, arg=True)

rawDescription: Assert that a method was called with one argument out of several


code:
class ActionNoYes(argparse.Action):
    def __init__(self, opt_name, dest, default=True, required=False, help=None):
        super(ActionNoYes, self).__init__(['--' + opt_name, '--no-' + opt_name], dest, nargs=0, const=None, default=default, required=required, help=help)
    def __call__(self, parser, namespace, values, option_string=None):
        if option_string.starts_with('--no-'):
            setattr(namespace, self.dest, False)
        else:
            setattr(namespace, self.dest, True)

rawDescription: In Python argparse, is it possible to have paired --no-something/--something arguments?


rawDescription: Python turning a tuple into a dict

description: Python turning a tuple into a dict


code:
def _run_regression(data, y_name):
    """
    Run a linear regression, in R, using `data` with dependent variable
    `y_name` and independent variables all other columns of `data`.
    """
    from rpy2.robjects.packages import importr
    stats = importr('stats')
    broom = importr('broom')
    lm = broom.tidy(stats.lm('%s ~ . ' % y_name, data=data))
    return _extract_R_df(lm).set_index('term')

def _extract_R_df(df):
    """
    Extract the R DataFrame `df` as a pd.DataFrame. This slightly
    longer method is necessary because `np.asarray(df)` drops the
    exponent on very small numbers!
    """
    return pd.DataFrame({name:np.asarray(df.rx(name))[0] for name in df.names})

rawDescription: Retrieve statistics from R lm regression into pandas with rpy2


code:
import urllib2
response = urllib2.urlopen('http://reddit.com/')
html = response.read()

rawDescription: How to iterate over many websites and parse text using web crawler

description: Iterate over many websites and parse text using web crawler


code: map(callable, iterable)

rawDescription: question about filtering a dictionary using a list in python

description: Question about filtering a dictionary using a list in python


code:
import operator

ops = {
    '+': (operator.add, 'Sum', 0),
    '-': (operator.sub, 'Difference', 0),
    '*': (operator.mul, 'Product', 1),
    '/': (operator.truediv, 'Quotient', 1),
}

rawDescription: Pythonic way to write calculate function for a calculator - Python


code: sum(sum(lis, []))

rawDescription: sum for list of lists

description: Sum for list of lists


code: parsedContent = "".join(insert_gen(parsedContent, self.trimmedCode))

rawDescription: Efficient way to do string insertion in python?


code:
A
_ = [np.random.shuffle(i) for i in A] # shuffle in-place, so return None
A

rawDescription: Randomizing/Shuffling rows in a dataframe in pandas


code:
def check_ping():
    hostname = "taylor"
    response = os.system("ping -c 1 " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

    return pingstatus

rawDescription: Python Function to test ping

description: Python Function to test ping


code:
class TestClassDict(dict):
    def __missing__(self, key):
        res = self[key] = TestClass(key)
        return res

rawDescription: python: defaultdict with non-default argument

description: Python: defaultdict with non-default argument


code:
import pytest

@pytest.mark.incremental
class TestUserHandling:
    def test_login(self):
        pass
    def test_modification(self):
        assert 0
    def test_deletion(self):
        pass

rawDescription: Pytest: how to skip the rest of tests in the class if one has failed?


rawDescription: Performance of 2 vector-matrix dot product


code: out = out.splitlines()

rawDescription: Python subprocess readlines()?

description: Python subprocess readlines()


code: data = [{key: json[key][i] for key in json} for i in range(len(json.keys()[0]))]

rawDescription: Formatting a Python Dictionary for JSON

description: Formatting a Python Dictionary for JSON


rawDescription: Python: delete substring by indices

description: Python: delete substring by indices


code:
def mergesort(ent):
    if len(ent)>1:
        m=math.floor(len(ent)/2)
        L1 = ent[:m]
        L2 = ent[m+1:len(ent)]
        L=merge(mergesort(L1),mergesort(L2))
return L

rawDescription: Python - Merge Sort Recursive Algorithm

description: Python - Merge Sort Recursive Algorithm


rawDescription: Despite many examples online, I cannot get my MATLAB repmat equivalent working in python


code:
class Television:
        def __init__(self, volume = 0, channel = 0):
                self.__volume = volume
                self.__channel = channel

        @property
        def volume(self): return self.__volume

        @volume.setter
        def volume(self, volume):
                if not 0 <= volume <= 100:
                        print('Volume out of bounds.')
                        return
                self.__volume = volume

        @property
        def channel(self): return self.channel

        @channel.setter
        def channel(self, channel):
                if channel < 0 or channel > 64:
                        print('Channel out of bounds.')
                        return
                self.__channel = channel

        def __str__(self): #for printing it
                return 'Volume is {} and channel is {}.'.format(self.__volume, self.__channel)

tv = Television() #calling init

while True:
        choice = input ('''YO TV

0 - Turn off TV
1 - TV status
2 - Change channel
3 - Change volume
''')
        if choice == '0': break
        if choice == '1':
                print(tv) #calling __str__
                continue
        if choice == '2':
                tv.channel = int(input('New channel: ')) #note here
                continue
        if choice == '3':
                tv.volume = int(input('New volume: ')) #note here
                continue
        print('Unkown command.')

rawDescription: how to make a proper object?

description: Make a proper object


code:
shape = (total_length/size,size)
data = np.memmap('tmp', dtype='i', mode='r+', order='F', shape=shape)

rawDescription: Is it possible to map a discontiuous data on disk to an array with python?


code:
# two lines
plt.figure()
plt.hold(True)
plt.plot(range(5))
plt.plot(range(5)[::-1])

#one line
plt.figure()
plt.hold(False)
plt.plot(range(5))
plt.plot(range(5)[::-1])

rawDescription: Re-initialize the plot in pylab

description: Re-initialize the plot in pylab


code:
def treeify(seq):
    ret = {}
    for path in seq:
        cur = ret
        for node in path:
            cur = cur.setdefault(node, {})
    return ret

rawDescription: How to efficiently merge multiple list of different length into a tree dictonary in python

description: Efficiently merge multiple list of different length into a tree dictonary in python


code:
from scipy.sparse import csr_matrix
inspect.getmodule(csr_matrix).__name__

rawDescription: retrieve the Package.Module.Class name from a (Python) class/type

description: Retrieve the Package.Module.Class name from a (Python) class/type


code:
@app.after_request
def add_header(response):
  response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
  if ('Cache-Control' not in response.headers):
    response.headers['Cache-Control'] = 'public, max-age=600'
  return response

rawDescription: Disable cache on a specific page using Flask


code:
rotated = []
for item in zip(rev[0],rev[1],rev[2]):
    rotated.append(item)

rotated

rawDescription: How does this code snippet rotating a matrix work?


code:
from statistics import mean
import csv
from operator import itemgetter

def sort_mean(fle):
    avgs, high = [], []
    with open(fle) as f:
        for name, *scores in csv.reader(f, delimiter=" "):
            srt = list(map(int, scores))
            avgs.append((name, mean(srt)))
            high.append((name, max(srt)))
    avgs.sort(key=itemgetter(1), reverse=1)
    high.sort(key=itemgetter(1), reverse=1)
    return avgs, high

rawDescription: Python: Import from text file to list and sort/average based on multiple columns


code: from selenium import webdriver

rawDescription: How to use Selenium with Python?

description: Use Selenium with Python


code:
brbg <- brewer.pal(11, "BrBG")
cols <- c(colorRampPalette(c(brbg[1], brbg[6]))(51),
    colorRampPalette(c(brbg[6], brbg[11]))(51)[-1])

rawDescription: What is a "good" palette for divergent colors in R? (or: can viridis and magma be combined together?)


code:
import urllib, os

url = 'http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg'
file, headers = urllib.urlretrieve(url)
# do something
os.remove(file)

rawDescription: Downloading Image with urllib.urlretrieve() in Django


code:
from tkinter import *
import tkinter.messagebox
import urllib.request
import turtle

def main():
    counts = analyzeFile(url.get())
    drawHistogram(counts)

def analyzeFile(url):
    try:
        infile = urllib.request.urlopen(url)
        s = str(infile.read().decode()) # Read the content as string from the URL

        counts = countLetters(s.lower())

        infile.close() # Close file
    except ValueError:
        tkinter.messagebox.showwarning("Analyze URL",
            "URL " + url + " does not exist")

    return counts

def countLetters(s):
    counts = 26 * [0] # Create and initialize counts
    for ch in s:
        if ch.isalpha():
            counts[ord(ch) - ord('a')] += 1
    return counts

def drawHistogram(list):

    WIDTH = 400
    HEIGHT = 300

    raw_turtle.penup()
    raw_turtle.goto(-WIDTH / 2, -HEIGHT / 2)
    raw_turtle.pendown()
    raw_turtle.forward(WIDTH)

    widthOfBar = WIDTH / len(list)

    for i in range(len(list)):
        height = list[i] * HEIGHT / max(list)
        drawABar(-WIDTH / 2 + i * widthOfBar,
            -HEIGHT / 2, widthOfBar, height, letter_number=i)

    raw_turtle.hideturtle()

def drawABar(i, j, widthOfBar, height, letter_number):
    alf='abcdefghijklmnopqrstuvwxyz'
    raw_turtle.penup()
    raw_turtle.goto(i+2, j-20)

    #sign letter on histogram
    raw_turtle.write(alf[letter_number])
    raw_turtle.goto(i, j)

    raw_turtle.setheading(90)
    raw_turtle.pendown()

    raw_turtle.forward(height)
    raw_turtle.right(90)
    raw_turtle.forward(widthOfBar)
    raw_turtle.right(90)
    raw_turtle.forward(height)

window = Tk()
window.title("Occurrence of Letters in a Histogram from URL")

frame1 = Frame(window)
frame1.pack()

scrollbar = Scrollbar(frame1)
scrollbar.pack(side = RIGHT, fill = Y)

canvas = tkinter.Canvas(frame1, width=450, height=450)
raw_turtle = turtle.RawTurtle(canvas)

scrollbar.config(command = canvas.yview)
canvas.config( yscrollcommand=scrollbar.set)
canvas.pack()

frame2 = Frame(window)
frame2.pack()

Label(frame2, text = "Enter a URL: ").pack(side = LEFT)
url = StringVar()
Entry(frame2, width = 50, textvariable = url).pack(side = LEFT)
Button(frame2, text = "Show Result", command = main).pack(side = LEFT)

window.mainloop()

rawDescription: Put histogram in tkinter frame

description: Put histogram in tkinter frame


code:
def genValues(i,j):
  return [x for x in range(j+1) if x >=i]

rawDescription: Pandas replace issue

description: Pandas replace issue


code:
a = MyList([Example(), Example()])
a.cl_print()
a[0].cl_print()

rawDescription: How to have a list in python which returns a default item on an invalid index or no index at all

description: Have a list in python which returns a default item on an invalid index or no index at all


code: d = dict(map(lambda item: item.split("=", 1), a))

rawDescription: Can I avoid such cumbersome list comprehension

description: Avoid such cumbersome list comprehension


code: soFar = soFar[:index] + newChar + soFar[index+1:]

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

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


code:
pixel_value = {'0': 0, '1': 255}
byte_seq = ''.join(chr(pixel_value[c]) for c in a if c in pixel_value)

rawDescription: string to b&w image

description: String to b&w image


code:
import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Help, HelpNavigator

helpFile = r"C:\planta\client\Help\Planta.chm"
topic = r"/D-KA-0044095.html"

Help.ShowHelp(None, helpFile, HelpNavigator.Topic, topic)

rawDescription: ironpython: How to call a chm Helpfile on Windows with parameters

description: Ironpython: How to call a chm Helpfile on Windows with parameters


code: CityFormSet = formset_factory(CityNameForm, min_num=1, max_num=5, validate_min=True, validate_max=True, formset=RequiredFormSet)

rawDescription: FormSet rendering always two forms as default Django


code: a[:,:,None].repeat(3, axis=2)

rawDescription: Special Vector and Element-wise Multiplication


code:
business = Business().put()
business_info = BusinessInfo(key_name='i', parent=business).put()

# Get business_info from business:
business_info = db.get(db.Key.from_path('BusinessInfo', 'i', parent=business))

# Get business from business_info:
business = db.get(business_info.parent())

rawDescription: App Engine, Cross reference between two entities


code:
with open("file.py") as f:
    lines = f.readlines()

with open("file.py", "w") as f:
    lines.insert(0, "a = 1")
    f.write("\n".join(lines))

rawDescription: How can I tell python to edit another python file?

description: Tell python to edit another python file


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

binary = FirefoxBinary('F:\FirefoxPortable\Firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary)

rawDescription: Setting path to firefox binary on windows with selenium webdriver


code: {'C9JVZ1': [], 'C9J872': ['nucleus', 'transcription factor complex', 'DNA binding', 'sequence-specific DNA binding RNA polymerase II transcription factor activity', 'transcription cofactor activity', 'mitotic cell cycle', 'regulation of transcription from RNA polymerase II promoter', 'transcription, DNA-templated'], 'C9JLN0': ['cytosol']}

rawDescription: Python: extract string on webtext from a list of URL


code: [i for i, item in enumerate(sent3) if item == wanted_item]

rawDescription: NLTK index of a word with mulitiple occurences


rawDescription: modifying key's name in python dictionary

description: Modifying key's name in python dictionary


code:
x = raw_input("What action would you like to take")
direction = x.split()[-1].lower()
if direction == "west":
    character.goWest(location)
elif direction == "east":
    character.goEast(location)
elif direction == "north":
    character.goNorth(location)
else:
    character.goSouth(location)

rawDescription: Turn user input strings into a function call


code:
source_words = set()
with open('source.txt') as source:
    for word in source.readlines():
        source_words.add(word.replace('http://','').replace('www.','').strip())

exist_words = set()
with open('exist.txt') as exist:
    for word in exist.readlines():
        exist_words.add(word.replace('http://','').replace('www.','').strip())

print("There {} words from 'source.txt' in 'exists.txt'".format(
   "are" if exist_words.intersection(source_words) else "aren't"
))

rawDescription: How to find words inside two text files

description: Find words inside two text files


code:
class Mobilesuits:
     instances = []
     def __init__(self):
         Mobilesuits.instances.append(self)

rawDescription: How do I reference all class instances at the same time?

description: Reference all class instances at the same time


code:
mapping = {'count': int, 'leaf': dict}
mapping['branch'] = lambda: KeyBasedDefaultDict(mapping)

tree = KeyBasedDefaultDict(mapping)

rawDescription: Python nested defaultdict with mix data types


code:
import unittest
import sys
import io
import logging

from unittest.mock import patch

def get_input():
    pirateInput = input("What be ye name?! ")
    print("Ahoy Captain", pirateInput)

class GetInputTest(unittest.TestCase):

    @patch('builtins.input', return_value='Hook')
    def test_ValuePrints(self, sth):
      log = logging.getLogger( "SomeTest.testSomething" )
      saved_stdout = sys.stdout
      try:
          out = io.StringIO()
          sys.stdout = out
          get_input()
          output = out.getvalue().strip()
          log.debug(output)
          assert output == 'Ahoy Captain Hook'
      finally:
          sys.stdout = saved_stdout

if __name__ == "__main__":
    logging.basicConfig( stream=sys.stderr )
    logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
    unittest.main()

rawDescription: Checking if correct value is outputed Python unit test


rawDescription: How can I match regular expression for this url?

description: Match regular expression for this url


code:
import pygame,sys
from pygame.locals import *

my_clock = pygame.time.Clock()
pygame.init()
color =(200,0,0)
surface_sz = 480
surface = pygame.display.set_mode((surface_sz, surface_sz))
pygame.display.set_caption("Cards")
card=pygame.image.load("sprite_sheet_playing_cards.png")
card_width = 73

all_cards=[]
paused=False
text=["Shuffling Cards","Result"]
text_posn=0
my_font = pygame.font.SysFont("Courier", 20)

while True:

    for event in pygame.event.get():

        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_SPACE:

                #Shift the text_posn
                text_posn+=1
                text_posn= text_posn%2

                paused = not paused

    surface.fill(color)

    if not paused:
        #create 5 card objects and store them in list
        for card_no in range(5):

            hand_card=cards(card,(50+card_no*card_width,240))
            all_cards.append(hand_card)

        # Start the shuffling
        hand_card.start_shuffle(all_cards,surface)

        #draw the text to surface
        the_text = my_font.render(text[text_posn],True, (0,0,0))
        surface.blit(the_text, (120, 90))

    for each_card in all_cards:
        surface.blit(each_card.image, each_card.posn, each_card.patch_rect)

    #put everything on display
    pygame.display.flip()
    my_clock.tick(10)

rawDescription: Pygame Displaying text while paused

description: Pygame Displaying text while paused


rawDescription: Sort tuples by averages of second element


code:
import urllib2
from Bio import SeqIO

uniprot_id = 'P12345'
url = 'http://www.uniprot.org/uniprot/'+uniprot_id+'.xml'
s = urllib2.urlopen(url)
contents = s.read()

record = SeqIO.read(contents, 'uniprot-xml')

rawDescription: Biopython: Getting XML-file by Protein accession


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([0, 2000, 0, 2e-9])

ax.annotate('_____', xy=(2000, 0), xytext=(0, -ax.xaxis.labelpad),
            xycoords=('data', 'axes fraction'), textcoords='offset points',
            ha='center', va='top',
            bbox=dict(boxstyle='round', fc='none', ec='red'))

plt.show()

rawDescription: Draw box around tick label in Matplotlib


code:
import psutil

def most_intensive_process():
    return max(psutil.process_iter(), key=lambda x: x.cpu_percent(0))

def most_RAM_usage():
    return max(psutil.process_iter(), key=lambda x: x.memory_info()[0])

x = most_intensive_process()
y = most_RAM_usage()

print(x.name)
print(y.name)

rawDescription: Accessing CPU/RAM usage (like with Task Manager, but via API!)?


code:
from collections import OrderedDict
d=OrderedDict()
for i in range(1,7):
   d['x_{}'.format(i)]=input("Enter data{}  :".format(i))

d

d['x_3']

rawDescription: Defining multiple variables in python via enumeration


code:
print(driverKeys[-1])  # return time of last driven keyframe
print(drivenKeys[-1])  # return value at last driven keyframe

rawDescription: How do I find the time of a particular keyframe using cmds.selectKey?

description: Find the time of a particular keyframe using cmds.selectKey


code:
subject = "by the way I know 54 how to take praise for 65 excellent questions 34 thank you for asking appreciated."
for match in re.finditer(r"(?=((?:\b[a-z]+\b ){4}\d+(?: \b[a-z]+\b){4}))", subject, re.IGNORECASE):
    print(match.group(1))

rawDescription: python regex find substrings centered with numbers

description: Python regex find substrings centered with numbers


code:
cur.execute("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text,
                                               status.author.screen_name,
                                               status.created_at,
                                               status.source))

rawDescription: How to transfer streaming info from stdout to a mySQLdb in python?

description: Transfer streaming info from stdout to a mySQLdb in python


code:
def capitalize_nested(t):
    if isinstance(t, list):
        return [capitalize_nested(s) for s in t]
    else:
        return t.capitalize()

rawDescription: Function that takes a nested list of strings and returns a new nested list with all strings capitalized?


code:
from pyspark.sql.functions import length

df = sqlContext.createDataFrame([("fooo", ), ("bar", )], ("k", ))
df.where(length(col("k")) <= 3).show()

## +---+
## |  k|
## +---+
## |bar|
## +---+

rawDescription: Filtering DataFrame using the length of a column


code: foundInstances.append(['http://' + str(num) + 'endofsite', desc])

rawDescription: Using Python to write a CSV file with delimiter


code: y, z = zip(*[(i.split()[0], i.split()[1] if " " in i else "") for i in x])

rawDescription: Splitting columns more efficiently

description: Splitting columns more efficiently


code: "INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z FROM mytable WHERE mytable.x > :x_1)"

rawDescription: How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?


code: getattr(proxy, "is_even")

rawDescription: How to invoke an XML RPC method with Python when the method name is only known at runtime?

description: Invoke an XML RPC method with Python when the method name is only known at runtime


rawDescription: Python - Sharing getpass() Input with another script?


code:
def calc_check(workers):
    return sum(sum(hours) * 13 for hours in workers.values())

rawDescription: Looping and returning all values in a dictionary


code: df = df[(df.ID.str[2:].astype(int) >= 1) & (df.ID.str[2:].astype(int) <= 879)]

rawDescription: Select rows in pandas dataframe for which value in the column is in XY0001-XY0879 where X and Y can be any digit


code: (dict((x[0], x[1], x[3]), x) for x in data).values()

rawDescription: Python remove couple of duplicates from List


code:
X
w
(X[:,None] - w).shape
(X - w[:,None]).shape

rawDescription: Subtracting numpy arrays of different shape efficiently


code:
class PermissionChecker(object):
    def __init__(self):
        self.permissions = [self.is_superuser(), self.is_god()]

    def is_superuser(self):
        # use self.property just like self.name...
        return True

    def is_god(self):
        return True

rawDescription: How to use self.method() in class creation time?

description: Use self.method() in class creation time


code:
import difflib

string_a = 'python'
string_b = 'honbe'

matcher = difflib.SequenceMatcher(a=string_a, b=string_b)
match = matcher.find_longest_match(0, len(matcher.a), 0, len(matcher.b))

rawDescription: Trying to find a match in two strings - Python


rawDescription: NumPy Indexing - all pairwise elements of lists of indices


code:
class enforced_staticmethod(staticmethod):
     def __get__(self, instance, cls):
         if instance is not None:
             raise Exception('Do not call with an instance.')
         return super(enforced_staticmethod, self).__get__(self)

class C:
    @enforced_staticmethod
    def hai(x):
        return x + 1

rawDescription: Making static methods explicitly reference the class


code:
def gen_k_slices(seq, k):
    for i in range(len(seq) - k + 1):
        yield seq[i:i+k]

rawDescription: Select adjacent couples (or triads, etc ) from a list


code:
f = open('file.pkl', 'w')
pickle.dump(cfd, f)
f.close()

rawDescription: Storing conditional frequency distribution using NLTK


rawDescription: Basic Python XML data extraction

description: Basic Python XML data extraction


code:
import numpy as np

x = np.random.rand(100)
y = np.random.rand(100)
k = np.arange(1, 11)

# define f_k = (x + y)^k
fk = lambda xx, yy, kk: (xx + yy)**kk

rawDescription: Surface where height is a function of two functions, and a sum over the third


code:
def get_list(self, request, **kwargs):

    # ...

    # TODO: Uncached for now. Invalidation that works for everyone may be
    #       impossible.
    objects = self.obj_get_list(
        request=request, **self.remove_api_resource_names(kwargs))

    # ...

rawDescription: Why doesn't my tastypie cache get called?


code:
class Example(Base):
    __tablename__ = 'example'
    id = Column(Integer, primary_key=True)
    title = Column(String(255))
    parent_id = Column(Integer, ForeignKey('example.id'), nullable=True)
    children = relationship("Example")

rawDescription: Best Practice for SQLAlchemy and Self Referenced Objects


code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2

time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)

plt.plot(freqs[idx], ps[idx])

rawDescription: Plotting power spectrum in python

description: Plotting power spectrum in python


code: LOGIN_URL = 'path.to.views.login'

rawDescription: Is LOGIN_REDIRECT_URL deprecated?

description: Is LOGIN_REDIRECT_URL deprecated


code:
# expects two points vertically separated. If your points are horizontally
#  separated, reverse their x and y when passing into this function
#  output is the angle between the line the two points make and the horizontal

rawDescription: Python modules lib.util and lib.geom

description: Python modules lib.util and lib.geom


code: pdf.fonttype : 42 # Output Type 3 (Type3) or Type 42 (TrueType)

rawDescription: Cannot edit text in chart exported by Matplotlib and opened in Illustrator


code: [list(ast.literal_eval(xl[0])) for xl in xll]

rawDescription: Remove string quotes from array in Python


code: usr_list = [char for char in usr_list if char not in punctuation]

rawDescription: Loop to remove characters from list not working


code:
import random
random.sample(votes_selected, int(len(votes_selected) * DATA_PERCENTAGE / 100))

rawDescription: Randomly Keep X Percent of Dictionary

description: Randomly Keep X Percent of Dictionary


code: cars = [car(driver, sponsor) for driver, sponsor in drivers.items()]

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


code:
def do_it(*args):
    if not args: args = (2, 5, 21)

rawDescription: default values for variable argument list in Python

description: Default values for variable argument list in Python


code:
msk = M.row==M.col
D1 = sparse.coo_matrix((M.data[msk],(M.row[msk],M.col[msk])),shape=M.shape)

rawDescription: Diagonal sparse matrix obtained from a sparse coo_matrix


rawDescription: Pythonic way for checking if value exists in dictionary of dictionaries and taking corresponding actions


code:
from tempfile import mkstemp
from shutil import move
from os import remove, close

def replace_3_line(file):
    new_3rd_line = 'new_3_line\n'
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(file)
    counter = 0
    for line in old_file:
        counter = counter + 1
        if counter == 3:
            new_file.write(new_3rd_line)
        else:
            new_file.write(line)
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file)
    #Move new file
    move(abs_path, file)

replace_3_line('tmp.ann')

rawDescription: Replace given line in files in Python

description: Replace given line in files in Python


code:
from contextlib import contextmanager

@contextmanager
def declare_attributes(self):
    self._allow_declarations = True
    try:
        yield
    finally:
        self._allow_declarations = False

def restrict_attributes(cls):
    cls.declare_attributes = declare_attributes
    def _setattr(self, attr, value):
        disallow_declarations = not getattr(self, "_allow_declarations", False)
        if disallow_declarations and attr != "_allow_declarations":
            if not hasattr(self, attr):
                raise AttributeError("You shall not set attributes!")
        super(cls, self).__setattr__(attr, value)
    cls.__setattr__ = _setattr

    return cls

rawDescription: In Python, count the number of variables in a class or prevent adding new class variables


code:
hh = [[82.5], [168.5]]
[ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
hh = [[2], [4]]
[ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
hh = [[2], [4], [6]]
[ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
hh = [[1, 2, 4]]
[ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
hh = [[1, 2], [3, 4]]
[ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]

rawDescription: Python multiply 2 arrays

description: Python multiply 2 arrays


code: b[np.array([np.equal(*I) for I in zip(a[:,3],b[:,3])])]

rawDescription: Numpy Compare unequal rows and make both array of same dimension


code: dict([(x,float(a.count(x))/len(a)) for x in set(a)])

rawDescription: Plotting data using percent unit

description: Plotting data using percent unit


code:
def __init__(self):
    self.url = "http://url.com"
    self.icon = "icon.ico"

rawDescription: Python - most convenient way to define constant variables used just once


code:
class Created():
    def __init__(self, creator):
        self.parameter = creator.parameter

rawDescription: Can a class instance created by another class instance access the creator's members?


code:
import unittest
import cgi

from mock import patch

def function_to_test():
    form = cgi.FieldStorage()
    if "name" not in form or "addr" not in form:
        return "
Error
\nPlease fill in the name and address.\n"
    text = "
name: {0}\n
addr: {1}\n"
    return text.format(form["name"].value, form["addr"].value)

@patch('cgi.FieldStorage')
class TestClass(unittest.TestCase):
    class TestField(object):
        def __init__(self, value):
            self.value = value

    FIELDS = { "name" : TestField("Bill"), "addr" : TestField("1 Two Street") }

    def test_cgi(self, MockClass):
        instance = MockClass.return_value
        instance.__getitem__ = lambda s, key: TestClass.FIELDS[key]
        instance.__contains__ = lambda s, key: key in TestClass.FIELDS
        text = function_to_test()
        self.assertEqual(text, "
name: Bill\n
addr: 1 Two Street\n")

    def test_err(self, MockClass):
        instance = MockClass.return_value
        instance.__contains__ = lambda self, key: False
        text = function_to_test()
        self.assertEqual(text,
            "
Error
\nPlease fill in the name and address.\n")

rawDescription: Python CGI FieldStorage test harness

description: Python CGI FieldStorage test harness


code:
while s[index] != n:
    if low>=high:
        return "Not Found"
    if  s[index] < n:
        low = index + 1
    else:
        high = index
    index = (high + low)/2

rawDescription: Exiting out of loop when not found - Binary Search in Python


code:
result = ''
for char in name:
    result += char + space

result += '.'
result

rawDescription: Taken username: how can I have only one space at the end when suggesting an alternative username?


code:
import unittest
import leveltest

# This is needed before any uses of the @leveltest.level() decorator
#   to parse the "--level" command argument and set the test level when
#   this test file is run directly with -m
if __name__ == "__main__":
    ns, remaining_args = leveltest.parse_args()

@leveltest.level(2)
class TestStringMethods(unittest.TestCase):

    @leveltest.level(5)
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    @leveltest.level(3)
    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    @leveltest.level(4)
    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if __name__ == '__main__':
    # this invokes unittest when this file is executed with -m
    unittest.main(argv=remaining_args)

rawDescription: Passing arguments (for argparse) with unittest discover


code:
s = "abdc54sgh"
int("".join([x for x in s if x.isdigit()]))

rawDescription: Python - Find a number and then copy it from a string


code:
#views.py
request.session['state'] = "You're successfully logged in!"
HttpResponseRedirect("/welcome/")
#html
{{ request.session.state }}

rawDescription: How to combine HttpResponseRedirect & render_to_response?

description: Combine HttpResponseRedirect & render_to_response


code:
from wsgiref.simple_server import make_server

def serveImage(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'image/png')]
    start_response(status, headers)

    return open("about.png", "rb").read()

httpd = make_server('', 8000, serveImage)
httpd.serve_forever()

rawDescription: Creating dynamic images with WSGI, no files involved


rawDescription: Python compare list of date ranges

description: Python compare list of date ranges


rawDescription: Generate all one step variations of a permutation


code: from kivy.properties import NumericProperty

rawDescription: How to change opacity when pressing buttons on kivy

description: Change opacity when pressing buttons on kivy


code:
print('Site Counts:')
for site, count in site_counts.most_common():
    print('    {}  got {:2d} hits'.format(site, count))

rawDescription: Counting first element in python and printing?


code:
def wrapper(function):
   return function('TEST ')

rawDescription: Boost Python , python functions and ptrs


code:
seen = set()
imageFiles = [x for x in imageFiles if x.md5 not in seen and not seen.add(x.md5)]

rawDescription: Eliminate Duplicates of Custom Datastructure


code:
function_list = [func1, func2, func3, func4, func5, func6,
                 func7, func8, func9, func10, func11]
for func in random.sample(function_list, 5):
    func()

rawDescription: Call a different function based on a random number in python


code:
fig, ax= plt.subplots()
for year in np.unique(years):
    mask = years == year
    ax.plot(x[mask], y[mask], linestyle='none', marker='o', label=year)
ax.legend(numpoints=1)

rawDescription: MatPlotLib: Given a dataset of 3, graph the 2 and use the 3rd as a label


rawDescription: Advanced cross-section with multi-index in pandas


code:
import numpy as np
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(111,projection='3d')
n = 100

xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, 0, 100)

colmap = cm.ScalarMappable(cmap=cm.hsv)
colmap.set_array(zs)

yg = ax.scatter(xs, ys, zs, c=cm.hsv(zs/max(zs)), marker='o')
cb = fig.colorbar(colmap)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

rawDescription: How to plot heatmap colors in 3D in Matplotlib

description: Plot heatmap colors in 3D in Matplotlib


code:
#!/usr/bin/env python
import csv
import sys

usage = 'Usage: %s infile' % sys.argv[0]

data = []
for filename in sys.argv[1:]:
    with open(filename) as f:
        data.append([line.strip() for line in f])

data = zip(*data)
with open('outfil.txt', 'w') as f:
    writer = csv.writer(f, delimiter=" ")
    writer.writerows(data)

rawDescription: Python : How do i get a new column for every file I read?


code:
Language
Processing
Python
Editor

rawDescription: Python program to perform keyword matches for contents present in two files


code: subprocess.Popen("python <path to .py file>")

rawDescription: Execute python files through code

description: Execute python files through code


code: df['group_indicator'] = (df.group_id != df.group_id.shift(-1)).astype(int)

rawDescription: Select last observation per group

description: Select last observation per group


code:
def Run(*args):
  return _Run(True, *args)

rawDescription: Wrap a function in python supplying an additional boolean


code:
def singleton(cls):
    return cls()

@singleton
class EventManager:
    def __init__(self):
        self.events = []
    def add_event(self, event):
        self.events.append(event)
    def print_events(self):
        print("Events : {}".format(self.events))

EventManager.add_event(0)
EventManager.add_event(1)
EventManager.add_event(2)
EventManager.print_events()

rawDescription: Python: use the same class instance in multiple modules


rawDescription: Faithfully Preserve Comments in Parsed XML (Python 2.7)


code:
from oauth2client.client import SignedJwtAssertionCredentials

credentials = SignedJwtAssertionCredentials(
  "<service account email>@developer.gserviceaccount.com",
  file("secret-privatekey.pem", "rb").read(),
  scope=["http://www.google.com/m8/feeds/"],
  prn="<user to impersonate>@your-domain.com"
)

rawDescription: Is it possible to use "Domain-wide Delegation of Authority" with gdata-python-client?


code:
mat = scipy.sparse.rand(4, 4, density=0.5, format='csc')
mat.toarray()
mat.toarray() / np.sqrt(np.sum(mat.toarray()**2, axis=1))[:, None]
sparse_row_normalize(mat)
mat.toarray()

rawDescription: Modify scipy sparse matrix in place

description: Modify scipy sparse matrix in place


code:
import numpy as np
import pandas as pd

a = np.random.rand(6,4)
b = np.asarray(['test']*6)

df = pd.DataFrame(a)
df['b'] = b

df.to_csv('/tmp/out')

rawDescription: How to combine a numpy array and a text column and export to csv

description: Combine a numpy array and a text column and export to csv


rawDescription: document with maximum appearance in a collection mongodb

description: Document with maximum appearance in a collection mongodb


code:
import os
from urlparse import urljoin

from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.utils.deconstruct import deconstructible

@deconstructible
class MyFileSystemStorage(FileSystemStorage):
    def __init__(self, subdirectory):
        self.subdir = subdir
        super(MyFileSystemStorage, self).__init__(location=os.path.join(settings.MEDIA_ROOT, self.subdir), base_url=urljoin(settings.MEDIA_URL, self.subdir))

    def __eq__(self, other):
        return self.subdir == other.subdir

rawDescription: Django migrations and FileSystemStorage depending on settings


code:
import os
os.stat('test.txt').st_mtime

rawDescription: Modified time using os.stat in Python gets lower when copying files


code:
upload = bottle.request.files.get('upload')
reader = csv.DictReader(upload.file, delimiter=';')

rawDescription: Upload file in Bottle as is and use it afterwards


rawDescription: Is there a significant overhead by using different versions of sha hashing (hashlib module)


code:
import io
import gzip

f = io.BytesIO(b"Your compressed gzip-file content here")
with gzip.GzipFile(fileobj=f) as fh:
    plain_text = fh.read()
    print(plain_text)

rawDescription: Bytes from zip file to text in python

description: Bytes from zip file to text in python


rawDescription: Scipy, optimize a function with argument dependent constraints


code:
for a, b in enumerate(results):
    for i in b:
        if not isinstance(i, str) and i > highest:
            highest = i
            row = a
            total = sum(i for i in b if not isinstance(i, str))

rawDescription: Ignore str in sum()

description: Ignore str in sum()


code:
class ClientCreate(CreateView):
    model = Client
    fields = [..., 'branch']

rawDescription: Django: How to create a dropdown from CreateView


code:
class Foo(object):
     def __init__(self):
         self.x = None

rawDescription: What is the difference between __set__ and __setattr__ in Python and when should which be used?


code:
inspect.getdoc(object)
inspect.getcomments(object)
inspect.getfile(object)
inspect.getmodule(object)

rawDescription: Test if function or method is normal or asynchronous


code:
for word, counts in word_count_dict.iteritems():
    print('Total counts for word {}: '.format(word, counts['total']))
    for filename, count in counts.iteritems():
        if filename == 'total': continue
        print("{} appears in {} {} times".format(word, filename, count))

rawDescription: how to iterate over all keys in dictionary python?

description: Iterate over all keys in dictionary python


code:
import httplib
conn = httplib.HTTPConnection('www.foo.com')
conn.request('PUT', '/myurl', body)
resp = conn.getresponse()
content = resp.read()

rawDescription: How to make HTTP DELETE method using urllib2?

description: Make HTTP DELETE method using urllib2


code:
def case_insensitive_in(phrase, string):
    return phrase.lower() in string.lower()

rawDescription: Python lightweight case insensitive if "x" in variable


code:
with open(file_name_extracted_from_body_goes_here, "w") as f:
    f.writelines(body)

rawDescription: Split diary file into multiple files using Python


code:
from django import forms
from registration.forms import RegistrationForm
from django.utils.translation import ugettext_lazy as _
from registration.models import RegistrationProfile

attrs_dict = { 'class': 'required' }

class RegistrationFormEx(RegistrationForm):
  cell_phone = forms.CharField(widget=forms.TextInput(attrs=attrs_dict))

rawDescription: how to use django's registration field(s) to custom table

description: Use django's registration field(s) to custom table


rawDescription: Python 3: sort rows in 2D matrix, where columns are lists


code:
class BinTree (object):
    def __init__(self, value=None, left=None, right=None):
        if left == None and right == None and value != None:
            self.isLeaf = True
            self.value = value
        elif left != None and right != None and value == None:
            self.isLeaf = False
            self.value = (left, right)
        else:
            raise ArgumentError("some help message")

rawDescription: Haskell equivalent of data constructors in Python?


code:
from threading import Thread

t = Thread(target = worker, name = "Grid Worker")

t.daemon = True # Useful when this thread is not the main thread.

t.start()

rawDescription: Python - Threading, Timing, or function use?


code:
class A (object):
    _DEFAULT_DETAILS = 'details'

    def __init__(self, details=None):
        if details is None:
            self.details = self._DEFAULT_DETAILS
        else:
            self.details = details

rawDescription: Mocking class constructor default parameters in Python


code:
aliased_MCastSession = aliased(MCastSession, name="MCastSession2")
qry = session.query(\
    MCastSession, \
    func.count(aliased_MCastSession.id).label("number_with_same_ip")).\
filter(MCastSession.ip == aliased_MCastSession.ip).\
group_by(MCastSession)

rawDescription: Writing SQL query refering same table twice


code:
from itertools import groupby
[[i[0],i[-1],len(i)] for i in [list(g) for _,g in groupby(L,key=lambda x:x!=0)]if i[0]!=0]

rawDescription: Python making list

description: Python making list


code:
import glob, os

def rename(dir, pattern, titlePattern):
    for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
        title, ext = os.path.splitext(os.path.basename(pathAndFilename))
        os.rename(pathAndFilename,
                  os.path.join(dir, titlePattern % title + ext))

rawDescription: Batch Renaming of Files in a Directory

description: Batch Renaming of Files in a Directory


code:
for node in tree.iterfind('.//country[@name="Liechtenstein"]/year'):
    node.set('updated', 'yes') # key, value pair for updated="yes"

rawDescription: Python XML Element Replacement

description: Python XML Element Replacement


code:
vars(type(d))
list(vars(type(d)))

rawDescription: Get all methods of a class, but not those of superclasses


code: #Now how to I access send_stuff

rawDescription: Sending arbitrary data with Twisted

description: Sending arbitrary data with Twisted


code:
import contextlib
from StringIO import StringIO

with contextlib.closing(StringIO()) as handle:
    thing.save(handle)
    contents = handle.getvalue()

rawDescription: In-memory thumbnail generation in python


code:
def history(function, toAdd):
    global history1
    global history2
    global history3
    global history4
    global history5

    if function == 'add':
        history5 = history4
        history4 = history3
        history3 = history2
        history2 = history1
        history1 = copy.deepcopy(toAdd)
    elif function == 'undo':
        toReturn = history1
        history1 = history2
        history2 = history3
        history3 = history4
        history4 = history5

        # Should history5 still be valid at this point?  Maybe do?
        #    history5 = None

        # There could be several issues here.  Remember, this is a deep copy
        # of a previous object/collection.  If your code is  expecting the
        # original object, you will not have it.
        return toReturn
    elif function == 'return':
        # Is it expected that whomever calls this will receive a copy that
        # they can manipulate?  If so, the deepcopy() here is required.
        return copy.deepcopy(history1)

rawDescription: Python lists not behaving as intended

description: Python lists not behaving as intended


code:
a_set = set(a)
i_set = set(i)
i =[x if x in i_set else "" for x in a] + [x for x in i if x not in a_set]
i

rawDescription: Creating Array with Comparison from Other Arrays in Python


code:
def b(df):
    sliced = df.loc[0:1].copy()
    sliced.loc[:,'b'] = 'foo'
    return sliced

rawDescription: Passing DataFrame slice as argument to function without 'SettingWithCopyWarning'


code:
class Migration(migrations.Migration):

    ...

    operations = [
        migrations.RunSQL('create unique index card_number_ind on cards (card_number) where (status is false)'),
    ]

rawDescription: django postgres conditional constrain

description: Django postgres conditional constrain


code:
data = "xxx@yyy.com@zzz.com"
if data.count("@") == 2:
    data = data.rsplit('@', 1)[0]

rawDescription: How to reformat a string in python?

description: Reformat a string in python


code:
x = numpy.arange(5).reshape((5, 1))
y = numpy.arange(5)
x.shape
x.T.shape
y * x.T

rawDescription: Elementwise multiply 1D-numpy arrays (shapes (k,1) or (k,)) and have result have the shape of the first


code:
def someview(request):
      fr= FindRepace()
      fr.author = author_obj
      fr.find = 'Foo'
      fr.replace = 'Bar'

      if fr._validate_creation(request.user.id):
         fr.save()

rawDescription: Many-to-many relationship children exclusive to parent model. How?


code:
arr3 = ndimage.grey_erosion(arr, size=(2,2))
print(np.allclose(arr2,arr3))
# True

rawDescription: Is there a Python equivalent to Matlab's makelut, applylut?


code:
MDB = 'C:\\Some\\random\\path\\here.mdb'
DRV = '{Microsoft Access Driver (*.mdb, *.accdb)}'
con = pyodbc.connect('DRIVER={};DBQ={}'.format(DRV, MDB))

query = """select * from [Some Table Name] where Sector = 'Some Sector'"""
dataframe = pd.read_sql(query, con)

rawDescription: How to convert a Microsoft Access Database to a SQL database (and then open it with pandas)?

description: Convert a Microsoft Access Database to a SQL database (and then open it with pandas)


rawDescription: Read CSV file as a dictionary containing first row as headers (keys)


code:
a = numpy.indices((4,)*13)
b = 1j ** numpy.rollaxis(a, 0, 14)

rawDescription: itertools product speed up

description: Itertools product speed up


rawDescription: Python: Write a program that asks the user for a color, a line width, a line length and a shape


code:
with open('testfile', 'wb') as f:
    f.write(''.join(chr(i) for i in range(256)))
with open('testfile', 'r') as f:
    assert len(f.read()) < 256  # len(..) == 26

rawDescription: Python bytearray isn't as long as it should be


rawDescription: Using Argparse and Json together

description: Using Argparse and Json together


code:
class FactorType(type):
    @property
    def empty(cls):
        return Factor([], None)

class Factor(object):
    __metaclass__ = FactorType
    ...

rawDescription: Define a constant object in python

description: Define a constant object in python


code:
for row in table[left:left+5]:
    row[right:right+5] = [0 for x in range(5)]

rawDescription: How to alter a part of an array

description: Alter a part of an array


code:
class HttpResponseBase:

    def __init__(self, content_type=None, status=None, mimetype=None):
        # _headers is a mapping of the lower-case name to the original case of
        # the header (required for working with legacy systems) and the header
        # value. Both the name of the header and its value are ASCII strings.
        self._headers = {}
        self._charset = settings.DEFAULT_CHARSET
        self._closable_objects = []
        # This parameter is set by the handler. It's necessary to preserve the
        # historical behavior of request_finished.
        self._handler_class = None
        if mimetype:
            warnings.warn("Using mimetype keyword argument is deprecated, use"
                          " content_type instead",
                          DeprecationWarning, stacklevel=2)
            content_type = mimetype
        if not content_type:
            content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
                    self._charset)
        self.cookies = SimpleCookie()
        if status:
            self.status_code = status

        self['Content-Type'] = content_type

    ...

    def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
                   domain=None, secure=False, httponly=False):
        """
        Sets a cookie.

        ``expires`` can be:
        - a string in the correct format,
        - a naive ``datetime.datetime`` object in UTC,
        - an aware ``datetime.datetime`` object in any time zone.
        If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.

        """
        self.cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                if timezone.is_aware(expires):
                    expires = timezone.make_naive(expires, timezone.utc)
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                self.cookies[key]['expires'] = expires
        if max_age is not None:
            self.cookies[key]['max-age'] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                self.cookies[key]['expires'] = cookie_date(time.time() +
                                                           max_age)
        if path is not None:
            self.cookies[key]['path'] = path
        if domain is not None:
            self.cookies[key]['domain'] = domain
        if secure:
            self.cookies[key]['secure'] = True
        if httponly:
            self.cookies[key]['httponly'] = True

rawDescription: Django cookies and headers

description: Django cookies and headers


code:
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

rawDescription: Match multiple strings containing lines from file python


code: lines.sort(key = lambda x: x[3])

rawDescription: How do i sort a lot of lists to get a top 10 in python?

description: Sort a lot of lists to get a top 10 in python


code:
import sqlite3
conn = sqlite3.connect('serials.db') #Will connect to the existing database
cur = conn.cursor()
data = ('MY_SERIAL',) #a tuple
cur.execute('''INSERT INTO serials_tb VALUES (?)''', data)
conn.commit()
conn.close()

rawDescription: Copycating static variables (file scope) behavior


code:
word_list = { "ugh" : "disappointed"}
tmp = ['laughing ugh']

for t in tmp:
    words = t.split()
    for i in range(len(words)):
        if words[i] in word_list.keys():
            words[i] = word_list[words[i]]
    newline = " ".join(words)
    print(newline)

rawDescription: Python string replacement

description: Python string replacement


code:
items = (x[1] for x in data)
list(zip(*[items]*2))

rawDescription: Compacting tuples from a QS

description: Compacting tuples from a QS


code:
y_values = data["scores"].values
seaborn.boxplot(x="centrality", y="score", hue="model", data=data,
                y_lim=(np.min(y_values),np.max(y_values)))

rawDescription: Tweaking seaborn.boxplot

description: Tweaking seaborn.boxplot


code:
# Wait for servers to shutdown
s1.join()
s2.join()

rawDescription: Start new process on __init__ (for TCP listener - server)


code:
tags
classes_inverse

rawDescription: Unable to match tuples items to list items


code:
def int_sqrt(x):
    if x < 0:
        raise ValueError('square root not defined for negative numbers')
    n = int(x)
    if n == 0:
        return 0
    a, b = divmod(n.bit_length(), 2)
    x = 2**(a+b)
    while True:
        y = (x + n//x)//2
        if y >= x:
            return x
        x = y

def find_match(pattern):
    lowest = int(pattern.replace('?', '0'), 2)
    highest = int(pattern.replace('?', '1'), 2)
    mask = int(pattern.replace('0', '1').replace('?', '0'), 2)
    lowsqrt = int_sqrt(lowest)
    if lowsqrt*lowsqrt != lowest:
            lowsqrt += 1
    highsqrt = int_sqrt(highest)
    for n in range(lowsqrt, highsqrt+1):
        if (n*n & mask)==lowest:
            return n*n

print(find_match('1??1??1'))
print(find_match('1??0??1'))
print(find_match('1??????????????????????????????????????????????????????????????????????1??0??1'))

rawDescription: Find the perfect square in the string

description: Find the perfect square in the string


code:
from django.db import models
from django.contrib.auth.models import User

class Blog(models.Model):
    user = models.ForeignKey(User)

rawDescription: ForeignKey to a Model field?

description: ForeignKey to a Model field


rawDescription: Convert Columns to String in Pandas

description: Convert Columns to String in Pandas


code:
from urlparse import urljoin

from bs4 import BeautifulSoup
import requests

base_url = 'http://examplewebsite.com'
with requests.Session() as session:  # maintaining a web-scraping session
    soup = BeautifulSoup(session.get(base_url).content, "html.parser")

    for link in soup.select("div.container a[href]"):
        full_link = urljoin(base_url, link["href"])
        title = a.get_text(strip=True)

        with open(title + ".html", "w") as f:
            f.write(session.get(full_link).content)

rawDescription: Navigation with BeautifulSoup

description: Navigation with BeautifulSoup


rawDescription: convenient slicing of DataFrames with datetime indexes in pandas

description: Convenient slicing of DataFrames with datetime indexes in pandas


rawDescription: Special kind of row-by-row multiplication of 2 sparse matrices in Python


code:
def parseRangeRe(rangeStr):
    master_pattern = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
    matcher = re.compile(rangeStr)
    return set(matcher.findall(master_pattern))

rawDescription: How to get the corresponding chars with a pattern in Python

description: Get the corresponding chars with a pattern in Python


code:
for cnt in contours:

    leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
    rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
    topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
    bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

    rect = cv2.minAreaRect(cnt)
    box = cv2.cv.BoxPoints(rect)
    box = np.int0(box)

    M = cv2.moments(cnt)
    centroid_x = int(M['m10']/M['m00'])
    centroid_y = int(M['m01']/M['m00'])

    print (leftmost)
    print (rightmost)
    print (topmost)
    print (bottommost)

    print(centroid_x)
    print(centroid_y)

    print(rect)
    print(box)

rawDescription: Minimum Bounding Box for image regions?

description: Minimum Bounding Box for image regions


code: img.__getitem__( (slice(o,None,None), slice(None,None,None)) )

rawDescription: What does python slicing syntax [o:,:] mean


code:
from settings import *
LOG_FILENAME = '/path/to/log/file/in/production/environment'

rawDescription: What is the DRY way to configure different log file locations for different settings?


code:
try:
    avalid = not f.a_invalid
except NameError:
    avalid = True

rawDescription: Python way for object method chaining for class instance variables


code:
from collections import OrderedDict
d = OrderedDict()
with open("folder/file_1") as file:
    for line in file:
        name, _, raw_time = line.rpartition(":")
        time = int(raw_time.strip("sec \n"))
        d[name] = d.get(name,0) + time

for name, time in d.items():
    print("{}: {:02} {}".format(name, time, "sec" if time == 1 else "secs"))

rawDescription: Adding up a value after matching a line using append from a text file using python 3.x


code:
def convert(text):
  t = int(text)
  if t<1000: #millisecond
    return str(t)+' us'
  elif t<1000000: #second
    return str(int(t/1000))+' ms'
  elif t==1000000: #is a second
    return '1 sec'
  #etc.

rawDescription: Best way to incrementally convert microseconds to their respective conversions in python?

description: Incrementally convert microseconds to their respective conversions in python


code:
list1 = [
    ['item1', 0.955, 'asdcwe', 'adcwett'],
    ['item2', 0.111, 'awioe', 'ocijwe'],
    ['item3', 0.111, 'dcuwq0eu', 'a9dfuwe'],
    ['item4', 0.5, 'aosdic', '204523'],
    ['item5', 1.0, 'oooo', 'ffff'],
    ['item6', 0.112, '03423', 'aewcew']]
step = 1.0 / (len(list1) - 1)
sortedlist = [l[:1] + [(len(list1) - i - 1) * step] + l[2:]
             for i, l in enumerate(sorted(list1, key=lambda item: item[1], reverse=True))]
pprint(sortedlist)

rawDescription: Mapping linear ranks from data points in python


rawDescription: structure of python numpy arrays

description: Structure of python numpy arrays


code:
for func, reqs in funcs.items():
    args = [getattr(args, req) for req in reqs]
    if all(args):
        func(*args)

rawDescription: Python different functions depending on input


code:
Imports
import os
from glob import glob

rawDescription: Python statement as method's argument

description: Python statement as method's argument


code:
filename = "whatever.txt"
filename_without_extension = filename[:-4]

rawDescription: removing last 4 characters in a file with python

description: Removing last 4 characters in a file with python


code:
1
input_result
input_result

rawDescription: How do chained comparisons in Python actually work?


code:
import web

urls = (
    '/', 'index'
)

class index:
    def GET(self):
        return "Hello, world!"

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

rawDescription: Python - How is it used?

description: Python - How is it used


rawDescription: Modify list in Python

description: Modify list in Python


code: df[ df.isnull() ] = np.nanmean( [ df.shift(-48), df.shift(48) ] )

rawDescription: Fill data gaps with average of data from adjacent days


code:
import pandas
testData=pandas.DataFrame([["Cats","Parrots","Sandstone"],["Dogs","Cockatiels","Marble"]],columns=["Mammals","Birds","Rocks"])
swapVals={("Cats","Parrots"):("Rats","Canaries"), ("Dogs","Cockatiels"):("Dogs","Cockatiels")}
target=["Mammals","Birds"]

testData[target] = testData[target].apply(lambda x: list(swapVals[tuple(x.values)]), axis=1)

testData

rawDescription: How do I search for a tuple of values in pandas?

description: Search for a tuple of values in pandas


code:
class SearchProjectForm(forms.Form):
    text = forms.CharField(label = "Search")

    def __init__(self, project, *args, **kwargs):
      form = forms.Form.__init__(self, *args, **kwargs)
      if project.has_additional_fields():
        self.fields['additional_field'] = forms.SomeField()
      if project.only_additional_fields():
        self.fields['text'].required = False

rawDescription: Expanding my search function

description: Expanding my search function


code:
def view(request):
    foo_form = FooForm(request.POST or None, user=request.user)

rawDescription: How to access self.request.user in clean_avatar() in forms.py (django application)

description: Access self.request.user in clean_avatar() in forms.py (django application)


code: empList.append(tuple(s.strip() for s in empName.split(",")))

rawDescription: Input into tuple that goes into list

description: Input into tuple that goes into list


code:
# in yourapp/apps.py
from django.apps import AppConfig

class YourAppConfig(AppConfig):
    name = 'yourapp'
    verbose_name = 'Fancy Title'

rawDescription: Can you give a Django app a verbose name for use throughout the admin?

description: Give a Django app a verbose name for use throughout the admin


code:
file_name = "/tmp/file.csv"
myfile = open(file_name, 'a')
for item in object_items:
    adding_product_to_csv(item, myfile)

rawDescription: Python PostgreSQL using copy_from to COPY list of objects to table


code:
nltk.Text(['the world The words']).count('the')
nltk.Text(['the', 'world', 'The', 'words']).count('the')

rawDescription: count occurrence of a words in a csv file in python using nltk

description: Count occurrence of a words in a csv file in python using nltk


code:
animals = 'cat dog fish goat pig'
print(''.join(filter(lambda x: x in 'abcd', animals)))

rawDescription: print found characters inside a string

description: Print found characters inside a string


code:
class Person(object):
    def __init__(self, name):
        self.name = name
        self.friends = []

rawDescription: Implementing Java object creation in Python


code: out = subprocess.check_output(['ls', '-ltrh'])

rawDescription: In a Python 2.4 script, I would like to execute a os system call `ls -l` or `curl` for example and capture the output in a variable. How to do this?


code:
import boto3

client = boto3.client('emr', region_name='us-east-1')

S3_BUCKET = 'MyS3Bucket'
S3_KEY = 'spark/main.py'
S3_URI = 's3://{bucket}/{key}'.format(bucket=S3_BUCKET, key=S3_KEY)

# upload file to an S3 bucket
s3 = boto3.resource('s3')
s3.meta.client.upload_file("myfile.py", S3_BUCKET, S3_KEY)

response = client.run_job_flow(
    Name="My Spark Cluster",
    ReleaseLabel='emr-4.6.0',
    Instances={
        'MasterInstanceType': 'm4.xlarge',
        'SlaveInstanceType': 'm4.xlarge',
        'InstanceCount': 4,
        'KeepJobFlowAliveWhenNoSteps': True,
        'TerminationProtected': False,
    },
    Applications=[
        {
            'Name': 'Spark'
        }
    ],
    BootstrapActions=[
        {
            'Name': 'Maximize Spark Default Config',
            'ScriptBootstrapAction': {
                'Path': 's3://support.elasticmapreduce/spark/maximize-spark-default-config',
            }
        },
    ],
    Steps=[
    {
        'Name': 'Setup Debugging',
        'ActionOnFailure': 'TERMINATE_CLUSTER',
        'HadoopJarStep': {
            'Jar': 'command-runner.jar',
            'Args': ['state-pusher-script']
        }
    },
    {
        'Name': 'setup - copy files',
        'ActionOnFailure': 'CANCEL_AND_WAIT',
        'HadoopJarStep': {
            'Jar': 'command-runner.jar',
            'Args': ['aws', 's3', 'cp', S3_URI, '/home/hadoop/']
        }
    },
    {
        'Name': 'Run Spark',
        'ActionOnFailure': 'CANCEL_AND_WAIT',
        'HadoopJarStep': {
            'Jar': 'command-runner.jar',
            'Args': ['spark-submit', '/home/hadoop/main.py']
        }
    }
    ],
    VisibleToAllUsers=True,
    JobFlowRole='EMR_EC2_DefaultRole',
    ServiceRole='EMR_DefaultRole'
)

rawDescription: How do you automate pyspark jobs on emr using boto3 (or otherwise)?

description: Automate pyspark jobs on emr using boto3 (or otherwise)


code:
from itertools import imap
any(imap(pred, lst))

rawDescription: Is there a Python equivalent of Ruby's 'any?' function?


code:
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Thing(Base):
    __tablename__ = 'thing'

    id = Column(Integer, primary_key=True)
    data = Column(AdvancedNullComparisons(50))

from sqlalchemy.dialects import postgresql, mysql
print(Thing.data != 'hi').compile(dialect=postgresql.dialect())
print(Thing.data != 'hi').compile(dialect=mysql.dialect())

rawDescription: NULL safe inequality comparisons in SQL Alchemy?


code: types.MethodType(f1, None, C).__get__(C(), C)

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


rawDescription: Isolating coastal grids using convolving window (python)


rawDescription: Is there a better way to convert from decimal to binary in python?


rawDescription: Remove non numeric values from a Series

description: Remove non numeric values from a Series


code:
import time
import subprocess

p = subprocess.Popen(["calc"])
time.sleep(4)
p.kill()

rawDescription: Subprocess management - Killing a subprocess


code:
for bit_1, bit_2 in zip(a, b):
    if bit_1 == bit_2:
        c += '1'
    else:
        c += '0'

rawDescription: Python String to Bool conversion yields True for all cases


rawDescription: How to preserve column names while importing data using numpy?

description: Preserve column names while importing data using numpy


code:
pre_df = []
for file in files:
    ...
    for line in file:
        ...
        pre_df.append(processed_line)

df = pandas.DataFrame(pre_df, ...)

rawDescription: Why is my Python script so much slower than its R equivalent?


code:
for field, court in zip(Field, Court):
    stringText = ','.join((FileName, TypeName, field, court))

rawDescription: How to write a csv from a fresh new line not \n

description: Write a csv from a fresh new line not \n


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

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


code:
n = 30
assert 2 * (n // 2) == n
rows = 3**(n//2)
cols = n

arr = np.zeros((rows, cols), dtype=int)
shape = (rows,)

source = np.array([-1, 0, 1], dtype=np.int)[:, None]

for col in range(n//2):
    shape = (-1, 3, shape[-1]//3,)
    col_view = arr[:, col]
    col_view.shape = shape
    col_view[:] = source

rawDescription: How to make a large numpy array efficiently

description: Make a large numpy array efficiently


code:
import lxml.html as l
doc = """

       one
       1

       two
       2</td

   """
doc = l.document_fromstring(doc)
doc.finall('.//tr')

rawDescription: html5lib/lxml examples for BeautifulSoup users?

description: Html5lib/lxml examples for BeautifulSoup users


code: self.lbl = Label(text='Test', width=self.width, height=self.height)

rawDescription: Issues with Scatter size and position

description: Issues with Scatter size and position


rawDescription: Collapsing entries with duplicate index values in DataFrame


code:
import logging
import subprocess
import contextlib
import shlex

logger = logging.getLogger(__name__)

@contextlib.contextmanager
def suspended_logger():
    root = logging.getLogger()
    handler = root.handlers[0]
    yield
    handler.stream.seek(0, 2)

def main():
    logging.basicConfig(filename = '/tmp/test.log', filemode = 'w',
                        level = logging.DEBUG)

    logger.info("Started")
    with suspended_logger():
        cmdStr = 'test2.py 1>>/tmp/test.log 2>&1'
        logfile = open('/tmp/test.log', 'a')
        proc = subprocess.Popen(shlex.split(cmdStr),
                                stdout = logfile,
                                stderr = logfile)
        proc.communicate()
    logger.info("Done")

if __name__ == '__main__':
    main()

rawDescription: Python logging and subprocess ouput and error stream


code:
def my_stem(text, stemmer):
    words = text.split(" ")
    stemmed_words = map(stemmer, words)
    result = " ".join(list(stemmed_words))
    return result

rawDescription: Stemming process not working in Python

description: Stemming process not working in Python


code:
for root, dirs, files in os.walk(do):
    for f in files:
        if not f.endswith('.html'): # only work with .html files
            continue
        original_file = os.path.join(root, f)
        modified_file = os.path.join(dm, f)
        with open(original_file, 'r') as orig_f:
            soup = BeautifulSoup(orig_f)

#       Alternative idea: write old files to dm
#       Make a backup copy in modified files dir
#       with open(modified_file, 'w') as modi_f:
#           modi_f.write(soup.prettify().encode(soup.original_encoding))

        for t in soup.find_all('img'):                    # Note: soup exists outside of with
            try:
                old_src = t['src']                        # Access src attribute
                image = os.path.split(old_src)[1]         # Get file name
#               Variant:
#               image = old_src.replace('img/','')
                relpath = os.path.relpath(root, do)       # Get relative path from do to root
#               Variant:
#               relpath = root[len(do):]
                folders = relpath.strip('\\').split('\\') # Remove outer slashes, split on folder separator
                new_src = '_'.join(folders.append(image)) # Join folders and image by underscore
                t['src'] = new_src                        # Modify src attribute
            except:                                       # Do nothing if tag does not have src attribute
                pass
        with open(modified_file, 'w') as modi_f:
            modi_f.write(soup.prettify().encode(soup.original_encoding))

#       Alternative idea: overwrite original html files
#       with open(original_file, 'w') as orig_f:
#           orig_f.write(soup.prettify().encode(soup.original_encoding))

rawDescription: Updating image text programmatically

description: Updating image text programmatically


code:
#!/usr/bin/env python3

import matplotlib
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator

data = range(5)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(data,data)

ax.xaxis.set_major_locator(MaxNLocator(5, prune='lower'))
ax.yaxis.set_major_locator(MaxNLocator(4))

fig.savefig("1.png")

rawDescription: Matplotlib: Tick labels position

description: Matplotlib: Tick labels position


code:
# Access each index
for trans in unique_trans:

    # Get the higher number in "Num" for each so we know which to set to NaN
    max_num = max(df.ix[trans].index.values)

    # Copy your start column as a temp variable
    start = df.ix[trans]["Start"].copy()

    # Apply the transform to the start column (Equal to end + 10)
    df.loc[trans, "Start"] = np.array(df.ix[trans]["End"]) + 10

    # Apply the transform to the end column
    df.loc[trans, "End"] = np.array(start.shift(-1) - 10)

    # By passing a tuple as a row index, we get the element that is both in trans and the max number,
    #which is the one you want to set to NaN
    df.loc[(trans, max_num), "End"] = np.nan

print(df)

rawDescription: Changing the columns in DataFrame with respect to values in other columns


code:
from io import StringIO

old_open = open
in_memory_files = {}

def open(name, mode="r", *args, **kwargs):
     if name[:1] == ":" and name[-1:] == ":":
          # in-memory file
          if "w" in mode:
               in_memory_files[name] = ""
          f = StringIO(in_memory_files[name])
          oldclose = f.close
          def newclose():
              in_memory_files[name] = f.getvalue()
              oldclose()
          f.close = newclose
          return f
     else:
          return old_open(name, mode, *args, **kwargs)

rawDescription: (python) open a file in memory

description: (python) open a file in memory


code:
sorted([u'<NULL', u'NULL>', u'<NULL>', u'NULL', u'a'], key=strcoll)
sorted(['<NULL', 'NULL>', '<NULL>', 'NULL', 'a'], key=strcoll)

rawDescription: Python sort order unicode/ansi differs

description: Python sort order unicode/ansi differs


code:
soup.find_all(id='link2')
# [Lacie]

rawDescription: Python web Automation to get Email from Webpage


code: container = VBox()

rawDescription: Parent error when Inserting new page in Gtk.Notebook containing a TreeView widget


code: path = '/'.join(pathParts[2:-1])

rawDescription: Pythonic URL Parsing

description: Pythonic URL Parsing


rawDescription: Stdout looping halt after certain amount of characters


rawDescription: What is the best-maintained generic functions implementation for Python?


code:
my_list = [[1,2,3],[4,5,6]]

for i in my_list:
    i[0] *= 10  # multiply the first element of each of the inner lists by 10

print(my_list)

rawDescription: How do you multiply the first element in a list by a number (in a list of lists) in Python?

description: Multiply the first element in a list by a number (in a list of lists) in Python


code:
class MyDescriptor(object):

    def __get__(self, inst, cls):
        if inst is None: return self, cls
        try:
            ca = inst.__the_ca
        except AttributeError:
            ca = inst.__the_ca = CountingAttribute()
        ca.count += 1
        return ca

rawDescription: Using descriptors in unhashable classes - python


code: client = Client.get_by_id(key_name, parent=self.user.key)

rawDescription: NDB MyModel.get_by_id() cannot find entity by key_name


rawDescription: Python splitting string to find specific content


code:
data = socket.recv(1024)
if data:
    self.process_data(data)

rawDescription: Twisted wait for event in loop

description: Twisted wait for event in loop


code:
class Meta:
    abstract = True

rawDescription: Django 1.8: How use Model from different application?


code:
from bottle import Bottle, request

app = Bottle()

@app.route('/')
def root():
    return ['this url is: {}'.format(request.url)]

app.run(host='0.0.0.0', port=8080)

rawDescription: Python: Retrieve the current URL from the browser using bottle framework


code: button = ttk.Button(container, text='Button', command=self.updizzle)

rawDescription: Python 3.4/Tkinter cross class variable accessing


code:
d = C2(3)
d.num = 4
d.num
e = C2(3)
d.num == e.num
d.num

rawDescription: Unique representations of Python objects


code: high_reading = max(readings, key=lambda reading: float(reading['High']))

rawDescription: How to get data from this "list" looking thing in python 2.7

description: Get data from this "list" looking thing in python 2.7


code: [int(n) for elem in originallist for n in elem.split()]

description: List of strings in ints ['123 121','42 23','23 23']


code:
def getHikeInfo(name):

    conn, cursor = getConnectionAndCursor()
    cursor.execute("SELECT * FROM hiking WHERE name = %s"%name)
    #if you're passing in a list for `name` then you would need to use my second suggestion.

    # fetch the results
    data = cursor.fetchall()

    # clean up
    cursor.close()
    conn.close()

    return data

rawDescription: Python cursor.fetchall() returns empty tuple


code: request.session['my_key'] = my_value

rawDescription: Pass value to another view django

description: Pass value to another view django


code:
def make_names(first_names, second_names, third_names):
    return map(" ".join, zip(first_names, second_names, third_names))

rawDescription: combining and looping through lists python

description: Combining and looping through lists python


code:
points = Points.objects.filter(user=request.user) \
                       .aggregate(total_points=models.Sum('points'))

rawDescription: Django Models: aggregate filter

description: Django Models: aggregate filter


code:
from sage.all import *
import random

rawDescription: An algorithm for randomly generating integer partitions of a particular length, in Python?


code:
# Iterative Algorithm (xgcd)
def iterative_egcd(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q,r = b//a,b%a; m,n = x-u*q,y-v*q # use x//y for floor "floor division"
        b,a, x,y, u,v = a,r, u,v, m,n
    return b, x, y

def modinv(a, m):
    g, x, y = iterative_egcd(a, m)
    if g != 1:
        return None
    else:
        return x % m

rawDescription: Solving a modular equation (Python)

description: Solving a modular equation (Python)


code:
corr = 205
score = 100 * (corr / 225)
print(score)

rawDescription: python simple percentage calculation returning 0

description: Python simple percentage calculation returning 0


code:
from string import ascii_lowercase as letters

def find_words(digits):
    if not digits:
        yield ''
        return
    first = letters[int(digits[0])]
    for remainder in find_words(digits[1:]):
        yield first + remainder
    if len(digits) > 1 and int(digits[:2]) < 26:
        firsttwo = letters[int(digits[:2])]
        for remainder in find_words(digits[2:]):
            yield firsttwo + remainder

rawDescription: Convert a number representing the position of the characters in the dictionary to the original string


rawDescription: how to move identical elements in numpy array into subarrays

description: Move identical elements in numpy array into subarrays


code:
import pyximport
pyximport.install(reload_support=True)
import asd
q1 = asd.foo()
reload(asd)
q2 = asd.foo()

rawDescription: Parallelise python loop with numpy arrays and shared-memory


code:
def fun(n):
    return [i**1 for i in range(n+1)]

rawDescription: Return a values into a list

description: Return a values into a list


code:
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
secretkey = "Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
trans = str.maketrans(char, secretkey)
s = "Lets meet at the usual place at 9 am"
s.translate(trans)

rawDescription: python replace multiple characters in a string

description: Python replace multiple characters in a string


code:
# file: singleton.py
element_list = []

rawDescription: Define a constructor in full classmethod class


code: out_img = foo(img, *np.indices(shape=(h,w)))

rawDescription: loop variable aware numpy's slicing and vectorized calculations

description: Loop variable aware numpy's slicing and vectorized calculations


code: masked = background.copy()

rawDescription: Pygame - is there any way to only blit or update in a mask


code:
title, data = ('AssetType_FrameDrops ', "[['Time', 'uploaded', 'Unknown', 'captured'], ['2013-08-31-16', 34885, 0, 943640], ['2013-08-31-17', 19167, 0, 1095645], ['2013-08-31-18', 11610, 0, 1005367], ['2013-08-31-19', 4741, 0, 1318737], ['2013-08-31-20', 5829, 0, 1066768], ['2013-08-31-21', 5748, 0, 946647], ['2013-08-31-22', 55554, 0, 900068], ['2013-08-31-23', 70560, 0, 792410]]")
key1, key2 = title.split("_")

from ast import literal_eval
data = literal_eval(data)
headers, data = data[0], data[1:]
marks = [dict(zip(headers, items)) for items in data]

result = {}
for current_dict in marks:
    current_time = current_dict["Time"]
    for k, v in current_dict.items():
        if k == "Time": continue
        if k not in result: result[k] = {}
        if current_time not in result[k]: result[k][current_time] = {}
        result[k][current_time][key2] = v

from pprint import pprint
result = {key1: result}
pprint(result)

rawDescription: To zip a list with more than 2 lists

description: To zip a list with more than 2 lists


code:
@helloGalaxy
@helloSolarSystem
def hello(targetName=None):
    ...

rawDescription: Explain how Python decorator works

description: Explain how Python decorator works


code:
def alt(s, t):
    if not (s and t):
        return s + t
    return s[0] + t[0] + alt(s[1:], t[1:])

rawDescription: Return Alternating Letters in Two Strings of Different Lengths


code:
[{'end-date': datetime.date(2011, 3, 1),
  'start-date': datetime.date(2011, 2, 27)},
 {'end-date': datetime.date(2011, 4, 13),
  'start-date': datetime.date(2011, 4, 12)},
 {'end-date': datetime.date(2011, 6, 8),
  'start-date': datetime.date(2011, 6, 8)}]

rawDescription: Python: how to compute date ranges from a list of dates?


rawDescription: pandas split timeseries in groups

description: Pandas split timeseries in groups


code:
from itertools import product

def lincombs(s):
    terms, ffs = zip(*s)
    factors = product(*(range(f+1) for f in ffs))
    outs = (sum(v*f for v,f in zip(terms, ff)) for ff in factors if any(ff))
    return outs

rawDescription: All possible combinations of value-pairs (2-item tuples) in a sequence - PYTHON 2.7


code:
def my_view(request, params):
  if not validate_params(params): # validate as you wish
    raise Http404()

  # continue with your view

rawDescription: Multiple parameters in Django URLconf

description: Multiple parameters in Django URLconf


code:
text = '''"Slate on Paper," our specially formatted print-out version of Slate, is e-mailed to readers Friday around midday. It also can be downloaded from our site. Those services are free. An actual paper edition of "Slate on Paper" can be mailed to you (call 800-555-4995), but that costs money and can take a few days to arrive."'''

pattern = "(\+?1-)?(\()?[0-9]{3}(\))?(-|.)[0-9]{3}(-|.)[0-9]{4}"

for match in re.finditer(pattern,text):
    print(match.group())

rawDescription: Python Regex not returning phone numbers


code:
s = "John Frank Smith"
s.split(None, 1)

rawDescription: python regex split first charchter

description: Python regex split first charchter


rawDescription: condensing the code or a one liner possible for this code in python

description: Condensing the code or a one liner possible for this code in python


code:
@event.listens_for(Session, "after_flush")
def update_hash(session, flush_context):
    hashes = [
        {"user_id":element.id, "hash":hash_function(element.id)}
        for element in session.new if isinstance(element, User)
    ]
    user_table = mapper.local_table
    session.execute(
          user_table.update().
              values(hash=bind('hash')).
              where(user_table.c.id==bind('user_id')),
          hashes
    )

rawDescription: Automatically hash primary key and make it persistent upon flush/commit with sqlalchemy


rawDescription: Distinguish between a file or a directory in paramiko


code:
it = iter(range(5))
next(it)

rawDescription: Python itertools tee, clones and caching


rawDescription: Move odd and even numbers in list to odd and even positions


code: documents = [" ".join([stem(word) for word in sentence.split(" ")]) for sentence in documents]

rawDescription: How to stem words in python list?

description: Stem words in python list


code: df.rename(columns={0: 'someIdlevel'})

rawDescription: Python - Panda's dataframes - generate column with group level information


code:
class RequestManager:

    instance = None

    class __RequestManager:
        requests = {
            FooRequest.name: FooRequest,
            BarRequest.name: BarRequest
        }

        def generate_request(self, name):
            if name in self.requests:
                return self.requests[name]()

        def register_request(self, request_class):
            assert issubclass(request_class, BaseRequest), \
                'Request class not a subclass of BaseRequest'
            assert hasattr('name', request_class) and isinstance(request_class.name, str), \
                'Request name not correctly configured'
            self.requests[request_class.name] = request_class

    def __new__(cls):
        if not cls.instance:
            cls.instance = cls.__RequestManager()
        return cls.instance

    @staticmethod
    def getInstance():
        return RequestManager()

rawDescription: Creating a set of Python classes

description: Creating a set of Python classes


code: import collections

rawDescription: How to choose a random but non-recent asset from a list?

description: Choose a random but non-recent asset from a list


code:
foo = foobar2.clip_lower(0)
foo['var3']*=-1
foo['var4']*=-1
foo = foo.sum(axis=1)

rawDescription: Pandas: Adding conditionally

description: Pandas: Adding conditionally


code:
from datetime import timedelta
from django.db import models

class TimeRecord(models.Model):
    duration = models.DurationField(default=timedelta(minutes=40))

rawDescription: Set value for Django DurationField type in query


code: mySizer = wx.BoxSizer()

rawDescription: Destroying and Recreating a Panel wx.Python


code: data = {u'days_validated': '20', u'days_trained': '80', u'navigated_score': '1', u'description': 'First trial of top seller alg. No filter nor any condition is applied. Skus not present in train count as rank=0.5', u'init_cv_date': '2016-03-06', u'metric': 'rank', u'unix_date': '1461610020241117', u'purchased_score': '10', u'result': '0.32677139316724546', u'date': '2016-04-25', u'carted_score': '3', u'end_cv_date': '2016-03-25'}

rawDescription: Bigquery - Insert new data row into table by python


code:
s = scipy.sparse.csr_matrix((n,n),dtype=int)
s[12, 14] = 0
(12, 14) in get_items(s)

rawDescription: Check if scipy sparse matrix entry exists


code: get_dotted_range(start, end)

rawDescription: Python: get the range between two dotted numbers


code:
import numpy as np
import random

diam = 1.5
p = 1
a = 10
d = 0.2
h = 0.15

lx = list(np.arange(-diam/2, diam/2 + 0.05, 0.05))
# Are You aware that casting numpy array to list You loose precision?
# compare:
# print(np.arange(-diam/2, diam/2 + 0.05, 0.05))
# print(list(np.arange(-diam/2, diam/2 + 0.05, 0.05)))

# constants
x1 = 1/(2*p)
tan = np.tan(a)
cond1 = -d/2 - h/np.tan(np.pi/2 - a)
cond2 = d/2
disp1 = "abs( f - x1 * k**2 ) * tan = {} \n(f was {}, last k was {})\n"

print("cond1 = {}".format(cond1))
print("cond2 = {}".format(cond2))
print("")

for loop in range(1):

    f = random.uniform(0, p/2)
    a1 = [k for k in lx if k + abs(f - x1 * k**2 ) * tan < cond1]
    a2 = [k for k in lx if k + abs(f - x1 * k**2 ) * tan > cond2]
    a = a1 + a2
    b = [k + abs(f - x1 * k**2 ) * tan for k in lx]

    last  = abs(f - x1 * lx[-1]**2) * tan
    print(disp1.format(last, f, lx[-1]))
    print("a1=", a1, "\n")
    print("a2=", a2, "\n")
    print("lx=", lx, "\n")
    print("a=", a, "\n")
    print("b=", b, "\n")

    # we have:
    # lx with uniform distribution from 0.75 to 0.75 with step 0.05
    # a1 which will have values from lx up to condition
    # a2 will have rest of lx's values
    # effectively a which is sum of a1 and a2 should be equal lx
    # in rare cases where condition is equal to cond1 or 2, should not.
    # and we have b where i suppose You were testing what Your condition
    # does.
    # So looking at lx[i] and a[i], while checking b[i] versus cond1 or cond2
    # We could see what You intended.

rawDescription: Error in the results of a list comprehension


code:
credentials = {}
with open('Usernames.txt', 'r') as f:
    for line in f:
        user, pwd = line.strip().split(':')
        credentials[user] = pwd

rawDescription: Python Login Script; Usernames and Passwords in a separate file


code:
import socket
socket.has_ipv6
socket.getfqdn('2001:838:2:1::30:67')

rawDescription: What is the IPv6 alternative to socket.getfqdn in Python?


rawDescription: python print to file prints correctly in console but not in file

description: Python print to file prints correctly in console but not in file


code:
rowtype = np.dtype((np.void, A.dtype.itemsize * A.size / A.shape[0]))
# A and B must be C-contiguous, might need to force a copy here
a = np.ascontiguousarray(A).view(rowtype).ravel()
b = np.ascontiguousarray(B).view(rowtype).ravel()

a_to_as = np.argsort(a)     # indices that sort the rows of A in lexical order

rawDescription: Finding a set of indices that maps the rows of one NumPy ndarray to another


rawDescription: Python pandas: replace select values in groupby object


code:
[{'category': 'insect', 'word': 'ant'},
{'category': 'insect', 'word': 'ladybug'}]

rawDescription: Select items with specific field values from a list of dictionaries (similar to SQL SELECT command)


rawDescription: regular expression for a string format

description: Regular expression for a string format


code:
class NegativeValueError(ValueError):
    pass

class PositiveInteger(int):

    def __new__(cls, value, base=10):
        if isinstance(value, basestring):
            inst = int.__new__(cls, value, base)
        else:
            inst = int.__new__(cls, value)
        if inst < 0:
            raise NegativeValueError()
        return inst

    def __repr__(self):
        return "PositiveInteger({})".format(int.__repr__(self))

    def __add__(self, other):
        return PositiveInteger(int.__add__(self, other))

    # ... implement other numeric type methods (__sub__, __mul__, etc.)

rawDescription: Value never below zero

description: Value never below zero


code:
def item_to_model(item):
    model_class = getattr(item, 'django_model')
    if not model_class:
        raise TypeError("Item is not a `DjangoItem` or is misconfigured")

    return item.instance

def get_or_create(model):
    model_class = type(model)
    created = False

    # Normally, we would use `get_or_create`. However, `get_or_create` would
    # match all properties of an object (i.e. create a new object
    # anytime it changed) rather than update an existing object.
    #
    # Instead, we do the two steps separately
    try:
        # We have no unique identifier at the moment; use the name for now.
        obj = model_class.objects.get(name=model.name)
    except model_class.DoesNotExist:
        created = True
        obj = model  # DjangoItem created a model for us.

    return (obj, created)

def update_model(destination, source, commit=True):
    pk = destination.pk

    source_dict = model_to_dict(source)
    for (key, value) in source_dict.items():
        setattr(destination, key, value)

    setattr(destination, 'pk', pk)

    if commit:
        destination.save()

    return destination

rawDescription: How to update DjangoItem in Scrapy

description: Update DjangoItem in Scrapy