code:
from tkinter import *

class Colors(Frame):
    def __init__(self):
        Frame.__init__(self)
        self._image = PhotoImage(file="r.gif")
        self._imageLabel = Label(self, image=self._image)
        self._imageLabel.grid()

        self.master.title("Color Changer")
        self.grid()

        self.red = Scale(self, from_=0, to=255, label="Red", fg="red", )
        self.red.grid(row=0, column=1)

        self.green = Scale(self, from_=0, to=255, label="Green", fg='green')
        self.green.grid(row=0, column=2)

        self.blue = Scale(self, from_=0, to=255, label="Blue", fg="blue")
        self.blue.grid(row=0, column=3)

        self.button = Button(self, text="Change Colors", command=self.changeColor)
        self.button.grid(row=1, column=2)

    def changeColor(self):
        red = self.red.get()
        blue = self.blue.get()
        green = self.green.get()
        for y in range(self._image.height()):
            for x in range(self._image.width()):
                self._image.put("#%02x%02x%02x" % (red,green,blue), (x, y))

def main():
    Colors().mainloop()

main()

rawDescription: How to change the pixel color of a PhotoImage python

description: Change the pixel color of a PhotoImage python


code:
class Base(object):
    def __mul__(self, lhs): print('Base.mul')
    def __rmul__(self, rhs): print('Base.rmul')

class Derived(Base):
    def __mul__(self, lhs): print('Derived.mul')
    def __rmul__(self, rhs): print('Derived.rmul')

class Unrelated(object):
    def __mul__(self, lhs): print('Unrelated.mul')
    def __rmul__(self, rhs): print('Unrelated.rmul')

print('Base * Base: ', end='')
Base() * Base()
for x, y in itertools.permutations((Base, Derived, Unrelated), 2):
    print('{} * {}: '.format(x.__name__, y.__name__), end='')
    x() * y()

rawDescription: How to determine which instance of an operator is being called?

description: Determine which instance of an operator is being called


code: np.all(image == color, axis=-1)

rawDescription: How do I avoid looping through an image pixel by pixel with opencv & numpy

description: Avoid looping through an image pixel by pixel with opencv & numpy


rawDescription: Pandas mul with dense with sparse

description: Pandas mul with dense with sparse


code:
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None

rawDescription: Two instances of django admin site - templates


code:
class AuthorAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'books_count',)

    def books_count(self, obj):
        return obj.books_count

    def get_queryset(self, request):
        return super(AuthorAdmin, self).get_queryset(
            request).annotate(books_count=Count('books'))

rawDescription: Django admin list display optimize queryset


rawDescription: Tag extra information to differentiate numbers in a list


rawDescription: Extract daily range from time series using Pandas


code:
df.index = ['row0', 'row1', 'row2', 'row3', 'row4', 'row5']
df

rawDescription: Pandas dataframe - how to assign index?

description: Pandas dataframe - how to assign index


code: typeB = lookup[typeA]

rawDescription: if typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause?

description: If typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause


rawDescription: Conditional regular expression to split on commas


code:
def sales(level, foo, bar):
    data = levels_dict[level]
    x = data.xcost + data.sale * foo
    y = data.ycost + data.sale * bar
    ...

rawDescription: Python: how to avoid writing numerous if/elifs in a function?


code:
def f(group):
    row = group.irow(0)
    return DataFrame({'class': [row['class']] * row['count']})
df.groupby('class', group_keys=False).apply(f)

rawDescription: pandas: apply function to DataFrame that can return multiple rows

description: Pandas: apply function to DataFrame that can return multiple rows


rawDescription: merging n sorted lists of tuples in python

description: Merging n sorted lists of tuples in python


code: treeFunction(2, 3)

rawDescription: Dynamically generating a function tree in Python.


code:
def commonElements(a1, a2):
    L = []
    for el in a1:
        if el in a2:
            L.append(el)
    return tuple(L)

rawDescription: How do I find every element that is in both of two other lists?

description: Find every element that is in both of two other lists


code:
from operator import itemgetter
d = {'A': 0.35, 'C': 0.2, 'T': 0.3, 'G': 0.15}

def W(d):
    ran = random.uniform(0, 1)
    tot = 0
    # sort from lowest value to highest
    for k, v in sorted(d.items(),key=itemgetter(1)):
        if tot <= ran < v + tot:
            return k
        tot += v

rawDescription: Python Dictionary, make range associated with its values and return them


code:
query = User.objects.filter(first__istartswith=token).order_by('last')
exacts = [user for user in query if user.first == token]
others = [user for user in query if user.first != token]
users = exacts + others

rawDescription: Return exact matches at top of Django Queryset


code: ffserver -d -f /etc/ffserver.conf

rawDescription: How to Capture Video Stream with OpenCV (Python)


code:
match_str = b"sape"
with open(exe_filePath,'rb') as file_obj:
    while True:
        data = file_obj.readline(100)
        if data.count(match_str) > 0:
            # This will overwrite any previous "out" from the last match!
            # Do you really want that?
            out = data.strip()[9:13]
        if data==b"":
            break
return out

rawDescription: reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2

description: Reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2


code:
import pandas as pd
df = pd.DataFrame({'COL1': ['A', np.nan]*100000,
                   'COL2' : ['A','A']*100000})

df.loc[df.COL1.isnull(), 'COL2'] = np.nan

rawDescription: Pandas Conditional Replace

description: Pandas Conditional Replace


code:
first_var='hello'
second_var='world'
subprocess.Popen(['program_name', first_var, second_var], shell=False)

rawDescription: How to pass more than one variable from Python script to c shell script

description: Pass more than one variable from Python script to c shell script


code:
alpha_data = [('A', 'Apple', 14.5), ('B', 'Banana', 23.4)]

user_input = "A"

[rec for rec in alpha_data if rec[0] == user_input]
Out[4]: [('A', 'Apple', 14.5)]

rawDescription: Comparing user input with tuple value

description: Comparing user input with tuple value


code: string += str(getbingint) + ":" + str("%.2f") % getsmallint + ","

rawDescription: Python basic maths

description: Python basic maths


code:
cv2.imshow('Extracted Image', out)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code: r = range(5)

rawDescription: Choosing random integers except for a particular number for python?


rawDescription: Why isn't my tkinter scrollbar working?

description: Why isn't my tkinter scrollbar working


code:
from numpy import r_, ones, pi, sort
from numpy.random import rand
from radial_grouper import tree, pre_order, post_order
from radial_visualizer import simple_link
from pylab import axis, figure, plot, subplot

# ToDo: create proper documentation
def _s(sp, t, o):
    subplot(sp)
    t.traverse(simple_link, order= o)
    axis('equal')

def demo1(n):
    p= r_[2* pi* rand(1, n)- pi, ones((1, n))]
    t= tree(p)
    f= figure()
    _s(221, t, pre_order)
    _s(222, t, post_order)
    t= tree(p, tols= sort(2e0* rand(9)))
    _s(223, t, pre_order)
    _s(224, t, post_order)
    f.show()
    # f.savefig('test.png')

# ToDO: implement more demos

if __name__ == '__main__':
    demo1(123)

rawDescription: How do I create a radial cluster like the following code-example in Python?

description: Create a radial cluster like the following code-example in Python


rawDescription: Pandas Drop Rows Outside of Time Range

description: Pandas Drop Rows Outside of Time Range


code:
t1 = 'a',hash('a')
[hash(x) for x in t1]  #both elements in the tuple have same hash value since `int` hash to themselves in cpython
t2 = hash('a'),'a'
hash(t1)
hash(t2)
d = {t1:1,t2:2}  #This is OK.  dict's don't fail when there is a hash collision
d
d[t1]+=7
d[t1]
d[t1]+=7
d[t1]
d[t2]   #didn't touch d[t2] as expected.

rawDescription: Hashing a tuple in Python where order matters?


code:
def dzip(f, a, b):
    return {key: f(a.get(key, ""), b.get(key, "")) for key in set.inersection(set(a.keys()) + set(b.keys()))}

rawDescription: Merge values of a dictionary by key based on custom function


code: values_string = ', '.join(['"{0}"'.format(query_data[key]) for key in fields])

rawDescription: Python sql query insert data in columns

description: Python sql query insert data in columns


rawDescription: how to get a dict of instance fields with in a class definition in python?

description: Get a dict of instance fields with in a class definition in python


code: caaaar

rawDescription: String manipulation in for loops

description: String manipulation in for loops


rawDescription: compare elements of two lists

description: Compare elements of two lists


code:
json_data = '{"foo": "bar", "bar": "baz"}'
json.loads(json_data)                                # old call gives unicode
json.loads(json_data, object_hook=ascii_encode_dict) # new call gives str

rawDescription: Forcing Python json module to work with ASCII


code:
class Phonenumber(db.Model):
    number_type = db.StringProperty()
    number = db.StringProperty()

rawDescription: AppEngine id/key/from_path is quite confusing what should I use


rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
data_stream = Popen(mycmd, stdout=PIPE)
for line in data_stream.stdout:
   ...  # Fine

rawDescription: python subprocess module: looping over stdout of child process

description: Python subprocess module: looping over stdout of child process


code:
import itertools as IT
IT.product('AGT', 'AGT', 'A', 'G', 'G', 'AG', 'G', 'AGT')
len(list(IT.product('AGT', 'AGT', 'A', 'G', 'G', 'AG', 'G', 'AGT')))

rawDescription: Python Permutations in which each position is limited


code:
@app.route('/delete/<int:id>', methods=['GET', 'POST', 'DELETE'])
def delete_data(id=None):
    if id is None:
        return 'Please provide an object ID to delete!'

    object_to_delete = db.session.query(Data).filter_by(id=id)
    db.session.delete(object_to_delete)
    db.session.commit()

rawDescription: Flask retrieve data

description: Flask retrieve data


code:
import re

def parse(data):
    stack = [{}]

    for x in data.splitlines():
        x = re.sub(r'\s+', '', x)

        m = re.match(r'(\w+):STRUCT', x)
        if m:
            d = {}
            stack[-1][m.group(1)] = d
            stack.append(d)
            continue

        m = re.match(r'(\w+):INT(?::=(\w+))?', x)
        if m:
            stack[-1][m.group(1)] = int(m.group(2) or 0)
            continue

        m = re.match(r'END_STRUCT', x)
        if m:
            stack.pop()
            continue

    return stack[0]

rawDescription: Efficiently extract blocks of text from a space-indent structured file


code:
class Foo(object):
    pass

foo = Foo()
foo.a = 3
Foo.b = property(lambda self: self.a + 1)
foo.b

rawDescription: How to add property to a python class dynamically?

description: Add property to a python class dynamically


code:
def __init__(self, ex_arg1, ex_arg2, *args):
    super().__init__(*args)
    # ...

rawDescription: How to Extend Large Class Methods?

description: Extend Large Class Methods


rawDescription: Why does s[len(s)-1:-1:-1] not work?

description: Why does s[len(s)-1:-1:-1] not work


code:
s = pd.concat([df.col1, df.col2], ignore_index=True)
s

rawDescription: How to count number of unique strings in two columns?

description: Count number of unique strings in two columns


code:
x = types.MappingProxyType({'foo': 'bar', 'baz': 'bla'})
x
x['hello'] = 'world'

rawDescription: Python: Freeze dict keys after creation

description: Python: Freeze dict keys after creation


code:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)

rawDescription: Is there a simple way to increment a datetime object one month in Python?


rawDescription: Pythonic ways to create independent lists from a list?


code:
stringC = 'normally'
print((('%s strange {} no one ' % stringA) + stringC).format(stringB), 'uses')

rawDescription: Simple adding spaces between variables in python3


code: y = dict(x, foo_bar='spam_eggs')

rawDescription: Is it possible to copy and update a python dictionary in a single chained expression?


code:
toolbar = tk.Frame(root)
sstatusbar = tk.Frame(root)

toolbar.grid(...)
statusbar.pack(...)

rawDescription: Is there any better method to manage place in Tkinter in Python?


rawDescription: How can I test this script that accesses urls through several different proxy servers?

description: Test this script that accesses urls through several different proxy servers


code:
import numpy as np
def unique(a):
    a = np.sort(a)
    b = np.diff(a)
    b = np.r_[1, b]
    return a[b != 0]

rawDescription: Removing duplicate columns and rows from a NumPy  2D array


code:
new_list = []
for i in range(int(len(file)/4)): #Iterates through 1/4 of the length of the file lines.
                                  #This is because we will be dealing in groups of 4 lines
    new_list.append(''.join(file[i*4:(i+1)*4])) #Joins four lines together into a string and adds it to the new_list

rawDescription: Read a text file into python by splitting the file into list items according to a set of characters


code:
import collections
import xml.etree.ElementTree as ET

with open("xmlbasic.txt") as lines_file:
    lines = lines_file.read()

root_dict = collections.defaultdict( dict )
for line in lines:
    head, subhead, tail = line.split(":")
    root_dict[head][subhead] = tail

root = ET.Element('root')
for head, branch in root_dict.items():
    head_element = ET.SubElement(root, head)
    for subhead, tail in branch.items():
        ET.SubElement(head_element,subhead).text = tail

tree = ET.ElementTree(root)
ET.dump(tree)

rawDescription: creating xml tree from a textfile with Python

description: Creating xml tree from a textfile with Python


code:
alphabet = "zyxwvutsrqpomnlkjihgfedcba"

new_list = sorted(inputList, key=lambda word: [alphabet.index(c) for c in word[0]])

rawDescription: Custom sort python

description: Custom sort python


code: from myimports import *

rawDescription: Is there an include file for class statements in python?


code:
inner = Rip_row_mat.dot( Rjp_col_mat ).data
Rip_m = np.sqrt( Rip_row_mat.dot( Rip_col_mat ).data )
Rjp_m = np.sqrt( Rjp_row_mat.dot( Rjp_col_mat ).data )

cos_sim = inner / ( Rip_m * Rjp_m )

rawDescription: Special cosine between scipy sparse matrices


rawDescription: Pandas: How to iterate over level one and randomly select from level 2 then add subselection to dataframe


rawDescription: Pandas: writing to original data frame. SettingWithCopyWarning


code: import os;

rawDescription: Is it possible to embed python without the standard library?


code:
One

Two

Three

rawDescription: Python Docx Carriage Return

description: Python Docx Carriage Return


rawDescription: Python regex \number adding \0x

description: Python regex \number adding \0x


code:
df
df['ids'] = df['ids_x'] + df['ids_y']
df
df = df.drop(['ids_x','ids_y'],axis=1)
df

rawDescription: How to merge two list columns when merging DataFrames?

description: Merge two list columns when merging DataFrames


code:
db.collection.mapReduce(
    mapper,
    reducer,
    {
        "out": { "replace": "newcollection" }
    }
)

rawDescription: Combine documents in MongoDB

description: Combine documents in MongoDB


code:
(session
    .query(AccessStringDetails)
    .filter(AccessStringDetails.menu_id.in_(menu_id_select))
    .delete(False))
(session
    .query(TimeDetails)
    .filter(TimeDetails.menu_id.in_(menu_id_select))
    .delete(False))
(session
    .query(RedirectorInputParams)
    .filter(RedirectorInputParams.command_id.in_(keyword_select))
    .delete(False))
# etc.

session.query(Redirector).filter(service_filter).delete(False)

rawDescription: Sqlalchemy mass deletion orm creation

description: Sqlalchemy mass deletion orm creation


rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


code:
def Latex(expr):
    return display(Math(latex(expr,mul_symbol='dot')))

rawDescription: Use a symbol for multiplication operator in sympy output in ipython notebook


rawDescription: input of a tuple on the command line and assigning it to a tuple

description: Input of a tuple on the command line and assigning it to a tuple


rawDescription: Pandas cumulative function of series with dates and NaT


code:
for i in XLE.index :
    XLE [ 'time' ][ i ]= datetime.strptime ( XLE [ 'time' ][ i], '%Y%m%dT%H%M%S')
XLE.index = XLE [ ' time ' ]; del XLE [ 'time']

rawDescription: How to reindex csv data efficiently?

description: Reindex csv data efficiently


code:
def location_title(sender, instance, created, **kwargs):
    # Don't fire up on updates.
    if not created:
        return

    # Only handle new superusers.
    if not instance.is_superuser or not instance.is_active:
        return

    # Create a `Location` entry for new superuser.
    l = Location(user_id=instance.pk)
    l.save()

post_save.connect(location_title, sender=User)

rawDescription: create row of date while creating superuser

description: Create row of date while creating superuser


code:
import subprocess
def get_pname(id):
    p = subprocess.Popen(["ps -o cmd= {}".format(id)], stdout=subprocess.PIPE, shell=True)
    return str(p.communicate()[0])
name = get_pname(1)
print(name)

rawDescription: How to get the process name by pid in Linux using Python?

description: Get the process name by pid in Linux using Python


code:
p = models.Person.query.get(3)
u = models.User(person=p, email="example@example.com")
u.set_password('password')
db.session.add(u)
db.session.commit()

rawDescription: How do I create a child class from a parent class in SQLAlchemy's Joined Table Inheritance?

description: Create a child class from a parent class in SQLAlchemy's Joined Table Inheritance


code:
import logging
import logging.config

logging.config.fileConfig('path_to_logging.conf')
logger = logging.getLogger()

if __name__ == '__main__':
    logger.info("logger")
    print("print")

rawDescription: Logger.info never outputs

description: Logger.info never outputs


code:
for row in xrange(rows - 2):
    self.neurons.append([Neuron(parents=self.neurons[-1] + [self.bias]) for output in xrange(outputs)])

rawDescription: What caused my ANN to take drastically less time to run?


code:
x = {
    'date': this_date.copy(),
    'read': False
    }

rawDescription: Odd Behaviour of Loop in Python

description: Odd Behaviour of Loop in Python


code: list_name.sort(key=lambda x: (-x[2],) + x[:2])

rawDescription: Organize Numerically Descending then Alphabetically Ascending by Different Elements in a List Python


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

plt.figure()
a = [1,2,5,6,9,11,15,17,18]
plt.hlines(1,1,20)  # Draw a horizontal line
plt.eventplot(a, orientation='horizontal', colors='b')
plt.axis('off')
plt.show()

rawDescription: 1D plot matplotlib

description: 1D plot matplotlib


code:
import pandas as pd
import numpy as np

def bollinger_bands(s, k=2, n=20):
    """get_bollinger_bands DataFrame
    s is series of values
    k is multiple of standard deviations
    n is rolling window
    """

    b = pd.concat([s, s.rolling(n).agg([np.mean, np.std])], axis=1)
    b['upper'] = b['mean'] + b['std'] * k
    b['lower'] = b['mean'] - b['std'] * k

    return b.drop('std', axis=1)

rawDescription: python panda to calculate rolling means

description: Python panda to calculate rolling means


code: t = (group.sort_index(ascending=True) for key, group in grouped.iteritems())

rawDescription: Extracting data from generator object

description: Extracting data from generator object


code:
import collections
from os.path import basename, splitext

x = collections.OrderedDict((e, i) for i, e in enumerate(x))

id_list = [j[0] for j in sorted(y, key=lambda e: x[splitext(basename(e[1]))[0]])]

rawDescription: fast ordered sort (and extract from) tuple based on list

description: Fast ordered sort (and extract from) tuple based on list


code:
class DBLogWrapper2(BaseWrapper):

    def __init__(self, instance, methods):
        super(DBLogWrapper, self).__init__(instance)

        self._methods = methods

    def __getattr__(self, attr):
        if attr not in methods:
            return getattr(self._instance, attr)

        def f(*args, **kwargs):
            return self.timed_method(getattr(self._item, attr),
                                     *args, **kwargs)
        return f

    def timed_method(method, *args, **kwargs):
        begin = datetime.datetime.now()
        return_val = method(*args, **kwargs)
        end = datetime.datetime.now()

        trace = traceback.format_stack()

        db_log(name,
            begin,
            end,
            info={
                'args': args,
                'kwargs': kwargs,
                'trace': trace
            }
        )
        return return_val

rawDescription: How to wrap python instance methods at runtime

description: Wrap python instance methods at runtime


code: df = df.merge(temp_df, on='Request', how='left')

rawDescription: Map string values in a Pandas Dataframe with integers


code:
i = randint(0, len(reduced_list) - 1) #get any valid index. -1 is needed because randint upperbound is inclusive
last5.append(reduced_list[i]) #the number is as what it pointed by the index: reduced_list[i], append that number to the last 5 list

rawDescription: Generate random numbers without using the last n values in Python


code:
import csv
from collections import defaultdict

with open("in.csv") as f, open("average.csv", "w") as out:
    wr = csv.writer(out)
    d = defaultdict(list)
    head = next(f)
    out.write(head)
    for row in csv.reader(f):
        d[tuple(row[:2])].append(int(row[-1]))

    for k, v in d.items():
        out.write("{},{},{}\n".format(k[0], k[1], sum(v, 0.0) / len(v)))

rawDescription: Using python, I need to average value based on two keys in two columns from a CSV file


code:
from itertools import dropwhile, izip_longest

def remove_common_prefix(*parts):
    # always leaves a last common element in place
    zipped = izip_longest(*(p[:-1] for p in parts), fillvalue=None)
    stripped = dropwhile(lambda v: len(set(v)) == 1, zipped)
    res = [filter(None, part) + (old[-1],) for part, old in zip(zip(*stripped), parts)]
    # filtered everything away? Then return just the last parts
    return res or [p[-1:] for p in parts]

def shorten_hostnames(machines):
    # edge-case; faster to just return the first part
    if len(machines) == 1:
        return {k: v.split('.', 1)[0] for k, v in machines.items()}
    keys, values = zip(*machines.items())  # for easier processing and re-assembling
    parts = remove_common_prefix(*(v.split('.')[::-1] for v in values))
    parts = remove_common_prefix(*(part[::-1] for part in parts))
    return {k: '.'.join(v) for k, v in zip(keys, parts)}

rawDescription: Remove common elements of hostnames (shorten hostnames) - DRY


code:
html = DIV(TABLE(THEAD(TR(TH('Row #'), TH('Col 1'), TH('Col 2'), TH('Col 3')), _id=0),
                 *[TR(response) for response in response_results],
                 _id='records_table', _class='table table-bordered'),
           _class='table-responsive')

rawDescription: Web2Py - using starred expression for rendering HTML table


code: db.test.update({ "ghi" : "jkl" }, { "ghio" : "jkl", "date" : datetime.today() })

rawDescription: MongoDb update by replacing the document while using update operation ($currentDate)[pymongo]


rawDescription: Pycharm and sys.argv arguments

description: Pycharm and sys.argv arguments


code: rgb = numpy.mean(np_pix)

rawDescription: Python: Iterate over a sub-2d (nested) array to calculate its sum


code:
from numpy import loadtxt
from scipy.sparse import coo_matrix
i,j,value=loadtxt('foobar.txt').T
m=coo_matrix((value,(i,j)))
print(m.todense())

rawDescription: MATLAB spconvert in Python

description: MATLAB spconvert in Python


code: str1 = str1.lstrip(' -')

rawDescription: pythonic way to replace special char at beginning or at the end of string

description: Pythonic way to replace special char at beginning or at the end of string


code:
l=[[int(i) if i.isdigit() else i for i in coor] for coor in re.findall(r'\((.*),(.*)\)',s)]
l[0]
l[0][0]

rawDescription: Using Python Regex to Separate a Coordinate Pair into X and Y Commponents


code: data = np.array([np.arange(10)]*3).T

rawDescription: Creating an empty Pandas DataFrame, then filling it?


code:
edges, weights = [], []
for line in open("input_file.txt"):
    u, v, weight = line.split()
    edges.append((int(u), int(v)))
    weights.append(float(weight))
g = Graph(edges, edge_attrs={"weight": weights})

rawDescription: Using igraph for read 'ncol' format while preserving labels


code:
#!/usr/bin/python3

def do_multiply(a, b):
    c = 0
    for i in range(0, a):
        c += b
    return c

rawDescription: Call python script from c++ without loading the file each time


code:
np.get_printoptions()
np.set_printoptions(precision = 17)
x

rawDescription: Numpy loadtxt rounding off numbers

description: Numpy loadtxt rounding off numbers


code:
nums = pd.Series(raw_data.split(), dtype=int)
ncut = pd.cut(nums, [0, 60, 70, 80, 90, 100])
d = ncut.describe()
d

rawDescription: how to use pandas.cut to group my data?

description: Use pandas.cut to group my data


code: Angle(angles_quantity).wrap_at('360d').value # This returns a simple ndarray again.

rawDescription: How to covert np.ndarray into astropy.coordinates.Angle class?

description: Covert np.ndarray into astropy.coordinates.Angle class


code:
my_list = [1, 2, 3, 4, 27]
def swap(l,n):
    ln = len(l)
    ind = my_list.index(n)
    l[ind], l[(ind + 1)% ln] = l[(ind + 1) % ln], l[ind]

rawDescription: moving elements in a list of Python

description: Moving elements in a list of Python


code:
import tarfile
tfile = tarfile.open("myfile.tar.gz", "r:gz")
# do stuff
tfile.close()

rawDescription: How do I import a file type .1.tar.gz into Python?

description: Import a file type .1.tar.gz into Python


rawDescription: Is it possible to make multiple instances of serial.Serial() in pyserial?


code:
output = subprocess.check_output('csvstat --count --c "col1" myfile.csv')
output = output.decode('ascii')  # Python 3: Convert from bytes to unicode
output = output.split()
result = output[-1]        # keep last word: the count
print(result)

rawDescription: Python subprocess access result in script


rawDescription: Regex one-liner for matching only what comes after a certain word?


code: wts = set(WrappedThingy(thingy) for thingy in thingies)

rawDescription: Custom comparison functions for built-in types in Python


code:
#file test.py
myvariable = 5  #myvariable has module-level scope

def func():
    x = 3  # x has "local" or function level scope.

rawDescription: In Python what is a global statement?

description: In Python what is a global statement


code:
x = np.random.random((1,10))
x
y = np.random.random((10))
y
idx = np.argsort(x)
idx
xsorted= x[idx]
xsorted
ysordedbyx = y[idx]
ysordedbyx

rawDescription: Sorting an Array Alongside a 2d Array

description: Sorting an Array Alongside a 2d Array


code: CONSTANT_NAME = None

rawDescription: Set global constant cross all the view

description: Set global constant cross all the view


code:
# content of: tox.ini , put in same dir as setup.py
[tox]
envlist = py26,py27
[testenv]
deps=pytest       # install pytest in the venvs
commands=py.test  # or 'nosetests' or ...

rawDescription: How to add a bootstrap script to tox's virtualenv?

description: Add a bootstrap script to tox's virtualenv


code:
from sklearn.feature_extraction.text import CountVectorizer

texts=["dog cat fish","dog cat cat","fish bird", 'bird']
cv = CountVectorizer()
cv_fit=cv.fit_transform(texts)

print(cv.get_feature_names())
print(cv_fit.toarray())
#['bird', 'cat', 'dog', 'fish']
#[[0 1 1 1]
# [0 2 1 0]
# [1 0 0 1]
# [1 0 0 0]]

rawDescription: Scikit Learn CountVectorizer

description: Scikit Learn CountVectorizer


code:
sum(generate() for i in range(1000000))
sum(generate() for i in range(1000000))
sum(generate() for i in range(1000000))
sum(generate() for i in range(1000000))
sum(generate() for i in range(1000000))

rawDescription: Python - modelling probability

description: Python - modelling probability


code:
class MySubProcess(multiprocessing.Process):
    def __init__(self, *args, **kwargs):
        super().__init__(self)
        # some more specific setup for your class using args/kwargs
    def run(self):
        # here's the code that is going to be run as a forked process
        pass

rawDescription: Python3 from Thread class to Process

description: Python3 from Thread class to Process


code:
success_codes = list(range(200, 300))
retry_code    = list(range(400, 405)) + list(range(500, 504))
fail_codes    = list(range(504, 507))

rawDescription: Python Integer for loop 200 to 205

description: Python Integer for loop 200 to 205


code:
c = DictControl()
c.word = 0x1234
hex(c['device_control'])
c['device_read_permissions'] = 0xFF
c.low
c.high = 0xAA
c['device_write_permissions']
hex(c.word)

rawDescription: Creating pythonic objects that share memory


code:
import re
s = "FEFEWFSTARTFFFPENDDCDCSTARTDOINVOIJHSDFDONEDFOIER"
re.findall("START.*?(?:END|DONE|NOMORE)", s)

rawDescription: Slicing by start and stop string values in Python


code:
result_list = [method(j) for j in some_list]
sums = tuple(sum(grouped) for grouped in zip(*result_list))

rawDescription: Most pythonic way to 'or' tuples?

description: Most pythonic way to 'or' tuples


code:
i = 0
"%" + str(i)
args[i]
s.replace("%" + str(i), args[i])

rawDescription: Replace % followed by a number in a string


code:
# session.py
import page
class Session(object):
    def __init__(self):
        self.page_list = []
    def addPage(self, url):
        self.page_list.append(page.Page(self, url))

# page.py
class Page(object):
    def __init__(self, session, url):
        self.session = session
        self.url = url

rawDescription: Way to alter behavior based on caller using property getter without reflection or making caller a member in Python


code:
def identity(obj):
    return obj

rawDescription: Is it possible to suppress Python's escape sequence processing on a given string without using the raw specifier?


code:
# This will break.
@logged(lambda: "Just for fun")
def some_function(x):
    pass

rawDescription: Python decorator optional argument

description: Python decorator optional argument


code:
def select_distinct(dictionaries, keys):
  seen = set()
  for d in dictionaries:
    v = tuple(d[k] for k in keys)
    if v in seen: continue
    yield v
    seen.add(v)

rawDescription: Implementing "select distinct ... from ..." over a list of Python dictionaries


rawDescription: How do I do this type of 2D "fancy" indexing without python loops?

description: Do this type of 2D "fancy" indexing without python loops


code: count = len(l)

rawDescription: trying to count down from a number, not working

description: Trying to count down from a number, not working


code:
['instancename', 'instancename2']
['US', 'US2']
['Active', 'Active']

rawDescription: Parsing nested XML with ElementTree

description: Parsing nested XML with ElementTree


rawDescription: Python Pandas Dataframe - remove data from dataframe if indexed date is older than a certain date


code:
data = [
    ('user_name', "Adam 'Adi' Bobek"), ('user_age', 23), ('person_name', "Jurek 'Jerry' Jimowski") ,('person_age', 28),
    ]
data = dict(data)
cols = ",".join(data.keys())
qmarks = ','.join(['?' for s in data.keys()])
values = [v for v in data.values()]
insert_statement = "INSERT INTO users (%s) VALUES (%s);" % (cols, qmarks)

import pyodbc
connection = pyodbc.connect('DSN=pglocal')
cursor = connection.cursor()
cursor.execute(insert_statement, values)
connection.commit()

rawDescription: How can in insert tuple data with python in postgres


code:
from scipy.ndimage import uniform_filter1d
test_mean2 = uniform_filter1d(test, 4, axis=0)

rawDescription: Python - Avarage values of numpy multidimensionnal array every specific time


code:
import re
string = "ts0060_LOD-70234_lr2_billboards_rgba_over_s3d_lf_v5_2Kdciufa_lnh"
re.findall(r"(?<![\da-z])[a-z]+(?![\da-z])", string.lower())

rawDescription: Finding letters in string, not followed by a number... possibly using RE?


code:
import numpy as np
import matplotlib.nxutils
import scipy.spatial

def find_convex_hull(points):
  triangulation = scipy.spatial.Delaunay(points)
  unordered = list(triangulation.convex_hull)
  ordered = list(unordered.pop(0))
  while len(unordered) > 0:
    next = (i for i, seg in enumerate(unordered) if ordered[-1] in seg).next()
    ordered += [point for point in unordered.pop(next) if point != ordered[-1]]
  return points[ordered]

rawDescription: Finding a partial or complete inclusion of a set of points in convex hull of other set of points in 2D in python


code:
from django.template import RequestContext
def my_view(request):
    #request stuff
    return render_to_response("mytemplate.html", {'extra context': None,}, context_instance=RequestContext(request))

rawDescription: What django resolve_variable do? (template.Variable)


rawDescription: Split Vector 3D Array Based on Z Value ~ Python


rawDescription: How and when to appropriately use weakref in Python


code:
file = open('testfile.txt')
it1 = iter(file)
it2 = iter(file)
id(it1)
id(it2)
id(file)

rawDescription: Finding words that are the reverse of each other in a file


code:
bot = num & 0x1fff
bin(bot)

rawDescription: Trouble with bit manipulation in python

description: Trouble with bit manipulation in python


code:
_balance = 4711

def get_balance():
    return _balance

def set_balance(new_balance):
    _balance = new_balance

rawDescription: How do I import and change a value from one script to another in python?

description: Import and change a value from one script to another in python


code:
import operator
return_queryset = model_name.objects(filter(reduce(operator.or_,
    (Q(Column_name=name) for name in request.POST.getlist('Column_name')))))

rawDescription: How can MultipleChoiceField be used with or querys in django?


code:
import cv2
import numpy as np

camera = cv2.VideoCapture(0)
(grabbed, frame) = camera.read()

def check(px):
    R, G, B = px
    return ( ((R > 95) and (G > 40) and (B > 20))
        and ((max(px)-min(px))>15) and (abs(R - G) > 15) and
        (R > G) and (R > B))

def check2(px):
    R, G, B = px
    return ((R >220) and (G > 210) and (B > 170) and
        (abs(R - G) <= 15) and (R > B) and (G > B))

def iterate_over_list(img):  # your method
    img = img.tolist()
    skinmask =  [[(1 if (check(px) or check2(px)) else 0) for px in row] for row in img]
    return skinmask

rawDescription: Select complex colour range for skin-colour detection in OpenCV with Python


rawDescription: How can I add a python tuple to a YAML file using pyYAML?

description: Add a python tuple to a YAML file using pyYAML


code:
def cache_w_keyfunc(keyfunc):
    def real_decorator(func):
        func.cache = {}
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # Create the key now out of the wrapped function's name and the given keys:
            key = (func.__name__, keyfunc(*args, **kwargs))
            try:
                return func.cache[cache_key]
            except KeyError:
                value = func(*args, **kwargs)
                func.cache.set(cache_key, value)
                return value
        return wrapper
    return real_decorator

rawDescription: python decorator parameter using variable from function its wrapping

description: Python decorator parameter using variable from function its wrapping


rawDescription: Scipy.misc.imread flatten argument -- converting to grey scale


code:
set1 = set(item for d in myList for item in d.items())
set2 = set(item for d in myNewList for item in d.items())

rawDescription: Python Check Duplicate in Array

description: Python Check Duplicate in Array


code:
pix = QtGui.QPixmap(widget.size())
widget.render(pix)
pix.save("save.png")

rawDescription: How to make a snapshot of a specific huge PyQt window?

description: Make a snapshot of a specific huge PyQt window


code:
import ast
import json

with open('file.txt') as f:
    contents = f.read()
contents = ast.literal_eval(contents)  # parses the string as if it were a Pytnon literal (which it is)

with open('file.txt', 'w') as f:
    json.dump(contents, f)  # write back as JSON this time

rawDescription: how do i find and replace items in a text file in pyscripter?

description: Find and replace items in a text file in pyscripter


code:
from PyQt4 import QtCore, QtGui

class CustomButton(QtGui.QPushButton):

    left_clicked= QtCore.pyqtSignal(int)
    right_clicked = QtCore.pyqtSignal(int)

    def __init__(self, *args, **kwargs):
        QtGui.QPushButton.__init__(self, *args, **kwargs)
        self.timer = QtCore.QTimer()
        self.timer.setInterval(250)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.timeout)
        self.left_click_count = self.right_click_count = 0

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.left_click_count += 1
            if not self.timer.isActive():
                self.timer.start()
        if event.button() == QtCore.Qt.RightButton:
            self.right_click_count += 1
            if not self.timer.isActive():
                self.timer.start()

    def timeout(self):
        if self.left_click_count >= self.right_click_count:
            self.left_clicked.emit(self.left_click_count)
        else:
            self.right_clicked.emit(self.right_click_count)
        self.left_click_count = self.right_click_count = 0

class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        self.button1 = CustomButton("Button 1")
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.button1)
        self.setLayout(hbox)
        self.button1.left_clicked[int].connect(self.left_click)
        self.button1.right_clicked[int].connect(self.right_click)

    def left_click(self, nb):
        if nb == 1: print('Single left click')
        else: print('Double left click')

    def right_click(self, nb):
        if nb == 1: print('Single right click')
        else: print('Double right click')

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = MyDialog()
    w.show()
    sys.exit(app.exec_())

rawDescription: Pyqt Mouse MouseButtonDblClick event

description: Pyqt Mouse MouseButtonDblClick event


code:
#!/usr/bin/env python

from distutils.core import setup
from distutils.extension import Extension

setup(name="PackageName",
    ext_modules=[
        Extension("hello", ["hellomodule.cpp"],
        libraries = ["boost_python"])
    ])

rawDescription: How to print to Python terminal with Boost::Python

description: Print to Python terminal with Boost::Python


code:
from collections import Counter

dict1 = {1:[ "red","blue","green"], 2: ["blue","blue","red"]}

weight = {1: 2, 2: 20}

score = 0

for k,v in dict1.iteritems():
    score += weight[k] * Counter(v)["red"] * Counter(v)["blue"]

rawDescription: efficiently do weighted count the elements in the list

description: Efficiently do weighted count the elements in the list


code:
import tkinter

app = tkinter.Tk()

# Create a set for all clicked buttons (set prevents duplication)
clicked = set()
# Create a tuple of words (your 180 verb goes here)
words = 'hello', 'world', 'foo', 'bar', 'baz', 'egg', 'spam', 'ham'

# Button creator function
def create_buttons( words ):
    # Create a button for each word
    for word in words:
        # Add text and functionality to button and we are using a lambda
        # anonymous function here, but you can create a normal 'def' function
        # and pass it as 'command' argument
        button = tkinter.Button( app,
                                 text=word,
                                 command=lambda w=word: clicked.add(w) )
        # If you have 180 buttons, you should consider using the grid()
        # layout instead of pack() but for simplicity I used this one for demo
        button.pack()

# For demo purpose I binded the space bar, when ever
# you hit it, the app will print you out the 'clicked' set
app.bind('<space>', lambda e: print( *clicked ))

# This call creates the buttons
create_buttons( words )

# Now we enter to event loop -> the program is running
app.mainloop()

rawDescription: Creating buttons dependent on input, getting user data


code:
first_price = 100
list_length = 20

def price_formula(previous_price):
    return previous_price * 1.2  # you would replace this with your actual calculation

prices = [first_price]  # create list with initial item
for i in range(list_length):  # repeats exactly 'list_length' times, turn number is 'i'
    prices.append(price_formula(prices[-1]))  # append new price to list
    # prices[-1] always returns the last element of the list, i.e. the previously added one.

print("\n".join(map(str, prices)))

rawDescription: Python: How to create a function that uses its own output and uses an array of random generated numbers


code:
#assume you stored every line of your input as a tuples (eventid, mnbr).
observations = [(20, 1), (26, 1), (12, 2), (14, 2), (15,3 ), (14, 3), (10, 3)]

#then creates an event link dictionary. i.e something that link every event to all its mnbrs
eventLinks = {}

for (eventid, mnbr) in observations :
    #If this event have never been encoutered then create a new entry in links
    if not eventid in eventLinks.keys():
        eventLinks[eventid] = []

    eventLinks[eventid].append(mnbr)

#collect the mnbrs
mnbrs = set([mnbr for (eventid, mnbr) in observations])

#create a member link dictionary. This one link a mnbr to other mnbr linked to it.
mnbrLinks = { mnbr : set() for mnbr in mnbrs }

for mnbrList in eventLinks.values() :
    #add for each mnbr all the mnbr implied in the same event.
    for mnbr in mnbrList:
        mnbrLinks[mnbr] = mnbrLinks[mnbr].union(set(mnbrList))

print(mnbrLinks)

rawDescription: Create adjacency matrix in python from csv dataset


code:
rsync_options = '-axh --delete --delete-excluded'
rsync_args = ['rsync'] + shlex.split(rsync_options) + ['/tmp/1', '/tmp/2']
rsync_args

rawDescription: Python: split and format space separated values in a string to use in subprocess.check_call


code:
def on_resize(self, window):
    width, height = self.get_size()
    self.pixbuf = self.loader.get_pixbuf()
    if float(width) / height > self.dimension:
        self.pixbuf = self.pixbuf.scale_simple(
            self.dimension * height,
            height,
            GdkPixbuf.InterpType.BILINEAR
        )
    else:
        self.pixbuf = self.pixbuf.scale_simple(
            width,
            width / self.dimension,
            GdkPixbuf.InterpType.BILINEAR
        )
    GLib.idle_add(self.image.set_from_pixbuf, self.pixbuf)

rawDescription: pyGtk: Image prevents window resize

description: PyGtk: Image prevents window resize


code:
hash(a) == hash(c)
a == c

rawDescription: Three tiers of equality comparison in Python


rawDescription: How to make a nested dictionary from a list's items?

description: Make a nested dictionary from a list's items


code:
from SendKeys import SendKeys

SendKeys(r"""
    {LWIN}
    {PAUSE .25}
    r
    C:\Tools\Dvb_pid_3_0.exe{ENTER}
    {PAUSE 1}
    1{ENTER}
    {PAUSE 1}
    2{ENTER}
    {PAUSE 1}
    {F3}
    {PAUSE 1}
    {F10}
""")

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


code:
import mock
import socket

class MyClass(object):

    def __init__(self):
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.connect('0.0.0.0', '6767')

with mock.patch('socket.socket'):
    c = MyClass()
    c.tcp_socket.connect.assert_called_with('0.0.0.0', '6767')

rawDescription: mocking a socket connection in Python

description: Mocking a socket connection in Python


code:
from functools import wraps
class Int4(int):
    def __new__(cls, i):
        return super(Int4, cls).__new__(cls, i & 0xf)

def add_special_method(cls, name):
    mname = '__{}__'.format(name)
    @wraps(getattr(cls, mname))
    def convert_to_cls(self, other):
        bound_original = getattr(super(cls, self), mname)
        return type(self)(bound_original(other))
    setattr(cls, mname, convert_to_cls)

for m in ('add', 'sub', 'mul', 'floordiv', 'mod', 'pow',
          'lshift', 'rshift', 'and', 'xor', 'or'):
    add_special_method(Int4, m)
    add_special_method(Int4, 'r' + m)  # reverse operation

x, y = Int4(10), Int4(9)
x + y
x * y

rawDescription: How to emulate 4-bit integer in Python 3?

description: Emulate 4-bit integer in Python 3


code:
if vowels[i] in name:
    count += 1

rawDescription: Counting vowels using nested loop in python


code:
lat = float(request.cookies['lat'])
lon = float(request.cookies['lon'])

rawDescription: Heroku Python: What is the proper way to set and get cookies?


rawDescription: How to parse CSV file and search by item in first column

description: Parse CSV file and search by item in first column


code: func(5, *some_list)

rawDescription: Passing a list of parameters into a Python function


code:
import re
import pandas as pd
def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    def atoi(text):
        return int(text) if text.isdigit() else text

    return [atoi(c) for c in re.split('(\d+)', text)]

columns = ['DIV10', 'DIV11', 'DIV12', 'DIV3', 'DIV4', 'DIV5']
df = pd.DataFrame([[1]*len(columns)], columns=columns)
print(df)
#    DIV10  DIV11  DIV12  DIV3  DIV4  DIV5
# 0      1      1      1     1     1     1

df = df.reindex(columns=sorted(df.columns, key=natural_keys))
print(df)

rawDescription: Sorting columns in pandas dataframe

description: Sorting columns in pandas dataframe


code:
df = pd.DataFrame.from_records(["foobar,"+"bar"])
df
df = pd.DataFrame(["foobar,"+"bar"])
df

rawDescription: Using Pandas to export multiple rows of data to a csv


rawDescription: Python use array axis to select slice

description: Python use array axis to select slice


code:
c = 'f'
chr(ord(c) + 1)

rawDescription: Python code for calculating number of an alphabet


code:
from itertools import repeat, izip

d = dict(izip(doc_uid,repeat(project_name)))

rawDescription: Create dictionary where keys from the list and value is common


code: def typecheck(obj): return hasattr(obj, '__iter__') and not isinstance(obj, str)

rawDescription: Type checking: an iterable type that is not a string


code:
mask = ~np.any(np.isnan(x), axis=1)
x = x[mask]
y = y[mask]

rawDescription: Remove NaN row from X array and also the corresponding row in Y


code:
with open("data.txt") as file:
    for index, line in enumerate(file):
        if index == 2: # looking for third line (0-based indexes)
            # do stuff with this line
            break # no need to go on

rawDescription: Python readline() on the Mac

description: Python readline() on the Mac


code: from registration.backends.default.views import RegistrationView

rawDescription: How to over-ride default registration form in Django-Registration version 1.0?

description: Over-ride default registration form in Django-Registration version 1.0


code:
import re
pat = re.compile(r'\s(?=[A-Z])|,')
pat.split(my_str)

rawDescription: Using the .split() function based on conditions?


code:
import re
import types

CONST_VARS = re.compile(r'[A-Z]+[_A-Z]*')

# Configuration primitives that allow for dynamic
# variable compilation for default/local/dev/etc settings files.
class ConfigType(type):
    def __init__(cls, name, bases, odict):
        if not hasattr(cls, 'vars'):
            cls.vars = {}
        reg_vars = filter(lambda x: CONST_VARS.match(x[0]), odict.items())
        for k, v in reg_vars:
            cls.vars[k] = v
            delattr(cls, k)
        super(ConfigType, cls).__init__(name, bases, cls.vars)

class Configuration(object):
    __metaclass__ = ConfigType

    def __init__(self):
        pass
    def __setattr__(self, key, value):
        self.vars[key] = value
    def __getattr__(self, item):
        ret = self.vars.get(item)
        if isinstance(ret, types.FunctionType):
            return ret(self)
        return ret
    def as_module(self):
        mod_vars = {}
        for k, v in self.vars.items():
            if isinstance(v, types.FunctionType) and callable(v):
                v = v(self)
            mod_vars[k] = v
        return type('Configuration', (object,), mod_vars)

rawDescription: How to implement compound configuration variables, or "module level properties?"

description: Implement compound configuration variables, or "module level properties?"


code: np.reshape(z, nrows+1,ncols)

rawDescription: Reshaping Arrays in Numpy with variables


code:
from scipy import stats

distA = stats.gamma(0.7, scale=50)
distB = stats.gamma(0.5, scale=70)

corrected_quantiles = distB.ppf(distA.cdf(quantiles[1:]))

rawDescription: How can I manipulate the CDF of a sample such that it matches that of a different sample?

description: Manipulate the CDF of a sample such that it matches that of a different sample


code:
from itertools import product
d = {'a':'','b':'2','c':'3'}
poss = [(k,v) if v else (k,) for k,v in d.items()]
list(product(*poss))

rawDescription: Combinations of elements in Dictionary in Python


rawDescription: Convert integer to binary array with suitable padding


code:
import re
p = re.compile(r',?\+\d+_[^,]+')
test_str = "+1223,+12_remove_me,+222,+2223_remove_me"
result = p.sub("", test_str)
print(result)
# => +1223,+222

rawDescription: Regex to remove specific words in python


code:
# Random array of integers
np.allclose(out_loopy,out_vectorized)

rawDescription: python: Sorting a list of lists over a range of elements

description: Python: Sorting a list of lists over a range of elements


rawDescription: How to split string on '/' delimiter but prevent splitting when '/ '  occurs just after ' \ '

description: Split string on '/' delimiter but prevent splitting when '/ '  occurs just after ' \ '


code:
y = Counter(b)
y.update(Counter(a))
y

rawDescription: How to keep my original dict when doing additon of Counter

description: Keep my original dict when doing additon of Counter


rawDescription: How to add column next to Seaborn heat map

description: Add column next to Seaborn heat map


code:
import unicodedata
def eval_unicode(s):
    #sum all the unicode fractions
    u = sum(map(unicodedata.numeric, filter(lambda x: unicodedata.category(x)=="No",s)))
    #eval the regular digits (with optional dot) as a float, or default to 0
    n = float("".join(filter(lambda x:x.isdigit() or x==".", s)) or 0)
    return n+u

rawDescription: How do I calculate the numeric value of a string with unicode components in python?

description: Calculate the numeric value of a string with unicode components in python


code:
def the_function_you_are_looking_for (keys, values):
    return dict (zip (keys, values) )

rawDescription: Obtain a dict from an array of keys and one array of values


code:
# Find how may pixels there are on the x-axis
x_pixels = ax[1].transAxes.transform((1,0)) - ax[1].transAxes.transform((0,0))
# Compute the ratio between the pixel offset and the total amount of pixels
pad_xaxis = pad_pixels/x_pixels[0]

rawDescription: Matplotlib: Adjust legend location/position


code:
class ParsedObject(object):
    def __init__(self, tokens):
        self.tokens = tokens
    def queryString(self):
        '''Abstract method to be overridden in subclasses'''

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


code:
for row in range(HEIGHT):
    for col in range(WIDTH):
        # Now we select the common keys between the stockgrid and the keygrid
        common_keys=[key for key in keygrid[row][col] if key in stockgrid[row][col]]
        # Add one in the common_keys
        for key in common_keys:
            stockgrid[row][col][key]+=1

rawDescription: Retreiving data from a nested deep.copy dictionary made by list comprehension in Python


code:
aList = ['A','B','C','D','E','F','G','H','I','J']
bList = len(aList)
grid = []
aWidth = 10
aHeight = 10

def garden(grid):
    colWidth=5
    print(" "*colWidth,end='') #This is needed as first column does not have a title.
    for j in range(0, bList):
        print(aList[j].center(colWidth), end = '')
    print( )
    for i in range(aWidth):
        if i+1 < 10:
            print(str(i+1).center(colWidth), end='')
        else:
            print(str(i+1).center(colWidth), end='')
        for j in range(aHeight):
                print('-'.center(colWidth), end='')
        else:
            print('\n',end='')

#Main
garden(grid)

rawDescription: Python 3.4.3 Aligning Columns

description: Python 3.4.3 Aligning Columns


code: df

rawDescription: Unpivot/Flatten pandas pivot table into one level index


code: b = a.reshape((3, 4))

rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
def hijack(mapper):
    from types import FunctionType
    def decorator(f):
        globals_ = {k: mapper(v) for k, v in f.__globals__.items()}
        closure_ = f.__closure__
        if closure_:
            closure_ = create_closure(i.cell_contents for i in closure_)
        return (lambda *arg, **kwarg:
                FunctionType(f.__code__, globals_, f.__name__,
                             f.__defaults__, closure_)(*arg, **kwarg))
    return decorator

rawDescription: How to apply a decorator to subroutines in python

description: Apply a decorator to subroutines in python


rawDescription: Getting 2-d array pattern from user inputs in python


code:
def cutoff(threshold, data):
    sortedData = sorted(data, key=lambda x: x[1])
    finalList = filter(lambda x: x[1] < threshold, sortedData)
    return finalList if len(finalList) > 2 else 'No values found'

rawDescription: Pick values only below a certain threshold


code:
class myAudio(object):
    _map = {
        'chunk': 'CHUNK',
        'fmt': 'FORMAT',
        'channels': 'CHANNELS',
        'rate': 'RATE',
        'record_seconds': 'RECORD_SECONDS',
    }

    def __init__(self, chunk=1024, fmt=pyaudio.paInt16, channels=1, rate=41000, record_seconds=5):
        self.p = pyaudio.PyAudio()
        self.CHUNK = chunk
        self.FORMAT = fmt
        self.CHANNELS = channels
        self.RATE = rate
        self.RECORD_SECONDS = record_seconds

    def openTheMic(self, **kwargs):
        for (k,v) in kwargs.iteritems():
            setattr(self, myAudio.__map[k], v)

        stream = self.p.open(
            format = self.FORMAT,
            channels = self.CHANNELS,
            rate = self.RATE,
            input = True,
            output = True,
            frames_per_buffer = self.CHUNK
        )

        print ("***mic is open***")

        for i in range(0, self.RATE / q.CHUNK * self.RECORD_SECONDS):
             data = stream.read(self.CHUNK)

if __name__ == '__main__':
    mic = myAudio()
    mic.openTheMic(record_seconds = 10)

rawDescription: Way to override a class __init__ in python


code:
class TestSomething(unittest.TestCase):
    __test__ = False
    def test_x(self):
        ...

class TestCase1(TestSomething):
    __test__ = True  #must put this
    def setUp(self):
        ...

rawDescription: Python nose test inheritance: load unit test fixtures from subclasses


code: query,result = row[x].strip('(').strip(')').split(", ")

rawDescription: python, Storing and Reading varying dictionary size information in a csv file

description: Python, Storing and Reading varying dictionary size information in a csv file


code:
spanish_question = Translation(id='es', parent=question.key)
spanish_question.text = "¿Te parece una buena idea?"
spanish_question.put()

rawDescription: What would be the appropiate design for storing content in multiple languages in Google App Engine?


code:
import os
import sys

from PyQt4.QtGui import QMainWindow
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QDockWidget
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QRadioButton
from PyQt4.QtGui import QPixmap
from PyQt4 import QtGui
from PyQt4 import QtCore

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.my_widget = QWidget()
        self.setCentralWidget(self.my_widget)

        self.createDockWindows()
        self.createButtons()

        self.show()

    def createDockWindows(self):
        #Here I create two QDockWidget and
        #I add into them a matplotlib figure created in another class

        # I do not have your matplotlib figures, so I've inserted
        # some labels instead.
        self.fig1 = QLabel("Hello")    #This is the matplotlib figure`s class
        self.fig2 = QLabel("World")

        dock1 = QDockWidget()
        dock2 = QDockWidget()

        dock1.setWidget(self.fig1)
        dock2.setWidget(self.fig2)

        self.addDockWidget(0x2, dock1)
        self.addDockWidget(0x2, dock2)

    def createButtons(self):
        #Here i add some buttons
        layout = QVBoxLayout()

        self.r_btn = QRadioButton()
        self.r_btn.setGeometry(10, 50, 10, 30)
        self.r_btn.setText("RadioButton 1")

        ###HERE IS WHERE I NEED TO ADD THE IMAGE FROM THE CREATEIMAGE CLASS###

        self.image = MyImage()

        layout.addWidget(self.r_btn)
        layout.addWidget(self.image)

        self.my_widget.setLayout(layout)

class MyImage(QWidget):

    def __init__(self):
        super(MyImage, self).__init__(parent = None)
        self.mainLayout = QtGui.QHBoxLayout()
        self.setLayout(self.mainLayout)
        self.setPicture()

    def setPicture(self):
        # For some reason, it only works on .png files, not on .jpg files!
        picPath = os.getcwd() + "\someFolder\myImage.png"
        print(picPath) # Check if the path to your picture is correct.
        picMap = QtGui.QPixmap(picPath)

        picLabel = QtGui.QLabel(parent = None)
        picLabel.setGeometry(10,10,800,600)
        picLabel.setPixmap(picMap.scaled(780,580,QtCore.Qt.KeepAspectRatio))
        self.mainLayout.addWidget(picLabel)

if __name__== '__main__':
    app = QtGui.QApplication(sys.argv)
    QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique'))
    myGUI = MainWindow()

    sys.exit(app.exec_())

rawDescription: Insert a Pixmap created in another class


code:
sel  = soup.select('div.participant-logo')
link = sel[0].find("img")["src"]

rawDescription: Extract src in beatifulsoup parser python


rawDescription: In Python, how to sum nested lists: [[1,0], [1,1], [1,0]] → [3,1]


code: [False, False, True]

rawDescription: Flipping the boolean values in a list Python


code:
def start(list_of_entries):
    map((lambda x:func(x.name,x.age)), list_of_entries)

rawDescription: Map/Iterating through List of Python Object


code:
import json
import urllib, urllib2
value = "ajax=1&htd=20131111&pn=p1&htv=l"
req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
response = urllib2.urlopen(req)
json.load(response).keys()
param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'}
value = urllib.urlencode(param)
value
req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
response = urllib2.urlopen(req)
json.load(response).keys()

rawDescription: Curl request in python

description: Curl request in python


code:
for line in proc.stdout:
    print(">>> " + str(line.rstrip()))

rawDescription: Real-time intercepting of stdout from another process in Python


code: a*c + b*d

rawDescription: How to find a point (if any) on quadratic Bezier with a given tangent direction?

description: Find a point (if any) on quadratic Bezier with a given tangent direction


rawDescription: several replacements in single regular expression

description: Several replacements in single regular expression


rawDescription: Get Request Headers for Urllib2.Request?

description: Get Request Headers for Urllib2.Request


code:
seed = 0
for i in range(10):
    seed = (seed * 1664525 + 1013904223) & 0xFFFFFFFF
    print(seed)

rawDescription: Implementing XorShift the same in Java and Python


code:
from bs4 import BeautifulSoup
import requests
from urllib.parse import  urljoin

RegionIDArray = [187147,187323,186338]
museumIDArray = [47,49]
dct = {187147: 'Paris', 187323: 'Berlin', 186338: 'London'}
already_printed = set()

def get_names(soup):
    for item in (a.text for a in soup.select("div.property_title a")):
        if item not in already_printed:
            already_printed.add(item)
            print("POI: {} | Location: {} | Art: Museum ".format(item, dct[reg]))

base = "https://www.tripadvisor.de"
for reg in RegionIDArray:
    r = requests.get("https://www.tripadvisor.de/Attractions-c[47,49]-g{}-oa.html".format(reg))
    soup = BeautifulSoup(r.content)

    # get links to all next pages.
    all_pages = (urljoin(base, a["href"]) for a in soup.select("div.unified.pagination a.pageNum.taLnk")[1:])
    # use helper function to print the names.
    get_names(soup)

    # visit all remaining pages.
    for url in all_pages:
        soup = BeautifulSoup(requests.get(url).content)
        get_names(soup)

rawDescription: Crawl Multiple pages from a website (BeautifulSoup,Requests,Python3)


rawDescription: Index a numpy array with another array

description: Index a numpy array with another array


code:
def Base(object):

    def __init__(self, attr1):
        self.attr1 = attr1

rawDescription: What is the practical use of the keyword super in Python inheritance?


rawDescription: Issue with creating variables on the go in a class in python


code:
def parafac(factors):
    ndims = len(factors)
    request=''
    for temp_dim in range(ndims):
        request+=string.lowercase[temp_dim]+'z,'
    request=request[:-1]+'->'+string.lowercase[:ndims]
    return einsum(request,*factors)

rawDescription: efficiently computing parafac / CP product in numpy

description: Efficiently computing parafac / CP product in numpy


code:
class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
            color == 'red' and emphasis == 'strong' or
            highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

rawDescription: Correct Style for Python Line breaks

description: Correct Style for Python Line breaks


code:
from datetime import date
t = date(2015, 1, 2)
f = date(2015, 2, 2)
t.replace(day=1) < f.replace(day=1)
t.year < f.year or (t.year == f.year and t.month < f.month)
(t.year, t.month) < (f.year, f.month)
t = date(2014, 12, 30)
f = date(2015, 1, 2)
t.replace(day=1) < f.replace(day=1)
t.year < f.year or (t.year == f.year and t.month < f.month)
(t.year, t.month) < (f.year, f.month)

rawDescription: Determine larger month, ignoring the day


code:
import re
[len(re.findall(r"\s", i)) for i in lst]

rawDescription: Finding how many of a certain character in each element in a list


code:
def test_good():
    for i in range(1000):
        print(i)

def test_bad():
    print('this should fail!')
    assert False

rawDescription: How to print to console in Py Test?

description: Print to console in Py Test


rawDescription: Find values in file, between keywords, using python


rawDescription: forcing genfromtxt output to no-vector

description: Forcing genfromtxt output to no-vector


code: [ x for x in dir(yourclass) if (type(x) is types.FunctionType) ]

rawDescription: retrieve non built-in functions in python

description: Retrieve non built-in functions in python


code:
from email.utils import formataddr
addresses = [("John Doe", "john@domain.com"), ("Jane Doe", "jane@domain.com")]
', '.join([formataddr(address) for address in addresses])

rawDescription: How to send Gmail email with multiple CC:'s

description: Send Gmail email with multiple CC:'s


code:
def is_domain(d):
    for suffix in suffixes:
        if d.endswith(suffix):
            # Get the base domain name without suffix
            base_name = d[0:-(suffix.length + 1)]
            # If it contains '.', it's a subdomain.
            if not base_name.contains('.'):
                return true
    # If we get here, no matches were found
    return false

rawDescription: Regex to match Domain.CCTLD

description: Regex to match Domain.CCTLD


rawDescription: How to assign multiple values to one variable

description: Assign multiple values to one variable


code:
def round_robin(n):
    is_even = (n % 2 == 0)
    schedule = []
    d = deque(range(n))
    for i in range(2 * ((n - 1) / 2) + 1):
        schedule.append(
                        [[d[j], d[-j-1]] for j in range(n/2)])
        if is_even:
            d[0], d[-1] = d[-1], d[0]
        d.rotate()
    return schedule

rawDescription: Generating all unique pair permutations

description: Generating all unique pair permutations


rawDescription: Django order_by last week days

description: Django order_by last week days


rawDescription: How can I lookup based on multiple parameters?

description: Lookup based on multiple parameters


rawDescription: Python: How do you call a method when you only have the string name of the method?


rawDescription: Optimize search to find next matching value in a list


code:
dict3 = { catname : [ item for item, itemcat in items.items() if itemcat == cat  ] for cat, catname in categories.items()  }
dict3

rawDescription: How to create a dict from 2 dictionaries in Python?

description: Create a dict from 2 dictionaries in Python


code:
from django.views.generic.detail import DetailView

class FacultyDetail(DetailView):
    model = Faculty
    slug_field = 'faculty_code'

rawDescription: django user queries to get data from database

description: Django user queries to get data from database


rawDescription: Sort list with multiple criteria in python


code:
import struct

response = (0, 0, 117, 143, 6)
struct.unpack(">I", ''.join([chr(x) for x in response[:-1]]))

rawDescription: How do I convert part of a python tuple (byte array) into an integer

description: Convert part of a python tuple (byte array) into an integer


code:
from collections import OrderedDict

results = OrderedDict()

for li in soup.find_all('li'):
    bold = li.b
    if bold is None:
        continue
    results[bold.get_text(strip=True)] = [
        link.get_text(strip=True) for link in li.find_all('a')
    ]

rawDescription: How to get print the content of tags in order in beautifulsoup?

description: Get print the content of tags in order in beautifulsoup


rawDescription: Creating a class signal with pyqt4

description: Creating a class signal with pyqt4


code:
import wikipedia
p = wikipedia.page("Python programming language")
print(p.url)
print(p.title)
content = p.content # Content of page.

rawDescription: Extract the main article text from a Wikipedia page using Python


code:
import logging

def initLogger(level=logging.DEBUG):
    if level == logging.DEBUG:
        # Display more stuff when in a debug mode
        logging.basicConfig(
            format='%(levelname)s-%(module)s:%(lineno)d-%(funcName)s: %(message)s',
            level=level)
    else:
        # Display less stuff for info mode
        logging.basicConfig(format='%(levelname)s: %(message)s', level=level)

rawDescription: Python logging in multiple modules

description: Python logging in multiple modules


code:
class MyIter(object):
    def __init__(self, source):
        self.source = iter(source)
        self.counter = 0

    def next(self):
        self.counter += 1
        return next(self.source)

    def __iter__(self):
        return self

    def tell(self):
        return self.counter

rawDescription: How should I create an iterator that also supports a tell() method?


code: speed = D/(t2-t1)

rawDescription: Find speed of vehicle from images

description: Find speed of vehicle from images


rawDescription: unzipping a file with Python and returning all the directories it creates

description: Unzipping a file with Python and returning all the directories it creates


code: print(self)

rawDescription: call __str__ inside a class? python 3.X

description: Call __str__ inside a class? python 3.X


code: ts

rawDescription: Selecting the first index after a certain timestamp with a pandas TimeSeries


code:
([9, 4] == Dj).all(1)
#>>> array([ True, False, False], dtype=bool)

rawDescription: Python - Uniquely determining which text file an element originated from


rawDescription: Grouping data in a dataframe to produce lists against unique ids in Pandas/Python


code:
image_data = browser.driver.find_element_by_tag_name("img").get_attribute("src")
image_data = image_data[22:]  # getting rid of data:image/png;base64,

fh = open(str(step+1) + '.png', "wb")
fh.write(image_data.decode('base64'))
fh.close()

rawDescription: saving inline image from splinter

description: Saving inline image from splinter


code:
a = ['h','e','l','l','o']
print( ''.join(a) ) # Prints: hello

rawDescription: Python-Unable to convert a list to string


rawDescription: Python: pick appropriate datatype size (int) automatically


code:
self.textPad = ScrolledText(self)
self.textPad.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)

rawDescription: Python Tk display and edit a file

description: Python Tk display and edit a file


code:
@proper

def factors(n):
    return set(reduce(list.__add__,
               ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

rawDescription: Remove a value from a set with a function decorator


rawDescription: Restore __builtins__ to default

description: Restore __builtins__ to default


code:
from fastavro import dump
from io import BytesIO

# A sample schema.
schema = {
  'name': 'Person',
  'type': 'record',
  'fields': [
    {'name': 'name', 'type': 'string'},
    {'name': 'age', 'type': 'int'}
  ]
}

record = {'name': 'Ann', 'age': 23} # Corresponding record.
buf = BytesIO() # Target buffer (any file-like object would work here).
dump(buf, record, schema) # Serialize record into buffer.
message = buf.getvalue() # The raw bytes of your message.

rawDescription: Brutally slow Apache Avro performance in Python, different results when encoding to messages vs. files


rawDescription: Splitting Lists into even places

description: Splitting Lists into even places


code:
for x in [1,2,3]:
    for y in [3,1,4]:
        if x != y:
            yield (x, y)

rawDescription: How to read aloud Python List Comprehensions?

description: Read aloud Python List Comprehensions


code:
one_add = 1 .__add__
one_add(2)

rawDescription: How can I get the addition object for integers?

description: Get the addition object for integers


code:
def Counter_inc(d):
   d['num'] += 1

def Counter_create():
   d = {
      'num': 0,
      'inc': Counter_inc,
   }
   return d

count = Counter_create()
count['inc'](count)

rawDescription: In Python, what is the difference between an object and a dictionary?


rawDescription: Format a number as a string

description: Format a number as a string


code: color = colors[math.trunc(data / step)]

rawDescription: Setting a colour scale in ipython

description: Setting a colour scale in ipython


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)

x = np.random.normal(5, 2, 10000)
y = np.random.normal(2, 1, 3000000)

xweights = 100 * np.ones_like(x) / x.size
yweights = 100 * np.ones_like(y) / y.size

fig, ax = plt.subplots()
ax.hist(x, weights=xweights, color='lightblue', alpha=0.5)
ax.hist(y, weights=yweights, color='salmon', alpha=0.5)

ax.set(title='Histogram Comparison', ylabel='% of Dataset in Bin')
ax.margins(0.05)
ax.set_ylim(bottom=0)
plt.show()

rawDescription: Plot two histograms on the same graph and have their columns sum to 100


code:
def countoverlappingdistinct(pattern, thestring):
  total = 0
  start = 0
  there = re.compile(pattern)
  while True:
    mo = there.search(thestring, start)
    if mo is None: return total
    total += 1
    start = 1 + mo.start()

rawDescription: Find out how many times a regex matches in a string in Python


code:
import csv
reader = csv.reader(open(file, "rb"), dialect="excel") # Python 2.x
# Python 3: reader = csv.reader(open(file, newline=""), dialect="excel")

rawDescription: Python script reading from a csv file

description: Python script reading from a csv file


rawDescription: Insert 0s into 2d array

description: Insert 0s into 2d array


code:
context = get_context()  # whatever
notifier.add_listener(partial(log_event, context))

rawDescription: How does the functools partial work in Python?


code:
a = numpy.array([1, 2, 1.8E308, 1.8E308, 42])
a[a < 1E308] # use whatever threshold you like

rawDescription: how to remove positive infinity from numpy array...if it is already converted to num a number?

description: Remove positive infinity from numpy array...if it is already converted to num a number


code:
mock_data != 0 # boolean array where you measured wind
np.diff(mock_data != 0) # boolean array which has True between no-wind and wind.
np.where(np.diff(mock_data != 0))[0] # array with indexes where it changed
# array([208, 397, 406, 687, 714, 735, 890], dtype=int64)

rawDescription: np.where() not returning expected indices in numpy python

description: Np.where() not returning expected indices in numpy python


code:
import calendar
monthmap = {calendar.month_abbr[i].upper(): '{:02d}'.format(i) for i in range(1, 13)}
monthmap.update({'{:02d}'.format(i):'{:02d}'.format(i) for i in range(1, 13)})
tmp['month'] = tmp['month'].map(monthmap)

rawDescription: Pandas: Change dates in dataframe to same date format


code:
def my_func(a,b):
    result = []
    for i in range(len(b)):
        if a[i] == 5:
            result.append(b[i])
    return np.asarray(result)

rawDescription: Function that extracts value from one array depending on the value of another array


rawDescription: generating list with permuted tuples in a list

description: Generating list with permuted tuples in a list


rawDescription: Dividing a list into two lists

description: Dividing a list into two lists


code:
isinstance(True, bool)
isinstance(1, bool)

rawDescription: Python - Enforce non-occurence of bool in list


code:
# I don't know how you extract name from component so this might be incorrect
maxLength = max(len(component.name) for component in component_list)

rawDescription: How to make specific parts of a text line indented properly?

description: Make specific parts of a text line indented properly


code:
import numpy as np
import math
import numba as nb
n, a, b, c = 500000, 0.0000002, 0.5, 0.4
eps = np.random.normal(0, 1, n)
sigma = np.ones(n) * np.sqrt(a)
r = np.zeros(n)

def initial(n, a, b, c, eps, sigma, r):
    for i in range(1,n):
        sigma[i] = np.sqrt(a + b * r[i-1] ** 2 + c * sigma[i-1] ** 2)
        r[i] = sigma[i] * eps[i]

def normal(n, a, b, c, eps, sigma, r):
    for i in range(1,n):
        sigma[i] = math.sqrt(a + b * r[i-1] ** 2 + c * sigma[i-1] ** 2)
        r[i] = sigma[i] * eps[i]

@nb.njit
def function(n, a, b, c, eps, sigma, r):
    for i in range(1,n):
        sigma[i] = math.sqrt(a + b * r[i-1] ** 2 + c * sigma[i-1] ** 2)
        r[i] = sigma[i] * eps[i]

rawDescription: Optimize this loop with numpy

description: Optimize this loop with numpy


code:
from . import settings # or just 'import settings' on old Python versions
class Helper(object):
      pass

rawDescription: How to import classes defined in __init__.py

description: Import classes defined in __init__.py


code:
import os

from django.conf import settings

def delete_file(path):
    """
    Deletes specified file from uploads.

    Usage:
        delete_file('path/to/file.extension')
    """
    os.remove(os.path.join(settings.MEDIA_ROOT, path))

rawDescription: Django remove image based on id

description: Django remove image based on id


rawDescription: Split array byte string in Python

description: Split array byte string in Python


code: re.split(r" m/| \+ ", yourString)[0]

rawDescription: Python Regex to match and exclude certain content


code:
class BlogPostSerializer(serializer.ModelSerializer):
    # ...
    likes_by_request_user = BlogPostLikesSerializer(many=True)

rawDescription: Django (django-rest-framework) looking for a best practice to find out wether request.user exists in blog.likes


code: ax.view_init(azim=60, elev=30)

rawDescription: 3D plot with Matplotlib

description: 3D plot with Matplotlib


code:
#!/usr/bin/env python

import os
import sys
from os.path import expanduser, join

path = os.environ.get('XDG_CONFIG_HOME')
if not path:
    path = expanduser("~/.config")
else:
    path = expanduser(path)
fn = join(path, 'pianobar', 'nowplaying')

info = sys.stdin.readlines()
cmd = sys.argv[1]

if cmd == 'songstart':
    with open(fn, 'w') as f:
        f.write("".join(info))

rawDescription: How do I retrieve the current song name and time left from pianobar using python?

description: Retrieve the current song name and time left from pianobar using python


code:
class Conversation(models.Model): # there is only one of these for each pair of users who message one another
    user_1 = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="conversations_as_user_1")
    user_2 = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="conversations_as_user_2")
    read_by_user_1 = models.BooleanField(default=False)
    read_by_user_2 = models.BooleanField(default=False)

    class Meta:
        unique_together = (("user_1", "user_2"),)

class Message(TimeTrackable):
    conversation = models.ForeignKey(Conversation, related_name="messages", blank=True, help_text="the conversation between these two users (ALWAYS selected automatically -- leave this blank!)")
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages_sent")
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages_received")
    text = models.TextField() # flat text, NOT bleached or marksafe
    archived_by_sender = models.BooleanField(default=False)
    archived_by_recipient = models.BooleanField(default=False)

rawDescription: Django order_by after distinct(). Or distinct?


code:
"hello world".title()
u"hello world".title()

rawDescription: How to capitalize the first letter of each word in a string (Python)?

description: Capitalize the first letter of each word in a string (Python)


code: ks_summ = "K-S D-value = {}\nK-S p-value = {:.3e}".format(round(ks_D, 3), ks_p)

rawDescription: How to set significant figures in pyplot annotation

description: Set significant figures in pyplot annotation


code:
import networkx as nx
import itertools as IT
G = nx.MultiGraph()
G.add_edges_from([('A', 'B'), ('B', 'C')])

missing = [pair for pair in IT.combinations(G.nodes(), 2)
           if not G.has_edge(*pair)]
print(missing)

rawDescription: List of edges that don't exist in a networkx graph?


code: document.getElementById("datatosendback").value = "OH! Mr KOTER! SEND ME!";

rawDescription: How to submit a javascript variable to the server side

description: Submit a javascript variable to the server side


code:
try:
    for value,label,other in self.choices:
        yield (value, label, other, selected)
except ValueError:
    for value, label in self.choices:
        yield (value, label, None, selected)

rawDescription: Loop with 3 or 2 items to unpack in Python


code:
def arguments_parsed(args):
   if args.datafile:
      load_stuff(args.datafile)

def add_arguments(ap):
   ap.add_argument('--datafile',
         help="Load additional input data")
   ap.add_reaction(arguments_parsed)

rawDescription: How to dynamically add options to optparser?

description: Dynamically add options to optparser


code:
My_dict = {'What is your name?':'Emma','What is your age':34,'What color eyes do you have':'Blue'}

x = iter(My_dict.keys())
for i in range(3):
    print(next (x))

rawDescription: Dictionary Query Python?

description: Dictionary Query Python


code: print(list([x, y] for x, y in zip(a, b)))

rawDescription: Function python list (zip)

description: Function python list (zip)


rawDescription: Why does recursive sequence not work correctly?


code:
segment(word)
str_segment(word)

rawDescription: Read all possible sequential substrings in Python


code:
def JoiningList(list):

    def join(self, iterable):
        new_list = iterable[0]
        for item in iterable[1:]:
            new_list.extend(self)
            new_list.append(item)
        return new_list

rawDescription: Why doesn't [].extend(list1) create an identical list to list1?


code:
for key in stopwords:
    row = row.replace(key, "")

rawDescription: Outputting to csv without stop words

description: Outputting to csv without stop words


code: common_keys = a.viewkeys() & b.viewkeys() & c.viewkeys()

rawDescription: Getting common keys from different dictionaries in python


code:
heights = np.random.randn(8)
sem = .4

for i, (height, color) in enumerate(zip(heights, errorbar_colors)):
    plt.plot([i, i], [height - sem, height + sem], c=color, lw=3)
plt.plot(heights, marker="o", ms=12, color=".3")

rawDescription: cmap to rgba in Matplotlib

description: Cmap to rgba in Matplotlib


code:
result = []
for item1, item2 in zip(list1, list2):
    for s in item2:
        result.append((item1, s))

rawDescription: Python: how to map one list and one list of list together


code:
print(Xtotal[-1])
print(Ytotal[-1])

rawDescription: How to create n lists in function of x python

description: Create n lists in function of x python


code:
bltin_any = any
from numpy import *

bltin_any(i % 3 for i in [3, 3, 4, 4, 3])

rawDescription: How to use a built-in function if its name is used by another module?

description: Use a built-in function if its name is used by another module


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


code:
arr    = df1.values[:,:-2]    # just the numbers
offset = df1.values[:,-1]     # just the offsets
column_pad = 2
arr2 = np.zeros( (arr.shape[0],arr.shape[1]+column_pad) )

rawDescription: Python - Pandas - Dataframe: Row Specific Conditional Column Offset


code:
x = v()
t = ast.parse('d[x] += v[y, x]')
x.visit(t)

rawDescription: Simple example of how to use ast.NodeVisitor?


code:
import pandas as pd

a1 = pd.DataFrame({'group':['x', 'x', 'a', 'a'],
                   'product':['y', 'b', 'b', 'c'],
                   'date':['z1', 'z2', 'z3', 'z4'],
                   'performance':range(1, 5)})
print(a1)

#   date group  performance product
# 0   z1     x            1       y
# 1   z2     x            2       b
# 2   z3     a            3       b
# 3   z4     a            4       c

rawDescription: Consolidate data in numpy arrays

description: Consolidate data in numpy arrays


rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


code:
import xml.etree.ElementTree as ET

root = ET.fromstring(doc)  # doc is a string containing the example file
body = root.find('body')
desired = ' '.join([ET.tostring(c).strip() for c in body.getchildren()])

rawDescription: python element tree xml parsing

description: Python element tree xml parsing


code:
df = MyDataFrameView(data)
df.x()

rawDescription: Dynamically Generating Pandas Views

description: Dynamically Generating Pandas Views


code: other_function(name, phone, some_function(some_string)[0], age)

rawDescription: Pass one element of tuple as argument along with other arguments


code:
data_tuples = []
for row in cursor:
    data_tuples.append(row)

rawDescription: matplotlib: how to prevent x-axis labels from overlapping each other

description: Matplotlib: how to prevent x-axis labels from overlapping each other


rawDescription: Dictionary that counts occurrences of its items


code: {k: paired(v) for k, v in input_dictionary.iteritems()}

rawDescription: Python: calculate value for each pair of values in list


rawDescription: Python - Create an array from columns in file


code:
import pytz
import datetime as dt
import time

eastern = pytz.timezone('US/Eastern')
kolkata = pytz.timezone('Asia/Kolkata')

naive_timetuple = time.localtime(0)
print(naive_timetuple)
# time.struct_time(tm_year=1969, tm_mon=12, tm_mday=31, tm_hour=19, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=365, tm_isdst=0)

rawDescription: How to add two offset in python?

description: Add two offset in python


code:
tst =  {'taste': ('sweet', 'sour', 'juicy', 'melon-like')}
tst.get('taste', ()) #default to () if does not exist.
key_list=['yuck!','tasty','smoothie']
tst['taste'] = tst.get('taste') + tuple(key_list)
tst

rawDescription: Python: Append a list to an existing list assigned to a key in a dictionary?


code:
import collections, itertools

def get_combos(branches):
  rc=collections.defaultdict(list)
  for b in branches:
    rc[b.r,b.c].append(b)
  return itertools.product(*rc.values())

rawDescription: Python Combinatorics, part 2

description: Python Combinatorics, part 2


code:
def quad(a, b, c):
    def __quad(x):
        return a * x**2 + b * x + c

    return __quad

rawDescription: Should I use a class? (Python)

description: Should I use a class? (Python)


rawDescription: python map vs itertools.map: Make the iterator version behave like the former

description: Python map vs itertools.map: Make the iterator version behave like the former


code:
pattern = '|'.join(mylist)
count = frame.a.str.contains(pattern).sum() # will add up True values
count/float(len(mylist))*100

rawDescription: Pandas Dataframe count availability of string in a list


code:
from unittest import TestCase
from unittest.mock import patch
import mock_print_module

import builtins
mock_print_module.print = lambda *args,**kwargs:builtins.print(*args,**kwargs)

class MyTestCase(TestCase):
    @patch("mock_print_module.print",autospec=True)
    def test_something(self,mock_print):
        mock_print_module.print_something()
        mock_print.assert_called_with("print something")

    @patch("builtins.print",autospec=True,side_effect=print)
    def test_somethingelse(self,mock_print):
        mock_print_module.print_something()
        mock_print.assert_called_with("print something")

rawDescription: Mocking print but allow using it in tests


code:
import functools

def hexify(algorithm):
    func = getattr(hashlib, algorithm)
    @functools.wraps(func)
    def hex_func(s):
        return func(s).hexdigest()

    return hex_func

algorithms = dict((name, hexify(name)) for name in hashlib.algorithms)

template.render(salt='3Fd0@5l4x', password='secret', **algorithms)

rawDescription: Use template to construct md5 hash algorithm


rawDescription: Python - how to store lines of numerical values?


code:
from psycopg2 import psycopg1

cur.execute(sql)
res = cur.dictfetchall()

rawDescription: [Openerp]How to make SQL Query with another database user from python code?


code:
def doctree_resolved(app, doctree, docname):
    secnums = app.builder.env.toc_secnumbers
    for node in doctree.traverse(nodes.reference):
        if 'refdocname' in node:
            refdocname = node['refdocname']
            if refdocname in secnums:
                secnum = secnums[refdocname]
                emphnode = node.children[0]
                textnode = emphnode.children[0]

                toclist = app.builder.env.tocs[refdocname]
                anchorname = None
                for refnode in toclist.traverse(nodes.reference):
                    if refnode.astext() == textnode.astext():
                        anchorname = refnode['anchorname']
                if anchorname is None:
                    continue
                linktext = '.'.join(map(str, secnum[anchorname]))
                node.replace(emphnode, nodes.Text(linktext
                    + ' ' + textnode))

rawDescription: Sphinx references to other sections containing section number and section title


code:
import ctypes
import time
import subprocess
import binascii

if __name__ =="__main__":
    response = "Y"

    p = subprocess.Popen("echo.bat", stdin = subprocess.PIPE)
    time.sleep(2)

    p.stdin.write(bytes(response, 'ascii')) #Answer the question
    print("injected string :", response)

rawDescription: How to give input to a batch file using Python script?

description: Give input to a batch file using Python script


code:
class NewLink(models.Model):
    def save(self, *args, **kw):
        self.votetotal = self.upvote + self.downvote
        super(NewLink, self).save(*args, **kw)

rawDescription: Django: How to sum downvote and upvote elements of a model in models.py and not in views.py?


code:
htmlfiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(path)
             for name in files
             if name.endswith((".html", ".htm"))]

rawDescription: Browse files and subfolders in Python

description: Browse files and subfolders in Python


rawDescription: Repeat each values of an array different times


code:
from sympy import solve
from sympy.abc import x, y

e = 2*x+3-y

solve(e,x)
#[y/2 - 3/2]
solve(e,y)
#[2*x + 3]

rawDescription: Algorithm to invert strings of algebraic expressions in Python


code: self.menu.setWindowFlags( QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint )

rawDescription: Python PySide modal Qdialog without OS decoration (title bar, ...)


code: git_branch = 'feature/awesome'

rawDescription: Getting variables from another python file WITHOUT importing


code: factory_two = blank.copy()

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


rawDescription: How to call a distant shell script from a python file?

description: Call a distant shell script from a python file


code:
if a==0:
   action = 0
elif a>1 and b==1:
   action = 1
elif a==1 and b>1:
   action = 2
elif a>1 and b>1:
   action = 3
else:
   action = -1

rawDescription: Refactoring long statement in Python

description: Refactoring long statement in Python


code: page = filehandle.read()

rawDescription: Open URL and place it to a string

description: Open URL and place it to a string


code: join = lambda *args: "/".join(args)

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


rawDescription: sorting a list with objects of a class as its items

description: Sorting a list with objects of a class as its items


code:
from pip.vcs import VcsSupport

req_url = 'git+git://url/repo'
dest_path = '/this/is/the/destination'

vcs = VcsSupport()
vc_type, url = req_url.split('+',1)
backend = vcs.get_backend(vc_type)
if backend:
    vcs_backend = backend(req_url)
    vcs_backend.obtain(dest_path)
else:
    print('Not a repository')

rawDescription: Using pip within a python script

description: Using pip within a python script


rawDescription: How can I append whole columns to a table (list of lists) in python?

description: Append whole columns to a table (list of lists) in python


code:
def Tree():
    return defaultdict(Tree)

rawDescription: Recursive definitions in Python

description: Recursive definitions in Python


code:
for i in soup.select('table'):
    if i.find('th', text = 'Foo'):
        ...
    break

rawDescription: Soup.select, get only first result back

description: Soup.select, get only first result back


code:
data = {"data" : "24.3"}
response = requests.post(url, json=data)

rawDescription: REST post using Python-Request

description: REST post using Python-Request


code:
from itertools import chain
set(chain.from_iterable(expected.itervalues()))

rawDescription: python set comprehension made out of different lists

description: Python set comprehension made out of different lists


rawDescription: Python comparing two massive sets of data in the MOST efficient method possible


code:
import string

params = [filter(lambda x: x in string.printable, item.text)
          for item in row.find_all('td')]

rawDescription: Scaping a table using mechanize & beautiful when some rows contain additional formatting


rawDescription: Reduce a key-value pair into a key-list pair with Apache Spark


rawDescription: Calling "del" on result of Function call results in "SyntaxError: can't delete function call"


code: re.findall('Message: (.+)', s)

rawDescription: How to solve this using regex?

description: Solve this using regex


code:
from functools import partial

def mykeyfunc(column, item):
    return item[column]

sorted(data, key=partial(mykeyfunc, 3))

rawDescription: Built-in sorted() function in Python

description: Built-in sorted() function in Python


rawDescription: How do I convert a Python list of lists of lists into a C array by using ctypes?

description: Convert a Python list of lists of lists into a C array by using ctypes


code:
d1 = {'status': ['online', 'Away', 'Offline'] ,'absent':['yes', 'no', 'half day']}
d2 = {'healthy': ['yes', 'no'], 'insane': ['yes', 'no']}
d1_columns = zip(*d1.values())
d2_columns = zip(*d2.values())
col_groups = [c1+c2 for c1, c2 in itertools.product(d1_columns, d2_columns)]
rows = zip(*col_groups)
combined_keys = list(d1) + list(d2)
d_combined = dict(zip(combined_keys, rows))

rawDescription: Cartesian Product for two dictionaries python


code: print( ' '.join(  '{}'.format(k) for k in lsta+lstb+lstc  ) )

rawDescription: common lisp like format directive to print lists

description: Common lisp like format directive to print lists


rawDescription: base64 encode a JSON for Mixpanel API pixel tracker

description: Base64 encode a JSON for Mixpanel API pixel tracker


code:
from tkinter import Button, Tk, HORIZONTAL

from tkinter.ttk import Progressbar
import time
import threading

class MonApp(Tk):
    def __init__(self):
        super().__init__()

        self.btn = Button(self, text='Traitement', command=self.traitement)
        self.btn.grid(row=0,column=0)
        self.progress = Progressbar(self, orient=HORIZONTAL,length=100,  mode='indeterminate')

    def traitement(self):
        def real_traitement():
            self.progress.grid(row=1,column=0)
            self.progress.start()
            time.sleep(5)
            self.progress.stop()
            self.progress.grid_forget()

            self.btn['state']='normal'

        self.btn['state']='disabled'
        threading.Thread(target=real_traitement).start()

if __name__ == '__main__':

    app = MonApp()
    app.mainloop()

rawDescription: tk gui with progress bar

description: Tk gui with progress bar


code:
with open('numbers.txt') as f:
    numbers = {line.strip() for line in f if line.strip()}

rawDescription: Python merging data in two files

description: Python merging data in two files


rawDescription: how does the python min function works

description: How does the python min function works


code: cur.executemany('INSERT INTO myTable (key, value) VALUES (%s, %s)', mydictionary.items())

rawDescription: Copy_from command to copy values of dictionary in a table


code:
class MyClass(object):
    def __init__(self):
        self.get_config()
        self.validate_config()
        self.hello()
    def get_config(self):
        self.message = "hello"
    def validate_config(self):
        # I'm not claiming this is good practice, just
        # an example of multiple methods that share state
        if not self.message:
            raise Exception()
    def hello(self):
        print(self.message)

if __name__ == "__main__":
    MyClass()

rawDescription: What is the pythonic way to instantiate a program based on a class


code:
def monkeypatched_call(self, field, **kwargs):
    kwargs.setdefault('id', field.id)
    if self.multiple:
        kwargs['multiple'] = True
    html = ['<select %s>' % html_params(name=field.name, **kwargs)]
    for (val, label, selected), (_, methodarg) in zip(field.iter_choices(), field._get_object_list()):
        html.append(self.render_option(val, label, selected, **{'data-mid': methodarg.mid}))
    html.append('</select>')
    return HTMLString(''.join(html))

Select.__call__ = monkeypatched_call

rawDescription: flask-admin form: Constrain Value of Field 2 depending on Value of Field 1

description: Flask-admin form: Constrain Value of Field 2 depending on Value of Field 1


code:
import ast

with open(filename, 'r') as fh:
    for line in fh:
        listobj = ast.literal_eval(line)

rawDescription: Python - How to read lines of lists in a text file directly into lists in python


code:
import dis
dis.dis(compile('s.__contains__(i)', '<>', 'exec'))

rawDescription: python 2.7 writing "x in set" vs "set.__contains__(x)"

description: Python 2.7 writing "x in set" vs "set.__contains__(x)"


code:
from django.db import connection
from excel_response import ExcelResponse

def vw_export_to_Excel(request):
    cursor = connection.cursor()
    cursor.execute("select * from vw_customer")
    return ExcelResponse(cursor.fetchall())

rawDescription: Export RawQuerySet to excel with ExcelResponse. Error "ExcelResponse requires a sequence of sequences"