code: newfoo = foo.preprocess(resize=(100, 100), cutoff=55)

rawDescription: Handling arguments in order for preprocessing in Python, when order matters


code:
class HybridPrimaryKeyRelatedField(serializers.HyperlinkedRelatedField):
    """Serializes out as hyperlink, in as primary key"""
    def to_internal_value(self, data):
        return self.get_queryset().get(pk=data)

rawDescription: Create resource via POST specifying related field ID


code:
import re

def tryint(x):
    try:
        return int(x)
    except ValueError:
        return x

def splittedname(s):
    return tuple(tryint(x) for x in re.split('([0-9]+)', s))

rawDescription: compare two python strings that contain numbers

description: Compare two python strings that contain numbers


code: response = self.client.post('/login', data=dict(name='admine1', email='admine2@gmail.com'))

rawDescription: how can test u=g.user in Flask

description: How can test u=g.user in Flask


code:
trans_tab = {ord(x):None for x in invalid}
s.translate(trans_tab)

rawDescription: Cleanup A String from Most Simply

description: Cleanup A String from Most Simply


code:
import csv
with open("file.txt", "rb") as infile:
    reader = csv.reader(infile, delimiter="\t")
    allData = list(reader)

rawDescription: Read datafile with python to an array

description: Read datafile with python to an array


rawDescription: Transformation of transactions to numpy array


code:
df_p.head()
df_p.tail()

rawDescription: Pivoting a Pandas dataframe with a gapless daterange as index


code: cls

rawDescription: Why isn't the instances variable lost after executing the function?


code:
import os

def deleteAll():
    blacklist = set(['names/of/files/to/be/deleted', 'number/of/files'])
    for fname in (f for f in os.listdir() if f not in blacklist):
        os.remove(fname)

rawDescription: Deleting specific files from a directory


rawDescription: Why is re.findall not being specific in finding triplet items in string. Python


code:
z.ravel()
z.ravel().reshape(2*3, 3)

rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


rawDescription: Zombie SharedDataMiddleware on Python Heroku


rawDescription: Keep QTableView scrolling to the last row when the model is growing


code:
from timeit import timeit
timeit('create_matrix(particle_id=None)', setup='def create_matrix(particle_id=None):\n    if particle_id:\t        return particle_id\n    else: return None', number=10000000)
timeit('create_matrix(particle_id=5)', setup='def create_matrix(particle_id=None):\n    if particle_id:\t        return particle_id\n    else: return None', number=10000000)
timeit('create_matrix(particle_id=5)', setup='def create_matrix(particle_id=None): return None', number=10000000)

rawDescription: Python args and kwargs arguments confusion


code:
import string

class Frame(object):
    """This is a single frame in an animation."""
    def __init__(self, fill=None, color=None):
        """Initializes the frame.

        >>> f = Frame()
        >>> f.print()
        aaaa
        aaaa
        aaaa
        aaaa
        >>> g = Frame(fill='c', color=(0, 255, 0))
        >>> g.print()
        cccc
        cccc
        cccc
        cccc
        """
        if fill is None:
            fill = 'a' # Or whatever default you want
        self.letterGrid = []
        for row in range(4):
            self.letterGrid.append([fill for col in range(4)])

        if color is None:
            color = (0, 0, 0)
        self.colorGrid = []
        for row in range(4):
            self.letterGrid.append([fill for col in range(4)])

    def set_grid(self, row, col, letter=None, color=None):
        """Sets the letter and/or color at the given grid.

        >>> f.set_grid(1, 1, 'b', (255, 0, 0))
        >>> f.print()
        aaaa
        abaa
        aaaa
        aaaa
        >>> f.set_grid(1, 3, letter='x')
        >>> f.print()
        aaaa
        abax
        aaaa
        aaaa
        >>> f.set_grid(3, 3, color=(255, 0, 0))
        """
        if letter is not None:
            self.letterGrid[row][col] = letter
        if color is not None:
            self.colorGrid[row][col] = color

    def position(row, col):
        return (row * 16, col * 16)

    def print(self):
        """Simple routine to print a frame as text."""
        for row in self.letterGrid:
            print(''.join(row))

class Animation(object):
    def __init__(self, frames=None):
        """Initializes an animation."""
        self.frames = frames or []

rawDescription: Python Class / Instance /Object Organization Question


rawDescription: replace with regular expression python

description: Replace with regular expression python


code:
def compute_products(numbers, repeat):
    if repeat == 1:
        yield from numbers
        return
    numbers = tuple(numbers)  # Only needed if you want to handle iterator/generator inputs
    for prod in compute_products(numbers, repeat-1):
        yield from (prod * x for x in numbers)

for prod in compute_products(numbers, n):
    print(prod)

rawDescription: Nest n loops for any n in Python

description: Nest n loops for any n in Python


code:
import csv

with open("test.csv", "r") as ins:
    for row in csv.reader(ins):
        print(sum(map(int, row)))

rawDescription: Import csv into python and sum the row of numbers


code:
masks = np.array([0b11000000, 0b00111000, 0b00000111], dtype=np.uint8)
shifts = np.array([6, 3, 0], dtype=np.uint8)
a
(a.reshape(-1,1) & np.array(masks, dtype=np.uint8)) >> np.array(shifts, dtype=np.uint8)

rawDescription: numpy parse int into bit groupings

description: Numpy parse int into bit groupings


rawDescription: author relation analysis with python

description: Author relation analysis with python


rawDescription: pandas dataframe from a nested dictionary (elasticsearch result)

description: Pandas dataframe from a nested dictionary (elasticsearch result)


code:
Rip = map( lambda x,y: 0 if y == 0 else x, Ri, Rj )
Rjp = map( lambda x,y: 0 if x == 0 else y, Ri, Rj )

rawDescription: Special cosine between scipy sparse matrices


code:
cols = ['col_%i' % (i+1) for i in xrange(7)]
test.set_index(cols, inplace=True)
data.set_index(cols, inplace=True)
tmp = pd.merge(test, data, how='inner', left_index=True, right_index=True)
test.reset_index(inplace=True)
data.reset_index(inplace=True)

rawDescription: Pandas Merge vs. Boolean Indexing

description: Pandas Merge vs. Boolean Indexing


code:
hours = (0 if time_string.split(":")[0] == "000" else int(time_string.split(":")[0].lstrip("0")) * 3600)
mins = (0 if time_string.split(":")[1] == "00" else int(time_string.split(":")[1].lstrip("0")) * 60)
secs = (0 if time_string.split(":")[2] == "00" else int(time_string.split(":")[2].lstrip("0")))

return hours + mins + secs

rawDescription: Python time format with three-digit hour


rawDescription: Panda dataframe conditional .mean() depending on values in certain column


code:
def fdrec(df):
    drec = dict()
    ncols = df.values.shape[1]
    for line in df.values:
        d = drec
        for j, col in enumerate(line[:-1]):
            if not col in d.keys():
                if j != ncols-2:
                    d[col] = {}
                    d = d[col]
                else:
                    d[col] = line[-1]
            else:
                if j!= ncols-2:
                    d = d[col]
    return drec

rawDescription: Pandas convert Dataframe to Nested Json

description: Pandas convert Dataframe to Nested Json


code:
import csv
import dateutil.parser

with open('file.csv') as f:
   reader = csv.reader(f)
   first = dateutil.parser.parse(reader.next()[3])
   for row in reader:
      pass
last = dateutil.parser.parse(row[3])

print('%s - %s' % (first, last))
# OUTPUTS:
# 2015-10-25T18:02:30.798426Z - 2015-10-25T18:02:30.862365Z

rawDescription: How to read head and tail of CSV file with python

description: Read head and tail of CSV file with python


code:
from PyQt5 import QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, databaseFilePath, userFilePath):
        super(MainWindow,self).__init__()
        self.databaseFilePath = databaseFilePath
        self.userFilePath = userFilePath
        self.createUI()

    def changeFilePath(self):
        print('changeFilePath')
        # self.userFilePath = functions_classes.changeFilePath()
        # functions_classes.storeFilePath(self.userFilePath, 1)

    def createUI(self):
        self.setWindowTitle('Equipment Manager 0.3')
        menu = self.menuBar().addMenu('File')
        action = menu.addAction('Change File Path')
        action.triggered.connect(self.changeFilePath)

if __name__ == '__main__':

    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow('some/path', 'some/other/path')
    window.show()
    window.setGeometry(500, 300, 300, 300)
    sys.exit(app.exec_())

rawDescription: I need help making a menu bar in PyQt5

description: I need help making a menu bar in PyQt5


code:
from distutils import sysconfig
sysconfig.get_python_lib()
sysconfig.get_python_inc()

rawDescription: How to find out where the Python include directory is?

description: Find out where the Python include directory is


code: g = df.groupby('key1')

rawDescription: SQL-like window functions in PANDAS: Row Numbering in Python Pandas Dataframe


code:
def drop_rows(date, subject):
    current_subject = subject[0] # changed here
    date_diff = date - date      # timedelta=0, same shape as date
    j = 1
    for i in range(1,len(date)):
        date_diff[i] = date[i] - date[i-j]
        if subject[i] == current_subject:
            if date_diff[i] < pd.Timedelta('365 Days'):
                date_diff.drop(i,inplace=True)
                j += 1
            else:
                j = 1
        else:
            date_diff[i] = pd.Timedelta('0 Days')    # changed here
            current_subject = subject[i]             # changed here
    return date_diff

rawDescription: drop values on datetime difference, with revision

description: Drop values on datetime difference, with revision


code:
def test():
    aList = getItemsAvailable('test')
    print (aList)

rawDescription: Python - Return values from a function

description: Python - Return values from a function


code:
mycounter = Counter([Type1(), Type1(), Type2(), Type2()])
mycounter
mycounter[Type1()]

rawDescription: Make Counter consider two objects of the same class the same


code:
import copy
world2 = copy.deepcopy(world)

rawDescription: List being altered while working on copy in Python 2.7


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

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left', borderpad=1.5, labelspacing=1.5)
plt.show()

rawDescription: How to adjust the size of matplotlib legend box?

description: Adjust the size of matplotlib legend box


rawDescription: SciPy interpolation ValueError: x and y arrays must be equal in length along interpolation axis


rawDescription: Can we republish messages in PUBNUB

description: Can we republish messages in PUBNUB


code:
import pandas as pd
import numpy as np
ser = pd.Series(np.random.normal(size=100))

rawDescription: Plotting CDF of a pandas series in python


code: pd.DataFrame([f.__dict__ for f in allFoo])

rawDescription: python class attributes to pandas dataframe

description: Python class attributes to pandas dataframe


code: return acronym

rawDescription: convert input into acronym in def function?

description: Convert input into acronym in def function


code:
for k in dict.items():
    if k[0] in newdicts:
        if k[1] not in newdicts[k[0]]:  # Do this test before adding.
            newdicts[k[0]].append(k[1])
    else:
        newdicts[k[0]]=[k[1]]

rawDescription: Python remove duplicate value in a combined dictionary's list


code:
## client side
sock.sendall("FILE %s\n")
sock.sendall(fd.read())

...
## server side
# data = read data here
newline = data.find('\n')
assert newline != -1 # some error handling here
header = data[newline]
filename = header[len("FILE "):]
content = data[newline+1:]

rawDescription: Unable to separate file names with file contents in Python socket programming


code:
a = [1+4j, 7+0j, 3+6j, 9+2j, 5+8j]
b = [2+5j, 8+1j, 4+7j, 0+3j, 6+9j]
keyed_a = ((n.real, n) for n in a)
keyed_b = ((n.imag, n) for n in b)
from itertools import chain
sorted_ab = zip(*sorted(chain(keyed_a, keyed_b), key=lambda t: t[0]))[1]
sorted_ab

rawDescription: Iterate over a pair of iterables, sorted by an attribute


code:
import cherrypy

class Root:
    def index(self):
        return "Hello, world!"
    index.exposed = True

class Admin:
    def user(self, name=""):
        return "You asked for user '%s'" % name
    user.exposed = True

class Search:
    def index(self):
        return search_page()
    index.exposed = True

cherrypy.root = Root()
cherrypy.root.admin = Admin()
cherrypy.root.admin.search = Search()

rawDescription: Running more than one class in Cherrypy

description: Running more than one class in Cherrypy


code: data[index] = new_value

rawDescription: What are the pythonic way to replace a specific set element?


code:
from django.db import models

class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, verbose_name, name, **kwargs)
    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)

rawDescription: How to limit the maximum value of a numeric field in a Django model?

description: Limit the maximum value of a numeric field in a Django model


code:
for row in reader:
    countries[row[0]] = Country(row[0], row[1], row[2])

rawDescription: reading file into a dictionary

description: Reading file into a dictionary


code:
class AlternativeName:
    def __init__(self, template, name="alt_name"):
        self.template = template
        self.name = "_" + name

    def __get__(self, instance, klass):
        try:
            return getattr(klass, self.name)
        except AttributeError:
            pass
        alt_name = self.template.format(klass.__name__)
        setattr(klass, self.name, alt_name)
        return alt_name

class Foo:
    alt_name = AlternativeName(template="{}_ending")

print(Foo.alt_name)

rawDescription: How to add or change a Class (not an instance)?

description: Add or change a Class (not an instance)


code:
def remove_empty(fn):
    def filtered(*args, **kwargs):
        return filter(lambda x: x != '', fn(*args, **kwargs))
    return filtered

class WeirdString(str):
    @remove_empty
    def split(self, *args, **kwargs):
        return super(WeirdString, self).split(*args, **kwargs)

'This decorator is unnecessary\n\n\n'.split('\n')
WeirdString('This decorator is unnecessary\n\n\n').split('\n')

rawDescription: Is it possible to apply my own decorators to builtin methods in Python?


code:
import json

data_str = '[53, 2]'

data = json.loads(data_str)

rawDescription: Assign part of a string to a variable [Python]


code:
import random
x = ''.join(i if random.randint(0, 1) else 'b' for i in x)

rawDescription: Replace 50% of characters (randomly) in a String


rawDescription: Reduce array over ranges

description: Reduce array over ranges


code:
lower = 10  # the lower bound for your values
shape = 1   # the distribution shape parameter, also known as `a` or `alpha`
size = 1000 # the size of your sample (number of random values)

rawDescription: How to generate random numbers in specyfic range using pareto distribution in Python

description: Generate random numbers in specyfic range using pareto distribution in Python


code:
my_string
import re
map(int,re.findall("#.* (\d+)\n",my_string))

rawDescription: take only text from a certain line of multi-line Python String

description: Take only text from a certain line of multi-line Python String


code:
dic = {item : []  for item in my_list}
dic

rawDescription: Create new empty lists from items within a Python list?


code: len(reduce(lambda x,y:x+y,ar1))

rawDescription: Using 'for loop' to sum nested list values and return (total of sum)


code: df

rawDescription: Pandas: Convert DataFrame to Mean and Standard Deviation of Each Cell


code:
username = splitted[1].split(", OU")[0]
username

rawDescription: Trying to create a list of users in AD

description: Trying to create a list of users in AD


code: [k for k,v in G.out_degree().iteritems() if v == 0]

rawDescription: How to list specific node/edge in networkx?

description: List specific node/edge in networkx


code:
print(df)
#        Tier  Oct  Nov  Dec
# 0  up to 2M    4    5   10
# 1        5M    3    2    7
# 2       10M    6    0    2
# 3       15M    1    3    5

# select the last two rows
print(df[2:4])
#   Tier  Oct  Nov  Dec
# 2  10M    6    0    2
# 3  15M    1    3    5

# sum over them
print(df[2:4].sum())
# Tier    10M15M
# Oct          7
# Nov          3
# Dec          7
# dtype: object

rawDescription: how to sum over certain row of a data frame in Python

description: Sum over certain row of a data frame in Python


rawDescription: computing rolling averages by integer days in pandas

description: Computing rolling averages by integer days in pandas


code: foo = __import__("foo")

rawDescription: Where does __import__ get alias names from?


code:
s = " id1    id2             id3         id4"
items = s.split()
items

rawDescription: How to replace consecutive spaces in a string in python

description: Replace consecutive spaces in a string in python


code:
from itertools import groupby
lst = ["A","B", "B", "C", "A", "A" ]
['{}-{}'.format(x, i) for k, g in groupby(lst) for i, x in enumerate(g, 1)]

rawDescription: find similar items following each other in a python list

description: Find similar items following each other in a python list


code:
mylist = ['Hometown City Heights', "Height 6'"]
[s for s in mylist if "Height" in s.split()]

rawDescription: Python - Search a list item that contains a string (match case)


rawDescription: pandas rank function yielding non-integers?

description: Pandas rank function yielding non-integers


code:
stars = Series(randint(1, 6, size=100))
vc = stars.value_counts().sort_index()
ax = vc.plot(kind='bar')
fig = ax.get_figure()
fig.autofmt_xdate()

rawDescription: How to create a bar chart/histogram with bar per discrete value?

description: Create a bar chart/histogram with bar per discrete value


code:
class Download(models.Model):
    user = models.OneToOneField('auth.User')  # one to one field limits to one download url per user
    download_url = models.CharField()

rawDescription: Django restrict pages to certain users

description: Django restrict pages to certain users


code: Counter(a for a,_ in spam)

rawDescription: Python - How to count the number of occurrences in a list


code:
forest.setp_param( oob_score    = True,   # set True to be able to read
                   #                      #     oob-samples score
                   random_state = 2015    # set so as to keep retesting
                   #                      #     possible / meaniningfull on
                   #                      #     an otherwise randomised
                   #                      #     learner construction
                   )

rawDescription: Why doesn't my Python RandomForestRegressor accurately predict training set data?


code: stringValue = otherString or defaultString

rawDescription: How can I closely achieve ?: from C++/C# in Python?

description: Closely achieve ?: from C++/C# in Python


code: rand('twister', 5489)

rawDescription: Is it possible to reproduce randn() of MATLAB with NumPy?


code:
start = mystring.find( '(' )
end = mystring.find( ')' )
if start != -1 and end != -1:
  result = mystring[start+1:end]

rawDescription: Remove text between () and [] in python

description: Remove text between () and [] in python


code:
convert_currency(3.50, 'ANG', 'EUR')
convert_currency(1.00, 'USD', 'EUR')

rawDescription: Curency Rate Conversion Wrong Base Currency


rawDescription: Python way of getting max of list containing integers and floats


rawDescription: Use Python to extract Branch Lengths from Newick Format


rawDescription: how to count the amount of sentences in a paragraph in python

description: Count the amount of sentences in a paragraph in python


code: from myapp.models import model_to_import

rawDescription: Django include models.py from project to multiple apps


code:
result = []
old_boundary = segment_boundaries[0]
for boundary in segment_boundaries[1:]:
    bounds = [old_boundary, boundary]
    middle = (old_boundary + boundary) / 2
    ids = [id for id, min, max in orig if min < middle < max]
    result.append(ids)
    result.append(bounds)
    old_boundary = boundary

rawDescription: python array challenge

description: Python array challenge


code:
import types

def comp(source, *args, **kwargs):
    """Compile the source string; takes the same arguments as builtin compile().
    Modifies the resulting code object so that the original source can be
    recovered with decomp()."""
    c = compile(source, *args, **kwargs)
    return types.CodeType(c.co_argcount, c.co_nlocals, c.co_stacksize,
        c.co_flags, c.co_code, c.co_consts + (source,), c.co_names,
        c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno,
        c.co_lnotab, c.co_freevars, c.co_cellvars)

def decomp(code_object):
    return code_object.co_consts[-1]

rawDescription: Reversible version of compile() in Python


code:
import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()
G.add_edges_from([('A','B'),('A','C'),('B','D'),('C','D')])
nx.draw(G)
plt.show()

rawDescription: How do you delete a node in networkx?

description: Delete a node in networkx


rawDescription: Reading and writing CSV files into a data structure suitable for Excel-style column/row manipulations


code:
import lxml.html

html = u'''

English: Ulm, Germany, old town with Münster, city wall and Metzgerturm, as seen from the south bank of the river Danube.

Deutsch: Ulm, Ansicht der Altstadt vom rechten Donauufer aus. Abgebildet ist das Donauschwabenufer, von der Altstadt sind erkennbar: Das dominante Münster mit Hauptturm, Schiff und zwei Chortürmen; unterhalb des Hauptturms des Münsters zwei Giebel, die zur historischen Krone gehören (linker Giebel größtenteils von Bäumen verdeckt); die Spitze der neuen, gläsernen Stadtbibliothek von Gottfried Böhm; weiter rechts zwei Giebel des Rathauses (gelb-braun); am rechten Rand der Metzgerturm als Teil der Stadtbefestigung.

Eesti: Olen loonud selle pildi, kui ma nägin arutelu uue Wiki logo.

English: "Prototype" for new Wiktionary Logo

'''

tree = lxml.html.fromstring(html)
for el in tree.cssselect('td.description p b, td.description span'):
    if el.text_content().startswith('English'):
        print(el.tail.strip())

rawDescription: Get text next to selected element in lxml / Python


code:
elements = {}
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
   # will prompt "Enter Element 1: " on the first iteration
   userInput = raw_input("Enter Element %s" % (i+1, ))
   userInput = userInput.lower()
   elements[userInput] = float(elem_data.get(userInput))

rawDescription: Generating raw_inputs based on user input? [Python]


rawDescription: How to get record numpy array with dates from pandas data frame?

description: Get record numpy array with dates from pandas data frame


code:
data[2] = eval(data[2]);
data[3] = eval(data[3]);

rawDescription: Removing double quotes after json

description: Removing double quotes after json


code:
import copy
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(copy.copy(wM)) # appends a copy to the list
    wM.reset()                      # clears the wM object

rawDescription: Add an object to a python list

description: Add an object to a python list


code:
word = raw_input('Enter a word:')
first = word[0]
first in letter

rawDescription: Checking if a value is equal to any value in an array


code:
def groupIt(digits, output=None):
    if output is None:
        output = []
    if len(digits)>1:
        for z in range(0,len(digits)-1):
            if digits[z]*digits[z+1]>=10:
                toStore=""
                for k in range(0,len(digits)):
                    toStore+=str(digits[k])
                output.append(int(toStore)) # note storage here
            else:
                digits_mod = digits[:]
                digits_mod.append(digits_mod.pop(z+1) * digits_mod.pop(z))
                digits_mod.sort()
                groupIt(digits_mod, output) # note call here
    else:
        return digits[0] # still need this for single digit case
    return min(output)

rawDescription: Python For Loop includes the end of the range


code:
tree = ElementTree.parse(fp)
root = tree.getroot()

target_tag = root.find('myTag')

#collect all text nodes in <myTag> and join
result = ''.join(target_tag.itertext())

print(result)

rawDescription: Xml in python with unbalanced/uneven elements/tags


code:
inner_text
''.join(inner_text)

rawDescription: Get text of HTML tags without text of inner child tags


code: ys = lowess(y, x)[:,1]

rawDescription: How to visualize a nonlinear relationship in a scatter plot

description: Visualize a nonlinear relationship in a scatter plot


code:
def position_of_ngram(words,hyp):
    lenght=len(words)
    for i,sublist in enumerate((hyp[i:i+lenght] for i in range(len(hyp)))):
        if words==sublist:
           return i
    return None

rawDescription: How to find position of an ngram in a sentence?

description: Find position of an ngram in a sentence


code: a = globals().get('b', 0)

rawDescription: Python : How to set a variable to something such as "None" or "0" when there is no value from the request


code:
def fibonacciRecursive(n):
    global recAdd
    if n == 1 or n == 0:
        return n  # <-- should this be return 1?
    else:
        recAdd = recAdd + 1
        return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2)

recAdd = 0
fibonacciRecursive(5)
print(recAdd)

rawDescription: I cannot print the final value of a variable


rawDescription: Removing rows by count from Pandas DataFrame


rawDescription: How do I use ParaView's CSVReader in a Python Script?

description: Use ParaView's CSVReader in a Python Script


code:
from decimal import Decimal

class PurchaseOrder(models.Model):
    # Always use a `DecimalField` when you're dealing with currency!!! `FloatField` and the underlying `float` datatype has it's rounding issues, and currency calculations have to be exact.
    _dollar_amount = models.DecimalField(verbose_name='Total price')

    @property
    def dollar_amount(self):
        if self._dollar_amount is None:
            if self.pk is None:
                # Has never been saved, so we can't do anything to calculate the price here.
                return Decimal(0.0)
            self._dollar_amount = sum(p.price_for_each_item for p in self.product.all())
            self.save(update_fields=['_dollar_amount']) # Or self.save() in Django < v1.5
        return self._dollar_amount

rawDescription: Making an instance of a class equal to a definition Django


code: cube4 = [c for c in (x ** 3 for x in range(1, 11)) if c % 4 == 0]

rawDescription: Is this list comprehension pythonic enough?


code:
out = {}
for e in mylist:
    key = f(e)
    if key not in out:
        out[key] = []
    out[key].append(e)

rawDescription: python : generate sublists depending on the elements values

description: Python : generate sublists depending on the elements values


rawDescription: Mqtt : Publish the last line from a file that is periodically updated


code:
for e in self.emitter:
   e.update()

rawDescription: How to implement a particle engine

description: Implement a particle engine


rawDescription: check if numpy array is subset of another array

description: Check if numpy array is subset of another array


code:
parser.add_argument("-e", nargs=6, metavar=('a', 'b', 'c', 'd', 'e', 'f'),
                        help="my help message", type=float,
                        default=None)

rawDescription: specify list of floats in argparse

description: Specify list of floats in argparse


code:
obj = []
obj = obj or 9000
obj
obj = None
obj = obj or True
obj

rawDescription: How can i omit the redundant words in python condition loop

description: Omit the redundant words in python condition loop


code:
for idx, line in enumerate(fin, start=1):
    if idx == line_number:
        print(line, end='')
        break

rawDescription: Python program prints an extra empty line when reading a text file


code: "".join(chr(x) for x in range(32,127))

rawDescription: Python: How to import ascii characters

description: Python: How to import ascii characters


code:
for row in data:
    row[ 1 ] += "Butter"

rawDescription: make a change to an element within a list within a list

description: Make a change to an element within a list within a list


code:
from itertools import combinations

def compositions(s,k):
    n = len(s)
    for c in combinations(range(1,n),k-1):
        yield [s[i:j] for i,j in zip((0,)+c,c+(n,))]

rawDescription: Create possible combinations of specific size


rawDescription: How can I vectorize the averaging of 2x2 sub-arrays of numpy array?

description: Vectorize the averaging of 2x2 sub-arrays of numpy array


code:
myShape = ShapeFactory.factories[id].create()
myShape.foo = foo
return myShape

rawDescription: Setting class variable during instatiation when using a factory in python


rawDescription: Is there a more vectorized way to perform numpy.outer along an axis?


code:
Key.from_path(kind, id_or_name, parent=none, namespace=None, **kwds)
Key.from_path('Pet', 'Dr Vet')
Key.from_path('Pet', 123)

rawDescription: How to query on ReferenceProperties?

description: Query on ReferenceProperties


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


code:
import xml.etree.ElementTree as ET

# get the root element
tree = ET.parse('some.xml')
root = tree.getroot()

elem = ET.Element('newchild')
elem.text = 'thiscamefromtextfile'
root.append(elem) # append to root or any other node, as you want

tree.write('some.xml')

rawDescription: Modifying XML Files in Python

description: Modifying XML Files in Python


rawDescription: Python matching regex multiple times in a row (not the findall way)


code: for address in ip_range('192.168.1-2.1-12'):  print(address)

rawDescription: Python - Generate a list of IP addresses from user input


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

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


rawDescription: making list of float from list and sub list ,also that list callable in another object

description: Making list of float from list and sub list ,also that list callable in another object


code:
items = list(d.items())
items
items[0]
items[1]

rawDescription: Accessing Items In a ordereddict

description: Accessing Items In a ordereddict


rawDescription: Calling cgi.FieldStorage for an arbitrary url


code: re.findall('(A[^A]+(?=A)?)', s, re.IGNORECASE | re.MULTILINE)

rawDescription: Python regex char pattern group

description: Python regex char pattern group


code: lambda x: x*x(x)

rawDescription: Why do parentheses appear to cause evaluation in Python?


code:
with file("...", 'r') as f:
    for l in f:
        g = generate_tokens(StringIO(l).readline)

rawDescription: USing a Scanner Import

description: USing a Scanner Import


code:
import re
import networkx as nx
from practnlptools.tools import Annotator

rawDescription: How to find the shortest dependency path between two words in Python?

description: Find the shortest dependency path between two words in Python


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

matplotlib.rcParams["text.usetex"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogy(np.linspace(0,5,200), np.exp(np.linspace(-2,3,200)*np.log(10)))
ax.yaxis.set_major_formatter(MyLogFormatter())
fig.savefig("/tmp/shorthyphen.png")

rawDescription: Matplotlib log-scale tick labels, minus sign too long in latex font


rawDescription: How to format axis number format to thousands with a comma in matplotlib

description: Format axis number format to thousands with a comma in matplotlib


code:
def insertionSort(mylist, key=lambda x: x):
    for index in range(1, len(mylist)):
        currentvalue = mylist[index]
        position = index
        while position > 0 and key(mylist[position - 1]) > key(currentvalue):
            mylist[position] = mylist[position - 1]
            position = position - 1
        mylist[position] = currentvalue
    return mylist

rawDescription: How do I insertion sort a list of lists?

description: Insertion sort a list of lists


code:
def my_func(names_addr, num_strs):
    type_char_p = ctypes.POINTER(ctypes.c_char_p)
    names = type_char_p.from_address(names_addr)
    for idx in range(num_strs):
        print(names[idx])

rawDescription: Create PyString from c character array without copying


rawDescription: mean average on the contents of a list

description: Mean average on the contents of a list


code: a.d = {'blah': 'blah'}

rawDescription: Python: Static objects in a class

description: Python: Static objects in a class


code: array([False,  True,  True, False, False], dtype=bool)

rawDescription: Python: Comparing all elements of two arrays and modifying 2nd array


rawDescription: python 2.7 function to convert temprature

description: Python 2.7 function to convert temprature


rawDescription: Formatting multiple datetimes into a string


code: x = mungesomedict(dict(adict, **anotherdict))

rawDescription: How can 2 Python dictionaries become 1?

description: How can 2 Python dictionaries become 1


code:
def split_tags(self):
    alltags =  self.tags.split(', ')
    result = []
    for tag in alltags:
        result.append(urlify(tag))
    return result

rawDescription: Django trying to split and urlify tags in models, but code isn't working


code:
class VisualVertexBuilder(AttributeCollectorBase):
    """Collects some visual properties of a vertex for drawing"""
    _kwds_prefix = "vertex_"
    color = ("red", self.palette.get)
    frame_color = ("black", self.palette.get)
    frame_width = 1.0
    ...

rawDescription: How to use igraph python's metamagic class?

description: Use igraph python's metamagic class


code:
file = open('file.txt', 'rb')
table = [row.strip().split('\t') for row in file]

rawDescription: Loading a file into a numpy array with python


code: [range(1, j+1) for j in c]

rawDescription: PYTHON - Output every possible outcome from a set of multiple choices?


code: fig, ax = plt.subplots()

rawDescription: Why do many examples use "fig, ax = plt.subplots()" in Matplotlib/pyplot/python


code: logger.debug("try to get queued task")

rawDescription: deadlock because of blocking Queue.get() method

description: Deadlock because of blocking Queue.get() method


code: add_params(request, {'abc':'123'})

rawDescription: Make callers use functools.partial or call a factory function?


code: [{"name": name} for name in names]

rawDescription: mapping dictonary a key with multiple values to json in python

description: Mapping dictonary a key with multiple values to json in python


code: punct = [(i, c) for i, c in enumerate(phrase) if not c.isalpha()]

rawDescription: Ignoring noncharacters in cypher text

description: Ignoring noncharacters in cypher text


code:
from pyspark.sql.functions import lit

new_df = old_df.withColumn('new_column', lit(None).cast(StringType()))

rawDescription: Add an empty column to spark DataFrame

description: Add an empty column to spark DataFrame


code: s = gtksheet.Sheet(20, 20, "Sheet 1", entry_type=PastableEntry)

rawDescription: Handling spreadsheet data through the clipboard in GTK


code:
ym = YourModel.objects.create()
ym.strings.create(string='string1')
ym.strings.create(string='string2')

rawDescription: A list model field for Models.Model

description: A list model field for Models.Model


rawDescription: How can I define a function with default parameter values and optional parameters in Python?

description: Define a function with default parameter values and optional parameters in Python


code: import loggingsetup as logging

rawDescription: "Unused import warning" and pylint

description: "Unused import warning" and pylint


code: axes.yaxis.grid(True, which='minor')

rawDescription: No minor grid lines on the x-axis only

description: No minor grid lines on the x-axis only


code: person = person.replace("art", "aart")

rawDescription: Python immutable object from within function


code:
time.struct_time(tm_year=2013, tm_mon=9, tm_mday=15, tm_hour=20,
                 tm_min=8, tm_sec=37, tm_wday=6, tm_yday=258, tm_isdst=1)

rawDescription: python script to check between 10pm and 9am

description: Python script to check between 10pm and 9am


code:
try:
    from functools import lru_cache  # Python 3.2+
except ImportError:  # Python 2
    # Python 2 and Python 3.0-3.1
    # Requires the third-party functools32 package
    from functools32 import lru_cache

@lru_cache(maxsize=None)
def f(arg):
    # expensive operations
    return result

x = f('arg that will take 10 seconds')  # takes 10 seconds
y = f('arg that will take 10 seconds')  # virtually instant

rawDescription: optimize function evaluations caching partial result

description: Optimize function evaluations caching partial result


code:
for k in sorted(myDict):
    myDict[k] # do something

rawDescription: Should dict store key in order by inc?

description: Should dict store key in order by inc


code:
ind | ind2
ind & ind2

rawDescription: DataFrame algebra in Pandas

description: DataFrame algebra in Pandas


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    CheckBox:
        active: root.is_active
    CheckBox:
        active: not root.is_active
    Button:
        text: 'toggle'
        on_press: root.toggle()
''')

class MyWidget(BoxLayout):
    is_active = BooleanProperty(False)

    def toggle(self):
        self.is_active = not self.is_active

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

rawDescription: How do I initialise CheckBox state in kivy

description: Initialise CheckBox state in kivy


code: documents = [sub_list[0] for sub_list in documents]

rawDescription: How to iterate through a list of lists in python?

description: Iterate through a list of lists in python


code:
def divide(x, y, output=(True, True)):
    quot, rem = x // y, x % y
    if all(output):
        return quot, rem
    elif output[0]:
        return quot
    return rem

quot = divide(x, y, (True, False))

rawDescription: How to get a single output from a function with multiple outputs?

description: Get a single output from a function with multiple outputs


code:
import operator
lst.sort(key=operater.itemgetter(2), reverse=True)

rawDescription: sorting a graph by its edge weight. python

description: Sorting a graph by its edge weight. python


code: X, Y = Z['Time'], Z['Profit']

rawDescription: Extract columns using "genfromtxt"

description: Extract columns using "genfromtxt"


code:
class Thing(object):
    def __init__(self, thing):
        self.value = thing
        self.name = str(thing)
    id = property(lambda s: id(s))
    #...
    def __repr__(self):
        return "I am a %s" %self.name

class ThingList(list):
    def __init__(self, items):
        for item in items:
            self.append(item)
    def append(self, value):
        list.append(self, Thing(value))
    def __setitem__(self, index, value):
        list.__setitem__(self, index, Thing(value))

rawDescription: Can you easily create a list-like object in python that uses something like a descriptor for it's items?

description: Easily create a list-like object in python that uses something like a descriptor for it's items


rawDescription: Python, sort a dict to represent a histogram


code:
def main():
    array = []
    string = input("Enter 3 numbers: ")
    lst = string.split()
    lst = [int(a) for a in lst]
    array.append(lst)
    while string != '':
        string = input("Enter 3 numbers: ")
        lst = string.split()
        array.append([int(a) for a in lst])
    print(array)
main()

rawDescription: Lists and columns in Python

description: Lists and columns in Python


rawDescription: Numpy: vectorizing two-branch test (ternary-operator like)


code: melted

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


code:
df['approx'] = df['Price'].round(2)
df.groupby('approx')['Volume'].sum()

rawDescription: How to compress a data frame within a range?

description: Compress a data frame within a range


code:
_list = range(1,6)
_list
id(_list)
_list = range(1,5)  # reinitialize
_list
id(_list)

rawDescription: Updating list with a for loop

description: Updating list with a for loop


code:
def org_app(A,B):
    M = len(A)
    C = np.zeros(M)
    for i in range(M):
        value = A[i]
        flag = A <= value
        C[i] = np.sum(flag * B)
    return C

def sum_based(A,B):
    return ((A <= A[:,None])*B).sum(1)

def dot_based(A,B):
    return (A <= A[:,None]).dot(B)

def bincount_based(A,B):
    row,col = np.nonzero(A <= A[:,None])
    return np.bincount(row,np.take(B,col))

def org_app_modified(A,B):
    M = len(A)
    C = np.empty(M)
    for i in xrange(M):
        C[i] = (A <= A[i]).dot(B)
    return C

def cumsum_trick(A,B):
    idx = A.argsort()
    return B[idx].cumsum()[idx.argsort()]

rawDescription: Efficient 1D array comparison, scaling and summation


code:
from scipy import weave

# [...] Set up code till "# Gauss-Seidel solver"

tic = time.time()
max_v_diff = 1;
A = cr * (1 - 1/(2*ri[1:nr,1:nz]))
B = cr * (1 + 1/(2*ri[1:nr,1:nz]))
expr = "temp = A*v[0:nr-1,1:nz] + B*v[2:nr+1,1:nz] + cz*(v[1:nr,0:nz-1] + v[1:nr,2:nz+1]); v[1:nr,1:nz] = temp"
temp = np.empty((nr-1, nz-1))
while (max_v_diff > tol):
    v_old = v.copy()
    # left boundary updates
    v[0,1:nz] = cr*2*v[1,1:nz] + cz*(v[0,0:nz-1] + v[0,2:nz+2])
    # internal updates
    weave.blitz(expr, check_size=0)
    # right boundary updates
    v[nr,1:nz] = cr*2*v[nr-1,1:nz] + cz*(v[nr,0:nz-1] + v[nr,2:nz+1])
    # reapply grid potentials
    v[31:,29:40] = 1000
    v[19:,54:65] = -200
    # check for convergence
    v_diff = v - v_old
    max_v_diff = np.absolute(v_diff).max()
toc = time.time() - tic

rawDescription: Improving Numpy speed for Gauss-Seidel (Jacobi) Solver


code:
s = g.subgraph(nx.shortest_path(g.to_undirected(),'B'))
s.edges()

rawDescription: Networkx: extract the connected component containing a given node (directed graph)


code:
def change_language(lang):
    if lang == 'English':
        root.title('Program')
        menuButton.config(text='Menu')
    elif lang == 'Spanish':
        root.title('Programa')
        menuButton.config(text='Menú')

rawDescription: Python Tk app - Allow for multiple languages


code: help(setattr)

rawDescription: How do you programmatically set an attribute in Python?

description: Programmatically set an attribute in Python


rawDescription: Pandas splitting strings from text and then inputting into a dataframe


rawDescription: Iterate over lists with a particular sum


code:
class BulkInsertManager(models.Manager):
    def _bulk_insert_or_update(self, create_fields, update_fields, values):

        from django.db import connection, transaction
        cursor = connection.cursor()

        db_table = self.model._meta.db_table

        values_sql = []
        values_data =[]

        for value_lists in values:
            values_sql.append( "(%s)" % (','.join([ "%s" for i in range(len(value_lists))]),) )
            values_data.extend(value_lists)

        base_sql = "INSERT INTO %s (%s) VALUES " % (db_table, ",".join(create_fields))

        on_duplicates = []

        for field in update_fields:
            on_duplicates.append(field + "=VALUES(" + field +")")

        sql = "%s %s ON DUPLICATE KEY UPDATE %s" % (base_sql, ", ".join(values_sql), ",".join(on_duplicates))

        cursor.executemany(sql, [values_data])
        transaction.commit_unless_managed()

rawDescription: MySQL INSERT ... ON DUPLICATE KEY UPDATE with django 1.4 for bulk insert


rawDescription: Python: Parse multiple datatypes using argparse


code: numpy.histogram(a, bins=10, range=None, normed=False, weights=None)

rawDescription: python: is there a frequency function?

description: Python: is there a frequency function


code:
a1 = fractional_polar_axes(f1, thlim=(-90, 90),step=(10, 0.2),
    theta_offset=90, rlabels = r_ticks)

rawDescription: How to change ticklabels within figure created with axisartist

description: Change ticklabels within figure created with axisartist


code:
import requests
import pprint

contents = requests.get("https://api.vaultofsatoshi.com/publi/ticker?order_currency=DOGE&payment_currency=USD")

j = contents.json()
pprint.pprint(j)

rawDescription: Trouble parsing API JSON output with python using 'requests'


code:
data = dict()
for x in xrange(1, 9):
    key = "text" + str(x)
    data[key] = eval(key)

rawDescription: Cycling through a group of variables with similar names


code: item = random.choice(lists[which_list])

rawDescription: How do I randomly pick an item from one of the lists inside a dictionary, and also get the key for the list?

description: Randomly pick an item from one of the lists inside a dictionary, and also get the key for the list


code:
FIELDS = ["name", "timeZone_label"]
for i in FIELDS:
    with open (path,'r') as p:
        reader=csv.DictReader(p)
        for row in reader:
            print (row[i])

rawDescription: nested loop in python is not looping more than once

description: Nested loop in python is not looping more than once


code:
from django.db import connection
cursor = connection.cursor()
cursor.execute( query )
rows = cursor.fetchall()

rawDescription: Django - determining if geographic coordinates are inside of an circle


code:
def main(*args):
    ...

main(*sys.argv)

rawDescription: Use *args without putting the arguments into a tuple?


code:
HEIGHT = 10
WIDTH = 40
MARKER = '*'
FILL_CHARACTER = ' '

coords = [(ch[0], ch[3]) for ch in band1.values()]
coords.sort(key=lambda ch: ch[1])

xmin = min(c[0] for c in coords)
xmax = max(c[0] for c in coords)
kx = (WIDTH - 1)  / (xmax - xmin)

ymin = min(c[1] for c in coords)
ymax = max(c[1] for c in coords)
ky = (HEIGHT - 1) / (ymax - ymin)

acoords = {}
for c in coords:
    x = round((c[0] - xmin) * kx)
    y = round((c[1] - ymin) * ky)
    if x not in acoords:
        acoords[x] = y
    else:
        acoords[x] = max(acoords[x], y)

for y in range(HEIGHT, -1, -1):
    chars = []
    for x in range(WIDTH):
        if acoords.get(x, 0) >= y:
            chars.append(MARKER)
        else:
            chars.append(FILL_CHARACTER)
    print(''.join(chars))

rawDescription: Ascii graph in python

description: Ascii graph in python


code:
# load the image first
myImage = Image(filename=r"c:\test.psd[0]")
myImage.format = "png"
myImage.sample(100, 100)
aBlob = myImage.make_blob()

# load the image data into QImage
myQImage = QtGui.QImage.fromData( aBlob )
myQPixmap = QtGui.QPixmap.fromImage( myQImage )
target_QLabel.setPixmap( myQPixmap )

rawDescription: How to Convert PSD into PNG, using Python Wand / ImageMagick?


code:
from django.contrib import admin

from .models import CMSMediaDocument

admin.site.register(CMSMediaDocument)

rawDescription: Python Django: How to upload a file with a filename based on instance pk


code:
A = np.array([1, 2, 3, 4, float("nan")]) # common type is float64
A
A[np.isnan(A)] = A.dtype.type() # nan is replaced with 0.0
A
B = np.array([1, 2, 3, -1, 5]) # common type is int64
B
B[B == -1] = B.dtype.type() # -1 is replaced with
B

rawDescription: Python3 - default keyword for default values for type?


code:
timeit.timeit('list(filter(None, myList))', 'from __main__ import myList')
timeit.timeit('[t for t in myList if t]', 'from __main__ import myList')

rawDescription: Python 3: Removing an empty tuple from a list of tuples


code:
import itertools
import numpy

def binomial_choice(L, p):
    iterator = iter(L)
    while True:
        to_skip = numpy.random.geometric(p) - 1
        yield next(itertools.islice(iterator, to_skip, None))

rawDescription: Given iterable, select each element independently with probability p


code:
x0 = 1
def fun2(f1, x):
    return f1(x)

rawDescription: How to pass additional parameters (besides of arguments) to a function in Python

description: Pass additional parameters (besides of arguments) to a function in Python


code:
class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.5
    changefreq = 'daily'

    def items(self):
        return ['home']

    def location(self, item):
        return reverse(item)

rawDescription: how do I add homepage to Django sitemap?

description: Add homepage to Django sitemap


code:
def tester(args):
    if (isinstance(args, str)):
        return "String"
    elif (isinstance(args, list)):
        return"List"
    else:
        return "You dun goofed"

rawDescription: Checking the type of parameter entered into a function


code:
exp = Account.objects.filter(expiration_date__lte = timezone.now())
if len(exp) == 0:
    return False
else:
    return True

rawDescription: Django templatetag return True or False

description: Django templatetag return True or False


code: myfunction(arg1, arg2)

rawDescription: Dynamically update attributes of an object that depend on the state of other attributes of same object


code:
def f():  # for demonstration
    pass

f.__doc__ = "Docstring!"
help(f)

rawDescription: Explicitly set docstring of a method

description: Explicitly set docstring of a method


rawDescription: Pandas df.to_records() returns a 1d numpy array


code:
oname = soup.find("title")
oname.text

rawDescription: How to get inner text value of an HTML tag with BeautifulSoup bs4?

description: Get inner text value of an HTML tag with BeautifulSoup bs4


code:
MyVar = 5
def ChangeMyVar(value):
    global MyVar
    MyVar = value
d['MyVar'] = ChangeMyVar

# later..
d['MyVar'](10)

rawDescription: Use a dictionary to handle variables

description: Use a dictionary to handle variables


code:
class InstagramFeed:
    api = InstagramAPI(client_id=settings.SOCIAL_AUTH_INSTAGRAM_KEY,
                       client_secret=settings.SOCIAL_AUTH_INSTAGRAM_SECRET)
    logger = logging.getLogger(__name__)

    def get_user_id(self, user_name):
        users = self.api.user_search(q=user_name)
        for user in users:
            if user_name == user.username:
                return user.id
            else:
                self.logger.error('Instagram User with username {0} NOT FOUND!', user_name)
                raise Exception('Instagram User with username {0} NOT FOUND!', user_name)

    @classmethod
    def get_media(cls, user_name, count=8):
        user_id = cls.get_user_id(cls, user_name)
        if user_id is None:
            return None

        recent_media, next_ = cls.api.user_recent_media(user_id=user_id, count=count)
        return recent_media

class InstagramEncoder(json.JSONEncoder):
    def default(self, o):
        if type(o) in (instagram.models.Comment, instagram.models.Image,
                       instagram.models.Location, instagram.models.Media,
                       instagram.models.MediaShortcode, instagram.models.Point,
                       instagram.models.Relationship, instagram.models.Tag,
                       instagram.models.User, instagram.models.Video, instagram.models.UserInPhoto,
                       instagram.models.Position):
            return o.__dict__
        elif isinstance(o, datetime.datetime):
            unix_time = time.mktime(o.timetuple())
            return str(unix_time)
        else:
            return default(o)

rawDescription: python instagram api user_recent_media returns None

description: Python instagram api user_recent_media returns None


code: d = {(item[0], item[1]):item[2] for item in lst1}

rawDescription: Nested list with dictionary as content

description: Nested list with dictionary as content


code:
from itertools import chain
print([item for lang in languages_list for item in chain([lang.code], lang.alt)])

rawDescription: Returning a list in each iteration using list comprehension


code:
line = open("ints.txt").read().split(",")
total = sum(int(i) for i in line)

rawDescription: Looping through columns in a .csv files in Python


code:
test_data = [
  exia.frame, exia.head, exia.swords, exia.legs,
  exia.arms, exia.pilot, exia.gn_drive, lockon_stratos.data,
  tieria_erde.data, ribbons_almark.data, otherstuff.dada
]

rawDescription: Python: finding files with matching extensions or extensions with matching names in a list


code: comp = numpy.logical_and(numpy.logical_and(array1 != 0, array2 != 0), array1 > (0.6+array2))

rawDescription: Printing 'True' index/es after comparing numpy arrays with numpy.logical_and(...)


code: df['a'] = df['a'].str.replace('\bHi\b', 'hi')

rawDescription: How to correct typos in pandas dataframe

description: Correct typos in pandas dataframe


code:
topleft = pts.min(axis=0) + [offsetx, offsety]
bottomright = pts.max(axis=0) + [offsetx, offsety]
cv2.rectangle(out_translate, tuple(topleft), tuple(bottomright), color=(255,0,0))

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code: 'Nunc dui mi'

rawDescription: Python - Conditionally split line

description: Python - Conditionally split line


code:
import numpy as np

def with_numpy(buffer):
    # Construct ndarray with: shape, dtype, buffer, offset, strides.
    rotational = np.ndarray((firingBlocks,), '<H', buffer, 42+2, (100,))
    distance = np.ndarray((firingBlocks,lasers), '<H', buffer, 42+4, (100,3))
    intensity = np.ndarray((firingBlocks,lasers), '<B', buffer, 42+6, (100,3))
    return rotational, distance*0.002, intensity

rawDescription: Speed up python's struct.unpack

description: Speed up python's struct.unpack


code: shutdown /r

rawDescription: How to make a python script which can logoff, shutdown, and restart a computer?

description: Make a python script which can logoff, shutdown, and restart a computer


code:
from operator import mul
from collections import deque
from copy import copy

def cal_max_prod(container, current_product):
    max_container = {'seq': copy(container), 'prod': current_product}
    for i in digits[13:]:
        popped_item = int(container.popleft())
        container.append(i)
        try:
            push_item = int(i)
            current_product = (current_product / popped_item) * push_item
        except ZeroDivisionError:
            if '0' not in container:
                current_product = reduce(mul, map(int, container))
        else:
            if current_product > max_container['prod']:
                max_container['prod'] = current_product
                max_container['seq'] = copy(container)

    return ''.join(max_container['seq'])

rawDescription: Largest product in a series in python

description: Largest product in a series in python


code:
def average():
    inputnum = 0
    numlist = []
    while inputnum <=100:
        inputnum = input("Please input a number: ")
        inputnum = float(inputnum)
        numlist.append(inputnum) if inputnum <=100 else None
    average = sum(numlist)/len(numlist)
    print(average)

average() # finally call the function

rawDescription: Average function in Python

description: Average function in Python


code:
def pop_std(x):
    return x.std(ddof=0)

result = df.groupby(['a'], as_index=False).agg({'c':['mean',pop_std],'b':'first', 'd':'first'})

result.columns = ['a','c','e','b','d']
result.reindex(columns=sorted(result.columns))

rawDescription: Groupby Pandas DataFrame and calculate mean and stdev of one column and add the std as a new column with reset_index


code:
def is_group(node):
    children = node.getChildren()
    for child in children:
        if type(child) is not pymel.core.nodetypes.Transform:
            return False
    return True

rawDescription: How to isolate group nodes in maya with python

description: Isolate group nodes in maya with python


code:
s = List()
s.push(10)
s.push(20)
s

rawDescription: Can I add an operation to a list in Python?

description: Add an operation to a list in Python


code: np.arccos(np.sum(a*b, -1))

rawDescription: Performance of 2 vector-matrix dot product


rawDescription: Data type problem using scipy.spatial

description: Data type problem using scipy.spatial


code:
r = repository('sigmavirus24', 'github3.py')
cs = r.iter_commits(50)  # Limit it to 50 commits
commits = [c.refresh() for c in cs]

rawDescription: github3.py. Empty list of commited files

description: Github3.py. Empty list of commited files


code:
denominator = 1 - 2 * R * c * z ** -1 + R ** 2 * z ** -2
gain / denominator
type(_) # The "_" is the last returned value in IPython

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code: ids, other = zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids))

rawDescription: Filtering two lists simultaneously

description: Filtering two lists simultaneously


rawDescription: Python code to open image in browser?

description: Python code to open image in browser


code:
def my_all_v2(a_list):
  return len(filter(None,a_list)) == len(a_list)

def my_any_v2(a_list):
  return len(filter(None,a_list)) > 0

rawDescription: How to apply a logical operator to all elements in a python list

description: Apply a logical operator to all elements in a python list


code:
tools = ManipulationTools()
tools.click(100,200,1) ## this should actually give you an error -- ManipulationTools.click gets called with 4 arguments (self, 100, 200, 1), but is only defined for 3 (self, y, numclicks)

rawDescription: Python - function arguments not working

description: Python - function arguments not working


code:
offset = df.index[0] % 100
df.index = pd.to_datetime((df.index.values*1e6).astype(int))
df.resample('100L', loffset='{}L'.format(offset))

rawDescription: How to resample starting from the first element in pandas?

description: Resample starting from the first element in pandas


rawDescription: python string array sorting

description: Python string array sorting


rawDescription: How do I convert a datetime.date object into datetime.datetime in python?

description: Convert a datetime.date object into datetime.datetime in python


code:
import pandas as pd
dataset = pd.read_table("toplot.txt", sep="\t")
#make D index (automatically puts it on the x axis)
dataset.set_index("D", inplace=True)
#plotting R vs. D
dataset.R.plot()
#plotting F vs. D
dataset.F.plot()

rawDescription: plot multiple data series from numpy array

description: Plot multiple data series from numpy array


rawDescription: Project Euler #29 alternative solution

description: Project Euler #29 alternative solution


code:
strs = " 'AMS_Investigation|txtt.co_BigtittedBlondOtherNight_1371078139195_+14155186442', {'cf:rv': '0'}"
first, sep, rest = strs.partition(',')
lis = first.rsplit('_', 2)
lis[1] = "1111111"
"_".join(lis) + sep + rest

rawDescription: Replace an underscore separated substring in the middle of a comma separated string


rawDescription: Python regex match all characters except tab


code:
for root, dirs, files in os.walk(path):
    regressionTest(root)

rawDescription: How can i make the attached pyunit python script search for tests in subfolders

description: Make the attached pyunit python script search for tests in subfolders


code:
stringToWrite = ""
for x in listOfNumbers:
    stringToWrite += x + "/n"

file.write(stringToWrite)

rawDescription: Python writing to file multiple lines at once


code:
line, = ax.plot(x, y, 'b.-', ...)
line.set_label('line 1')

rawDescription: How do I set label for an already plotted line in matplotlib?

description: Set label for an already plotted line in matplotlib


code: np.argmin(pd.isnull(df).values, axis=1)

rawDescription: Is there a better more readable way to coalese columns in pandas


code:
key2line = {}
with open(secondfile) as f:
    for line in f:
        key2line[getkey(line)] = line

with open(firstfile) as f:
    order = [line.strip() for line in f]

with open(outputfile, 'w') as f:
    for key in order:
        f.write(key2line[key])

rawDescription: Iterate through a file multiple times

description: Iterate through a file multiple times


code:
print(sum(ord(i) for i in a+b))
# 695

rawDescription: Converting String to Ordinal Value

description: Converting String to Ordinal Value


code:
import nstest
nstest.__path__.insert(0, 'nstest')
from nstest import foo
foo.__file__

rawDescription: Import local testing version of a Python namespace package


code:
tag1 = soup.find(id='link1')
tag2 = soup.find(id='link2')
tag1, tag2
all_tags = soup.find_all(True)
all_tags.index(tag1)
all_tags.index(tag2)

rawDescription: BeautifulSoup order of occurrence of Tags


code:
class AccountForm(forms.ModelForm):

  class Meta(object):
    model = Account

  parent = forms.ModelChoiceField(queryset=Account.objects.filter(level=2))

rawDescription: Django CreateView filter foreingkey

description: Django CreateView filter foreingkey


code:
ROSTER = dict()

class Player():
    def __init__(self, name, score = 0):
        self.name = name
        self.score = score
        ROSTER[self.name] = self

rawDescription: Simple OOP query. Python: saving object names in __init__


code:
data = data = [{'day': day, 'amt': amt} for day, amt in zip(sale_day, sale_amt)]
json_data = json.dumps(data)
return render(request, 'dashboard/index.html', {"data": json_data})

rawDescription: how to append django data to javascript

description: Append django data to javascript


code:
df1 = pd.DataFrame({'a':list('AAABB'), 'b':list('BBBAA'), 'c':range(5), 'd':range(5)})
df1
df1.groupby(['a','b']).filter(lambda x: len(x) > 2)

rawDescription: How to delete minority rows from a pandas data frame?

description: Delete minority rows from a pandas data frame


rawDescription: Recursion Formula for Integer Partitions


code:
self.w = QWhatever();
self.w.setContextMenuPolicy(Qt.CustomContextMenu)
self.connect(self.w,SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)

rawDescription: Qt and context menu

description: Qt and context menu


code:
def saveToFile(fileName, data): # You are just declaring a function here
    f = open(fileName, "w")     # You are opening a file fileName in "w" or write mode (because you will write to the file)
    f.write(data)               # You write the data
    f.close()                   # Since you opened a file you need to close it. You do it here.

rawDescription: Save variable a user input

description: Save variable a user input


code: from __future__ import unicode_literals

rawDescription: Encoder for a string - Python

description: Encoder for a string - Python


code: info_as_json = json.dumps(info)

rawDescription: Converting "true" (JSON) to Python equivalent "True"


code:
def fun():
    x = X()

rawDescription: PyEval_GetLocals returns globals?

description: PyEval_GetLocals returns globals


code:
[np.where(_ < cump)[0][0] for _ in sample]
np.searchsorted(cump, sample)

rawDescription: Make Numpy.where stop after first true encountered


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

def sorted_table_plot(data, labels, categories, cmap=None, ax=None):

    # check if an axes was supplied
    if ax is None:
        ax = plt.gca()

    # check if a colormap was supplied
    if cmap is None:
        cmap = plt.cm.jet

    # generate the grid arrays with the coordinates for the annotations
    yy, xx = np.mgrid[:data.shape[0], :data.shape[1]]
    x = xx.flatten()
    y = yy.flatten()
    d = data.flatten()

    # a norm object which we will use with the colorbar
    norm = plt.Normalize(d.min(), d.max())

    # iterate over the data points and draw the labels
    for di, xi, yi in zip(d, x, y):
        color = cmap(norm(di))
        hsv = mcolors.rgb_to_hsv(color[:3])
        fc = 'w' if hsv[2] < 0.7 else 'k'
        ax.annotate(str(di), xy=(xi,yi), xycoords="data",
                va="center", ha="center", color=fc,
                bbox=dict(boxstyle="circle", fc=color))

    # iteratve over all the appearing values and draw the lines
    for i in np.unique(data):
        xi, yi = x[d==i], y[d==i]
        idx = np.argsort(xi)
        plt.plot(xi[idx], yi[idx], color=plt.cm.jet(norm(i)), lw=2)

    # add the axes labels
    ax.set_xticks(xx[0,:])
    ax.set_xticklabels(categories)
    ax.set_yticks(yy[:,0])
    ax.set_yticklabels(labels)

    # adjust the axes ranges
    ax.set_xlim(xx[0,0] - 0.5, xx[-1,-1] + 0.5)
    ax.set_ylim(yy[-1,-1] + 0.5, yy[0,0] - 0.5)

rawDescription: Trying to visualize a sorted table with matplotlib (parallel coordinates?)


code: ", ".join('{}-{}'.format(x, i) for k, g in groupby(lst) for i, x in enumerate(g, 1))

rawDescription: find similar items following each other in a python list

description: Find similar items following each other in a python list


code: subprocess.call(('sshpass', '-p', 'YOUR_PASSWORD', 'ssh', '-o', 'StrictHostKeyChecking=no', 'foo{}.bar'.format(number)))

rawDescription: Passing a variable into bash command using python


code: chr(int(base, 16))

rawDescription: Python3: Creating a string with an unescaped backslash


rawDescription: Meaning of the map function in couchdb-pythons ViewField


code:
async def display_dt1():

    display_count = 0
    stop_future = asyncio.Future()
    stop_handle = loop.call_later(DISPLAY_DT_TIMEOUT, stop, stop_future, display_count)

    while not stop_future.done() and display_count < MAX_DISPLAY_COUNT:
        print('dt-1', display_count, datetime.datetime.now())
        try:
            await asyncio.wait_for(asyncio.shield(stop_future), COUNT_TIMEOUT)
        except asyncio.TimeoutError:
            print('timeout', datetime.datetime.now())
        print('dt-2', display_count, datetime.datetime.now())
        display_count += 1

    if not stop_future.done():
        stop_handle.cancel()
        stop_future.cancel()
        print('check-2', datetime.datetime.now(), stop_future)

rawDescription: How to cleanup asyncio.sleep() in a coro when te coro finishes before the sleep timeout

description: Cleanup asyncio.sleep() in a coro when te coro finishes before the sleep timeout


code:
class Vertex:
   # def __init__(self): ...

   def allEdges(self):
      return self.outEdges + self.inEdges

rawDescription: What good are python classes?

description: What good are python classes


rawDescription: Plotting errorbar with mean and std after grouping


code: contains_Hamburg = any('Hamburg' in c for c, s in cities)

rawDescription: Use in, on a list to check one item in tuple


rawDescription: Displaying a 32-bit image with NaN values (ImageJ)


code:
#!/usr/bin/env python
from pony.orm import *

db = Database()
db.bind('sqlite', ':memory:', create_db=True)

class Car(db.Entity):
    image = Set("Image", lazy=True)
    name = Required(str, 40)

class Image(db.Entity):
    name = Required(str, unique=True)
    car = Required(Car)

db.generate_mapping(create_tables=True)

sql_debug(True)

with db_session:
    car1 = Car(name='car1')
    car2 = Car(name='car2')
    image1 = Image(name='image1', car = car1)
    image2 = Image(name='image2', car = car1)
    image3 = Image(name='image3', car = car2)
    cars = select((car, car.name, image, image.name) for car in Car for image in car.image if image.id == min(car.image.id)).show()

rawDescription: How to get only one image from Set() in Pony ORM

description: Get only one image from Set() in Pony ORM


code:
annotated_films = []
for film in films:
    film.followed_actors = film.actors.filter(id__in=actor_ids)
    film.followed_genres = film.genres.filter(id__in=genre_ids)
    annotated_films.append(film)

rawDescription: Find related objects and display relation


rawDescription: Leibniz formula for π - Is this any good? (Python)


code: a[tuple(b) + (slice(None),) + tuple(c)]

rawDescription: How to return a subarray of a multidimensional array in Python?

description: Return a subarray of a multidimensional array in Python


code: idx_vals = df[df['preciptotal'] > 1].index

rawDescription: Slicing based on dates Pandas Dataframe

description: Slicing based on dates Pandas Dataframe


code:
class A(object):
    pass

class B(A):
    pass

class C(A):
    pass

rawDescription: How to obtain all subclasses (of a specific class) defined by a module?

description: Obtain all subclasses (of a specific class) defined by a module


code: [anim for item in animals for anim in item]

rawDescription: How do I remove extra parsing characters in a list?

description: Remove extra parsing characters in a list


code:
sec = {} #construct a dictionary
for index, directionpair in enumerate(sections):
    long_name = directionpair[1] #take the second element of the pair
    short_name = long_name.replace('/','-').replace(' ','-').replace("'",'').replace('.','').lower()
    sec[short_name] = index

rawDescription: Python - Can someone explain to me what this does and how it works?


code: zip(*zipp)

rawDescription: Getting values out of a python dictionary


code:
def f(x,y): return x**2 + 2*y

x,y = np.mgrid[0:10, 0:10]
fxy = np.vectorize(f)(x.ravel(),y.ravel()).reshape(x.shape)

rawDescription: Python: An elegant/efficient way to evaluate function over bi-dimensional indexes?


code:
func1 = class1.func1
func1()

rawDescription: Access a Python variable which is inside a function, in another function


code: v.set("Internet is offline!  Downtime: " + str(time.time() - start_time))

rawDescription: Tkinter set new value for labels

description: Tkinter set new value for labels


code:
for a1, a2, a in it:
    a[()] = a1 if -a1 < a2 else a2

rawDescription: Correct usage of numpy.nditer?

description: Correct usage of numpy.nditer


code:
import nstest
nstest.__path__

rawDescription: Import local testing version of a Python namespace package


code:
from django.core.cache import cache

# Generate HTML block to cache
html = '
Calendar
'

# Cache the HTML as 'google_calendar'
cache.set('google_calendar', html, 3600)

rawDescription: Caching calendar data from Google Calendar


code:
def readFromFile(fileName):
    f = open(fileName, "r")
    data = f.read()
    f.close()
    return data

name = readFromFile("name.txt")
age = readFromFile("age.txt")

print("Your name is: " + name)
print("Your age is: " + age)

rawDescription: Save variable a user input

description: Save variable a user input


code:
[[cell.get_text(strip=True)
  for cell in row.find_all("td")]
 for row in table.find_all("tr")[2:]]

rawDescription: Python+BeautifulSoup: scraping a particular table from a webpage


rawDescription: How to check dictionary items are present in the list ? PYTHON

description: Check dictionary items are present in the list ? PYTHON


rawDescription: Different Dictionaries sharing the same instance


code:
for row in right_table.select("tr"):
    increment = row.find('span',{"class":'increase'})
    if increment:
        increment = increment.text
        place = int(row.td.text)
        title = row.select("a[data-full-image]")[0].text
        alt = (row.find("img")["alt"])
        table_dict[place] = {"title":title,"alt":alt, "inc":increment}

from pprint import pprint as pp

pp(table_dict)

rawDescription: BeautifulSoup: Extract "img alt" content Web Scraping in Python


rawDescription: Expanding a logical statement (multiplying out)


code: df.dayOfWeek2 == df.dayOfWeek

rawDescription: Deriving new data from Pandas datetime column


code:
def toNumber(s):
    if not s:
        return 0

    first = s[0]
    value = int(first) if first.isdigit() else 0
    return value + toNumber(s[1:])

rawDescription: Python using recursion to take a mixed string and add up the integers in the string


code:
right_table = soup.find('table', class_='table table-bordered table-striped table-condensed movers-table')

print([img["alt"] for img in right_table.select("img[alt]")])
['ORI', 'PRM', '8ED', 'EX', 'TSB', 'WL', 'ROE', 'ZEN', 'FUT', 'FUT']

description: BeautifulSoup: Extract "img alt" content Web Scraping in Python


code:
if any(aboveAdj1) and any(aboveAdj2):
    perAboveFix = 100 * (sum(aboveAdj1) + sum(aboveAdj2)) / (len(aboveAdj1) + len(aboveAdj2))

rawDescription: Check if list is either empty or only containing zeroes


code:
OrderedDict([(u'id', u'0'), (u'last_modified', u'undefined')])
OrderedDict([(u'last_modified', u'undefined'), (u'id', u'0')])

rawDescription: Converting string to ordered dictionary?

description: Converting string to ordered dictionary


rawDescription: remove tick labels in Python but keep gridlines

description: Remove tick labels in Python but keep gridlines


code:
board = [['1'] * n for _ in range(n)]
zeros = [0, 2, 4, 1, 9, 11, 13, 3, 12, 8, 5, 14, 6, 10, 7]
for row, idx in zip(board, zeros):
  row[idx] = '0'

pprint.pprint(board)

rawDescription: Translating from numpy to pure python

description: Translating from numpy to pure python


code:
[ x for x in itertools.takewhile(
    lambda line: sync(line) == 0,    # <- predicate
    open("file.txt")) ]              # <- iterable

rawDescription: One-liner for calling a function for each line in a file


code:
dfN = df["path"].str.split(',').apply(lambda x: pd.Series(Counter(x)))
pd.DataFrame(dfN, columns=wordlist).fillna(0)

rawDescription: pandas dataframe count row values

description: Pandas dataframe count row values


code: t = Thing(something=1)

rawDescription: Python 3 object construction: which is the most Pythonic / the accepted way?


code:
s = "abc\u20ac\U00010302\U0010fffd"
len(s)
for c in s:
    print('U+{:04X}'.format(ord(c)))

rawDescription: How to iterate over Unicode characters in Python 3?

description: Iterate over Unicode characters in Python 3


code: results = [list_test[list_test.index(name)] for name in list_test_for]

rawDescription: test list for membership and store only first true item + python

description: Test list for membership and store only first true item + python


code: count = itertools.count()

rawDescription: Python post increment variable in function call


code:
s = 'Four score and seven years ago.'
ss = s + 5*' '; [ss[i:i+6] for i in range(0, len(s) - 1, 6)]

rawDescription: greedy regex split python every nth line

description: Greedy regex split python every nth line


code:
# mod_main/views.py
from flask import current_app

from . import mod_main

@mod_main.route('/')
def index():
    return current_app.send_static_file('index.html')

rawDescription: send_static_file not picking up from static folder at root in Blueprint

description: Send_static_file not picking up from static folder at root in Blueprint


rawDescription: How can I solve system of linear equations in SymPy?

description: Solve system of linear equations in SymPy


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

delays = np.array([0.5, 2.3, 'L', 0.9, 'L', 2], dtype=object)
x = np.arange(delays.size)

fig, ax = plt.subplots()
ax.plot(x[delays != 'L'], delays[delays != 'L'], 'bo')

# Expand axis limits by 0.5 in all directions for easier viewing
limits = np.array(ax.axis())
ax.axis(limits + [-0.5, 0.5, -0.5, 0.5])

flag_positions = x[delays == 'L']
ax.plot(flag_positions, np.zeros_like(flag_positions), 'rx',
        clip_on=False, mew=2)

plt.show()

rawDescription: matplotlib: draw special symbol when a value appears

description: Matplotlib: draw special symbol when a value appears


code: new_array = array[(array < 0) & (array > 0)]

rawDescription: Remove a value from 1D array

description: Remove a value from 1D array


code:
def makeSuffixDict (inputfile="smallReads.fna", n=15):
    my_dict = {}
    with open(inputfile) as file:
        for line in file:
            words = line.split()
            if len(words) == 3:  # <-- replaced "last word" with "3rd word"
                word = words[2]
                my_dict[word[:-n]] = word[-n:]
    return my_dict

if __name__ == "__main__":
    my_dict = makeSuffixDict()
    for key,value in my_dict.items():
        print(key, value)

rawDescription: Create dictionary from Fasta file

description: Create dictionary from Fasta file


code: new_list = l[:]

rawDescription: python variable assignment using time slices

description: Python variable assignment using time slices


code:
from subprocess import Popen, PIPE, STDOUT

p = Popen(['./inout'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, bufsize=0)  # bufsize=0 keeps stdout from being buffered.

# Send first line to inout
p.stdin.write(b'Why is this twice\n')

# Read first line out output
first = p.stdout.readline()
print("got {}".format(first))

# Get line from user
a = input()

# Send second line to inout
p.stdin.write('{}\n'.format(a).encode('utf-8'))

# Read second line from inout
second = p.stdout.readline()
print('also got {}'.format(second))

p.wait()
print("done")

rawDescription: Python subprocess input is read twice

description: Python subprocess input is read twice


code:
@property
def foo(self): return self._foo

rawDescription: How does the @property decorator work?

description: How does the @property decorator work


code: #!/bin/env python2.7

rawDescription: Dealing with multiple python versions when python files have to use #!/bin/env python


code:
dct = {'s1': "MP", 's2': "GP", 's3': "MP"}
IndexDict = {}
for key, value in  dct.iteritems():
    for i, v in enumerate(value):
       IndexDict.setdefault(i, {})[key] = v

IndexDict
from collections import defaultdict
IndexDict = defaultdict(dict)
for key, value in  dct.iteritems():
    for i, v in enumerate(value):
       IndexDict[i][key] = v

IndexDict

rawDescription: How to map string id, index and value in a nested python dictionary

description: Map string id, index and value in a nested python dictionary


code:
list1 = [0,0,0,0,0,0]
all(item == 0 for item in list1)

rawDescription: how do I print in python if a list contains only 0s?

description: Print in python if a list contains only 0s


rawDescription: How do I print colored output to the terminal in Python?

description: Print colored output to the terminal in Python


rawDescription: How to fit the following function using curve_fit

description: Fit the following function using curve_fit


rawDescription: python making list of tuples into definite sized intervals

description: Python making list of tuples into definite sized intervals


code: len(z["results"])

rawDescription: Python - Count JSON elements before extracting data


rawDescription: Betweenness centrality in NetworkX: logical error


code: strCursosArreglo = ", ".join("".join(i) for i in cursosArreglo)

rawDescription: How can i print a list without the brackets?

description: Print a list without the brackets


rawDescription: python - matplotlib - How to specify the scale for x axis

description: Python - matplotlib - How to specify the scale for x axis


code:
p = np.random.permutation(len(a))
p[np.argpartition(a[p], -4)[-4:]]

rawDescription: Get indices of N maximum values in a numpy array, with random tie-breaking


code:
mask = arr[None,:]>thresholds[:,None]
mask

# Output
# array([[False, False, False, False, False,  True,  True,  True, False],
#        [ True,  True,  True,  True,  True,  True,  True,  True, False]], dtype=bool)

rawDescription: Fastest way to filter values in np array based on changing threshold


code:
def make_init(d):
    def __init__(self, **kwargs):
        for name in d:
            setattr(self, name, kwargs[name])
    return __init__

rawDescription: How to convert Python dict to a specifically-typed object?

description: Convert Python dict to a specifically-typed object


code: arr[:] = [u + 1 for u in arr]

rawDescription: Edit a list while iterating over it (the pythonic way!)


rawDescription: Extract bitfields from an int in Python

description: Extract bitfields from an int in Python


code: map(lambda x:x.test(), lobj)

rawDescription: Iterate python list object and invoke each object's method


code:
import __builtin__

__builtin__.assertAndTerminate = assertionFunction

rawDescription: Python: setting __globals__ for modules and their imports


code:
import requests
url = 'https://www.google.com/url?rct=j&sa=t&url=http://www.statesmanjournal.com/story/opinion/readers/2014/10/13/gmo-labels-encourage-people-make-choices/17171289/&ct=ga&cd=CAIyGjkyZjE1NGUzMGIwZjRkNGQ6Y29tOmVuOlVT&usg=AFQjCNHrCLmbml7baTXaqySagcuKHp-KHA'
response = requests.get(url)
response.url
response.text

rawDescription: Python - Get redirected url of links from Google Alerts feeds


code: df

rawDescription: Combining rows in pandas

description: Combining rows in pandas


code:
def change(s):
     try:
          return '{}{}'.format('0'*s.index('1'),int(s,2))
     except ValueError:
          return s

change('000000')
change('000001')
change('000011')

rawDescription: Convert from bin to int/char without loosing leading "0"


rawDescription: How can I find all substrings that have this pattern: some_word.some_other_word with python?

description: Find all substrings that have this pattern: some_word.some_other_word with python


code:
import re
def make_rule(rule):  # where rule for example "H*X-9387"
   return re.compile("^" + ".*".join(re.escape(i) for i in rule.split("*")) + "$")

rawDescription: Reading and correctly understanding/interpreting control characters from a file (python)


code:
def next_chunk(self, fmt): # fmt can be a group such as "iifff"
    sz = struct.calcsize(fmt)
    self.recv_buf_i += sz
    return struct.unpack_from(fmt, self.recv_buf, self.recv_buf_i-sz)

rawDescription: Faster sockets in Python

description: Faster sockets in Python


code:
df = DataFrame(np.random.randn(len(midx),1),index=midx)
df

rawDescription: Pandas multi-index slices for level names


code:
"""
Usage example: guess_chain_encodings.py "u'баба'" "u'\xe1\xe0\xe1\xe0'"
"""
import argparse
import binascii
import zlib
import ast
import collections
import itertools
import random

Errors = (IOError, UnicodeEncodeError, UnicodeError, LookupError,
          TypeError, ValueError, binascii.Error, zlib.error)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('start', type = ast.literal_eval, help = 'starting unicode')
    parser.add_argument('stop', type = ast.literal_eval, help = 'ending unicode')
    parser.add_argument('--all', '-a', action = 'store_true')
    args = parser.parse_args()
    min_len = None
    for encs, text in breadth_first_search(args.start, args.all):
        if min_len is not None and len(encs) > min_len:
            break
        if type(text) == type(args.stop) and text == args.stop:
            print(fmt(encs, args.start))
            min_len = len(encs)

def breadth_first_search(text, all = False):
    seen = set()
    tasks = collections.deque()
    tasks.append(([], text))
    while tasks:
        encs, text = tasks.popleft()
        for enc, newtext in candidates(text):
            if repr(newtext) not in seen:
                if not all:
                    seen.add(repr(newtext))
                newtask = encs+[enc], newtext
                tasks.append(newtask)
                yield newtask

def fmt(encs, text):
    encode_decode = itertools.cycle(['encode', 'decode'])
    if not isinstance(text, unicode):
        next(encode_decode)
    chain = '.'.join( "{f}('{e}')".format(f = func, e = enc)
                     for enc, func in zip(encs, encode_decode) )
    return '{t!r}.{c}'.format(t = text, c = chain)

def candidates(text):
    f = text.encode if isinstance(text, unicode) else text.decode
    results = []
    for enc in encodings:
        try:
            results.append((enc, f(enc)))
        except Errors as err:
            pass
    random.shuffle(results)
    for r in results:
        yield r

def all_encodings():
    modnames = set([modname for importer, modname, ispkg in pkgutil.walk_packages(
        path = [os.path.dirname(encodings.__file__)], prefix = '')])
    aliases = set(encodings.aliases.aliases.values())
    return modnames.union(aliases)

encodings = us.all_encodings()

if __name__ == '__main__':
    main()

rawDescription: Fixing faulty unicode strings

description: Fixing faulty unicode strings


code:
def multiple_linregress(x, y):
    x_mean = np.mean(x, axis=1, keepdims=True)
    x_norm = x - x_mean
    y_mean = np.mean(y, axis=1, keepdims=True)
    y_norm = y - y_mean

    slope = (np.einsum('ij,ij->i', x_norm, y_norm) /
             np.einsum('ij,ij->i', x_norm, x_norm))
    intercept = y_mean[:, 0] - slope * x_mean[:, 0]

    return np.column_stack((slope, intercept))

rawDescription: Python Multiple Simple Linear Regression


code: df.apply(lambda x: '{A} ({B})'.format(**x), axis=1)

rawDescription: How to combine tags in pandas dataframe using str.format?

description: Combine tags in pandas dataframe using str.format


rawDescription: pandas asfreq returns NaN if exact date DNE

description: Pandas asfreq returns NaN if exact date DNE


code:
def mylogin(request, **kwargs):
    if request.user.is_authenticated():
        if 'next_url' in request.session:
            url = request.session['next_url']
            del request.session['next_url']  # Cleaning next_url val
            return HttpResponseRedirect('/%s' % url)
        else:
            return HttpResponseRedirect('/')
    return login(request, **kwargs)

@csrf_protect
def login(request, template_name='registration/login.html'):
    """Displays the login form and handles the login action."""
    retval = django.contrib.auth.views.login(request, template_name)
    clear_session_data(request.session)
    return retval

rawDescription: How to access & modify Django template context variables

description: Access & modify Django template context variables


code:
class Pizza(models.Model):
   topping = models.ForeignKey('Topping')

class Topping(models.Model):
   name = models.CharField(max_length=100)

class AssembledPizza(models.Model):
   topping = models.ForeignKey('Topping')
   pizza = models.ForeignKey('Pizza')

rawDescription: How does a model relate to another model via Foreignkey?


code:
import numpy as np
import pandas as pd

arr = np.arange(15, dtype='float').reshape(5,3) % 4
arr[arr > 2] = np.nan

df = pd.DataFrame(arr, columns=list('abc'))
#     a   b   c
# 0   0   1   2
# 1 NaN   0   1
# 2   2 NaN   0
# 3   1   2 NaN
# 4   0   1   2

mask = (df['a'].isnull()) | (df['c'] == 0)
df = df.loc[~mask]

rawDescription: Drop observations from the data frame in python


code:
import multiprocessing
import os
import random

class simulation(multiprocessing.Process):
    def __init__(self, name):
        # must call this before anything else
        multiprocessing.Process.__init__(self)

        # then any other initialization
        self.name = name
        self.number = 0.0
        sys.stdout.write('[%s] created: %f\n' % (self.name, self.number))

    def run(self):
        sys.stdout.write('[%s] running ...  process id: %s\n'
                         % (self.name, os.getpid()))

        self.number = random.uniform(0.0, 10.0)
        sys.stdout.write('[%s] completed: %f\n' % (self.name, self.number))

rawDescription: Python Multiprocessing - apply class method to a list of objects


code: ['GOODLINE1\n      property1=e\n      property2=f', 'GOODLINE2\n      property1=e\n      property2=f']

rawDescription: Python RegEx: How to deal with lines

description: Python RegEx: How to deal with lines


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

import os

import cherrypy

DownloadPath = '/home/user/Videos'

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return 'Download test'

  @cherrypy.expose
  def native(self, name):
    basename = os.path.basename(name)
    filename = os.path.join(DownloadPath, basename)
    mime     = 'application/octet-stream'
    return cherrypy.lib.static.serve_file(filename, mime, basename)

  @cherrypy.expose
  def nginx(self, name):
    basename = os.path.basename(name)
    cherrypy.response.headers.update({
      'X-Accel-Redirect'    : '/download/{0}'.format(basename),
      'Content-Disposition' : 'attachment; filename={0}'.format(basename),
      'Content-Type'        : 'application/octet-stream'
    })

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: Large file downloads in cherrypy

description: Large file downloads in cherrypy


code:
rank_lookup = {rank: n for n,(rank,rank) in enumerate(rank_choices[::-1])}
ranks = Rank.objects.filter(...).values_list('rank', flat=1)
ranks = sorted(ranks, key=rank_lookup.get)

rawDescription: How can I order a Django query against a custom list of values?

description: Order a Django query against a custom list of values


rawDescription: How to find the index of the maximum absolute of the first time in a list of tuples?

description: Find the index of the maximum absolute of the first time in a list of tuples


code:
def main(argv):
  global myGlobal
  #...
  myGlobal = "bar"

rawDescription: Global variables confusion in python

description: Global variables confusion in python


code:
data = ['This', 'is', 'a', 'test', 'of', 'the', 'list']
replaceText = 'test'
replaceData =['new', 'test']
pos = data.index(replaceText)
data[pos:pos+1] = replaceData

rawDescription: python: how to replace a string in a list of string with a list of strings?

description: Python: how to replace a string in a list of string with a list of strings


code:
with cbreak():
    single_char_no_newline = sys.stdin.read(1)

rawDescription: Python, "filtered" line editing, read stdin by char with no echo


code:
def edit_article(request):
    article = Article.get(...)
    form = MyForm(request.POST, article)

rawDescription: how to give a pre-defined value to TexareaField?

description: Give a pre-defined value to TexareaField


rawDescription: How to sub with matched groups and variables in Python

description: Sub with matched groups and variables in Python


code:
import requests_cache
requests_cache.install_cache('bla')
import grequests

rawDescription: Is it possible to make grequests and requests_cache work together?


rawDescription: Iterate through 2 lists with different length in reverse order


code:
data, mask = [1, 2, 3], [1, 0, 1]
[item for index, item in enumerate(data) if mask[index]]

rawDescription: Python reduce list by mask

description: Python reduce list by mask


code:
import operator
from collections import defaultdict
listoflists = [['A', 'B', 'C', 'D'], ['B', 'A', 'C', 'D'], ['B', 'C', 'D', 'A']]

def borda(listoflists):
   outdict = defaultdict(int)
   for item in listoflists:
      outdict[item[0]] += 3
      outdict[item[1]] += 2
      outdict[item[2]] += 1

   highestitem = max(outdict.iteritems(), key=operator.itemgetter(1))[0]
   outlist = [outdict[item[0]] for item in sorted(outdict.keys())]

   return (highestitem, outlist)

rawDescription: Reiterating over lists and dictionaries

description: Reiterating over lists and dictionaries


code:
#This can contain line breaks too!  See?
''' triple-single
    quotes '''

rawDescription: String literal with triple quotes in function definitions


code: df = pd.DataFrame({'time(s)' : a, 'voltage(V)' : b, 'current(A)' : c})

rawDescription: Writing lists of data to a text file column by column


code:
class dataMatrix:
    def __init__(self, filepath):
        self.path = filepath

        # Load the .csv file to count the columns.
        self.csvdataframe = pd.read_csv(filepath)
        # Count the columns.
        self.numcolumns = len(self.csvdataframe.columns)

        # Re-load the .csv file, manually setting the column names to their
        # number.
        self.csvdataframe = pd.read_csv(filepath,
                                        names=range(self.numcolumns))

rawDescription: Using Pandas read_csv() on an open file twice


code: [d['value'] for d in l]

rawDescription: python getting a list of value from list of dict

description: Python getting a list of value from list of dict


code: forms[3]['sex'] = 'male'

rawDescription: How do you select choices in a form using Python?

description: Select choices in a form using Python


code: [myList[slice(*s)] for s in slice_indices(l=11, n=3)]

rawDescription: Splitting a list into a list of block indices


code:
outliers = []
for (x,y) in zip(a,b):
  if not inAnyPolygons(x,y,polygons):
    outliers.append((x,y))
return outliers

rawDescription: Removing points inside several polygons

description: Removing points inside several polygons


code: a = defaultdict(lambda: 1)

rawDescription: defaultdict with a parameter to the class constructor

description: Defaultdict with a parameter to the class constructor


code:
arr
arr_out

rawDescription: Python get get average of neighbours in matrix with na value


code:
def entropy(X, Y):
    probs = []
    for c1 in set(X):
        for c2 in set(Y):
            probs.append(np.mean(np.logical_and(X == c1, Y == c2)))

    return np.sum(-p * np.log2(p) for p in probs)

rawDescription: Shannon entropy to mutual information

description: Shannon entropy to mutual information


code:
from ..models import User
# ...
u = User.query.filter_by(email=form.name.data).first()
if u is not None:
  login_user(u)

rawDescription: Flask display user register, or already login in every template of each module


code:
df.rename(columns={"A": "series formerly known as A"}, inplace=True)
df

rawDescription: python pandas: Rename a series within a dataframe?

description: Python pandas: Rename a series within a dataframe


code:
orders_fields = (
    'order_id',
    'order_date',
    'order_date_shipped',
    # ... etc.
    )

rawDescription: python json to csv converting script?

description: Python json to csv converting script


rawDescription: Assign array to key dictionary in python


code:
f(g(x))
f(g(x)).simplify()

rawDescription: SymPy: simplifying of inverse function

description: SymPy: simplifying of inverse function


code:
from functools import partial

def g(accuracy, nstep):
    print ('g', accuracy, nstep)

def f(accuracy=1e-3, nstep=10):
    g(accuracy, nstep)
    print ('f', accuracy, nstep)

def fg(func, accuracy=1e-3, nstep=10):
    return partial(func, accuracy=accuracy, nstep=nstep)

fg(g)()
fg(f, 2e-5)()
fg(f, nstep=32)()

rawDescription: Avoiding code repetition in default arguments in Python


code:
from itertools import combinations
from random import randint

A = [[randint(-5,5) for coord in range(3)] for point in range(500)]

def square_distance(x,y): return sum([(xi-yi)**2 for xi, yi in zip(x,y)])

max_square_distance = 0
for pair in combinations(A,2):
    if square_distance(*pair) > max_square_distance:
        max_square_distance = square_distance(*pair)
        max_pair = pair

rawDescription: Max Distance between 2 points in a data set and identifying the points


code:
import socket, itertools
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 5555))
s.listen(1)
accepter = s.accept()
reduce(lambda x, y: accepter[0].recv(1024), itertools.count())

rawDescription: Python one liner silent socket listener

description: Python one liner silent socket listener


code:
class MyConcreteClass(MyAbstractClass):
    pass

MyConcreteClass()

rawDescription: Pure virtual methods in Python

description: Pure virtual methods in Python


code:
class RootObj(object):
   def __init__(self):
    self.internalarray = []
    self.intObj2 = InternalObject2()
    self.val1 = ""
    self.stat2 = ""
    self.stat1 = ""

class InternalObject2(object):
   def __init__(self):
    self.val2 = 0
    self.val1 = 0

class InternalObject(object):
   def __init__(self):
    self.val2 = 0
    self.val1 = 0

rawDescription: using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class

description: Using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class


code: new_max_value = max_value_observed + 1

rawDescription: Learning Python: Find and Add value inside file


rawDescription: Storing multiple get.arguments in a dict


code:
import ctypes
import ctypes.wintypes

def current_user_is_admin():
    return user_token_is_admin(0)

def user_is_admin(username, password, domain=None):
    """note that username, password, and domain should all be unicode"""

    LOGON32_LOGON_NETWORK = 3
    LOGON32_PROVIDER_DEFAULT = 0
    token = ctypes.wintypes.HANDLE()
    if ctypes.windll.advapi32.LogonUserW(username, domain, password,
            LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ctypes.byref(token)) == 0:
        raise Exception("user logon failed")

    try:
        return user_token_is_admin(token)
    finally:
        ctypes.windll.kernel32.CloseHandle(token)

def user_token_is_admin(user_token):
    """
    using the win32 api, determine if the user with token user_token has administrator rights
    """
    class SID_IDENTIFIER_AUTHORITY(ctypes.Structure):
        _fields_ = [
            ("byte0", ctypes.c_byte),
            ("byte1", ctypes.c_byte),
            ("byte2", ctypes.c_byte),
            ("byte3", ctypes.c_byte),
            ("byte4", ctypes.c_byte),
            ("byte5", ctypes.c_byte),
        ]
    nt_authority = SID_IDENTIFIER_AUTHORITY()
    nt_authority.byte5 = 5

    SECURITY_BUILTIN_DOMAIN_RID = 0x20
    DOMAIN_ALIAS_RID_ADMINS = 0x220
    administrators_group = ctypes.c_void_p()
    if ctypes.windll.advapi32.AllocateAndInitializeSid(ctypes.byref(nt_authority), 2,
        SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
        0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0:
        raise Exception("AllocateAndInitializeSid failed")

    try:
        is_admin = ctypes.wintypes.BOOL()
        if ctypes.windll.advapi32.CheckTokenMembership(
                user_token, administrators_group, ctypes.byref(is_admin)) == 0:
            raise Exception("CheckTokenMembership failed")
        return is_admin.value != 0

    finally:
        ctypes.windll.advapi32.FreeSid(administrators_group)

rawDescription: Check if an arbitrary user is in Administrator Group with Python


code:
for issue in myVals:
    assignee = (issue['fields']['assignee'] or {}).get('displayName', 'Unassigned')

rawDescription: Checking null object from JSON response in Python