code:
import requests
import bs4
url = "http://lyrics.wikia.com/wiki/Agalloch:The_Wilderness"
req = requests.get(url)
soup = bs4.BeautifulSoup(req.text, "html.parser")
lyrics = soup.find("div", {"class":"lyricbox"})
lyrics.get_text().rstrip()

rawDescription: Proper parsing of a html-page with escaped ascii-strings


code:
import os
import zipfile

from flask import Flask
from flask import Response

app = Flask(__name__)

gallery_path = 'galleries'

@app.route('/')
def index():
    html = '{0}'
    gallery_zips = os.listdir(gallery_path)
    gallery_names = [os.path.splitext(zfile)[0] for zfile in gallery_zips]
    galleries = [html.format(gallery) for gallery in gallery_names]
    return '
'.join(galleries)

@app.route('/<gallery>')
def gallery(gallery):
    zip_path = os.path.join(gallery_path, gallery + '.zip')
    html = '{1}'
    with zipfile.ZipFile(zip_path, 'r') as zfp:
        images = zfp.namelist()
        image_list = [html.format(gallery, image) for image in images]
        return '
'.join(image_list)

@app.route('/<gallery>/<path:image>')
def image(gallery, image):
    zip_path = os.path.join(gallery_path, gallery + '.zip')
    with zipfile.ZipFile(zip_path) as zfp:
        image_fp = zfp.open(image, 'r')
        return Response(image_fp, mimetype='image/jpeg')

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: Any way to serve user uploaded images from inside zips with python?


code:
#!/usr/bin/env python
from glob import glob
from subprocess import check_call

cmd = 'java -cp stanford-ner.jar edu.stanford.nlp.process.PTBTokenizer'.split()
with open('output.txt', 'wb', 0) as file:
    check_call(cmd + glob('*.txt'), stdout=file)

rawDescription: python or bash script to pass all files in a folder to java command line

description: Python or bash script to pass all files in a folder to java command line


code:
while True:
    newfiles = check_for_new_files()
    process(newfiles)
    time.sleep(pollinterval)

rawDescription: How do you check when a file is done being copied in Python?

description: Check when a file is done being copied in Python


code:
import re
test = "blade, coffeen,    , cardiac"
re.split('[, ]*?', test)

rawDescription: using non-greedy qualifiers in regular expression '*?'

description: Using non-greedy qualifiers in regular expression '*?'


code:
def change_Vid(self, next_vid):
        self.ids.video.vid = next_vid
        return self.ids.video.vid

rawDescription: Kivy - Change a video source using button


rawDescription: How to return all opposite pairs in a Pandas DataFrame?

description: Return all opposite pairs in a Pandas DataFrame


code:
urlpatterns = patterns('',
   url(r'^$', 'app.account.site.views.page_dispatcher'),
   url(r'^(?P<path>.+)$', 'app.account.site.views.page_dispatcher'),
)

rawDescription: Subdomain-based URL configuration in Django app


rawDescription: Select everything but a list of columns from pandas dataframe


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


code:
import csv
import re

with open('alcohol_rehab_ltp.csv', 'rb') as csv_f, \
    open('cities2.txt', 'rb') as cities, \
    open('drug_rehab_city_state.csv', 'wb') as out_csv:
    writer = csv.writer(out_csv, delimiter = ",")
    reader = csv.reader(csv_f)

    city_re = re.compile(r'\b('+ '|'.join(c.strip() for c in cities.readlines()) + r')\b')

    for row in reader:
        match = city_re.search(row[0])
        if match:
            writer.writerow(row)

rawDescription: Faster Approach of Double for loop when iterating large list (18,895 elements)


code:
def make_A():
    private = {
        'a' : 1,
        'b' : 2,
        'z' : 26,
        }
    class A:
        def __init__(self):
            self.catch = 100
            private['a'] = 2    # you can modify the private data
        def foo(self):
            print(private['a']) # you can access the private data
    return A

A = make_A()

a=A()

a.foo()
# 2

rawDescription: Data Hiding in Python Class

description: Data Hiding in Python Class


code:
from tastypie.resources import ModelResource

class MyResource( ModelResource ):

    def obj_create( self, bundle, request = None, **kwargs ):
        # ...
        # create User instance based on what's in the bundle
        # user = ...
        # ...
        # kwargs[ 'user' ] = user < will be set on Candidate instance in super()
        # ...

        # call super, resulting in creation of the Candidate model
        super( MyResource, self ).obj_create( self, bundle, request, **kwargs )

rawDescription: django tastypie update two models

description: Django tastypie update two models


code:
def simulation():
    sum = 0
    for i in range(10):
        sum += random.random()
    return sum / 10

# Think about how to test that code without
# monkey-patching random.random.

rawDescription: Why do I get different results with same random seed, same computer, same program


rawDescription: Is there a way to 'search' in a pandas DataFrame for 2 specific numbers in columns and return the index if it exists?


rawDescription: The method urllib.urlopen python 2.x does not work in python 3.x


code: import client_module

rawDescription: Replace a client library with a mock from a test?


code:
x = np.random.normal(0,.5,1000)
y = np.random.normal(0,.5,100000)

xhist, xbins = np.histogram(x, normed=True)
yhist, ybins = np.histogram(x, normed=True)

rawDescription: Normalize a multiple data histogram

description: Normalize a multiple data histogram


code:
class C(object):
    pass
c = C()
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.parse_args(args=['--foo', 'BAR'], namespace=c)
c.foo

rawDescription: Is it possible to reconstruct a command line with Python's argparse?


code:
def create_text():
    x = input("Text title: ")
    y = input("Text : ")
    userinput = {x: y}
    return userinput

rawDescription: Function that allows the user to specify title and words for a text and keep them also outside the function?


code:
class RateableThing(db.Model):
    num_ratings = db.IntegerProperty()
    avg_rating = db.FloatProperty()

rawDescription: Google app engine How to count SUM from datestore?


code:
from itertools import izip_longest, chain

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = list(chain.from_iterable(reversed(list(grouper(lst, 3)))))

rawDescription: Manipulating a list by slicing in Python3.x


code:
context['idp'].append(['provider', 'login_url'])
context['idp'].append(['provider', 'login_url'])
context['idp'].append(['provider', 'login_url'])

rawDescription: Webapp2 Jinja2 Dict in List in Dict

description: Webapp2 Jinja2 Dict in List in Dict


code:
from itertools import chain
d = {'seq2': [(1,6)], 'seq1': [(1, 12), (16, 9), (32,9)], 'seq3': [], 'seq4': []}
max(chain.from_iterable(d.values()),key=lambda x: x[1])

rawDescription: Parsing through a dictionary of tuples

description: Parsing through a dictionary of tuples


rawDescription: What is the easiest way to print 10 characters in Python?


code:
class B(object):
    A = A
    def func(self):
        self.a = self.A()

rawDescription: Python inheritance and scoping question

description: Python inheritance and scoping question


code:
class structure:
    def __init__(self, handle):
        self.handle = handle
    def __hash__(self):
        return hash(self.handle)
    def __eq__(self, other):
        if not isinstance(other, structure):
            # only equality tests to other `structure` instances are supported
            return NotImplemented
        return self.handle == other.handle
    def __repr__(self):
        return '<structure({!r})>'.format(self.handle)
list_of_structures = [structure('foo'), structure('bar'), structure('foo'), structure('spam'), structure('spam')]
set(list_of_structures)

rawDescription: Unique class instances in Python3

description: Unique class instances in Python3


rawDescription: How do I store identical arguments to be used by multiple functions

description: Store identical arguments to be used by multiple functions


code:
import re
content = "fox iN a blog"
query = "in"
bolded = re.sub(r"(?i)(%s)" % query, r"<b>\1</b>", content)
bolded

rawDescription: Boldening parts of string ignoring case python,HTML


code: in_network = (a & mask) == netw

rawDescription: Python - ip <-> subnet match?

description: Python - ip <-> subnet match


rawDescription: Celery discover tasks in files with other filenames


rawDescription: Get entries by values in child model

description: Get entries by values in child model


code: nodes[i].addconnection(nodes[j]) #connects the nodes together

rawDescription: Python Neural Networking: Run 10 iterations but I get the same output


code:
from itertools import izip,islice,tee

def sub_findre(s,substring,diffnumber):
    sublen=len(substring)
    zip_gen=(izip(substring,islice(s,i,i+sublen)) for i in xrange(len(s)))
    for z in zip_gen:
        l,z=tee(z)
        if sum(1 for i,j in l if i==j)>=sublen-diffnumber:
            new=izip(*z)
            next(new)
            yield ''.join(next(new))

rawDescription: String regex two mismatches Python

description: String regex two mismatches Python


code:
def scanTiles(self):
    m = curMap.map # this is a 2d matrix filled with tile-objects
    x = int(self.trueX) # trueX & trueY allow me to implement
    y = int(self.trueY) # a 'camera system'
    curTile = m[y // T_SIZE[1]][x // T_SIZE[0]]
    i = curTile.index # (x, y) coordinate of tile on map

    nw = None # northwest
    n = None # north
    ne = None # northeast
    e = None # east
    se = None # southeast
    s = None # south
    sw = None # southwest
    w = None # west

    # Each if-statement uses map indices
    # to identify adjacent tiles. Ex:
    # NW  N  NE
    # W  CUR  E
    # SW  S  SE

    if i[0] > 0 and i[1] > 0:
        nw = m[i[1]-1][i[0]-1]
    if i[1] > 0:
        n = m[i[1]-1][i[0]]
    if i[0] < len(m[0])-1 and i[1] > 0:
        ne = m[i[1]-1][i[0]+1]
    if i[0] < len(m[0])-1:
        e = m[i[1]][i[0]+1]
    if i[0] < len(m[0])-1 and i[1] < len(m)-1:
        se = m[i[1]+1][i[0]+1]
    if i[1] < len(m)-1:
        s = m[i[1]+1][i[0]]
    if i[1] < len(m)-1 and i[0] > 0:
        sw = m[i[1]+1][i[0]-1]
    if i[0] > 0:
        w = m[i[1]][i[0]-1]
    return [nw, n, ne, e, se, s, sw, w]

rawDescription: Python, Pygame, and collision detection efficiency


code:
def save_session(self, app, session, response):
    domain = self.get_cookie_domain(app)
    path = self.get_cookie_path(app)

    ...

rawDescription: How to configure a single flask application to handle multiple domains?

description: Configure a single flask application to handle multiple domains


code: return not (tokensI - tokensO) and not (set(tokensO) - set(tokensI))

rawDescription: How to compare two files that have the same unsorted (and additional unimportant) content?

description: Compare two files that have the same unsorted (and additional unimportant) content


rawDescription: variation of a paramentes for numbers smaler than 1

description: Variation of a paramentes for numbers smaler than 1


code:
s='abcdefghij'
len(s)

rawDescription: How to count the number of letters in a string with a list of sample?

description: Count the number of letters in a string with a list of sample


code:
counter = 0
for x,y in enumerate(prices.items()):
    print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
    counter += 1

rawDescription: Python - Alignment of output of two dictionaries into one table


rawDescription: Selenium/Python2.7 Find elements with similar src?


code:
original = open(filename)
newfile = []
for line in original:
    if line.split('~!')[0] == ex[4]:
        line += "~!" + mask[0]
        line = line.rstrip() + "\n"
    newfile.append(line)
original.close()
amended.open(filename, "w")
amended.writeLines(newfile)
amended.close()

rawDescription: Replacing a line on Python

description: Replacing a line on Python


code:
values = raw_input()
# 1 3 15
a, b, c = values.split()

rawDescription: Read more numbers in a line in Python

description: Read more numbers in a line in Python


code:
def isPrime(i,n):
    if ((n % i == 0) and (i <= math.sqrt(n))):
        return False
    if (i >= math.sqrt(n)):
        print ("is Prime: ",n)
        return True
    else:
        # No return here
        isPrime(i+1,n)

rawDescription: Python issues with return statement

description: Python issues with return statement


code:
import random
from timeit import timeit
testlist = [''.join([chr(random.randint(48, 127)) for _ in range(random.randrange(10, 30))]) for _ in range(1000)]
def str_threevalue_concat(lst):
    res = ''
    for elem in lst:
        res = res + '\n' + elem

def str_twovalue_concat(lst):
    res = ''
    for elem in lst:
        res = res + ('\n%s' % elem)

timeit('f(l)', 'from __main__ import testlist as l, str_threevalue_concat as f', number=10000)
timeit('f(l)', 'from __main__ import testlist as l, str_twovalue_concat as f', number=10000)

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


code:
while True:
    d = input()
    if d == '': break
    print(d)

rawDescription: Input() to Allow <Enter Key> to Insert New Line Instead Of Returning Out of the Code in Python 3.x


rawDescription: Make lists into further sublists

description: Make lists into further sublists


code:
class MyTextInput(TextInput):
    def __init__(self, **kwargs):
        super(MyTextInput, self).__init__(kwargs)

    def on_validate(self):
        #do other stuff perhaps
        self.focus = True

rawDescription: How to set cursor position in TextInput in Kivy

description: Set cursor position in TextInput in Kivy


code:
def animate(self):
    if not self.should_stop:
        self.draw_one_frame()
        self.after(100, self.animate)

rawDescription: simple animation using tkinter

description: Simple animation using tkinter


code:
['a', 'b', 'c'] == ['a', 'c', 'b']    #same keys, but not equal
set(['a', 'b', 'c']) == set(['a', 'c', 'b']) #sets compare fine

rawDescription: How to check if the keys of two dictionaries are the same

description: Check if the keys of two dictionaries are the same


code:
def parse(astr):
    astr=astr.replace(',','')
    astr=astr.replace('and','')
    tokens=astr.split()
    dept=None
    number=None
    result=[]
    option=[]
    for tok in tokens:
        if tok=='or':
            result.append(option)
            option=[]
            continue
        if tok.isalpha():
            dept=tok
            number=None
        else:
            number=int(tok)
        if dept and number:
            option.append((dept,number))
    else:
        if option:
            result.append(option)
    return result

if __name__=='__main__':
    tests=[ ("CS 2110" , [[("CS", 2110)]]),
            ("CS 2110 and INFO 3300" , [[("CS", 2110), ("INFO", 3300)]]),
            ("CS 2110, INFO 3300" , [[("CS", 2110), ("INFO", 3300)]]),
            ("CS 2110, 3300, 3140", [[("CS", 2110), ("CS", 3300), ("CS", 3140)]]),
            ("CS 2110 or INFO 3300", [[("CS", 2110)], [("INFO", 3300)]]),
            ("MATH 2210, 2230, 2310, or 2940", [[("MATH", 2210), ("MATH", 2230), ("MATH", 2310)], [("MATH", 2940)]])]

    for test,answer in tests:
        result=parse(test)
        if result==answer:
            print('GOOD: {0} => {1}'.format(test,answer))
        else:
            print('ERROR: {0} => {1} != {2}'.format(test,result,answer))
            break

rawDescription: Python: How best to parse a simple grammar?


code:
while True:
    option = input("\nEnter a Number [1][2][3]: ")
    if option in options:
        print ("Great")
    else:
        print ("Sorry, Invalid Input! Please Enter either [1] [2] [3]")

rawDescription: How to validate an input to certain numbers?

description: Validate an input to certain numbers


rawDescription: Generate special list from file in python


code:
i='0'
count = 0
while i.isdigit():
    i = raw_input("Enter a number: ")

rawDescription: python while loop user input

description: Python while loop user input


rawDescription: Scipy: Do sparse matrices support advanced indexing?


code:
s1 = sns.jointplot(data.columns[i],
                   data.columns[j],
                   data=data, kind = 'kde',
                   space=0, color="b", stat_func=None,
                   marginal_kws={"kernel":"biw"})  # like this

rawDescription: is it possible to use a non gaussian kernel for the two lateral distributions in seaborn jointplot

description: Is it possible to use a non gaussian kernel for the two lateral distributions in seaborn jointplot


code:
import abc
class Shape(object):
    __metaclass__ = abc.ABCMeta
    def __init__(self, name):
        self.name = name
    @abc.abstractmethod
    def number_of_edges(self):
        pass

class Triangle(Shape):
    pass

Triangle('t3')
class Triangle(Shape):
    def number_of_edges(self):
        return 3

Triangle('t3')

rawDescription: Python base class that makes abstract methods definition mandatory at instantiation


code:
import zlib

# FILL IN: ZHEAD is two bytes with the actual ZLIB settings in the input
ZHEAD = CMF+FLG

def findstart(header, buf, source):
    """Find `header` in str `buf`, reading more from `source` if necessary"""

    while buf.find(header) == -1:
        more = source.read(2**12)
        if len(more) == 0:  # EOF without finding the header
            return ''
        buf += more

    offset = buf.find(header)
    return buf[offset:]

rawDescription: Python and zlib: Terribly slow decompressing concatenated streams


code:
def appstruct(self):
    """ Returns the appstruct model for use with deform. """

    appstruct = {}
    for k in sorted(self.__dict__):
        if k[:4] == "_sa_":
            continue

        appstruct[k] = self.__dict__[k]

    # Special case for the categories
    appstruct['categories'] = set([str(c.id) for c in self.categories])

    return appstruct

rawDescription: Working with Many to Many Relationships in Deform/Colander HTML Select Field


code:
ind = [slice(None)]*4
ind[2] = 3
myarray(tuple(ind))
# same as myarray[:,:,3,:]
# myarray.take(3, axis=2)

rawDescription: Indexing ndarray of variable number of dimensions


rawDescription: Getting indices of both zero and nonzero elements in array


code:
L = list(range(1, 1000000))
random.shuffle(L)  # shuffles in-place

rawDescription: Unordered list generation in python

description: Unordered list generation in python


rawDescription: Cumulative addition whilst looping over a list


code:
def build_tree(l):
    exists = set(map(lambda x : x['id'], l))

    tops = []
    children = {}
    for e in l:
        parent = e['parent']
        if not parent:
            tops.append(e)
            continue

        parent = int(parent[1:])
        if parent not in exists:
            tops.append(e)
            continue

        if parent in children:
            children[parent].append(e)
        else:
            children[parent] = [ e ]

    return children, tops

rawDescription: Building a list with a parent-child dependency


code:
from logging import FileHandler
import logging

def setup_logger(name):
    logger = logging.getLogger(name)
    handler = FileHandler('%s.log' % name)
    logger.addHandler(handler)
    return logger

rawDescription: How to structure the Logging in this case (python)

description: Structure the Logging in this case (python)


code:
query_string = query_array[1:-1] #remove the parentheses with slicing
queries_with_whitespace = query_string.split(",") #split the string into a list
queries = [query.strip() for query in queries_with_whitespace] #remove whitespace
# queries = [item.strip() for item in query_array[1:-1].split(",")] #all in one

rawDescription: arrays using python

description: Arrays using python


code:
parser.add_argument('--carpark',
                    dest='carpark_ids',
                    type=int,
                    action='append',
                    default=[],
                    help="One carpark ID (can be used multiple times)"
)

rawDescription: Argparse nargs="+" is eating positional argument


code:
import pandas as pd
import numpy as np
df = pd.DataFrame({'Fare': np.random.uniform(0, 600, 400),
                   'Survived': np.random.randint(0, 2, 400)})

rawDescription: Dividing Histograms in Pandas

description: Dividing Histograms in Pandas


code:
g = np.meshgrid(poro_g, sw_g)
g_arr = np.array(g)
g_arr = g_arr.swapaxes(0,1).swapaxes(1,2)

#I compute z value on the grid, `g_arr`
hcpv = np.array([[cpt_hcpv(p, s, poro, sw) for p,s in r] for r in g_arr])

rawDescription: Python heatmap from 3d coordinates

description: Python heatmap from 3d coordinates


code: [x for x, freq in dic.most_common(3)]

rawDescription: Selecting items in a dictionary using python


code:
sets = [
    [["a", 1], ["b", 5], ["c", 9]],
    [["c", 3], ["d", 1], ["e", 5]]
]
pairs = {}
for set in sets:
    processed_pairs = []
    for first in set:
        for second in set:
            if first[0] is second[0]:
                continue

            pair = first[0]+second[0]
            if pair in processed_pairs:
                continue
            processed_pairs.append(pair)
            if second[0] not in pairs:
                pairs[second[0]] = {}
            if first[0] not in pairs[second[0]]:
                pairs[second[0]][first[0]] = {}
            pairs[second[0]][first[0]] = second[1]/first[1]
pairs

rawDescription: Ordering items with known pair distances


code:
p = ggplot2.ggplot(mydata) + \
    ggplot2.scale_x_continuous(parse('paste(alpha, " and ", beta)'))

rawDescription: Plotting greek letters and plain text in ggplot2 graphs via Rpy2


code:
df.index = new_index
df
df.head()

rawDescription: How to change a groupby DF to a monthly datetime series in Python Pandas

description: Change a groupby DF to a monthly datetime series in Python Pandas


rawDescription: Best Pythonic way to replace any non-A-Z, non numbers, with a dash


code:
def gen_days_inclusive(start_date, end_date):
    delta_days = (end_date - start_date).days
    for day in xrange(delta_days + 1):
        yield start_date + datetime.timedelta(day)

rawDescription: python, datetime.date: difference between two days

description: Python, datetime.date: difference between two days


code:
output = False
def handler():
    nonlocal output
    output = True

button.pressed.connect(handler)

rawDescription: One-liner to set a variable value with signal handler function in response to a signal from GUI?


code:
for e in comb:
     if sum(sugar for name, sugar in e) == max_sugar:
         print([name for name, sugar in e])

rawDescription: How to select only integers in a list of strings/integers?

description: Select only integers in a list of strings/integers


code:
class Sample(object):
  _count = 0

  def __init__(self):
    Sample._count += 1

  @property
  def count(self):
    return Sample._count

rawDescription: What's the equivalent of Ruby's class @@variable in Python?


code:
def crc32_combine(crc1, crc2, len2):
    """Explanation algorithm: http://stackoverflow.com/a/23126768/654160
    crc32(crc32(0, seq1, len1), seq2, len2) == crc32_combine(
        crc32(0, seq1, len1), crc32(0, seq2, len2), len2)"""
    # degenerate case (also disallow negative lengths)
    if len2 <= 0:
        return crc1

    # put operator for one zero bit in odd
    # CRC-32 polynomial, 1, 2, 4, 8, ..., 1073741824
    odd = [0xedb88320] + [1 << i for i in range(0, 31)]
    even = [0] * 32

    def matrix_times(matrix, vector):
        number_sum = 0
        matrix_index = 0
        while vector != 0:
            if vector & 1:
                number_sum ^= matrix[matrix_index]
            vector = vector >> 1 & 0x7FFFFFFF
            matrix_index += 1
        return number_sum

    # put operator for two zero bits in even - gf2_matrix_square(even, odd)
    even[:] = [matrix_times(odd, odd[n]) for n in range(0, 32)]

    # put operator for four zero bits in odd
    odd[:] = [matrix_times(even, even[n]) for n in range(0, 32)]

    # apply len2 zeros to crc1 (first square will put the operator for one
    # zero byte, eight zero bits, in even)
    while len2 != 0:
        # apply zeros operator for this bit of len2
        even[:] = [matrix_times(odd, odd[n]) for n in range(0, 32)]
        if len2 & 1:
            crc1 = matrix_times(even, crc1)
        len2 >>= 1

        # if no more bits set, then done
        if len2 == 0:
            break

        # another iteration of the loop with odd and even swapped
        odd[:] = [matrix_times(even, even[n]) for n in range(0, 32)]
        if len2 & 1:
            crc1 = matrix_times(odd, crc1)
        len2 >>= 1

        # if no more bits set, then done
    # return combined crc
    crc1 ^= crc2
    return crc1

rawDescription: Using zlib crc32_combine in Python

description: Using zlib crc32_combine in Python


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

x = np.random.random(18)
y = np.random.random(18)

def simData():
    """updates the points position on your lattice.
    replace with your own code - can call a helper function to accomplish this task
    """
    x = np.random.random(18)
    y = np.random.random(18)
    yield x, y

def simPoints(simData):
    """initializes the points position on your lattice.
    replace with your own code - can call a helper function to accomplish this task
    """
    x = np.random.random(18)
    y = np.random.random(18)
    line.set_data(x, y)
    return line,

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

line, = ax.plot(x, y,'bo', ms=8)

ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=200)

plt.show()

rawDescription: Python multi-body animation does not work


code:
import warnings

def hello(s):
    if isinstance(s, int):
        deprecation('Use of integers is deprecated.')
    else:
        print(s)

def deprecation(msg):
    warnings.warn(msg, DeprecationWarning, stacklevel=3)

hello(1)

rawDescription: How to print the calling method name and line number for Deprecation Warning message in python?

description: Print the calling method name and line number for Deprecation Warning message in python


code:
stockList1 = getTID('TID_1.cvs')
stockList2 = getTID('TID_2.cvs')

rawDescription: Python 3.5, how to remove the brackets and quotes from an element when printing or sending the value to a function?


code: my_dict = defaultdict(lambda:([], [], []))

rawDescription: Add multiple values to python dictionary


rawDescription: Correct usage of scipy.interpolate.RegularGridInterpolator


code: mydict.setdefault(obj.value, obj)

rawDescription: Is there a comparison key for set objects?


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

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

x1 = [1,2,3,4,5,6,7,8]
y1 = [20,100,50,120,55,240,50,25]
x2 = [3,4,5,6,7,8,9]
y2 = [25,35,14,67,88,44,120]

ax.plot(x1, y1, color='lightblue',linewidth=3)
ax.plot(x2, y2, color='darkgreen', marker='^')

# Get the common range, from `max(x1[0], x2[0])` to `min(x1[-1], x2[-1])`
x_begin = max(x1[0], x2[0])     # 3
x_end = min(x1[-1], x2[-1])     # 8

points1 = [t for t in zip(x1, y1) if x_begin<=t[0]<=x_end]  # [(3, 50), (4, 120), (5, 55), (6, 240), (7, 50), (8, 25)]
points2 = [t for t in zip(x2, y2) if x_begin<=t[0]<=x_end]  # [(3, 25), (4, 35), (5, 14), (6, 67), (7, 88), (8, 44)]

idx = 0
nrof_points = len(points1)
while idx < nrof_points-1:
    # Iterate over two line segments
    y_min = min(points1[idx][1], points1[idx+1][1])
    y_max = max(points1[idx+1][1], points2[idx+1][1])

    x3 = np.linspace(points1[idx][0], points1[idx+1][0], 1000)      # e.g., (6, 7) intersection range
    y1_new = np.linspace(points1[idx][1], points1[idx+1][1], 1000)  # e.g., (6, 7) corresponding to (240, 50) in y1
    y2_new = np.linspace(points2[idx][1], points2[idx+1][1], 1000)  # e.g., (6, 7) corresponding to (67, 88) in y2

    tmp_idx = np.argwhere(np.isclose(y1_new, y2_new, atol=0.1)).reshape(-1)
    if tmp_idx:
        ax.plot(x3[tmp_idx], y2_new[tmp_idx], 'ro')                 # Plot the cross point

    idx += 1

plt.show()

rawDescription: Finding the point of intersection of two line graphs drawn in matplotlib


code:
# settings.py
SUB_SITE = "/test/"

rawDescription: Default redirect url in Django

description: Default redirect url in Django


code: '1 repeats 1, 0 repeats 3, 1 repeats 2, 0 repeats 1, 1 repeats 1, and 0 repeats 1'

rawDescription: Count consecutive characters

description: Count consecutive characters


rawDescription: How to do an inverse `range`, i.e. create a compact range based on a set of numbers?

description: Do an inverse `range`, i.e. create a compact range based on a set of numbers


code: helloworld = Blueprint('helloworld', __name__, static_folder='static')

rawDescription: custom location for templates and static resources in flask

description: Custom location for templates and static resources in flask


code:
def init_window(self):
    self.master.title("Player")
    root.geometry("850x550")
    self.pack(fill="both", expand=1)

    self.healthAdd = tk.Button(self, text="+", font= 13, fg='white', bg='#000080',
                               width = 2,
                               command=lambda: self.update("addHealth"))
    self.healthSub = tk.Button(self, text="--", font=13, fg='white', bg='red',
                               width = 2,
                               command=lambda: self.update("subHealth"))
    self.HealthTotal = tk.Label(self, text="Health: {}".format(self.health),
                                font=15, fg='#01ffff', bg='black', width=16)
    self.healthAdd.config(height = 0)
    self.HealthTotal.grid(row=1, column=0, columnspan=3)
    self.healthAdd.grid(row=1, column=10, padx=6)
    self.healthSub.grid(row=1, column=20)

def update_window(self):
    self.HealthTotal.configure(text="Health: {}".format(self.health))

rawDescription: How to place buttons in a very specific place?

description: Place buttons in a very specific place


code:
class MeasurementList:

  def __init__(self, measurement_list):
    self._measurements = measurement_list

  # readonly
  @property
  def measurements(self):
    return self._measurements

  # computed property
  @property
  def count(self):
    return len(self.measurements)

  def foo(self):
    print("there are %d measurements" % (self.count))

  def bar(self):
    print(self.measurements)

rawDescription: Refer to a property from inside the class itself


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'foo':['100-200','1000-1100','1100-1200','200-300']*100})

arr = df['foo'].map(lambda item: map(int, item.split('-'))).values
order = np.argsort(arr)
df = df.take(order)

rawDescription: Numbers with hyphens or strings of numbers with hyphens


code:
leg = plt.legend()
if leg:
    leg.draggable()

rawDescription: How to create a draggable legend in matplotlib?

description: Create a draggable legend in matplotlib


rawDescription: Dictionaries in Python

description: Dictionaries in Python


code:
arr_s = np.sort(arr, order='b')
arr_s
dtype=[('a',np.int64),('b',np.int64),('c', np.int64)]
arr = np.array([(5,2,3),(3,4,1)], dtype=dtype)
arr
arr_s = np.sort(arr, order='a')
arr_s
arr_s = np.sort(arr, order='b')
arr_s
arr_s = np.sort(arr, order='c')
arr_s

rawDescription: why setting dtype on numpy array changes dimensions?

description: Why setting dtype on numpy array changes dimensions


code:
@csrf_exempt
def emulate_create(request):
    args = json.loads(
        request.body,
        object_hook=utils._datetime_decoder
    )
    resourceId, count, hours = args['resourceId'], args['count'], args['hours']

    timeFrom, timeTo = time_encode(hours)

    reservation = ReservationProspect(
        byUser=request.user,
        forUser=request.user,
        resource=get_object_or_404(Resource, uuid=resourceId),
        modality=get_object_or_404(Modality, name="online"),
        timeFrom=timeFrom,
        timeTo=timeTo,
        count=count
     )

    return HttpResponse(
        json.dumps(
            [reservation.toDict()],
            default=utils._datetime_encoder
        )
    )

rawDescription: Refactoring/cleaningup time function in django view


code: df2.index = np.searchsorted(df1.ATime.values, df2.loc[:, 'Absolute Time'].values)

rawDescription: Python Pandas dataframe

description: Python Pandas dataframe


code:
for i in range(len(list1)):
    list4.append(list1[i])
    list4.append(list2[i])

rawDescription: Adding elements to a list in Python 3.3 by extracting consecutive elements from two other lists


code:
def write(self, pdf, x1=0, y1=0, x2=0, y2=0, text='', font="arial", size=1,
          bold=False, italic=False, underline=False, align="", link='http://example.com',
         foreground=0, *args, **kwargs):
    if pdf.text_color!=rgb(foreground):
        pdf.set_text_color(*rgb(foreground))
    font = font.strip().lower()
    if font == 'arial black':
        font = 'arial'
    style = ""
    for tag in 'B', 'I', 'U':
        if (text.startswith("<%s>" % tag) and text.endswith("</%s>" %tag)):
            text = text[3:-4]
            style += tag
    if bold: style += "B"
    if italic: style += "I"
    if underline: style += "U"
    align = {'L':'L','R':'R','I':'L','D':'R','C':'C','':''}.get(align) # D/I in spanish
    pdf.set_font(font,style,size)
    ##m_k = 72 / 2.54
    ##h = (size/m_k)
    pdf.set_xy(x1,y1)
    pdf.write(5,text,link)

rawDescription: PyFPDF create link in template

description: PyFPDF create link in template


code:
import os

def find_file(target, folder):
    for f in os.listdir(folder):
        path = os.path.join(folder, f)
        if os.path.isdir(path):
            result = find_file(target, path)
            if result is not None:
                return result
            continue
        if f == target:
            return path

rawDescription: Search all drives for a file

description: Search all drives for a file


code: ax = plt.gca()

rawDescription: How to get a matplotlib Axes instance to plot to?

description: Get a matplotlib Axes instance to plot to


code:
file = 'foo'
for line in file:
    print(line)

rawDescription: Python: Parse file for a string and return value as variable


code:
class Booking(models.Model):
    customer = models.ForeignKey(Customer, related_name='bookings')
    # other fields

rawDescription: Displaying multiple objects in a DetailView


code:
addText(map,21,34,"%.9f" % total_dist)
repaint(map)

rawDescription: combining distance between pixels during while loop

description: Combining distance between pixels during while loop


rawDescription: Remove Keys in Dictionary and Store Values in a Dictionary of Lists


code:
import numpy as np
a = np.empty((15,))
a[::2] = 1
a[1::2] = -1

rawDescription: How can I get an array of alternating values in python?

description: Get an array of alternating values in python


code:
keys = set(yourdict.keys())
[elem for col in zip(*yourdict.values()) for elem in (keys, set(col))]

rawDescription: accessing individual elements from a python dictionary

description: Accessing individual elements from a python dictionary


code:
with open('file_with_multiple_xmldocuments') as fileobj:
    for xml in xml_documents(fileobj):
        tree = ElementTree.fromstring(xml)

rawDescription: Parsing large combined XML document with Python


code:
def storescores():
    if linecache.getline("hst.txt", 10):
        print("Already stored 10 scores, sorry")
        return
    hs.close()
    hs = open("hst.txt", "a")
    hs.write(name + " ")
    hs.write(str(score) + "\n")
    hs.close()

rawDescription: Maximum pieces of data appending to a file


rawDescription: Python Numpy Loadtxt - Convert unix timestamp


code:
from scipy import stats
f_value, p_value = stats.f_oneway(data1, data2, data3, data4, ...)

rawDescription: What statistics module for python supports one way ANOVA with post hoc tests (Tukey, Scheffe or other)?


rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


code:
[ob for ob in CPIobvs['observations']['observation'] if
    ob['realtime_start'] <= aDate]

rawDescription: Find dictionary with greatest date less than or equal to variable, return value


code:
buff = """
functionOne("I want this text", iDontWantThis);
functionTwo("I also want this text");"""
re.findall("(?:functionOne|functionTwo)\(.*?\"(.*?)\".*?\)",buff)

rawDescription: How do I find the contents of two functions with regex in python?

description: Find the contents of two functions with regex in python


code:
# this code assumes Python 2.7
from itertools import groupby, izip
from operator import attrgetter

INPUT    = "file.txt"
HOMO_YES = "homologs.txt"
HOMO_NO  = "nonhomologs.txt"
MAX_DIFF = 5

class Row:
    __slots__ = ["line", "con", "protein", "start", "end"]

    def __init__(self, s):
        self.line    = s.rstrip()
        data         = s.split()
        self.con     = data[0]
        self.protein = data[1]
        self.start   = int(data[2])
        self.end     = int(data[3])

    def __str__(self):
        return self.line

def count_homologs(items, max_diff=MAX_DIFF):
    num_items  = len(items)
    counts     = [0] * num_items
    # first item
    for i, item_i in enumerate(items):
        max_start = item_i.start + max_diff
        max_end   = item_i.end   + max_diff
        # second item
        for j in xrange(i+1, num_items):
            item_j = items[j]
            if item_j.start > max_start:
                break
            elif item_j.end <= max_end:
                counts[i] += 1
                counts[j] += 1
    return counts

def main():
    with open(INPUT) as inf, open(HOMO_YES, "w") as outhomo, open(HOMO_NO, "w") as outnothomo:
        # skip header
        next(inf, '')
        rows = (Row(line) for line in inf)

        for con, item_iter in groupby(rows, key=attrgetter("con")):
            # per-con list of Rows sorted by start,end
            items = sorted(item_iter, key=attrgetter("start", "end"))
            # get #homologs for each item
            counts = count_homologs(items)
            # do output
            for c,item in izip(counts, items):
                if c:
                    outhomo.write(str(item) + "\n")
                else:
                    outnothomo.write(str(item) + "\n")

if __name__=="__main__":
    main()

rawDescription: Removing redundancies in a loop using python


code: [X,y] = read_images("/path/to/some/folder", (100,100))

rawDescription: Face recognition in OpenCV Python FAR/FRR


code: thread.setdaemon = True

rawDescription: SimpleHTTPServer launched as a thread: does not daemonize


rawDescription: How to initialize NumPy structured array with different default value for each column?

description: Initialize NumPy structured array with different default value for each column


code:
my_array
dt = np.dtype((np.void, my_array.dtype.itemsize * my_array.shape[1]))
b = np.ascontiguousarray(my_array).view(dt)
unq, cnt = np.unique(b, return_counts=True)
unq = unq.view(my_array.dtype).reshape(-1, my_array.shape[1])
unq
cnt

rawDescription: Count how many times each row is present in numpy.array


code:
import signal
def SigIntHand(SIG, FRM):
    print("Please Right click-copy. Ctrl-C does not work on the cmd prompt")

signal.signal(signal.SIGINT, SigIntHand)

rawDescription: How to prevent termination of a running program using "ctrl+c" in Linux using python?

description: Prevent termination of a running program using "ctrl+c" in Linux using python


rawDescription: Pandas return index and column name based on the item value


code:
SAMPLE
SAMPLE
AB

rawDescription: Search and replace string under specific line


rawDescription: Django virtual host setup. Apache mod_wsgi


rawDescription: Export Python interpreter history to a file?


code:
from itertools import groupby

lst = [list(v) for k,v in groupby(l, key=bool) if k]

rawDescription: python: break list into pieces when an empty entry is found

description: Python: break list into pieces when an empty entry is found


code: dict(map(getter, lst))

rawDescription: Pythonic way to make a key/value pair a dictionary


code:
import csv

with open('Class1.txt') as fd:
    s = {row[0]:[int(n) for n in row[1:]] for row in csv.reader(fd, delimiter=',')}

def average():
    avg_mark = lambda name : sum(s[name])/len(s[name])
    for name in sorted(s, key=avg_mark, reverse=True):
        print(name, avg_mark(name))  # newline prints automatically

rawDescription: Sorting some code and i need to shorten it


code:
@property
def upvote(self):
    answer = 0
    for vote in self.vote_set.all ():
        if vote.vote_type:
            answer += 1
    return answer

@property
def downvote(self):
    answer = 0
    for vote in self.vote_set.all ():
        if not vote.vote_type:
            answer += 1
    return answer

rawDescription: optimizing no. of queries being fired in django orm for a given model

description: Optimizing no. of queries being fired in django orm for a given model


rawDescription: Save table to different Excel sheets using python


code:
import psutil
pid = 1034  # some pid
psutil.pid_exists(pid)

rawDescription: Python library for Linux process management


code: list_dict = { t[0] : t for t in tuple_list }

rawDescription: Python: using a dict to speed sorting of a list of tuples


rawDescription: NumPy: Execute function over each ndarray element


code:
from bs4 import BeautifulSoup
collection = BeautifulSoup(open("foo.xml").read(),"html.parser")
e1 = collection.find('doc').find_all('a')
e2 = collection.find_all('doc')[1].find_all('a')
(len(e1))
(len(e2))
(len(collection.find_all("a")))
(len(collection.find('doc').text))
(len(collection.find_all('doc')[1].text))
(len(collection.text))

rawDescription: BeautifulSoup first element incorrect

description: BeautifulSoup first element incorrect


code:
@app.route("/category/<int:category_1_id>/<int:category_2_id>/", methods=["POST"])
def get_request(category_1_id,category_2_id):
    data = [(x) for x in enumerate(extra,1)
        if x[0] != category_1_id and x[0] != category_2_id]
    response = make_response(json.dumps(data))
    response.content_type = 'application/json'
    return response

rawDescription: Dynamically populate multiple (more than one) dropdown choices/options (Flask, python, Ajax)


code:
def InputName():
    name = input("Name: ")
    return name

def InputCourseName():
    courseName = input("Course: ")
    return courseName

rawDescription: function set value for another function

description: Function set value for another function


code:
sandwich= ["BLTsandwich_bread_bacon_lettuce_tomato_bread",
"BREADsandwich_bread_bread_bread",
"HAMsandwich_bread_ham_bread"]

to_replace = ["bacon"]

def NoBacon(sandwich):
    replacements_made = []
    for line in sandwich:
        for word in to_replace:
            words_replaced = []
            if word in line:
                words_replaced.append(word)
                line = line.replace(word, "")
        replacements_made.append((words_replaced, line))
    return replacements_made

print (NoBacon(sandwich))

rawDescription: Needs to remove word from string and display both the removed word + remaining string, possible tuple?


code:
import copy
def format_serialized(query, counter, lst):
    counter = counter or 0
    ex = expression_tuple(query)
    if ex:
        lst.append(copy.copy(ex)) # you need to copy the list since it is mutable
    conditions = query.get("conditions")
    if conditions:
        for i in query.get("conditions"):
            if ex:
                lst.append(aggregatorConvert(query.get("aggregator")))
            format_serialized(query.get("conditions")[i], counter + 1, lst)
    return lst

rawDescription: Converting dict to list

description: Converting dict to list


rawDescription: Elegant data processing in Python

description: Elegant data processing in Python


code:
s = '\n'.join(
    '\t'.join(
        str(v1[b] / v2[b])
        for b in boxes
    )
    for v1, v2 in zip(video[0::2], video[1::2])
)
print(s)

rawDescription: Within a nested for loop, how can I print tab and carriage return delimited groups of data?


code: list(tails(data))

rawDescription: Extract parent and child node from python tree representation


code: {key: value for key, value in [string.split(': ')]}

rawDescription: Convert string from external file to Python dictionary


code:
from itertools import tee

with open("SFU.txt") as inf:
    # set up iterators
    cfg,res = tee(inf)
    # advance cfg by four lines
    for i in range(4):
        next(cfg)

    for c,r in zip(cfg, res):
        if "configuration" in c:
            print(r)

rawDescription: print a previous line based on a condition in python

description: Print a previous line based on a condition in python


code:
class heap(list):
    def __init__(self,xs):
        super(heap,self).__init__(xs)
        self._index_table = {x:i for i,x in enumerate(self)}

    def __setitem__(self,i,v):
        print("SETITEM")
        print(i,v)
        super(heap,self).__setitem__(i,v)
        self._index_table[v] = i

    def append(self,x):
        print("APPEND")
        super(heap,self).append(x)
        self._index_table[x] = len(self)-1

h = heap([4,3,2,1])
heapify(h)
h
h._index_table
heappush(h,42)
h
h._index_table

rawDescription: Intercepting heapq

description: Intercepting heapq


code:
d = dict()

for i in xrange(100):
    key = i % 10
    if key in d:
        d[key] += 1
    else:
        d[key] = 1

rawDescription: Check if a given key already exists in a dictionary


code:
class ClassAndInstanceProperty(object):
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            obj = objtype
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

rawDescription: Python descriptor returning itself not value when called from class


code: self.dissect('python   language           opensource')

rawDescription: Dissecting a string with python regex, using named groups and substitution


code:
import os
os.system('say "your program has finished"')

rawDescription: Python: Sound alarm when code finishes

description: Python: Sound alarm when code finishes


code: itertools.chain([a], other_list)

rawDescription: What is the right way to create a list from variable and another list?


code:
def home():
    return 'home'

home = app.route('/')(home)

rawDescription: How to centralise routing in Flask using a single file instead of decorators?

description: Centralise routing in Flask using a single file instead of decorators


code:
myFile = open("/tmp/testfile", "w")
myFile.write(long_string)
myFile.close()

rawDescription: Python equivalent for write in file like in shell


rawDescription: Get the full substring matching the regex pattern


code:
from lxml.etree import fromstring, Element, tostring

data = """
<seg id="1" text="some text"/>
"""
element = fromstring(data)

tag_name = 'in_' + element.tag
tag_id = 'sent' + element.attrib['id']
tag_text = element.attrib['text']

new_element = Element(tag_name, attrib={'id': tag_id})
new_element.text = tag_text
print(tostring(new_element))

rawDescription: parsing and reformatting elements in Python3

description: Parsing and reformatting elements in Python3


code:
import time
time.gmtime()
x = time.gmtime()
x.tm_year
x.tm_mon
x.tm_mday
x.tm_hour

rawDescription: Import Error: No module named pytz after using easy_install


code: range(N, -1, -1) is better

rawDescription: Python - getting list of numbers N to 0

description: Python - getting list of numbers N to 0


code:
result = root.xpath("//tag/*[starts-with(local-name(), 'TEXT')]")
assert(' '.join(e.text for e in result) == 'one two three')

rawDescription: lxml find tags by regex

description: Lxml find tags by regex


code:
if __name__ == '__main__':
    seed1 = '123'
    seed2 = 'asd'
    rows, cols = 100, 3
    mu, sd = 0, 1

    # This will create a new RNG, take 1 result and throw the RNG away
    r1 = next(reikna_norm_rng(seed1, rows, cols, mu, sd))
    r2 = next(reikna_norm_rng(seed2, rows, cols, mu, sd))
    r3 = next(reikna_norm_rng(seed1, rows, cols, mu, sd))
    r4 = next(reikna_norm_rng(seed2, rows, cols, mu, sd))

    err1 = r1 - r3
    err2 = r2 - r4

    print("all(err1 == 0):", np.all(err1 == 0))
    print("all(err2 == 0):", np.all(err2 == 0))

rawDescription: Regenerate vector of randoms in Python

description: Regenerate vector of randoms in Python


rawDescription: pandas dataframe groupby summation

description: Pandas dataframe groupby summation


code:
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
indices = numpy.random.permutation(x.shape[0])
training_idx, test_idx = indices[:80], indices[80:]
training, test = x[training_idx,:], x[test_idx,:]

rawDescription: Numpy: How to split/partition a dataset (array) into training and test datasets for, e.g., cross validation?


code:
def get_leaf_nodes(self):
    leafs = []
    self._collect_leaf_nodes(self.root,leafs)
    return leafs

def _collect_leaf_nodes(self, node, leafs):
    if node is not None:
        if len(node.children) == 0:
            leafs.append(node)
        for n in node.children:
            self._collect_leaf_nodes(n, leafs)

rawDescription: How to get leaf nodes of a tree using Python?

description: Get leaf nodes of a tree using Python


rawDescription: Executing code through python eval

description: Executing code through python eval


code: write_file("outputfile.txt", out_text)

rawDescription: parse blocks of text from text file using Python

description: Parse blocks of text from text file using Python


rawDescription: How to dynamically add keys and values in python

description: Dynamically add keys and values in python


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

rawDescription: isinstance check if any of the variables has a certain class

description: Isinstance check if any of the variables has a certain class


code: photo_image = PhotoImage(file=filename)

rawDescription: Tkinter create_image not displaying

description: Tkinter create_image not displaying


rawDescription: Django:how to concatenate the seperated integer field (Year, month) as date range to filter the database


code:
first = [x for x in range(999) if x % 2 == 0]
second = [x for x in range(999) if x % 4 == 0]

values = first + second

def str_method(values):
    distinct_string = ""
    for i in values:
        if not str(i) in distinct_string:
            distinct_string += str(i) + " "
    return [int(s) for s in distinct_string.split()]

def list_method(values):
    distinct_list = []
    for i in values:
        if not i in distinct_list:
            distinct_list.append(i)
    return distinct_list

def set_method(values):
    seen = set()
    return [val for val in values if val not in seen and seen.add(val) is None]

if __name__ == '__main__':
    assert str_method(values) == list_method(values) == set_method(values)
    import timeit
    funcs = [func.__name__ for func in (str_method, list_method, set_method)]
    setup = 'from __main__ import {}, values'.format(', '.join(funcs))
    for func in funcs:
        print(func)
        print(timeit.timeit(
            '{}(values)'.format(func),
            setup=setup,
            number=1000
        ))

rawDescription: Concatenating strings faster than appending to lists


code:
class MustacheRendererFactory(object):
  def __init__(self, info):
    self.info = info

  def __call__(self, value, system):
    package, filename = resolve_asset_spec(self.info.name)
    template = os.path.join(package_path(self.info.package), filename)
    template_fh = open(template)
    template_stream = template_fh.read()
    template_fh.close()
    return pystache.render(template_stream, value)

rawDescription: How to integrate pystache with pyramid?

description: Integrate pystache with pyramid


code:
df_daily = df.groupby('meternumber')['daily_consumption'].resample(
                                        '1d',fill_method='bfill').reset_index()

rawDescription: Impute daily values based on erratic monthly data measures in Python / Pandas


code:
def f(x, a={"value":0}):
    a["value"] += 1
    #Do other stuff

rawDescription: change value of parameters of a function within the function python

description: Change value of parameters of a function within the function python


code:
def bar(a, g):
    print(a)
    print(g)

rawDescription: Python - Database query function with non-consistent arguments


code:
summary = pd.DataFrame()
summary['mean'] = df2.groupby('type').mean()['value']
summary['min'] = df2.groupby('type').min()['value']
summary['max'] = df2.groupby('type').max()['value']

rawDescription: how to apply different functions to each group of pandas groupby?

description: Apply different functions to each group of pandas groupby


code: open(URL,data)

rawDescription: Python - POSTing with a urllib2 opener

description: Python - POSTing with a urllib2 opener


code:
re.findall(r'[a-z]+', 'HELLO world')         # No flag
re.findall(r'(?i)[a-z]+', 'HELLO world')     # With ignore case flag

rawDescription: What does (?ui) mean in a Python regex?

description: What does (?ui) mean in a Python regex


code:
#while j <= len(array):
for i in array:
    new_program += program[:i] #(program[:array[j]])

rawDescription: index out of range even after initialization of var serving as index

description: Index out of range even after initialization of var serving as index


code:
num=raw_input ("enter the numbers : ")
l=[int(i) for i in num]
l

rawDescription: Python parsing, convert string to list of integers


code:
outerdict = defaultdict(lambda: defaultdict(list))
with open(filename) as infh:
    for line in infh:
        name, _, type_, values = line.split(None, 3)
        outerdict[name][type_].extend(map(int, values.split()))

rawDescription: Python idiom for creating dict of dict of list


code:
f = Foo()
f.barfunc(10)
f.barbar()

rawDescription: python class methods: parameter as class variables pros and cons

description: Python class methods: parameter as class variables pros and cons


code:
print("Lotto number",index,"is",lotto[index],"!")
index = index + 1

rawDescription: Sequence elements will not modify (Python 3.4)


code:
I
J
res1

rawDescription: How can I create a sparse matrix instead of a dense one in this program?

description: Create a sparse matrix instead of a dense one in this program


code:
indx=[i for i,j in enumerate(a) if j==0]+[len(a)]
indx
zip(indx,indx[1:])

rawDescription: indexing one array and doing operation on another

description: Indexing one array and doing operation on another


rawDescription: Use of lambda in the following expression


code:
#!/usr/bin/python3.5

import random
with open('file1', 'w') as f1, open('file2', 'w') as f2:
    for _ in range(10):
        f1.write('{},{},{},{},track-{}\n'.format(*[random.randrange(5) for x in range(5)]))
        f2.write('stage-{},{},{},{},{}\n'.format(*[random.randrange(5) for x in range(5)]))

rawDescription: Fast process each line of one file for each line in another file


code: np.concatenate([v for k,v in sorted(store.items(), key=...)], 1)

rawDescription: Python: concatenate arrays stored in a dictionary


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

data = np.array([[0,1,1,1], [1,0,0,1], [1,1,1,0], [0,0,0,1]])

# get the indices where data is 1
x,y = np.argwhere(data == 1).T

plt.scatter(x,y)
plt.show()

rawDescription: Scatter a 2D numpy array in matplotlib

description: Scatter a 2D numpy array in matplotlib


code:
class BlogPost(Document):
    tags = ListField(StringField())
    # other things

rawDescription: How to prepend an element to a list in Mongoengine

description: Prepend an element to a list in Mongoengine


code:
PlayerID,Partner
1038005,EXT
254034,EXT

rawDescription: Download "csv-like" text data file and convert it to CSV in python


code: canvas.create_rectangle(x0, y0, x1, y1)

rawDescription: How do I selectively delete drawings in Tkinter?

description: Selectively delete drawings in Tkinter


code:
import ipaddress
ip_addr = ipaddress.ip_address("2001:db8::1")
_reverse_pointer(ip_addr)

rawDescription: python ipaddress()reverse_pointer equivalent for 3.4

description: Python ipaddress()reverse_pointer equivalent for 3.4


rawDescription: Pyglet not running properly on AMD HD4250


code:
import operator

def sumproduct(*lists):
    return sum(reduce(operator.mul, data) for data in zip(*lists))

rawDescription: sum of products for multiple lists in python

description: Sum of products for multiple lists in python


code:
import threading
def your_sniff_function():
    connreq = sniff(filter=connfilter, prn=handshake)
    # save sniff result to local file here

t = threading.Thread(target=your_sniff_function, args=[])
t.start()
t.join(timeout=4) # use timeout here to force termination
# you can start as many subthreads as you want here

rawDescription: Send a new packet without waiting for the previous packet reply


rawDescription: Working with the Python graphics module: is there any way to save the current window as an image?


code:
import pandas as pd

d = {pd.Timestamp('2015-01-02'):{'days_delinquent':11}, pd.Timestamp('2015-01-15'):{'days_delinquent':23}}
df = pd.DataFrame.from_dict(d,orient='index')
df['returned_on'] = df.index + df.days_delinquent.astype('timedelta64[D]')

rawDescription: Adding days to column in pandas using separate column integers


Earth

plants: yes

animals: yes

cryptonite: no

rawDescription: Howto Format dict string outputs nicely

description: Howto Format dict string outputs nicely


code: last_list = [tuple(y.replace('/', '@') for y in x) for x in Long_list]

rawDescription: Convert a list of lists back into a list of tuples


rawDescription: numerical operation on two numpy ndarrays

description: Numerical operation on two numpy ndarrays


rawDescription: How do I get values from a dictionary run them through an equation and return the key with the greatest value

description: Get values from a dictionary run them through an equation and return the key with the greatest value


code: next(iter(setobj), None)

rawDescription: How to get item in set

description: Get item in set


code:
def rep_sum(c, *L):
  d = Counter(L)
  return sum(k for k in d if d[k]==c)

rawDescription: Python sum of non duplicate int

description: Python sum of non duplicate int


code:
import numpy
numpy.subtract((10, 10), (4, 4))

rawDescription: Elegant way to perform tuple arithmetic

description: Elegant way to perform tuple arithmetic


code:
import numpy as np
import tstI # loads module
y = tstI.view_x() # get memory view
y[:10]
y[:10] = np.zeros(10)
tstI.print_x() # dump memory contents

rawDescription: python memap or pybuffer for large image processing

description: Python memap or pybuffer for large image processing


code:
from collections import Counter
li= [11, 11, 2, 3, 4]
[k for k, v in Counter(li).iteritems() if v == 1]

rawDescription: Removing repeated element from a list

description: Removing repeated element from a list


code: rollAgain = "Yes" or "yes" or "y"

rawDescription: Dice game query While loop

description: Dice game query While loop


rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


code:
from C.E.m1 import my_func1
from C.F.m2 import my_func2

my_func1()
my_func2()

rawDescription: Importing Modules from Multiple Parallel Subdirectories (Python)


code:
def pad(s):
    n = AES.block_size - len(s) % AES.block_size
    return s + bytearray([n] * n)

def unpad(s):
    return s[:-s[-1]]

rawDescription: Decrypting a file to a stream and reading the stream into pandas (hdf or stata)


code:
# from PyQt5.QtWidgets import (
from PyQt4.QtGui import (
    QApplication, QWidget, QVBoxLayout, QPushButton, QLabel,
    )

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QPushButton('Test', self)
        self.label = QLabel(self)
        self.button.clicked.connect(self.handleButton)
        layout = QVBoxLayout(self)
        layout.addWidget(self.label)
        layout.addWidget(self.button)

    def handleButton(self):
        self.label.setText('Button Clicked!')

if __name__ == '__main__':

    import sys
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt5: How can I connect a QPushButton to a slot?


rawDescription: How can I create crossproduct tuple for list of n list?

description: Create crossproduct tuple for list of n list


code:
#!/bin/bash
#/path/to/run-daily
run-parts /path/to/daily/jobs

rawDescription: Cronjobs per package

description: Cronjobs per package


code:
import pandas as pd
csvinputlist = ['file1.csv','file2.csv','file3.csv']
csvinput = csvinputlist
df = pd.DataFrame()
for i, csvinput in enumerate(csvinputlist):
    reader = pd.read_csv(csvinput)
    df['A{}'.format(i+1)]=reader['A']

df.to_csv('constructed.csv')

rawDescription: Writing to specific column from csv file


code:
def restore_object(self, attrs, instance=None):
    referrer = attrs.pop('referrer')
    # parse referrer to referral_campaign, referral_media_source, inviting_user
    ...
    instance = super(UserSerializer, self).restore_object(attrs, instance=instance)
    instance.referral_campaign = referral_campaign
    instance.referral_media_source = referral_media_source
    instance.inviting_user = inviting_user
    return instance

rawDescription: DRF - ModelSerializer with a non-model write_only field


code:
for subsection in soup.select('div#reportsubsection #subsection'):
    if not subsection.find('h2', text=re.compile('part 2')):
        continue
    # do something with this subsection

rawDescription: Python/Beautiful Soup find particular heading output full div


code:
my_transformed_list = [s[-1] for s in join_values]
concatenated = ''.join(my_transformed_list)

rawDescription: How to concatenate bytes together

description: Concatenate bytes together


code:
with open('RelationshipRequest.json', 'r') as fh:
    json_data = json.load(fh)

rawDescription: Parsing the pointers in JSON using python


rawDescription: Evaluation with variable pointing to operator


code: dict1.viewitems() & dict2.items()

rawDescription: Merge Two Dictionaries that Share Same Key:Value


code:
from functools import lru_cache

@lru_cache(16)  # cache 16 different `x` return values
def costly_function_a(x):
    print("costly_function_a has been called.")
    return x #Dummy operation.

@lru_cache(32)  # cache 32 different `x` return values
def costly_function_b(x):
    print("costly_function_b has been called.")
    return 5.*x #Dummy operation.

rawDescription: Minimizing the number of costly function calls when the parameters remain the same (python)


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

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, normed=True)
fig.canvas.draw()
plt.show()

rawDescription: plotting histograms whose bar heights sum to 1 in matplotlib

description: Plotting histograms whose bar heights sum to 1 in matplotlib


code:
path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

rawDescription: Open File in Another Directory (Python)

description: Open File in Another Directory (Python)


rawDescription: Synchronizing markdown automatically in the translated text (ProGit book, sources available)


rawDescription: How does Python handle equality checking?


code: r = requests.get(url, params='format=json&key=site:dummy+type:example+group:wheel')

rawDescription: How to prevent python requests from percent encoding my URLs?

description: Prevent python requests from percent encoding my URLs


code:
import pygame
import os

# let's address the class a little later..

pygame.init()
screen = pygame.display.set_mode((640, 400))
# you only need to call the following once,so pull them out of the  while loop.
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
clock = pygame.time.Clock()

running = True
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = False

    screen.fill((255, 255, 255)) # fill the screen
    screen.blit(bird, (0, 0))    # then blit the bird

    pygame.display.update() # Just do one thing, update/flip.

    clock.tick(40) # This call will regulate your FPS (to be 40 or less)

rawDescription: How to move Sprite in Pygame

description: Move Sprite in Pygame


code:
for c in range(1, num):
    print(' '*(num-1-c), *range(c-1, 0, -1), sep='')

rawDescription: Triangle number pattern in python

description: Triangle number pattern in python


rawDescription: String of bytes into an int

description: String of bytes into an int


code:
kargs = {'dollar': 1, 'euro': 3, 'foo': 'bar'}
kargs.viewkeys() & {'dollar', 'euro'}
del kargs['euro']
kargs.viewkeys() & {'dollar', 'euro'}
del kargs['dollar']
kargs.viewkeys() & {'dollar', 'euro'}

rawDescription: Require one out of two keyword arguments


code:
words = ''
with open(ifile_name,"r") as file:
    for line in file:
        list_of_words = line.split(' ')
        for key, word in enumerate(list_of_words):
            if 'l' in word:
                list_of_words[key] = ''

        words += ' '.join(w for w in list_of_words if w != '')
        words += '\n'

with open(ofile_name, "w+") as file:
    file.write(words)

rawDescription: Python remove word containing "l"

description: Python remove word containing "l"


code:
html = requests.get("http://www.killedbypolice.net/kbp2013.html").content
soup = BeautifulSoup(html, "html5lib")

# get all the table rows
table = soup.find("table")

rawDescription: Web Scraping Python Access Table data

description: Web Scraping Python Access Table data


code:
with open(filename) as f:
    while True:
        next10k = list(islice(f, 10000))  # need list to do len, 3 lines down
        for ln in next10k:
            process(ln)
        if len(next10k) < 10000:
            break

rawDescription: Is there a way to read 10000 lines from a file in python?


code:
def show_other_field(self):
    return self.other_field
show_other_field.admin_order_field = "other_field"

rawDescription: Django admin change list view disable sorting for some fields


rawDescription: Subsetting a 2D numpy array

description: Subsetting a 2D numpy array


code:
import copy
d = { ... }
d2 = copy.deepcopy(d)

rawDescription: Deep copy of a dict in python

description: Deep copy of a dict in python


code:
x = np.linspace(-5,9,10000)
plot1=plt.plot(x,mlab.normpdf(x,m1,std1))
plot2=plt.plot(x,mlab.normpdf(x,m2,std2))
plot3=plt.plot(result,mlab.normpdf(result,m1,std1),'o')

rawDescription: Python: finding the intersection point of two gaussian curves


code:
x = X.toarray()
mask = x == 0
x *= v[:, np.newaxis]
x = c - x
x[mask] = 0
x
Y.toarray()

rawDescription: Scipy Sparse Matrix special substraction


code: ' '.join(''.join(e) for e in  izip(data, data[1:]))

rawDescription: Parse String every 2 letters

description: Parse String every 2 letters


code:
# Apply predicate.
df[['s1', 's2']] = df[['s1', 's2']].gt(2)
df[['s3', 's4']] = df[['s3', 's4']].gt(4)

# Remove rows that are all False and convert to 0/1.
df = df.loc[df.any(axis=1), :].astype(int)

rawDescription: Creating and manipulating dataframes with only binary values


code:
import logging

logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

logging.debug(yourdataToSaveInFile)

rawDescription: Is it possible to create a log file in the terminal in python?


code:
import traceback

class Watcher(object):
    def __init__(self, obj=None, attr=None, log_file='log.txt', include=[], enabled=False):
        """
            Debugger that watches for changes in object attributes
            obj - object to be watched
            attr - string, name of attribute
            log_file - string, where to write output
            include - list of strings, debug files only in these directories.
               Set it to path of your project otherwise it will take long time
               to run on big libraries import and usage.
        """

        self.log_file=log_file
        with open(self.log_file, 'wb'): pass
        self.prev_st = None
        self.include = [incl.replace('\\','/') for incl in include]
        if obj:
            self.value = getattr(obj, attr)
        self.obj = obj
        self.attr = attr
        self.enabled = enabled # Important, must be last line on __init__.

    def __call__(self, *args, **kwargs):
        kwargs['enabled'] = True
        self.__init__(*args, **kwargs)

    def check_condition(self):
        tmp = getattr(self.obj, self.attr)
        result = tmp != self.value
        self.value = tmp
        return result

    def trace_command(self, frame, event, arg):
        if event!='line' or not self.enabled:
            return self.trace_command
        if self.check_condition():
            if self.prev_st:
                with open(self.log_file, 'ab') as f:
                    print >>f, "Value of",self.obj,".",self.attr,"changed!"
                    print >>f,"###### Line:"
                    print >>f,''.join(self.prev_st)
        if self.include:
            fname = frame.f_code.co_filename.replace('\\','/')
            to_include = False
            for incl in self.include:
                if fname.startswith(incl):
                    to_include = True
                    break
            if not to_include:
                return self.trace_command
        self.prev_st = traceback.format_stack(frame)
        return self.trace_command
import sys
watcher = Watcher()
sys.settrace(watcher.trace_command)

rawDescription: Watch for a variable change in python

description: Watch for a variable change in python


code:
def flatten(it):
    for x in it:
        if (isinstance(x, collections.Iterable) and
            not isinstance(x, str)):
            yield from flatten(x)
        else:
            yield x

rawDescription: Python: Function to flatten generator containing another generator


code:
def roundPartial (value, resolution):
    if resolution == 0:
        return 0
    return round (value / resolution) * resolution

rawDescription: Round float to the nearest 2/100

description: Round float to the nearest 2/100


code:
from collections import namedtuple
Person = namedtuple('Person', 'first_name last_name')
search_result = [Person('John', 'James'), Person('Andrew', 'James'), Person('Nigel', 'Reynolds'), Person('Nikos', 'Galis')]
search_result.sort(key=lambda x: (x.last_name, x.first_name))
from pprint import pprint
pprint(search_result)
import random
from operator import attrgetter
random.shuffle(search_result)
search_result.sort(key=attrgetter('last_name', 'first_name'))
pprint(search_result)

rawDescription: python sorting objects in a list using to criteria

description: Python sorting objects in a list using to criteria


code: [d['birth_year'] for d in dayList]

rawDescription: Using Python's Higher Order Functions on a CSV


code:
df
grouped = df.groupby('Name')
grouped.agg(sum)

rawDescription: how to apply functions to grouped dataframes in Python pandas?

description: Apply functions to grouped dataframes in Python pandas


code:
toChange = [0, 0, slice(None, None, None)]
a[toChange] = 0
a

rawDescription: Passing list as slice for a N-dimensional numpy array


code:
inputlist = ['0xe1', '0xd7', '0x7', '0x0']
'0x' + ''.join([format(int(c, 16), '02X') for c in reversed(inputlist)])

rawDescription: How to append a list of Hex to one Hex number

description: Append a list of Hex to one Hex number


code: x = np.linspace(xStart, xStop, num=(xStop-xStart)*100)

rawDescription: Python pylab: Making a plot with adjusted spines, but doesn't plot


code: [part for item in mylist for part in item.split()]

rawDescription: separating multiple words out of the same index

description: Separating multiple words out of the same index


code: lst = [Object() for i in range(100)]

rawDescription: Initialize a list of objects in Python

description: Initialize a list of objects in Python


rawDescription: sqlalchemy object saved to complete action

description: Sqlalchemy object saved to complete action


code:
def filter(dict):
        filter1 = rad_type(dict)
        i = 0
        for k ,val in dict.items():
              dict[k] = filter1[k[0]]
              i +=1
        mini_key = [k for k , val in filter1.items() if val == min([value for key ,  value in filter1.items()])][0]
        filter2 = {tuple(y for y in key if y != mini_key):value for key, value in dict.items()}
        filter3 = rad_type(filter2)
        return filter3

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

description: Remove duplicate items in multiple tuples of a dictionary


code: sum(1 for _ in takewhile(lambda x:x==a[0], a))

rawDescription: Find number of consecutive elements that are the same before they change


rawDescription: Regex through a string with Python 2.7

description: Regex through a string with Python 2.7


code:
print(list)
[{'key-2': 'value-2', 'key-1': 'value-1'}, {'key-B': 'value-B', 'key-A': 'value-A'}]

rawDescription: How do I add keys to a dictionary in a list of dictionaries?

description: Add keys to a dictionary in a list of dictionaries


rawDescription: Is there a direct approach to format numbers in jinja2?


code:
import logging
import sys
import requests
import httplib

# HTTP stream handler
class WritableObject:
    def __init__(self):
        self.content = []
    def write(self, string):
        self.content.append(string)

# A writable object
http_log = WritableObject()
# Redirection
sys.stdout = http_log

# Enable
httplib.HTTPConnection.debuglevel = 2

# get operation
requests.get('http://httpbin.org/headers')

# Remember to reset sys.stdout!
sys.stdout = sys.__stdout__
debug_info = ''.join(http_log.content).replace('\\r', '').decode('string_escape').replace('\'', '')

# Remove empty lines
debug_info = "\n".join([ll.rstrip() for ll in debug_info.splitlines() if ll.strip()])

rawDescription: How to make httplib debugger infomation into logger debug level

description: Make httplib debugger infomation into logger debug level


code: [i for i, elem in enumerate(mylist) if re.match(pattern, elem['rep_main'])]

rawDescription: Get index of dictionary item in list by regexp


code:
eggs = 3
spam = eggs

rawDescription: Getting name of local variable at runtime in Python


code:
def func(number):
    return next(t[1] for t in lst if t[0] == number)

rawDescription: function search in a list

description: Function search in a list


code:
# Define kernel
K1 = np.array([[0,1,1,0]]) # Edit this for different island lengths
K2 = 1-K1

# Generate masks of same shape as img amd based on TRUE and inverted versions of
# kernels being convolved and those convolved sums being compared against the
# kernel sums indicating those spefic positions have fulfiled both the ONES
# and ZEROS criteria
mask1 = convolve2d(img, K1, boundary='fill',fillvalue=0, mode='same')==K1.sum()
mask2 = convolve2d(img==0, K2, boundary='fill',fillvalue=0, mode='same')==K2.sum()

# Use a combined mask to create that expanses through the kernel length
# and use it to set those in img to zeros
K3 = np.ones((1,K1.size))
mask3 = convolve2d(mask1 & mask2, K3, boundary='fill',fillvalue=0, mode='same')>0
img_out = img*(~mask3)

rawDescription: Flipping continuous chunks of 1's up to a certain size in a binary numpy matrix


code:
from itertools import islice
lista = [2,4,6,8,3,4,6,2,1,4,23]
splitby = [2,4,2,3]
ilista = iter(lista)
groups = [list(islice(ilista, 0, n)) for n in splitby]
print(groups)

rawDescription: How to group a list by n elements, where n is defined in a list

description: Group a list by n elements, where n is defined in a list


code:
words = string.split()
words.index('my') #Out: 2

rawDescription: Position of query word

description: Position of query word


code:
s = 'abc'
list(enumerate(s, start=1-len(s)))

rawDescription: For x in string , how to check if x is last


code: df['unix'] = pd.to_datetime(df['unix'], unit='s')

rawDescription: Convert tick data to daily

description: Convert tick data to daily


code:
df['C'] = df.groupby('A').transform(lambda x: pd.Series(x.B.max()))
df

rawDescription: Equivalent of R function 'ave' in Python Pandas


rawDescription: Python PySide and Progress Bar Threading


code:
seen = set()
with open('test.csv') as input, open('test_out.csv', 'w') as output:
    for line in input:
        value = float(line)
        while value in seen:
            value -= 0.000001
        seen.add(value)
        output.write(str(value) + '\n')

rawDescription: slightly fidgeting data that is equal

description: Slightly fidgeting data that is equal


code:
m2m_tbl = Product.tags.through._meta.db_table
qs = Product.objects.exclude(pk=the_given_product.pk)
alias_1 = qs.query.get_initial_alias()
alias_2 = qs.query.join((alias_1, m2m_tbl, 'id', 'product_id'))
alias_3 = qs.query.join((alias_2, m2m_tbl, 'tag_id', 'tag_id'))
qs = qs.annotate(similar_tags_count=models.Count('tags__id')).extra(where=[
    '{alias_2}.product_id != {alias_3}.product_id'.format(alias_2=alias_2, alias_3=alias_3),
    '{alias_3}.product_id = %s'.format(alias_3=alias_3)
], params=[the_given_product.pk])

rawDescription: Django Query - Sort by Tags in common

description: Django Query - Sort by Tags in common


code:
from lxml.html import fromstring
mySearchTree = fromstring(your_input_string)

rawDescription: Need python lxml syntax help for parsing html


code:
from xml.etree import ElementTree as ET
tree = ET.fromstring('''\
<root>
    <field name ="1">
        <field name ="2" showname ="ZZZ">
            <field name ="3" showname="YYY">
                <field name ="4" showname="XXX"/>
            </field>
        </field>
    </field>
</root>
''')
tree.find(".//field[@showname='XXX']")
tree.find(".//field[@showname='XXX']").get('name')

rawDescription: recursion None python

description: Recursion None python


code:
def connection(*args, **kw):
    return DB(*args, **kw).open_then_close_db_when_connection_closes()

rawDescription: How to set cache size in ZODB?

description: Set cache size in ZODB


code:
import re
import collections
class Group:
    def __init__(self):
        self.members = []
        self.text = []

with open('text1.txt', "r+") as f:
    # so specific lines can be edited
    lines = f.readlines()

    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'^(\S+)\((.*)\)$')
    current_group = None

    for line in range(len(lines)):
        curr_line = lines[line]

        # to prevent searches on lines with no group
        if "(" in curr_line:
            curr_line = curr_line.strip()
            m = group_pattern.match(curr_line)
            if m:
                group_name, group_members = m.groups()
                groups[group_name].members += filter(lambda x: x not in groups[group_name].members, group_members.split(','))
                current_group = group_name

    already_seen = []
    for line in range(len(lines)):
        curr_line = lines[line]

        for key in groups.keys():
            if key in curr_line.strip():
                if key in already_seen:
                    lines[line] = ""
                else:
                    already_seen.append(key)
                    open_par = curr_line.index("(")
                    close_par = curr_line.index(")")

                    member_str = ",".join(groups[key].members)

                    lines[line] = curr_line[:open_par+1] + member_str + curr_line[close_par:]

    # clear the file and reset the file cursor
    f.truncate()
    f.seek(0)

    for line in lines:
        f.write(line)

rawDescription: python to make changes in existing file

description: Python to make changes in existing file


code: L = re.findall(r"(?:http|https)://[^/\"]+/", site_str)

rawDescription: Python regex alternation

description: Python regex alternation


code:
sg = list()
for region in regions:
  connection=ec2.connect_to_region(region)
  sg.extend(connection.get_all_security_groups())

rawDescription: How to iterate through all aws region to get security group info

description: Iterate through all aws region to get security group info


code:
from collections import defaultdict
import itertools

frequencies = defaultdict(int)
for line in open_file:
    line = line.strip().split()
    list1_used = ...
    list2_used = ...
    for combination in itertools.product(list1_used, list2_used):
        frequencies[combination] += 1

rawDescription: Find combination of items in the same line in one file text and thei frequency


code: player_names = [row[0] for row in your_list]

rawDescription: Selecting elements from Python array

description: Selecting elements from Python array


rawDescription: format list depending on number of items in it

description: Format list depending on number of items in it


code: theGraph.node[nodeID]["viz"] = {'position': {'x': coordX, 'y': coordY, 'z': 0}}

rawDescription: Python / networkx: creation of note attributes fails erratically


code:
import numpy as np

# Perform lex sort and get the sorted indices
sorted_idx = np.lexsort(xyz.T)
sorted_xyz =  xyz[sorted_idx,:]

# Differentiation along rows for sorted array
df1 = np.diff(sorted_xyz,axis=0)
df2 = np.append([True],np.any(df1!=0,1),0)

# Get unique sorted labels
sorted_labels = df2.cumsum(0)-1

# Get labels
labels = np.zeros_like(sorted_idx)
labels[sorted_idx] = sorted_labels

# Get unique indices
unq_idx  = sorted_idx[df2]

# Get unique xyz's and the mass counts using accumulation with bincount
xyz_unique = xyz[unq_idx,:]
mass_unique = np.bincount(labels, weights=mass)

rawDescription: Find indices of unique values of a 3-dim numpy array


code:
adict = {}
key1 = 'contains(%s)' % a
value1 = True
adict[key1] = value1
adict
key2 = 'contains(%s)' % o
value = 'orange'
value2 = False
adict[key2] = value2
adict

rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


rawDescription: I want to be able to isolate a non-specific string from a list using python


code:
class MyClass(metaclass=MyMetaClass):
  pass

rawDescription: Metaclass Arguments for Python 3.x

description: Metaclass Arguments for Python 3.x


code: ['I am', 'show']

rawDescription: Python matching words with same index in string


code: df = df.set_index('Class')

rawDescription: Sorting a pandas DataFrame by the order of a list


code: 'Hello, two is a number'[7:12]

rawDescription: python copy string from position to position

description: Python copy string from position to position


code: singleitem = mylist[-1]

rawDescription: Getting only element from a single-element list in Python?


rawDescription: BBP-Algorithm in Python - Working with Arbitrary-precision arithmetic


code:
def grouper(n, iterable):
    "s -> (s0,s1,...sn-1), (sn,sn+1,...s2n-1), (s2n,s2n+1,...s3n-1), ..."
    return izip(*[iter(iterable)]*n)

rawDescription: Creating a python dictionary from a line of text


code:
from collections import Counter

values = Counter([(entry[1], entry[4]) for entry in long_array])
for value, count in values.items():
    if count > 1:
        print(str(count) + " duplicates of " + str(value))

rawDescription: Python3 search value in this array

description: Python3 search value in this array


rawDescription: How can i print the result in a file after for loop

description: Print the result in a file after for loop


rawDescription: unable to find the right regex

description: Unable to find the right regex


code: y = [v for z in ('a', 'b\nc', 'd') for v in z.splitlines()]

rawDescription: Can this generator expression be modified to match for loop result?


code:
import os
import shutil

from tempfile import mkstemp

class CachedFileObject(object):

    def __init__(self, cache_dir="/tmp"):
        self.cache_dir = cache_dir
        self.local_file = None
        self.local_path = None
        self.remote_path = None
        self.mode = None

    def open(self, path, mode="r", buffering=-1):
        if self.local_file and not self.local_file.closed:
            raise ValueError("Already open")
        fd, self.local_path = mkstemp(dir=self.cache_dir)
        os.close(fd)
        try:
            if "r" in mode and not os.path.exists(path):
                raise ValueError("No such remote file")
            if os.path.exists(path):
                # have remote file
                self._cache_remote(path, self.local_path)
            self.local_file = open(self.local_path, mode=mode, buffering=buffering)
            self.mode = mode
            self.remote_path = path
        except Exception as e:
            os.unlink(self.local_path)
            raise

        return self

    def close(self):
        self.local_file.close()
        try:
            if set("wa+").intersection(set(self.mode)):
                # have writes, sync file back to remote side
                self._sync_remote(self.remote_path, self.local_path)
        finally:
            os.unlink(self.local_path)

    def _cache_remote(self, remote_path, local_path):
        # simple cp
        shutil.copy(remote_path, local_path)

    def _sync_remote(self, remote_path, local_path):
        shutil.copy(local_path, remote_path)

    def __getattr__(self, attr):
        if self.local_file is not None:
            return getattr(self.local_file, attr)
        else:
            raise ValueError("File is not opened")

rawDescription: (locally) cached file object in Python

description: (locally) cached file object in Python


code: df.apply(lambda x: x.oldColumn * x.otherOldColumn, axis=1)

rawDescription: Add a column to a pandas data frame using a pandas operation


code: y = np.recarray(x.shape, buf=x, strides=x.strides, dtype=dt2)

rawDescription: Python numpy recarray: Can one obtain a view into different fields using pointer arithmetic?


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

import numpy as np

def old_dihedral2(p):
    """http://stackoverflow.com/q/20305272/1128289"""
    b = p[:-1] - p[1:]
    b[0] *= -1
    v = np.array( [ v - (v.dot(b[1])/b[1].dot(b[1])) * b[1] for v in [b[0], b[2]] ] )
    # Normalize vectors
    v /= np.sqrt(np.einsum('...i,...i', v, v)).reshape(-1,1)
    b1 = b[1] / np.linalg.norm(b[1])
    x = np.dot(v[0], v[1])
    m = np.cross(v[0], b1)
    y = np.dot(m, v[1])
    return np.degrees(np.arctan2( y, x ))

def wiki_dihedral(p):
    """formula from Wikipedia article on "Dihedral angle"; formula was removed
    from the most recent version of article (no idea why, the article is a
    mess at the moment) but the formula can be found in at this permalink to
    an old version of the article:
    https://en.wikipedia.org/w/index.php?title=Dihedral_angle&oldid=689165217#Angle_between_three_vectors
    uses 1 sqrt, 3 cross products"""
    p0 = p[0]
    p1 = p[1]
    p2 = p[2]
    p3 = p[3]

    b0 = -1.0*(p1 - p0)
    b1 = p2 - p1
    b2 = p3 - p2

    b0xb1 = np.cross(b0, b1)
    b1xb2 = np.cross(b2, b1)

    b0xb1_x_b1xb2 = np.cross(b0xb1, b1xb2)

    y = np.dot(b0xb1_x_b1xb2, b1)*(1.0/np.linalg.norm(b1))
    x = np.dot(b0xb1, b1xb2)

    return np.degrees(np.arctan2(y, x))

def new_dihedral(p):
    """Praxeolitic formula
    1 sqrt, 1 cross product"""
    p0 = p[0]
    p1 = p[1]
    p2 = p[2]
    p3 = p[3]

    b0 = -1.0*(p1 - p0)
    b1 = p2 - p1
    b2 = p3 - p2

    # normalize b1 so that it does not influence magnitude of vector
    # rejections that come next
    b1 /= np.linalg.norm(b1)

    # vector rejections
    # v = projection of b0 onto plane perpendicular to b1
    #   = b0 minus component that aligns with b1
    # w = projection of b2 onto plane perpendicular to b1
    #   = b2 minus component that aligns with b1
    v = b0 - np.dot(b0, b1)*b1
    w = b2 - np.dot(b2, b1)*b1

    # angle between v and w in a plane is the torsion angle
    # v and w may not be normalized but that's fine since tan is y/x
    x = np.dot(v, w)
    y = np.dot(np.cross(b1, v), w)
    return np.degrees(np.arctan2(y, x))

rawDescription: Dihedral/Torsion Angle From Four Points in Cartesian Coordinates in Python


code:
import test
test.foo()

rawDescription: Reloading a changed python file in emacs python shell


code:
class SimulationFilter(logging.Filter):
    def __init__(self, context):
        """
        Set up with context passed in which allows access
        to simulation times.
        """
        self.context = context

    def filter(self, record):
        "Add sim_time field to record, formatted as you wish"
        record.sim_time = '%s' % self.context.get_sim_time()
        return True

rawDescription: Best way to add custom information to for logging

description: Add custom information to for logging


code:
# variable-specific patterns
patterns = {
    'remote_addr': r'(\d{1,3}\.){3}\d{1,3}',
    'body_bytes_sent': r'\d+',
    # etc
}

regex = ''.join(
    '(?P<%s>%s)' % (g, patterns.get(g, '.*?')) if g
        else re.escape(c)
    for g, c in re.findall(r'\$(\w+)|(.)', conf))

rawDescription: How to generate regex to match access.log acording to its format config?

description: Generate regex to match access.log acording to its format config


rawDescription: "Slicing" in Python Expressions documentation


code:
opts, args = getopt.getopt(sys.argv[1:], "cs:n:p:hv",
#                                             ^ insert colon here
    ["cli", "server", "username", "password", "help", "verbose"])

rawDescription: Why does my getopts fail if I specify a username?


code:
test = r"""'xx\'x,x\\x"xx\\\'\\',1,2,'xx\'x\''"""
map(print, parse_quoted_strings_list(test))

rawDescription: How to parse a simple quoted string (handling escapes)

description: Parse a simple quoted string (handling escapes)


code:
from django.db import connections
cursor = connections['old'].cursor()
cursor.execute("SELECT...")
cursor.fetchall()

rawDescription: Is there any method in django to use database without creating models.py file?


code:
anArray
resultArray

rawDescription: How to convert a series of index/category, into a classification array

description: Convert a series of index/category, into a classification array


code:
Chloe
Megan
Chloe

rawDescription: Python Splitting a file into many files and adding in extra info


code:
s='i cant sleep what should i do'
p='cant sleep'
lh, _, rh = s.partition(p)

rawDescription: Python find n-sized window around phrase within string


code:
@app.route("/mainsite/<path:varargs>")
def api(varargs=None):
    # for mainsite/key1/key2/key3/keyn
    # `varargs` is a string contain the above
    varargs = varargs.split("/")
    # And now it is a list of strings

rawDescription: Flask: URLs w/ Variable parameters

description: Flask: URLs w/ Variable parameters


code:
class B(object):
    def add_items(self):
        self.foo = 'Baz'

b = B()
b.add_items()

rawDescription: Write attribute to scope above current one


code:
import zerorpc
import os

# extract any public callable.
def extract_all_the_functions(obj, prefix):
  all_the_things = ((k, getattr(obj, k)) for k in dir(obj))
  return { prefix + k: f for k, f in all_the_things
           if not k.startswith('_') and callable(f) }

class MyObject(object):
  def add(self, a, b):
    return a + b

funcs = extract_all_the_functions(os, 'os_')
funcs.update(extract_all_the_functions(MyObject(), 'myobj_'))
s = zerorpc.Server(funcs)
s.bind('tcp://127.0.0.1:4242')
s.run()

rawDescription: ZeroRPC: How to expose a module

description: ZeroRPC: How to expose a module


code:
def format_float(value, ndigits=4):
    try:
        j = min(i-1 for i in range(ndigits+1) if value >= 10 ** (ndigits - i))
        return '{:.0{num_digits}f}'.format(value, num_digits=max(0,j))
    except ValueError:
        s = '{:.20f}'.format(value).rstrip('0')
        _, dec_part = s.split('.')
        if len(dec_part) > ndigits:
            if set(dec_part[:ndigits]) != {'0'}:
                dec_part = dec_part[:ndigits]
            else:
                for i, char in enumerate(dec_part):
                    if char != '0':
                        dec_part = dec_part[:i+1]
                        break
        if not dec_part:
            # should happen only if the input is 0.0
            return '0'
        else:
            return '{}.{}'.format(0, dec_part)

rawDescription: Decimal formatting based on number of digits in integer and decimal parts


rawDescription: Why can't I import a model from a file containing import of any of the Google App Engine components?


code:
f = open('array.dat', "wb")
a.tofile(f)
f.close()

rawDescription: Storage size of array.array in a file

description: Storage size of array.array in a file


code:
repl=lambda x: x.group(1) + (x.group(2).rstrip('0').rstrip('.'))
re.sub('(?<!\d)(\d+)(\.\d*)(?!\d)',repl,string)

rawDescription: Python: Remove 0s from floats in string

description: Python: Remove 0s from floats in string


rawDescription: in python is it possible to write a method that will be automatically called after __init__ of subclass

description: In python is it possible to write a method that will be automatically called after __init__ of subclass


code:
for i in range(num1, num2 + 1):
        print(i)

rawDescription: Need to add all the integers between 2 other integers


code: someElement in someList

rawDescription: How does Python check if an element exists in a list?


code:
import string
import json
import functools

quote_swap = functools.partial(
    string.translate, table=string.maketrans('\'"', '"\'')
)

def encode_single_quoted_js_string(s):
    return quote_swap(json.dumps(quote_swap(s)))

rawDescription: Escaping JavaScript Strings in Python

description: Escaping JavaScript Strings in Python


code:
from tempfile import NamedTemporaryFile
from shutil import move

with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as out:
    for line in f:
        if line.startswith("$ yum"):
            out.write(line)
            for _line in f:
                if _line.startswith("$"):
                    out.write("I am a new line\n")
                    out.write(_line)
                    break
                out.write(_line)
        else:
            out.write(line)

move(out.name,"in.txt")

rawDescription: inserting a line in a file using python

description: Inserting a line in a file using python


code:
def getHierarchy(item_id,array_of_tuple,separator="/"):

  for i, (tuple_name, tuple_id, tuple_parent_id) in enumerate(array_of_tuple):
      if item_id == tuple_id:
          if tuple_parent_id == 0:
              return separator+tuple_name
          else:
              return separator+tuple_name+getHierarchy(tuple_parent_id,array_of_tuple)
  return ""

rawDescription: appending a list or tuple as value to a dictionary - or other solution to building a parent child relationship

description: Appending a list or tuple as value to a dictionary - or other solution to building a parent child relationship


code:
def generatePureHWSim(self) :
  output_list = []
  output_list.append(ShangHWSimStep(self))
  num_iter = self.max_scheduling_iterations
  if num_iter > 1 :
    for i in range(1) :
      sim_step = ShangHWSimStep(self)
      sim_step.option = self.option.copy()
      sim_step.hls_base_dir = os.path.join(sim_step.hls_base_dir, str(i))
      sim_step.rtl_output = os.path.join(sim_step.hls_base_dir, sim_step.test_name + ".sv")
      sim_step.option['max_scheduling_iterations'] = i + 1
      output_list.append(sim_step)
  return output_list

rawDescription: Questions about Python 'yield' keyword that I have not found answers elsewhere, and its specific use in a code I am working on


code:
list = [{
            'id': '1',
            'elements': 'A',
            'table': 'path/to/table1',
            'chart': 'path/to/chart1',
        },
        {
            'id': '2',
            'elements': 'B',
            'table': 'path/to/table2',
            'chart': 'path/to/chart2',
        },
        {
            'id': '3',
            'elements': 'C',
            'table': 'path/to/table3',
            'chart': 'path/to/chart3',
        },]
selectionsFromTable = [{'A','2011','Table','Total'},
                       {'C','2011','Bar','Total'},
                       {'B','Pie','2001','Total'}]
arr = []
for data in list:
    elem = next((s for s in selectionsFromTable if data['elements'] in s), None)
    if elem:
        inner = []
        if 'Table' in elem:
            print("table")
            inner.append({'id': data['id'],
                          'section_title': data['elements'],
                          'tableorChart': data['table'],
                          })
        elif ('Bar' in elem) or ('Pie' in elem):
            print("chart")
            inner.append({'id': data['id'],
                          'section_title': data['elements'],
                          'tableorChart': data['chart'],
                          })
        arr.append(inner)
import pprint
pprint.pprint(arr)

rawDescription: How to retreive particular values from a list: python

description: Retreive particular values from a list: python


code:
filename = 'newfile.txt'
data = []
source = open(filename)
for line in source:
    data.append(int(line))
source.close()

print(mean(data))
print(deviation(data))
# more stuff with data

rawDescription: I'm having trouble with input and output from files


code:
def key_func(item):
    value = item[1]
    order = value[1]
    return order
for key, value in sorted(starters.items(), key=key_func):
    ...

rawDescription: I am having difficulty sorting a dictionary by value


code:
df3 = pd.ewma(df2, span=7)
df3.columns = pd.MultiIndex.from_tuples([('EWMA', item[1]) for item in df3.columns])
df2 = pd.concat([df2, df3], axis=1)

print(df2)

rawDescription: Pandas: Exponential smoothing function for column


code:
def recode(s, threshold):
    b = s.groupby(s).transform(lambda x: x.count() >= threshold).astype('bool') # True/False
    s[~b] = 'X'
    return s

rawDescription: Column recoding based on count of distincts


rawDescription: Python group by

description: Python group by