code:
m1 = 10
m2 = 30
statement = 'm1 < m2 and m2 == 30'
eval(statement)

rawDescription: How to write a python script using declarative logic

description: Write a python script using declarative logic


code:
def setter(fn):
    def _get(self):
        return getattr(self, '_' + fn.__name__)
    def _set(self, val):
        return fn(self, val)
    return property(_get, _set)

rawDescription: Defining setter in a shorter way

description: Defining setter in a shorter way


code:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def home(request):
    dishes = Dishes.objects.all()
    return_list = []
    for dish in dishes:
        return_list.append((dish, dish.likes_set.filter(user=request.user)))
    return render(request, 'dish_list.html', {'dishes': return_list})

rawDescription: How to show whether user already liked object instance in Django

description: Show whether user already liked object instance in Django


code: [x.strip() for x in str(test.parent).split('<br />')]

rawDescription: python - beautifulsoup - find variable amount of text in between tags

description: Python - beautifulsoup - find variable amount of text in between tags


code:
ap.parse_args(['--toggle'])
options = ap.parse_args(['--no-toggle'])
options.toggle

rawDescription: Python argparse --toggle --no-toggle flag


rawDescription: Regex in Django for URL with % or &

description: Regex in Django for URL with % or &


rawDescription: How can I add background color inside html code using beautifulsoup?

description: Add background color inside html code using beautifulsoup


code: untilnbsp = str.split(".&nbsp")[0]

rawDescription: Get regex to match a group any amount of times


code:
for pm in sorted(projection_map, key=dfs_code_key):
    pm

rawDescription: Sorting a list of dictionary key objects with custom comparison function in Python


code:
import numpy as np
a = np.array([1+2j, 3+4j, 5+6j])
a.view(np.float).reshape(a.shape[0],2)

rawDescription: Creating new numpy scalar through C API and implementing a custom view


code:
def my_suspicious_method(*args):
    my_cool_object = CoolClass()
    # puts somewhere into global namespace, other threads access it
    publish(my_cool_object)
    my_cool_object.prepare(*args)
    # another thread modifies it now
    return my_cool_object.result()

rawDescription: If I have an @staticmethod in my python webapp, do I need to protect it with threading.RLock()?


code:
# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
import os

DEBUG = False

TEMPLATE_DEBUG = DEBUG

# Activate django-dbindexer for the default database
DATABASES['native'] = DATABASES['default']
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}
AUTOLOAD_SITECONF = 'indexes'

INSTALLED_APPS = (

    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.sessions',
    'djangotoolbox',
    'autoload',
    'dbindexer',

    # djangoappengine should come last, so it can override a few manage.py commands
    'djangoappengine',
    )

MIDDLEWARE_CLASSES = (
    # This loads the index definitions, so it has to come first
    'autoload.middleware.AutoloadMiddleware',

    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    )

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'context_processors.general'
    )

ADMIN_MEDIA_PREFIX = '/media/'
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates'),
    os.path.join(os.path.dirname(__file__), 'media'),

    )

rawDescription: GAE Configure for Django App

description: GAE Configure for Django App


code:
multilist = []
for i in range(rowNum):
    row = []
    for j in range(colNum):
        row.append(0)
    multilist.append(row)

rawDescription: Cannot understand a python code

description: Cannot understand a python code


code:
dates = Dating.objects.filter((Q(creator=user) | Q(assignee=user)) & Q(accepted=True)) \
                  .exclude(id__in=alreadyRated, finalDate__lt=datetime.today())

rawDescription: Discard older elements in Django queryset


code:
with open("welcome.py") as f:
    code = compile(f.read(), "welcome.py", 'exec')
    exec(code)

rawDescription: How to execute another python program when some condition is met?

description: Execute another python program when some condition is met


code:
allrays=np.array([r1,r2,r3,r4])
allrays

rawDescription: Efficient way of appending / extracting list elements


code:
try:
    assert_frame_equal(csvdata, csvdata_old)
    return True
except:  # appeantly AssertionError doesn't catch all
    return False

rawDescription: Comparing two pandas dataframes for differences


code:
def FileOpen(userPhrase):
    """FileOpen allows users to upload their own text document."""

    filename = input("Enter File Name (followed by .txt): ")
    text = open(filename, 'r').read()
    text = text.lower()
    for ch in ('!"#$%&()*+,-./:;<=>?@[\\]^_{}~'):
        text = text.replace(ch, " ")
    words = text.split()

    counts = {}
    for w in words:
        counts[w] = counts.get(w, 0) + 1
    n = eval(input("Output how many words?"))

    items = list(counts.items())
    items.sort(key=byFreq, reverse=True)
    for i in range(n):
        word, count = items[i]
        print("{0:<15}{1:>5}".format(word, count))

rawDescription: Files won't be read in GUI program, only in shell


rawDescription: Python fig.text() - retrieve the height of the text for alignment purposes


code: lines = [lineOne, lineTwo, lineThree, ..., lineFifty]

rawDescription: Python - most efficient way of matching a list


rawDescription: How do I skip a few iterations in a for loop

description: Skip a few iterations in a for loop


rawDescription: Concat DataFrame Reindexing only valid with uniquely valued Index objects


code:
def which_artist(self,radiob):
        """Return star's name
        """
        self.artists = {
                        1:"YOWERI KAGUTA MUSEVENI",
                        2:"KIIZA BESIGYE",
                        3:"AMAAMA JOHN MBABAZI",
                        4:"KARUNGI SHARON",
                        5:"BYAMUKAMA OSCAR",
                        6:"MATILDA MOREEN",
                        7:"DUNCANS",
        }
        return self.artists.get(radiob,"Unknown")

rawDescription: how to connect to mysql database from gui made in python

description: Connect to mysql database from gui made in python


code:
import csv
from itertools import islice

with open('input.csv', 'rb') as inf, open('output.csv', 'wb') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    for row in reader:
        while not row:
            # skip empty rows
            continue

        result = row
        for extra_row in islice(reader, 3):
            result.append(extra_row[1])
        result.extend(next(reader))
        result.append(next(reader)[1])

        writer.writerow(result)

rawDescription: CSV parsing and conversion

description: CSV parsing and conversion


code: groups

rawDescription: Deleting repeated element if it occurs twice in the sublist of a list


code:
import sympy

t = sympy.Symbol('t')

y = sympy.Function('y')(t)
p = sympy.Function('p')(t)
q = sympy.Function('q')(t)

y_ = sympy.Derivative(y, t)

# y' + p(t)y - q(t)
sol = sympy.dsolve(y_ + p*y - q, y)

print(sol)

rawDescription: how to solve first-order linear differential equations analytically and numerically with sympy?

description: Solve first-order linear differential equations analytically and numerically with sympy


code: [a[i] for i in b]

rawDescription: How can we fetch the elements of the list of specific index?


code:
from decimal import Decimal

def roundable(a, b):
    a = Decimal(str(a))
    b = Decimal(str(b))
    return a.quantize(b) == b

rawDescription: Python: a could be rounded to b in the general case


code:
# content of test_module.py

import pytest
import os
import time

# run test function 50 times with different argument
@pytest.mark.parametrize("arg", range(50))
def test_func(arg):
    time.sleep(0.05) # each tests takes a while
    if arg % 19 == 0:
        os.kill(os.getpid(), 15)

rawDescription: nose2 vs py.test with isolated processes

description: Nose2 vs py.test with isolated processes


code:
candles_data = data.pop('candles')
df = pd.DataFrame(candles_data)
for k, v in data.iteritems():
    df[k] = v

rawDescription: Working with JSON Nested in JSON Using Python/Pandas


code:
import collections
counter = collections.defaultdict(int)
for row in data:
    counter[row[0]] += 1

rawDescription: python csv: getting subset

description: Python csv: getting subset


code:
import numpy as np
a=np.random.randint(0,5,(50,50))
rand=np.random.rand(5)
rand
b=np.take(rand,a)
np.bincount(a,weights=b)
np.bincount(a.flat,weights=b.flat)

rawDescription: Vectorizing feature hashing in python

description: Vectorizing feature hashing in python


code:
def last_index(xs, key):
    index = None
    for i in xrange(len(xs)):
        if xs[i] == key:
            index = i  # override index, result in the rightmost index of key
    return index  # returns None if key is not on the list

rawDescription: How to get the last occurrence of list as output?

description: Get the last occurrence of list as output


code: ' '.join([word for word in source if isinstance(word, str)])

rawDescription: Searching for strings in list

description: Searching for strings in list


code: A = np.zeros((n,), dtype=dt)

rawDescription: Python generate from list instead of Genfromtext


code:
if original_colors['blue'] == color['green']:
    ...

rawDescription: Comparing dictionary to itself? python

description: Comparing dictionary to itself? python


code:
S = []
for i in range(0,24):

     s = np.arange(i*100,i*100+60)
     s = list(s)
S = S + s #keep only last s

rawDescription: To fill the missing data lines with pandas reindex function


rawDescription: Combining Lists in python with common elements


rawDescription: Obfuscated mandlebrot function - can someone deobfuscate it?


code:
from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

counts = OrderedCounter(['b', 'c', 'b', 'b', 'a', 'c'])
for k, c in counts.items():
    print(k, c)

rawDescription: How to optimize word_count in python

description: Optimize word_count in python


code:
class ErrorLog(models.Model):

    class Meta:
        app_label = 'core'

rawDescription: making a variable name variable?

description: Making a variable name variable


code:
hours = np.unique(time.hour) # array([0,1,2,...,21,22,23])
X, hours_2d = np.meshgrid([0, 1], hours)

rawDescription: Plotting colormap graph for each day side by side


code: query._group_by = []

rawDescription: Is it possible to reset group_by items of a sqlalchemy query object in python?


code:
alist=[1,2,3]

# Open for read/write with file initially at beginning
with open("file.txt", "r+") as f:
    # Make new lines
    newlines = ['{} {}\n'.format(old.rstrip('\n'), toadd) for old, toadd in zip(f, alist)]
    f.seek(0)  # Go back to beginning for writing
    f.writelines(newlines)  # Write new lines over old
    f.truncate()  # Not needed here, but good habit if file might shrink from change

rawDescription: Appending each element of list at the end of file lines


rawDescription: How to write a reduce phase function in erlang on riak database

description: Write a reduce phase function in erlang on riak database


code: pl.hist2d(df_points.x, df_points.y, weights=df_points.v, bins=20, cmap="viridis");

rawDescription: Find a easier way to cluster 2-d scatter data into grid array data


code:
a = numpy.zeros((3, 3, 3))
a += numpy.array((1, 3, 2)).reshape((3, 1, 1))
b = numpy.arange(3*3*3).reshape((3, 3, 3))
sort_indices = numpy.argsort(a, axis=0)
static_indices = numpy.indices((3, 3, 3))
b[sort_indices, static_indices[1], static_indices[2]]

rawDescription: Sort a numpy array by another array, along a particular axis


code: [x for x in sys.modules.keys() if "my" in x]

rawDescription: how do python module variables work?

description: How do python module variables work


code:
import  wx
class   MyCustomPanel(wx.Panel):
    def __init__(self,parent,id):
        wx.Panel.__init__(self,parent,id)
        self.sz =   wx.GridSizer(5,5,0,0)
        for i   in  range(25):
            self.sz.Add(wx.StaticText(self,-1,str(i)))
        self.SetSizer(self.sz)
        self.Bind(wx.EVT_PAINT,self.OnPaint)
    def OnPaint(self,evt):
        self.dc =   dc  =   wx.PaintDC(self)
        w,h = self.sz.GetSize()
        nr = self.sz.GetRows()
        nc = self.sz.GetCols()
        cell_w = float(w)/nc
        cell_h = float(h)/nr
        hlines = [(0,i*cell_h,w,i*cell_h)for i in range(nr+1)]
        vlines = [(i*cell_w,0,i*cell_w,h)for i in range(nc+1)]
        self.dc.DrawLineList(hlines+vlines)

if  __name__    ==  "__main__":
    a   =   wx.App(redirect=False)
    f1 = wx.Frame(None,-1)
    f   =   MyCustomPanel(f1,-1)
    #f.OnPaint(None)
    f1.Show()
    a.MainLoop()

rawDescription: How to make a Grid in wxPython?

description: Make a Grid in wxPython


code: d = dict((var, rest) for var, equals, rest in (l.split(None, 2) for l in path_output))

rawDescription: Using Python2.6 to Parse Bash Output

description: Using Python2.6 to Parse Bash Output


rawDescription: Read text file as a whole

description: Read text file as a whole


code: set(['john', 'hi', 'today'])

rawDescription: How to find words that are not the same between two text files

description: Find words that are not the same between two text files


rawDescription: update method of python dictionary did not work

description: Update method of python dictionary did not work


code: 'some, name, with, way, too, many, commas'.split(', ', 1)

rawDescription: Swapping first and last name positions

description: Swapping first and last name positions


code:
text = "text, 1CTT, 2IR8, 35TR, 4T1R, smth else, 35TT35XYZ"
pattern = re.compile(r"\b[0-9][A-Z0-9]{3}\b")
pattern.findall(text)

rawDescription: define a regular expression in python

description: Define a regular expression in python


code:
import sys
import subprocesss
code = "raise Exception()"
bad_rc = subprocess.call([sys.executable, '-c', code])
assert bad_rc == 1

rawDescription: How to execute a string containing a script using python subprocess module

description: Execute a string containing a script using python subprocess module


code: quotes = string.split('"')[1::2]

rawDescription: How can I select a string using start and endpoints (characters)?

description: Select a string using start and endpoints (characters)


code: help('FUNCTIONS')

rawDescription: Python: Function Documentation

description: Python: Function Documentation


code:
path = QtGui.QFileDialog.getOpenFileName(self, tips, QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation), expand)
if path:
    self.ui.listWidget.addItem(MyItem(path))

rawDescription: How to get the file name and show it on Qlistwidget?

description: Get the file name and show it on Qlistwidget


code:
[{u'ingreds': [
  u' 2 piernas o dos paletillas de cordero lechal o recental ',
  u'3 dientes de ajo',
  u'una copita de vino tinto / o / blanco',
  u'una copita de agua',
  u'media copita de aceite de oliva',
  u'or\xe9gano, perejil',
  u'sal, pimienta negra y aceite de oliva']}]

rawDescription: How to extract a list of items using scrapely?

description: Extract a list of items using scrapely


rawDescription: Get values from matplotlib AxesSubplot

description: Get values from matplotlib AxesSubplot


code:
import win32api
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("calc")
win32api.Sleep(100)
shell.AppActivate("Calculator")
win32api.Sleep(100)
shell.SendKeys("1{+}")
win32api.Sleep(500)
shell.SendKeys("2")
win32api.Sleep(500)
shell.SendKeys("~") # ~ is the same as {ENTER}
win32api.Sleep(500)
shell.SendKeys("*3")
win32api.Sleep(500)
shell.SendKeys("~")
win32api.Sleep(2500)

rawDescription: How can I paste some string to the active window in Python?

description: Paste some string to the active window in Python


code:
import os, time
time.strftime('%X %x %Z')
os.environ['TZ'] = 'Europe/London'
time.tzset()
time.strftime('%X %x %Z')

rawDescription: Setting timezone in Python

description: Setting timezone in Python


code:
requests = Request.query.all()
for request in requests:
    demand_date = getattr(
        request, 'demand_date', 'demand_date not available on this type')
    print(request.type, demand_date)

rawDescription: Bidirectional behavior in relationships to different models


rawDescription: Constructing String Without Concatenation in Python 2.7


code:
L = len(hugelist) - 1
auxdict = dict((item, L-i) for i, d in enumerate(reversed(hugelist)) for item in d['ids'])

rawDescription: Python: find index of item containing X in list


code:
from collections import Sequence
from itertools import chain, count

def depth(seq):
    seq = iter(seq)
    try:
        for level in count():
            seq = chain([next(seq)], seq)
            seq = chain.from_iterable(s for s in seq if isinstance(s, Sequence))
    except StopIteration:
        return level

rawDescription: Counting "deepness" or the deepest level a nested list goes to


code:
import json

def loads_jsonp(jsonp, callback_name):
    jsonp = jsonp.strip()
    if jsonp.startswith(callback_name + '(') and jsonp.endswith(')'):
        # remove the leading "callback(" and trailing ")", then parse the json
        return json.loads(jsonp[len(callback_name) + 1:-1])
    raise ValueError.new("Callback names do not match, or invalid JSONP format")

rawDescription: How to write a regular expression to search such string?

description: Write a regular expression to search such string


code:
from bs4 import BeautifulSoup

html_doc = """

        <title>A test</title>

                    Stuff here with a link

Or paragraph tags

Or a DIV

                Another TD element, without the MenuTD id

"""

soup = BeautifulSoup(html_doc)

rawDescription: Remove matched tags in html files?

description: Remove matched tags in html files


code:
position = defaultdict(lambda: defaultdict(defaultdict_int))
gap = defaultdict(lambda: defaultdict(defaultdict_int))
absolute_total = 0

for gap, count, prefered, channel, position in raw_data:
    absolute_total += count

    posd = position[position]
    posd.setdefault('total', 0)
    posd['total'] += count
    posd['tid'][tid] += count
    posd['channel'][channel] += count

    gapd = gap[gap]
    gapd.setdefault('total', 0)
    gapd['total'] += count
    gapd['tid'][tid] += count
    gapd['channel'][channel] += count

rawDescription: Python trying to Refactor (DRY out) a long Control Flow


code: main_module = __import__(main_module_name, fromlist=[str('bar')])

rawDescription: Portable code: __import__ parameter string type between Python 2 and Python 3


code: [obj for obj in dir(x) if not obj.startswith('__')]

rawDescription: Parse Python file to retrieve variables, values, function definitions


code:
fwd = Widget(...)
fwd.pack()

rawDescription: Is it possible to run a while loop and check for tkinter input in python 3


code:
import wx

class Frame ( wx.Frame ):
    def __init__( self ):
       wx.Frame.__init__ ( self, None, id = wx.ID_ANY, title = wx.EmptyString, pos =
                         wx.DefaultPosition, size = wx.Size( 500,300 ),
                         style = wx.DEFAULT_FRAME_STYLE & ~   (wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX|wx.RESIZE_BORDER) )
       nums = (('1',(0,3)), ('2',(2,3)), ('14', (3,3)), ('15',(4,3)), ('16',(5,3)), ('17',(6,3)), ('18',(7,3)),
         ('3',(1,0)), ('4',(1,1)), ('5',(1,2)), ('6',(1,3)), ('7',(1,4)), ('8',(1,5)), ('9',(1,6)), ('10',(1,7)),
         ('11',(1,8)), ('12',(1,9)), ('13',(1,10)))

       panel = wx.Panel(self,-1)
       panel.SetBackgroundColour("green")
       grid = wx.GridBagSizer(2,2)

       for num, pos in nums:
           button = wx.Button(panel, wx.NewId(), size=(10,-1), label = num)
           grid.Add(button, pos, flag=wx.EXPAND)

       for i in range(11):
           grid.AddGrowableCol(i)

       bs2 = wx.BoxSizer(wx.VERTICAL)
       bs2.Add(grid, 0, wx.EXPAND,0)

       panel.SetSizer(bs2)
       panel.Layout()
       self.mainSizer = wx.BoxSizer(wx.VERTICAL)
       self.mainSizer.Add(panel, 0, wx.EXPAND, 0)
       self.SetSizer(self.mainSizer)
       self.Layout()

if __name__=='__main__':
    app=wx.PySimpleApp()
    app.frame = Frame()
    app.frame.Center()
    app.frame.Show(True)
    app.MainLoop()

rawDescription: wxPython: Problems with GridBagSizer

description: WxPython: Problems with GridBagSizer


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

class Neuralnet:
    def __init__(self, neurons, activation):
        self.weights = []
        self.inputs = []
        self.outputs = []
        self.errors = []
        self.rate = 0.5
        self.activation = activation    #sigmoid or tanh

        self.neurons = neurons
        self.L = len(self.neurons)      #number of layers

        eps = 0.12;    # range for uniform distribution   -eps..+eps
        for layer in range(len(neurons)-1):
            self.weights.append(np.random.uniform(-eps,eps,size=(neurons[layer+1], neurons[layer]+1)))

    ###################################################################################################
    def train(self, X, Y, iter_count):

        m = X.shape[0];

        for layer in range(self.L):
            self.inputs.append(np.empty([m, self.neurons[layer]]))
            self.errors.append(np.empty([m, self.neurons[layer]]))

            if (layer < self.L -1):
                self.outputs.append(np.empty([m, self.neurons[layer]+1]))
            else:
                self.outputs.append(np.empty([m, self.neurons[layer]]))

        #accumulate the cost function
        J_history = np.zeros([iter_count, 1])

        for i in range(iter_count):

            self.feedforward(X)

            J = self.cost(Y, self.outputs[self.L-1])
            J_history[i, 0] = J

            self.backpropagate(Y)

        #plot the cost function to check the descent
        plt.plot(J_history)
        plt.show()

    ###################################################################################################
    def cost(self, Y, H):
        J = np.sum(np.sum(np.power((Y - H), 2), axis=0))/(2*m)
        return J

    ###################################################################################################
    def feedforward(self, X):

        m = X.shape[0];

        self.outputs[0] = np.concatenate(  (np.ones([m, 1]),   X),   axis=1)

        for i in range(1, self.L):
            self.inputs[i] = np.dot( self.outputs[i-1], self.weights[i-1].T  )

            if (self.activation == 'sigmoid'):
                output_temp = self.sigmoid(self.inputs[i])
            elif (self.activation == 'tanh'):
                output_temp = np.tanh(self.inputs[i])

            if (i < self.L - 1):
                self.outputs[i] = np.concatenate(  (np.ones([m, 1]),   output_temp),   axis=1)
            else:
                self.outputs[i] = output_temp

    ###################################################################################################
    def backpropagate(self, Y):

        self.errors[self.L-1] = self.outputs[self.L-1] - Y

        for i in range(self.L - 2, 0, -1):

            if (self.activation == 'sigmoid'):
                self.errors[i] = np.dot(  self.errors[i+1],   self.weights[i][:, 1:]  ) *  self.sigmoid_prime(self.inputs[i])
            elif (self.activation == 'tanh'):
                self.errors[i] = np.dot(  self.errors[i+1],   self.weights[i][:, 1:]  ) *  (1 - self.outputs[i][:, 1:]*self.outputs[i][:, 1:])

        for i in range(0, self.L-1):
            grad = np.dot(self.errors[i+1].T, self.outputs[i]) / m
            self.weights[i] = self.weights[i] - self.rate*grad

    ###################################################################################################
    def sigmoid(self, z):
        s = 1.0/(1.0 + np.exp(-z))
        return s

    ###################################################################################################
    def sigmoid_prime(self, z):
        s = self.sigmoid(z)*(1 - self.sigmoid(z))
        return s

    ###################################################################################################
    def predict(self, X, weights):

        m = X.shape[0];

        self.inputs = []
        self.outputs = []
        self.weights = weights

        for layer in range(self.L):
            self.inputs.append(np.empty([m, self.neurons[layer]]))

            if (layer < self.L -1):
                self.outputs.append(np.empty([m, self.neurons[layer]+1]))
            else:
                self.outputs.append(np.empty([m, self.neurons[layer]]))

        self.feedforward(X)

        return self.outputs[self.L-1]

###################################################################################################
#                MAIN PART

activation1 = 'sigmoid'     # the input should be scaled into [ 0..1]
activation2 = 'tanh'        # the input should be scaled into [-1..1]

activation = activation1

net = Neuralnet([1, 6, 1], activation) # structure of the NN and its activation function

##########################################################################################
#                TRAINING

m = 1000 #size of the training set
X = np.linspace(0, 4*math.pi, num = m).reshape(m, 1); # input training set

Y = np.sin(X) # target

kx = 0.1 # noise parameter
noise = (2.0*np.random.uniform(0, kx, m) - kx).reshape(m, 1)
Y = Y + noise # noisy target

# scaling of the target depending on the activation function
if (activation == 'sigmoid'):
    Y_scaled = (Y/(1+kx) + 1)/2.0
elif (activation == 'tanh'):
    Y_scaled = Y/(1+kx)

# number of the iteration for the training stage
iter_count = 20000
net.train(X, Y_scaled, iter_count) #training

# gained weights
trained_weights = net.weights

##########################################################################################
#                 PREDICTION

m_new = 40 #size of the prediction set
X_new = np.linspace(0, 4*math.pi, num = m_new).reshape(m_new, 1);

Y_new = net.predict(X_new, trained_weights) # prediction

#rescaling of the result
if (activation == 'sigmoid'):
    Y_new = (2.0*Y_new - 1.0) * (1+kx)
elif (activation == 'tanh'):
    Y_new = Y_new * (1+kx)

# visualization
plt.plot(X, Y)
plt.plot(X_new, Y_new, 'ro')
plt.show()

raw_input('press any key to exit')

rawDescription: Neural network backpropagation algorithm not working in Python


code:
def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

rawDescription: Setting a value in a nested python dictionary given a list of indices and value


code:
if __name__ == '__main__':
    import sys
    import subprocess

    if len(sys.argv) > 1:
        # child process
        import time
        hEvent = int(sys.argv[1])
        kernel32.SetEvent(hEvent)
        time.sleep(120)
        sys.exit(0)

    wintypes.SIZE_T = ctypes.c_size_t
    kernel32.ReadProcessMemory.argtypes = (wintypes.HANDLE,
                                           wintypes.LPVOID,
                                           wintypes.LPVOID,
                                           wintypes.SIZE_T,
                                           ctypes.POINTER(wintypes.SIZE_T))

    class SECURITY_ATTRIBUTES(ctypes.Structure):
        _fields_ = (('nLength',              wintypes.DWORD),
                    ('lpSecurityDescriptor', wintypes.LPVOID),
                    ('bInheritHandle',       wintypes.BOOL))
    def __init__(self, *args, **kwds):
        super(SECURITY_ATTRIBUTES, self).__init__(*args, **kwds)
        self.nLength = ctypes.sizeof(self)

    WAIT_OBJECT_0 = 0
    CREATE_NO_WINDOW = 0x08000000

    sa = SECURITY_ATTRIBUTES(bInheritHandle=True)
    hEvent = kernel32.CreateEventW(ctypes.byref(sa), 0, 0, None)
    script = os.path.abspath(__file__)
    p = subprocess.Popen([sys.executable, script, str(hEvent)],
                         close_fds=False,
                         creationflags=CREATE_NO_WINDOW)
    try:
        result = kernel32.WaitForSingleObject(hEvent, 60 * 1000)
        if result != WAIT_OBJECT_0:
            sys.exit('wait failed')
        # kernel32 should load at the same address in a given session.
        hModule = GetRemoteModuleHandle(p.pid, 'kernel32')
        assert hModule == kernel32._handle
        remote_addr = GetRemoteProcAddress(p.pid,
                                           'kernel32',
                                           'LoadLibraryExW')
        local_addr = ctypes.c_void_p.from_buffer(
                        kernel32.LoadLibraryExW).value
        assert remote_addr == local_addr
        remote_bytes = (ctypes.c_char * 1000)()
        read = wintypes.SIZE_T()
        kernel32.ReadProcessMemory(int(p._handle),
                                   remote_addr,
                                   remote_bytes, 1000,
                                   ctypes.byref(read))
        local_bytes = ctypes.string_at(kernel32.LoadLibraryExW, 1000)
        assert remote_bytes[:] == local_bytes
    finally:
        p.terminate()

rawDescription: GetModuleHandleA fails to get modules not used by python.exe when attached to another process


rawDescription: Python Code to combine duplicated element


code: b, a = sg.butter(10, 1./np.sqrt(N))

rawDescription: MATLAB fftfilt equivalent for Python

description: MATLAB fftfilt equivalent for Python


code:
numbers = [3, 5, 77, 8]
max_number = max(numbers)
numbers[:] = [number for number in numbers if number != max_number]
numbers

rawDescription: How do you find and delete the highest integer in a list of unknown integers

description: Find and delete the highest integer in a list of unknown integers


code:
from Levenshtein import distance
from bktree import BKtree
def remove_duplicates(lst, threshold):
    tr = BKtree(iter(lst), distance, threshold)
    return tr.nodes.keys()

rawDescription: Generating a list of distinct (distant, by edit distance) words by filtering


rawDescription: Python regular expression for getting html code excluding commented code in page source


code:
if len(lst) >= 4:             # Tuple w/ sort info first
    lines[n] = (lst[4], lines[n])
else:                         # Short lines to end
    lines[n] = (['\377'], lines[n])

rawDescription: Schwartzian sort example in "Text Processing in Python"


code:
import re

fishlength = re.compile("max length : ([\d.]+) ([cm]{1,2})", re.I).search

def get_length_in_cm(html):
    m = fishlength(html)
    if m:     # match found
        value = float(m.group(1))
        unit  = m.group(2)
        if unit == "cm":
            return value
        elif unit == "m":
            return value * 100.
        else:
            raise ValueError("Unknown unit: {}".format(unit))
    else:
        raise ValueError("Length not found")

rawDescription: Python Search and Scrape

description: Python Search and Scrape


code:
with PatchContextManager('mymodule.method', 'return_string') as mocked:
    a = mymodule.method(47) # a == 'return_string'
    mocked.assert_called_with(47)
    ...

rawDescription: Python 3 urlopen context manager mocking


code: ct

rawDescription: Using pandas for the probability of two nodes to be linked in a network


rawDescription: Accessing a repeated element in the list and printing the element next to it


rawDescription: How do you iterate over two dictionaries and grab the values at the same path?

description: Iterate over two dictionaries and grab the values at the same path


code:
def content_test(term):
    return any(c.isalpha() for c in term)

rawDescription: Pythonic String Testing

description: Pythonic String Testing


code:
htmlcontent = 'Hi @user.name. How are you?'
re.sub(r'((\@)([\w.-]+[\w]+))', r"\1", htmlcontent)

rawDescription: Using python regex to exclude '.' at the end but not inside a string


code: temp = [line[:-1] for line in file]

rawDescription: Reading a file without newlines

description: Reading a file without newlines


code:
def one_op (op, arg1, arg2):
    return  If(op==1,
               arg1*arg2,
               If(op==2,
                  arg1-arg2,
                  If(op==3,
                     arg1+arg2,
                     arg1+arg2)))

rawDescription: (Z3Py) any limitations in functions declaring?


code:
b = np.array([1, 3, 1, 2, 4, 3, 3, 2, 0])
idx = np.argsort(b, kind='mergesort')  # need stable sort
sorted_b = b[idx]
sorted_b
sorted_is_first = np.concatenate(([True], sorted_b[1:] != sorted_b[:-1]))
sorted_is_first
is_first = sorted_is_first[idx.argsort()]
is_first

rawDescription: Indirect-ish sort with Numpy

description: Indirect-ish sort with Numpy


code:
def get_parent(self):
    """Should return the object that should be queried for ownership information"""
    pass
def owned_by(self, user):
    """Should return a boolean indicating whether `user` owns the object, by querying `self.get_parent().owned_by(user)`"""
    pass

rawDescription: Django Admin Non Staff Access Data Filtering


code:
obj = None
obj = (obj,[1,2,3])[::cmp(bool(obj),0.5)]
obj
obj = True
obj = (obj,[1,2,3])[::cmp(bool(obj),0.5)]
obj

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

description: Omit the redundant words in python condition loop


code:
def anyof_v2(short_group_list, adu):
  gset = set(short_group_list)
  return any(g for gs in adu.get('memberOf',()) for g in grps(gs) if g in gset)

rawDescription: Finding partial strings in a list of strings - python


code:
msg = 'Enter the base path of the images: '
try:
    # python 2
    path = raw_input(msg)
except NameError:
    # python 3
    path = input(msg)

rawDescription: Curious behaviour of print_function in __future__ module on Python 3


code:
if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    ui = Ui_Form()
    ui.show()
    sys.exit(app.exec_())

rawDescription: Does closing a GUI in PyQt4 destroy its children Qobjects by default


code:
import b

def doX():
    print("in x") # line 4
    b.doY()

if __name__ == "__main__":
    doX()

rawDescription: Remember breakpoints when debugging using ipython


code:
student = Student(name='Jim')
session.add(student)
session.flush()
for enr in ('Maths', 'Physics', 'Art'):
  session.add(StudentEnrollment(student_id=student.student_id, subject=enr))
session.flush()
session.commit()

rawDescription: SQLAlchemy relationships populating foreign key fields


code:
OrderedDict.__repr__
OrderedDict.__repr__.__func__
OrderedDict.__repr__.__func__.__get__(None, OrderedDict)
OrderedDict.__repr__.__func__ is OrderedDict.__repr__.__func__

rawDescription: Very strange behavior of operator 'is' with methods


code:
from ctypes import *
int_array = (c_int * 4)(1, 2, 3, 4)
n_doubles = sizeof(int_array) // sizeof(c_double)
array_t = c_double * n_doubles
double_array = array_t.from_buffer(int_array)

rawDescription: How to interpret a integer as a float

description: Interpret a integer as a float


code: [{'phone': 'None', 'Name': 'Bala1'}, {'phone': 'None', 'Name': 'Bala'}]

rawDescription: Remove duplicate JSON objects from list in python


code:
l = ['animals|fish|salmon', 'fish|salmon', 'fish', 'animals', 'furniture',
    'animals|big cats|lions', 'animals|birds|fisher bird']

def simplify (data):
    data = ['|{}|'.format (e) for e in data]
    return [e [1:-1] for e in data if all (e is other or e not in other for other in data) ]

print (simplify (l) )

rawDescription: Identifying elements that occur within strings in a list


code:
from multiprocessing import Process, Pipe

plugins = {}

for plugin in PluginLoader("plugins"):
    ... #select plugin(s)
    if selected:
        plugins[plugin.__name__], child = Pipe()
        p = Process(target=plugin, args=(child,))
        p.start()

...

for plugin in plugins.values():
    plugin.put("EventHappened")

...

for plugin in plugins.values():
    event = plugin.get(False)
    if event:
       ... #handle event

rawDescription: Plugin manager in python

description: Plugin manager in python


rawDescription: Make Pandas groupby act similarly to itertools groupby


rawDescription: Django reverse relations

description: Django reverse relations


rawDescription: How to split a column based on several string indices using pandas

description: Split a column based on several string indices using pandas


code: test = requests.get('https://utas.s2.fut.ea.com/ut/game/fifa16/trade/{}/bid'.format(playerNumber), headers=headers, cookies=cookies)

rawDescription: Adding a param to a URL in Python

description: Adding a param to a URL in Python


rawDescription: Python: How to know if two dictionary have the same keys


code:
def every_hour():
    [...]

db = None
def app1_init():
    global db
    Monitor(cherrypy.engine, every_hour, frequency=60 * 60).start()
    db = peewee.SqliteDatabase('app1.db', threadlocals=True)

class App1():
    def __init__(self, root_dir):
        self.root_dir = root_dir
        my_path = os.path.dirname(__file__)
        self.config = {'/%s/css' % root_dir: {'tools.staticdir.on': True, 'tools.staticdir.dir': '%s\\css' % my_path},
                       '/%s/img' % root_dir: {'tools.staticdir.on': True, 'tools.staticdir.dir': '%s\\img' % my_path}}

rawDescription: Prevent code from running at import time


code:
import os
print(os.environ['ans'])

rawDescription: How to make a script auto-provide arguments to another without passing via command line?

description: Make a script auto-provide arguments to another without passing via command line


code: instance = getattr(different_classes, class_type)(x, y, z)

rawDescription: Class as an input in a function

description: Class as an input in a function


code: attrs = [getattr(MyClass, column_name) for column_name in column_names]

rawDescription: return NOT NULL columns from class with sqlalchemy

description: Return NOT NULL columns from class with sqlalchemy


code: reload(mf)

rawDescription: how to reload a cython module interactively using pyximport

description: Reload a cython module interactively using pyximport


code:
# file a.py
from b import foo
import args
args.parser.add_argument('-a')

# only actually parse args if we are invoked as main script; mere `import a`
# shouldn't run the parser
if __name__ == '__main__':
    args = parser.parse_args()
    ...

# file b.py
import args
args.parser.add_argument('-b')

foo = 1

rawDescription: What is the scope of python argparse

description: What is the scope of python argparse


code:
from sqlalchemy import event

class ModelChangeEvent(object):
    def __init__(self, session, *callbacks):
        self.model_changes = {}
        self.callbacks = callbacks

        event.listen(session, 'before_flush', self.record_ops)
        event.listen(session, 'before_commit', self.record_ops)
        event.listen(session, 'after_commit', self.after_commit)
        event.listen(session, 'after_rollback', self.after_rollback)

    def record_ops(self, session, flush_context=None, instances=None):
        for targets, operation in ((session.new, 'insert'), (session.dirty, 'update'), (session.deleted, 'delete')):
            for target in targets:
                state = inspect(target)
                key = state.identity_key if state.has_identity else id(target)
                self.model_changes[key] = (target, operation)

    def after_commit(self, session):
        if self._model_changes:
            changes = list(self.model_changes.values())

            for callback in self.callbacks:
                callback(changes=changes)

            self.model_changes.clear()

    def after_rollback(self, session):
        self.model_changes.clear()

rawDescription: Run function after a certain type of model is committed


code:
def new_leap(start, end):
    return [x for x in xrange(start, end + 1)
            if (x % 400 == 0) or (x % 4 == 0 and not x % 100 == 0)]

rawDescription: Leap-year program in Python

description: Leap-year program in Python


code: povijest = sorted([sorted(i) for i in provijest])

rawDescription: sorting list of lists Python 2.7

description: Sorting list of lists Python 2.7


rawDescription: Why is numpy/pandas returning only the first character when I use .astype(str)


code:
# static consts - outside so that every instance of Particle doesn't take them along
# for the ride...
MAX_X = 150,000
X_STEP = 8000
# etc.

class Particle(object):

    def __init__(self, data):
        self.x = data[xvalue]
        self.y = data[yvalue]
        self.z = data[zvalue]
        self.compute_box_label()

    def compute_box_label(self):
        import math

        x_label = math.floor(self.x / X_STEP)
        y_label = math.floor(self.y / Y_STEP)
        z_label = math.floor(self.z / Z_STEP)
        self.box_label = str(x_label) + '-' + str(y_label) + '-' + str(z_label)

rawDescription: Quickly counting particles in grid

description: Quickly counting particles in grid


code: "google, Inc.".replace(', Inc.', '')

rawDescription: what is the asterisk in "replace(*something)" for? (python)

description: What is the asterisk in "replace(*something)" for? (python)


code:
from bs4 import BeautifulSoup as Soup
from itertools import chain

soup = Soup(xml, 'html.parser')

bins = []
for message in soup.findAll('groupname'):
    min = message.find('min').text
    try:
        max = message.find('max').text
        bins.append([min, max])
    except:
        bins.append([min]) # For max bin

rawDescription: Grouping values using pandas cut

description: Grouping values using pandas cut


code: from .my_class import MyClass  # noqa

rawDescription: python pep8 class in init imported but not used

description: Python pep8 class in init imported but not used


code:
x = Int('x')
y = Int('y')
max = If(x > y, x, y)
max
simplify(max)

rawDescription: Z3: how to encode If-the-else in Z3 python?


rawDescription: Subprocess calls are they done in parallel?


code:
import Tkinter as tk
import ttk

class MyMenu(tk.Menu):
    pass

class MyNotebook(ttk.Notebook):
    pass

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.frame = ttk.Frame(self)
        self.notebook = MyNotebook(self.frame)
        self.frame.pack()
        self.notebook.pack()
        self.add_tab()

        menu = MyMenu()
        menu.add_command(label="Add tab", command=self.add_tab)
        self.config(menu=menu)

    def add_tab(self):
        text = "Tab {}".format(len(self.notebook.tabs()))
        frame = ttk.Frame(self.notebook, width=100, height=100)
        self.notebook.add(frame, text=text)

app = App()
app.mainloop()

rawDescription: interaction of different elements of window in Tkinter

description: Interaction of different elements of window in Tkinter


rawDescription: Passing arguments to views in Django from constrained choices


rawDescription: Get the first 100 elements of OrderedDict


rawDescription: Strange performance results for numpy matrix multiplication


code:
{u'altSymbol': u'CL/M5',
 u'assetType': u'DERIVATIVE',
 u'change': u'-1.39',
 u'code': 0,
 u'curmktstatus': u'REG_MKT',
 u'currencyCode': u'USD',
 u'encodedSymbol': u'CLCV1',
 u'exchange': u'New York Mercantile Exchange',
 u'high': u'61.31',
 u'last': u'59.54',
 u'low': u'59.14',
 u'name': u"WTI Crude Oil (Jun'15)",
 u'noStreaming': u'false',
 u'open': u'60.69',
 u'provider': u'CNBC Quote Cache',
 u'realTime': u'false',
 u'shortName': u'OIL',
 u'source': u'',
 u'symbol': u'CLCV1',
 u'symbolType': u'symbol',
 u'timeZone': u'EDT',
 u'volume': u'189607'}

rawDescription: Extracting between specific <script> </script> tag


rawDescription: For loop, how can i use loop variable outside loop


code: soup.find_all("a", href=lambda href: href and "price" in href)

rawDescription: Navigation with BeautifulSoup

description: Navigation with BeautifulSoup


code:
class TextAutocomplete(TextCtrl, AutoComplete):
    pass

rawDescription: How to change baseclass

description: Change baseclass


rawDescription: How to get the optimal optimization variables in Pulp with Python?

description: Get the optimal optimization variables in Pulp with Python


code:
pokemon
pokemon.apply(pokes.get)

rawDescription: Map each element in a Series to a Series and combine the result into a DataFrame


code:
longref = pd.DataFrame([('Item {}'.format(item), row['Position'])
                        for index, row in reference.iterrows()
                        for item in row['Item(s)']], columns=['Item', 'Position'])

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


code:
spreadout(range(6), list("ABC"))
xy_wrapper(5, 17)

rawDescription: Python - "properly" organise (spread out) x and y data


code:
for key, value in dict.items():
    # You don't need to do dict.get anymore, you already have it:
    if value == 'gas':
        list.append(key)

rawDescription: Working with tuples and dictionaries

description: Working with tuples and dictionaries


code:
from collections import deque
from itertools import permutations
from operator import itemgetter

def comparisons(seq):
    return [abs(a-b) for a, b in zip(seq, seq[1:])]

def best_order(n):
    temp = deque([0, n-1])
    low = 1
    high = n-2
    while low < high:
        left = temp[0]
        right = temp[-1]
        if left < right:
            temp.append(low)
            temp.appendleft(high)
        else:
            temp.append(high)
            temp.appendleft(low)
        low += 1
        high -= 1
    if len(temp) < n:
        temp.append(low)
    return list(temp)

def brute_force(n):
    getcomp = itemgetter(2)
    return max([(list(a), comparisons(a), sum(comparisons(a))) for a in permutations(range(n))], key=getcomp)

for i in range(2, 6):
    print("Algorithmic:", best_order(i), comparisons(best_order(i)), sum(comparisons(best_order(i))))
    print("Brute Force:", *brute_force(i))

rawDescription: Comparison between adjacent elements in sequences


code:
strs = "foo bat foo"
set(strs.split())

rawDescription: word frequency calculation in multiple files

description: Word frequency calculation in multiple files


code:
from itertools import *
c=count(1)
lis=[0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]
list(chain(*[list(g) if k!=1 else [next(c)]*len(list(g)) for k,g in groupby(lis)]))

rawDescription: Increment list based on number pattern

description: Increment list based on number pattern


rawDescription: Find there is an emoji in a string in python3


code:
# create a dictionary of column names and the value you want
d = dict.fromkeys(l, 0)
df.assign(**d)

rawDescription: Add multiple columns with zero values from a list to a Pandas data frame


rawDescription: solving for a compound interest between PV and "summation" FV?

description: Solving for a compound interest between PV and "summation" FV


code:
def examineVar():
  container = list(input('Which var would you like to examine? '))
  for i in range (len(container)):
    print(container[i])

rawDescription: How can I allow users to reference variables and other data structures via input?

description: Allow users to reference variables and other data structures via input


code:
#!/bin/bash
command1
command2
command3
...

rawDescription: Running a Python script automatically when launching a Docker container


rawDescription: Is this the best way to add an extra dimension to a numpy array in one line of code?


code:
@userreg.route('/pic/<name>')
def getpic(name):
     qu=db.Query(MyPics).filter('name =',name).get()
     if qu.pic is None:
         return "hello"
     else:
         mimetype = 'image/png'
         return current_app.response_class(qu.pic,mimetype=mimetype,direct_passthrough=False)

rawDescription: Storing images in google datastore using Flask (Python)


rawDescription: moving a function out of my method in django

description: Moving a function out of my method in django


code:
import re
a = """
01:09:25.258 mta         Messages       I Doc O:NVS:SMTP/alarm@yyy.xx R:NVS:SMS/+654811 mid:6261
01:09:41.965 mta         Messages       I Rep O:NVS:SMTP/alarmes.techniques@xxx.de R:NVS:SMS/+455451 mid:6261
01:09:41.965 mta         Messages       I Rep 6261 OK, Accepted (ID: 26)
08:14:14.469 mta         Messages       I Doc O:NVS:SMTP/alarm@xxxx.en R:NVS:SMS/+654646 mid:6262
08:14:30.630 mta         Messages       I Rep O:NVS:SMTP/alarm@azea.er R:NVS:SMS/+33688704859 mid:6262
08:14:30.630 mta         Messages       I Rep 6262 OK, Accepted (ID: 28)"""
m = re.findall(".*?I Doc O:.*",a)
tableau = []
for line in m:
    tableau.append( extraire(line) )

tableau

rawDescription: Read only lines that contain certain specific string and apply regex on them


code:
f = make_fun(['a', 'b'])
import inspect
print(inspect.signature(f).parameters)

rawDescription: Programmatically create function specification


code:
def get_new_point():
    # After going 1 km North, 1 km East, 1 km South and 1 km West
    # we are back where we were before.
    return (-24680.1613, 6708860.65389)

rawDescription: Calculate point based on distance and direction


code:
class Character():
    def __init__(self):
        self.name = None
        self.hp = None
        self.mp = None

rawDescription: Saving and Loading a Class Instance

description: Saving and Loading a Class Instance


code: #define HDIO_GET_IDENTITY       0x030d  /* get IDE identification info */

rawDescription: How to get hard disk serial number using Python

description: Get hard disk serial number using Python


rawDescription: Grouping and finding most frequent values


code: file_out[-1] = file_out[-1].strip('\n')

rawDescription: Python - delete blank lines of text at the end of the file


code:
#Import the necessary namespaces
from Spotfire.Dxp.Application.Visuals import VisualContent
from Spotfire.Dxp.Application.Visuals import AxisRange
from Spotfire.Dxp.Data import DataPropertyClass

#Define variables
min = Document.Properties["StartDate"]
max = Document.Properties["EndDate"]

#Cast visual as specific plot type
#Note use of VisualContent for any chart type
plot1= plot1.As[VisualContent]()
plot2= plot2.As[VisualContent]()
plot3= plot3.As[VisualContent]()

#Set visualization parameters
plot1.XAxis.Range = AxisRange(min,max);
plot2.XAxis.Range = AxisRange(min,max);
plot3.XAxis.Range = AxisRange(min,max);

rawDescription: Set Spotfire Graph Axis Range Programatically


code: [t for t in myList if t]

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


code:
try:
    import Queue as queue  # python2
except:
    import queue
output = queue.Queue()

def run(self):
    result = TS(self.param)
    output.append(result)

rawDescription: Complete a multithreading parallelize process with k threads


rawDescription: Python, Numpy - Trying split an array according to a condition


code:
class ClassView(View):
    def get(self, request):
        return HttpResponse("test")

    def post(self, request):
        # do something
        return redirect("test")

rawDescription: Django class based generic view redirect


rawDescription: 2-d interpolation ignoring nan values

description: 2-d interpolation ignoring nan values


code:
import string
string.lowercase[:14]
string.lowercase[:14:2]

rawDescription: Python: how to print range a-z?

description: Python: how to print range a-z


code: A.objects.exclude( ~Q(b__x=1) , ~Q(c__y=2)).distinct()

rawDescription: Full outer Join in Django with all columns (null if not existing)


code:
import scitools.filetable

with open("blabla.dat", "r") as fp:
    fp.next()

    a, b, c, d, e = scitools.filetable.read_columns(fp)

rawDescription: Read columns from file where first row is string


code:
Col1   -693
Col2   -204
dtype: int64

rawDescription: Python/Pandas subtracting numbers in a column


code: sorted(inputlist, key=lambda t: t == (0, 0))

rawDescription: For Python, how to sort and lump elements in a fixed-sized list


code:
from bs4 import BeautifulSoup
import requests

URL = "http://sports.williamhill.com/bet/en-gb/betting/y/5/tm/0/Football.html"
response = requests.get(URL)

soup = BeautifulSoup(response.content, 'html.parser')

for fraction in soup.findAll("div", { "class" : "eventprice" }):
    print(fraction.get_text(strip=True))

rawDescription: Extracting string with BeautifulSoup

description: Extracting string with BeautifulSoup


code:
scores = '''\
Imran - 8
Joeseph - 5
Test1 - 6
Test2 - 4
Joeseph - 10
Aaron - 4
Test1 - 1
Zzron - 1
Joeseph - 3
Test1 - 10
Joeseph - 4
'''.splitlines(True)
user_scores = {}
for line in scores:
    name, score = line.rstrip('\n').split(' - ')
    score = int(score)
    if name not in user_scores or user_scores[name] < score:
        user_scores[name] = score

for name in sorted(user_scores):
    print(name, '-', user_scores[name])

rawDescription: Displaying only a person's highest score from a .txt file (Python 3)


code: new_image= image.point(lambda value: value<<4 | value>>8)

rawDescription: Rescale intensities of a PIL Image

description: Rescale intensities of a PIL Image


rawDescription: Writing with numbers

description: Writing with numbers


code: np.nanmean(arr, axis=1)

rawDescription: Read data with NAs into python and calculate mean row-wise


code:
print(ET.tostring(dom))
# <Envelope>
#   <Header>
#     <Version>1</Version>
#   </Header>
#   <Body>
#     some stuff
#   </Body>
# </Envelope>

rawDescription: lxml etree xmlparser namespace problem

description: Lxml etree xmlparser namespace problem


rawDescription: Python cosine-similarity on all possible pairs in list


rawDescription: Using pyinotify to watch for file creation, but waiting for it to be completely written to disk


code:
from collections import defaultdict
def group_by_both(filenames):
    '''Puts the filenames in the given iterable into two dictionaries,
    where in the first, the key is the first component of the filename,
    and in the second, the key is the last component of the filename.
    The values in each dictionary are lists of the filenames with that
    base or extension.'''
    by_name = defaultdict(list)
    by_ext = defaultdict(list)
    for f in filenames:
        name, ext = f.split('.', 1)
        by_name[name] += [f]
        by_ext[ext] += [f]
    return by_name, by_ext

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


rawDescription: How to make QTableWidget's columns assume the maximum space?

description: Make QTableWidget's columns assume the maximum space


rawDescription: Labels for scatterplot-matrices

description: Labels for scatterplot-matrices


code:
class LectureAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(LectureAdmin, self).get_queryset(request)
        if 'all' not in request.GET:
            qs = qs.exclude(Status='Completed')
        return qs

rawDescription: Overidde queryset filters while generating django admin URLs


code:
import lxml.etree as ET
import xmltodict
import json

# LOAD XML AND XSL
dom = ET.parse('soap.xml')
xslt = ET.parse('XSLTScript.xsl')

# TRANSFORM
transform = ET.XSLT(xslt)
newdom = transform(dom)

# NEW TREE OUTPUT
return_xml = ET.tostring(newdom, encoding='UTF-8', pretty_print=True, xml_declaration=True)
print(return_xml.decode("utf-8"))

return_dict = xmltodict.parse(return_xml)
print(return_dict)

return_json = json.dumps(return_dict, indent=4)
print(return_json)

rawDescription: Fetch the details from SOAP xml response


code:
from multiprocessing import Queue
from example import Example
q = Queue()
e = Example(q)
e.run('123', m='Yes')

rawDescription: Multiprocessing using imported modules

description: Multiprocessing using imported modules


code: tempArray = [x[::-1] for x in reversed(self.topArea)]

rawDescription: Inversing a twodimensional array in python


code:
import logging
from bs4 import BeautifulSoup

log = logging.getLogger(__name__)

def html2csv(html_file, csv_file):
    writerow = csv.writer(csv_file, dialect=csv.excel_tab).writerow
    div = BeautifulSoup(html_file).find('div', 'frmhdtitle')
    try:
        rows = div.find_next('table').tbody.find_all('tr')[1:]
    except AttributeError:
        log.warning("No info in %s file", html_file.name)
    else:
        for tr in rows:
            writerow([td.get_text().encode('utf-8')
                      for td in tr.find_all('td')[:8]] + [html_file.name])

rawDescription: Iterate a piece of code over a set of files


code:
minLength = 5000
minBF = 10

resfile = open("simple" + str(minLength) + str(minBF) + ".csv","w")

resfile.close()

rawDescription: Include changing variables into name of output file in Python


code:
def linearResample(arr, newLength):
    spacing = len(arr) / newLength
    return arr[::spacing]

rawDescription: Compress an array in python?

description: Compress an array in python


rawDescription: Mapping result rows to namedtuple in python sqlite


rawDescription: Reading tabular data with python

description: Reading tabular data with python


rawDescription: Change string encoding of pandas MultiIndex


code:
Imports
from mpl_toolkits.basemap import Basemap
import osr, gdal
import matplotlib.pyplot as plt
import numpy as np

rawDescription: Plot GDAL raster using matplotlib Basemap


code: soup.select("div#test + p")

rawDescription: BeautifulSoup consecutive blocks

description: BeautifulSoup consecutive blocks


code:
from werkzeug.wrappers import Response
from werkzeug.exceptions import NotFound

Users = pymongo.Connection("localhost", 27017)["mydb"]["users"]

class User(Resource):

    def GET(self, request, username):
        spec = {
            "_id": username,
            "_meta.active": True
        }
        # this is a simple call to pymongo - really, do
        # we need anything else?
        doc = Users.find_one(spec)
        if not doc:
            return NotFound(username)
        payload, mimetype = representation(doc, request.accept)
        return Response(payload, mimetype=mimetype, status=200)

    def PUT(self, request, username):
        spec = {
            "_id": username,
            "_meta.active": True
        }
        operation = {
            "$set": request.json,
        }
        # this call to pymongo will return the updated document (implies safe=True)
        doc = Users.update(spec, operation, new=True)
        if not doc:
            return NotFound(username)
        payload, mimetype = representation(doc, request.accept)
        return Response(payload, mimetype=mimetype, status=200)

rawDescription: MongoKit vs MongoEngine vs Flask-MongoAlchemy for Flask


code: {country:{os:count} for (country,os),count in sorted(os_stats.items(), key=lambda rec:rec[1])}

rawDescription: Python. Get pairs of keys (n0, _), (n1, _) with maximum values for each key pair (n0, a), (n0, b) in a dictionary. Not a trivial task


code:
def httpstatus(self, url, data=None, timeout=None):
    kwargs = {}
    if timeout is not None:
        kwargs['timeout'] = timeout
    urlopen(url, data, **kwargs)

rawDescription: How to use a default in a correct way

description: Use a default in a correct way


rawDescription: Digit or Number limit with exact match on Python Regex


code:
def square(x):
    return globals()['mul'](x, x)

rawDescription: Query on local frame and global frame in python Environment


rawDescription: Adding null values to a pandas dataframe


rawDescription: Inserting rows into dataframe by reindexing


code:
[lookup[x] for x in start]
Out[9]: [3, 1, 2]

rawDescription: Python reduce a list by order

description: Python reduce a list by order


rawDescription: Python - Can't code iteration or recursion


code: inner_has_been_true |= True

rawDescription: Python: Concise way to toggle boolean "once" (i.e., in one direction)


code:
class Actor(object):

  def __init__(self, **kwargs):
    self.image_key = kwargs['image_key']

rawDescription: How should I serialize game objects containing pygame surfaces?


code:
colors = []
for item in data:
    if item < 0:
        colors.append('r')
    else:
        colors.append('g')

rawDescription: multi colored plots in matplotlib plt based on certain properties of data

description: Multi colored plots in matplotlib plt based on certain properties of data


code: e = next(iter(s))

rawDescription: How to retrieve an element from a set without removing it?

description: Retrieve an element from a set without removing it


code: values = [d[ind] for ind in sub_list]

rawDescription: Retrieve properties of a class instance stored in a dictonary


code:
A
np.flipud(A)

rawDescription: Flip (reverse) image vertically given its string?


code: data = np.array([x[0] for x in data])

rawDescription: How to feed numeric data into a classifier?

description: Feed numeric data into a classifier


code:
def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x)-1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    calc_stats(thisx, thisy)
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw()

rawDescription: Return a portion of a plot using matplotlib


code:
class AllCategories(ListView):
    model = Category
    template = 'category_all.html'

rawDescription: Make that my categories displays each respective content isolatedly


code:
import unicodedata

def normalize_char(c):
    try:
        cname = unicodedata.name(c)
        cname = cname[:cname.index(' WITH')]
        return unicodedata.lookup(cname)
    except (ValueError, KeyError):
        return c

normalize_char('ę') == 'e'
normalize_char('Ę') == 'E'
normalize_char('ś') == 's'

rawDescription: Translating letters not in 7bit ASCII to ASCII (like ń to n and ą to a)


code:
checkNameArr = [['551002', 'Derek Jones'],
                ['940874', 'Hugh Lunny'],
                ['104741', 'Richard Plaith'],
                ['310125', 'Aideen Toner'],
                ['305795', 'Vikki Trench'],
                ['218714', 'Paul Cutland'],
                ['401741', 'Russell Smith'],
                ['223996', 'Chloe Green'],
                ['845216', 'Simon Fallon'],
                ['402258', 'Chris Worth']]
queryNameArr = [['551002', 'Derek Jones'],
                ['940874', 'Hugh Lunny'],
                ['823085', 'Brian Deans'],
                ['310125', 'Aideen Toner'],
                ['571454', 'Pam Scales'],
                ['967825', 'Una Lingus'],
                ['401741', 'Russell Smith'],
                ['682301', 'Hannah Jacobs'],
                ['914774', 'Elaine Glass'],
                ['402258', 'Chris Worth']]
checkNameSet = set(map(operator.itemgetter(0), checkNameArr))
found = []
notfound = []
for i in queryNameArr:
    if i[0] in checkNameSet:
            found.append(i)
    else:
            notfound.append(i)
found
notfound

rawDescription: Iterating and comparing list of lists in Python


rawDescription: numpy get mask from the array

description: Numpy get mask from the array


code:
# Bind the identifier `restore` to the number object 1.
restore = 1
# Bind the identifier `restore` to the string object 'Some string.'
# The original object that `restore` was bound to is unaffected.
restore = 'Some string.'

rawDescription: How do I copy only the values and not the references from a Python list?

description: Copy only the values and not the references from a Python list


code: arr[row_num] = new_row

rawDescription: Efficient manipulations of binary matrix in numpy


code:
# DON'T do this

data = ['abc', 'def', 'ghi', 'jkl']
reversed_data = [s[::-1] for s in data]
reversed_data.sort()
data = [s[::-1] for s in reversed_data]

# Do this

data.sort(key=lambda s: s[::-1])

rawDescription: How does the key argument in python's sorted function work?


code:
my_start,my_end = 1,10
my_a,my_m,my_d = 1,1,1
my_data = [1.5,1.6,1.8,2.1,2.2,3.3,4,6,8,9]
stats.kstest(my_data,lambda x: bekkers_cdf(x,my_a,my_m,my_d,my_start,my_end))

rawDescription: How to perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python?

description: Perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python


code: getattr(myObject, 'factorial', '3')()

rawDescription: C#: reflection-like mechanism into python file (get functions, parameters etc)


code: cursor.execute("""insert into Tableimport(name) values (k)""")

rawDescription: How to import access table to another access table using Python

description: Import access table to another access table using Python


code:
MIDDLEWARE_CLASSES = (
   'django.contrib.sessions.middleware.SessionMiddleware',
   'solid_i18n.middleware.SolidLocaleMiddleware',
   'django.middleware.common.CommonMiddleware',
)

rawDescription: Default language when using i18n_patterns


code:
col = collect(Det, [X1, Y1], evaluate=False)
A = col[X1]
B = col[Y1]
C = col[S.One]

rawDescription: coefficient grouping: coefficient equation from a longer expression

description: Coefficient grouping: coefficient equation from a longer expression


rawDescription: Python 2.7 Multiprocessing

description: Python 2.7 Multiprocessing


code:
for day, times in groupby(list2, lambda x: x[:10]):
    first, *mid, last = times
    print(first)
    print(last)

rawDescription: Remove certain dates in list. Python 3.4


code:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        return False

    if keys[pygame.K_LSHIFT]:
        block_speed = 5
    else:
        block_speed = 3

    if keys[pygame.K_d]:
        player.change_x += block_speed
    if keys[pygame.K_a]:
        player.change_x += -block_speed
    if keys[pygame.K_w]:
        player.change_y += -block_speed
    if keys[pygame.K_s]:
        player.change_y += block_speed

    elif event.type == pygame.KEYUP:
        if event.key == pygame.K_d or event.key == pygame.K_a:
            player.change_x = 0
        elif event.key == pygame.K_w or event.key == pygame.K_s:
            player.change_y = 0

rawDescription: pygame - How do I change a variable while it is being used?

description: Pygame - How do I change a variable while it is being used


code:
import dis
def my_func(a):
    return a + 2

dis.dis(my_func)

rawDescription: where are operators mapped to magic methods in python?

description: Where are operators mapped to magic methods in python


rawDescription: How to determine scaling factor so that covariance matrix has a first element of 1?

description: Determine scaling factor so that covariance matrix has a first element of 1


rawDescription: Stable sorting in Jinja2

description: Stable sorting in Jinja2


code:
import re
re.search(r'<code>(.*?)</code>', text).group(1)

rawDescription: How to extract string between selected string in python

description: Extract string between selected string in python


code: vectors[i][ordering[key]] = dic.get(key, 0)

rawDescription: Optimizing something in Python

description: Optimizing something in Python


code:
p = np.poly1d([1, 1, -10])  # Use a poly1d to represent the polynomial.
y = 100
(p - y).roots

rawDescription: Inverse function of numpy.polyval()

description: Inverse function of numpy.polyval()


code:
def myget(url,service=None):

    def myconverter(x):
        logfile = url.replace('/',':')+'.log'
        logfile = logfile[len('http://gdata.youtube.com/feeds/api/'):]
        my_logger.info("myget: %s" % url)

        if service == 'user_feed':
            return gdata.youtube.YouTubeUserFeedFromString(x)

        if service == 'comment_feed':
            return gdata.youtube.YouTubeVideoCommentFeedFromString(x)

        if service == 'comment_entry':
            return gdata.youtube.YouTubeVideoCommentEntryFromString(x)

        if service == 'video_feed':
            return gdata.youtube.YouTubeVideoFeedFromString(x)

        if service == 'video_entry':
            return gdata.youtube.YouTubeVideoEntryFromString(x)

    return api.GetWithRetries(url,
            converter=myconverter,
            num_retries=3,
            delay=2,
            backoff=5,
            logger=my_logger
            )

mapper={}
mapper[api.GetYouTubeUserFeed]='user_feed'
mapper[api.GetYouTubeVideoFeed]='video_feed'
mapper[api.GetYouTubeVideoCommentFeed]='comment_feed'

rawDescription: How to gather personal information (age,gender..) of all the authors of the comments on a specific video, with Python YouTube API

description: Gather personal information (age,gender..) of all the authors of the comments on a specific video, with Python YouTube API


code:
import cookielib
import urllib
import urllib2

amazon_username = ...
amazon_password = ...

login_data = urllib.urlencode({'action': 'sign-in',
                               'email': amazon_username,
                               'password': amazon_password,
                               })

cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
opener.addheaders = [('User-agent', ...)]

response = opener.open('https://www.amazon.com/gp/sign-in.html')
print(response.getcode())

response = opener.open('https://www.amazon.com/gp/flex/sign-in/select.html', login_data)
print(response.getcode())

response = opener.open("https://www.amazon.com/") # it should show that you are logged in
print(response.getcode())

rawDescription: Why I can log in amazon website using python mechanize, but not requests or urllib2


code:
from itertools import combinations
from collections import Counter
N = 5
c = Counter(tuple(sorted(a)) for a in combinations(textNP.split(), 2))
c.most_common(N)

rawDescription: Creating a dictionary with calculated values


code:
if not x%3 and not x%5:
    print ("FizzBuzz")

rawDescription: how to check the result is multiples (python)?

description: Check the result is multiples (python)


code:
import sys, random
from decimal import Decimal

def _random_decimal(minval, maxval, added_prec):
    # generate a Decimal in the range [minval, maxval) with the
    # precision of additional ADDED_PREC binary digits
    rangelen = maxval - minval
    denom = rangelen << added_prec
    return minval + Decimal(rangelen) * random.randrange(denom) / denom

def arbitrary():
    min_exp = sys.float_info.min_exp - sys.float_info.mant_dig
    max_exp = sys.float_info.max_exp
    return float(2 ** _random_decimal(min_exp, max_exp, 64))

rawDescription: How to generate scale-independent random floating point numbers?

description: Generate scale-independent random floating point numbers


code:
import sys
from pprint import PrettyPrinter

class NoStringWrappingPrettyPrinter(PrettyPrinter):
    def _format(self, object, *args):
        if isinstance(object, str):
            width = self._width
            self._width = sys.maxsize
            try:
                super()._format(object, *args)
            finally:
                self._width = width
        else:
            super()._format(object, *args)

NoStringWrappingPrettyPrinter().pprint(yourobject)

rawDescription: Can I make pprint in python3 not split strings, like in python2?

description: Make pprint in python3 not split strings, like in python2


code:
import collections
l = range(10)
s = "Hello World"
isinstance(l, collections.MutableSequence)
isinstance(s, collections.MutableSequence)

rawDescription: Chart of mutable versus immutable types

description: Chart of mutable versus immutable types


code:
def update_subplot(image):
  global fig, ax_list
  ax_list = ax_list.ravel()
  # ax_list[0] refers to the first subplot
  ax_list[0].imshow(image)
  plt.draw()

rawDescription: Update subplots in Matplotlib figure that is already open


rawDescription: Batch/Bulk SQL insert in Scrapy Pipelines [PostgreSQL]


code:
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code

rawDescription: How do you send an HTTP Get Web Request in Python?

description: Send an HTTP Get Web Request in Python


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

data = np.array([(2,3),(3,3),(45,4),(3,65)])
N = data.max() + 5

# color the background white (1 is white)
arr = np.ones((N,N), dtype = 'bool')
# color the dots black (0)
arr[data[:,1], data[:,0]] = 0

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.imshow(arr, interpolation='nearest', cmap = 'gray')
ax.invert_yaxis()
# ax.axis('off')
plt.show()

rawDescription: plotting coordinate as a matrix matplotlib python

description: Plotting coordinate as a matrix matplotlib python


code:
Output
'This is a matched string_1.\nThis is a matched string_22.\n'
'This is a matched string_1.\nThis is a matched string_22.\n'

rawDescription: Match multi-line using python in linux

description: Match multi-line using python in linux


code: upper_var1 = var1.upper()

rawDescription: How do you calculate the amount of characters including spaces and numbers in a string

description: Calculate the amount of characters including spaces and numbers in a string


code:
class inherit_and_append(object):
    def __init__(self, *attrs):
        super(inherit_and_append, self).__init__()

        self._attrs = attrs

    def __call__(self, klass):
        parent = klass.__bases__[0]  # Assuming you have a single parent class
        for attr in self._attrs:
            if not hasattr(parent, attr):
                raise AttributeError("'{}' class has no '{}' attribute".format(parent.__name__, attr))

            parent_value = getattr(parent, attr)
            klass_value = getattr(klass, attr)
            setattr(klass, attr, parent_value + klass_value)

        return klass

rawDescription: Python Class Attributes and Subclassing

description: Python Class Attributes and Subclassing


code:
with open('original_file.txt', 'r') as infile,open("ABC1.txt","a") as ab1,open("ABC2.txt","a") as ab2,\
    open("ABC3.txt","a") as ab3,open("ABC4.txt","a") as ab4:
        for line in infile:
            if line.startswith("ABC1"):
                ab1.write(line)
            elif line.startswith("ABC2"):
                ab2.write(line)
            elif line.startswith("ABC3"):
                ab3.write(line)
            elif line.startswith("ABC4"):
                ab4.write(line)

rawDescription: How do you read a text file, then split that text file into multiple text files with python?

description: Read a text file, then split that text file into multiple text files with python


code:
vals.sort()
bins = np.linspace(0, 1, nbins+1)
inds = np.searchsorted(vals, bins[1:-1])

result = [func(group) for group in np.split(vals, inds)]

rawDescription: Efficiently get indices of histogram bins in Python


code: [el if sum(x, el) < 5 else el + 1 for el in elements]

rawDescription: Incrementing variable counter when iterating through a list


layer3_2: string

rawDescription: Can I implement custom indentation for pretty-printing in Python’s JSON module?

description: Implement custom indentation for pretty-printing in Python’s JSON module


code:
with open('datafile') as f:
    for line in f:
        numbers_float = map(float, line.split())
        #work with numbers_float here

rawDescription: Reading multiple numbers from a text file


code:
s = "Adriano Celentano"
import random
from string import ascii_letters
inds = [i for i,_ in enumerate(s) if not s.isspace()]

sam = random.sample(inds, 3)

letts =  iter(random.sample(ascii_letters, 3))
lst = list(s)
for ind in sam:
    lst[ind] = next(letts)

print("".join(lst))

rawDescription: Python replace 3 random characters in a string with no duplicates


code:
from tkinter import *
import time

root = Tk()
text = "Hello World"
theLabel = Label(root,text = text,font=("Arial",200),height = 100,)
theLabel.pack()

#after 5000 miliseconds(5 seconds) of root being 'alive', execute root.destroy()
root.after(5000, root.destroy) #notice no parenthesis () after destroy

root.mainloop()

rawDescription: Python 3 | Closing Window on Tkinter

description: Python 3 | Closing Window on Tkinter


code: df.iloc[:, 1:].apply(func, axis=1)

rawDescription: Apply function row wise on pandas data frame on columns with numerical values


code:
import datetime
print(datetime.datetime.today().weekday())
# prints '0' because it's Monday

rawDescription: import only day specified from url list

description: Import only day specified from url list


code: file_list = [fle for fle in os.listdir('dir') if os.stat(fle).st_gid == gid]

rawDescription: Python - list files that belong to specific 'group'


rawDescription: python - urls.py regex help with coordinates

description: Python - urls.py regex help with coordinates


rawDescription: How to remove a column from a structured numpy array *without copying it*?

description: Remove a column from a structured numpy array *without copying it*


rawDescription: How to remove decimal points in pandas

description: Remove decimal points in pandas


code:
myDlg = MyDialog(*args)
myDlg.ShowModal()

rawDescription: wxPython and add Options Menu when select in Menu Bar

description: WxPython and add Options Menu when select in Menu Bar


code:
list2 = [element] + list
list = list2

rawDescription: Arguments are passed by reference or not in Python


code:
packet_types = {'CMD', 'RES', 'ERR', 'CMD/RES'}
assert not packet_types.symmetric_difference(pkt_lengths)

rawDescription: How to ensure solid contracts without strong typing?

description: Ensure solid contracts without strong typing


code: data = [ (cleanup(item.bandname_alt), item) for item in m ]

rawDescription: Django/python: loop through a dictionary and add an item to it


code:
s = "This is an {example} with {vars}".format(vars="variables", example="example")
s

rawDescription: Python multiline string - $ for variables


code:
import yaml

with open('points.yml', 'r') as f:
     doc = yaml.load(f)

print([tuple(p['point']) for p in doc['type']])

rawDescription: Store and retreive coordinates using python and yaml


code: [e.subs({ysym:ylist[randmid]}).evalf() for e in x_result]

rawDescription: Python -- sympy solve() returning another equation instead of value


code:
def find(myStr, end=None):
    end = len(myStr) if end is None else end

rawDescription: one argument default value depends on the len(otherArgument)

description: One argument default value depends on the len(otherArgument)


rawDescription: finding nearest points in python

description: Finding nearest points in python


code:
from multiprocessing import Pool, cpu_count

p = Pool(cpu_count())
results = p.map(transitionFunction, stateDict.values())

rawDescription: Using multiprocessing with multiple return values and ordered dictionaries


code:
divtdi = datetime.timedelta.__div__
def divtd(td1, td2):
    if isinstance(td2, (int, long)):
        return divtdi(td1, td2)
    us1 = td1.microseconds + 1000000 * (td1.seconds + 86400 * td1.days)
    us2 = td2.microseconds + 1000000 * (td2.seconds + 86400 * td2.days)
    return us1 / us2 # this does integer division, use float(us1) / us2 for fp division

rawDescription: How can I perform divison on a datetime.timedelta in python?

description: Perform divison on a datetime.timedelta in python


code:
constants='''\
Some text
Some more text
Even more text'''

rawDescription: Python list value setting

description: Python list value setting


code:
from collections import Mapping

zipcode1 = {'placemark1':{'AddressDetails':{'Country':{'AdministrativeArea':{'SubAdministrativeArea':{'Locality':{'PostalCode':{'PostalCodeNumber':"94043"}}}}}}}}
zipcode2 = {'placemark2':{'AddressDetails':{'Country':{'AdministrativeArea':{'Locality':{'PostalCode':{'PostalCodeNumber':'11201'}}}}}}}

def treeGet(d, name):
    if isinstance(d, Mapping):
        if name in d:
            yield d[name]
        for it in d.values():
            for found in treeGet(it, name):
                yield found

rawDescription: Python: Searching a multi-dimensional dictionary for a key


code:
a
a.T

rawDescription: Merge Python List

description: Merge Python List


code: [[int(i) if i.isdigit() else i for i in tup] for tup in zip(*[i.split('_') for i in l])]

rawDescription: How do I split the lists in python

description: Split the lists in python


code: call(r'''(find $readDir -type f -print0  | sort -z | xargs -0 sha1sum; find $readDir \( -type f -o -type d \) -print0 | sort -z | xargs -0 stat -c '%n %a') | sha1sum''', shell=True)

rawDescription: shell command in python for sha

description: Shell command in python for sha


rawDescription: Extract timestamp from large string

description: Extract timestamp from large string


code: elements = [tag.text for tag in offers]

rawDescription: Python Beautifulsoup4 remove <span> tags


code:
class Room(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

rooms = {}
names = ['a', 'b', 'c', 'd']
locations = [[1,1], [1,2], [2,1], [2,2]]
for name, loc in zip(names, locations):
    rooms[name] = Room(*loc)

rooms
rooms['c']
rooms['c'].x
rooms['c'].y

rawDescription: Can you make a function that would create several instances of a class for you in Python?

description: Make a function that would create several instances of a class for you in Python


code:
import itertools
items = ["a", "a", "b", "c", "b", "b", "b"]
[(k, sum(1 for _ in vs)) for k, vs in itertools.groupby(items)]

rawDescription: Finding consecutively repeating strings in Python list


code:
N, bins, patches = ax.hist(values, **hist_kwds)
for bin_size, bin, patch in zip(N, bins, patches):
    if bin_size > 200:
        patch.set_facecolor("green")
        patch.set_label("max")
    elif bin_size < 50:
        patch.set_facecolor("red")
        patch.set_label("min")

rawDescription: How to use color coding for intervals for scatter plot matrix in a python pandas code?

description: Use color coding for intervals for scatter plot matrix in a python pandas code


code:
repl = {'*': 'star', '%': 'pct', '&': 'and'}
repl = str.maketrans(repl)
string = string.translate(repl)

rawDescription: Replacing a string's content with something from a list or dictionary in Python 3


code:
def ScalarMult(A,s):
    As = []
    for row in A:
        As.append([s*i for i in row])
    return As

rawDescription: How do nested list comprehensions work in python?


rawDescription: Transpose a Python Dataframe according many variables


code:
def sum_list(l):
    sum = 0
    for x in l:
        sum += x
    return sum

rawDescription: Python: Total sum of a list of numbers with the for loop


code:
sample = """
   Place order.Call us (period: split)
   ever after.(The end) (period: split)
   U.S.A.(abbreviation: don't split internally)
   1.3 How to work with computers (dotted numeral: don't split)
   ever after...The end (ellipsis: don't split internally)
   (This is the end.)   (period inside parens: don't split)
   """

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:
def helper_function(win, circle_params):
    circle_obj_lst = map(lambda param:Circle(Point(param[0], param[1]), param[2]).setFill(param[3]).draw(win) ,circle_params)

rawDescription: creating multiple objects graphics

description: Creating multiple objects graphics


code: [[sum(item) for item in zip(*items)] for items in zip(*data)]

rawDescription: Sum of multiple list of lists index wise


code:
with open("example.txt") as f:
    d = dict([line.strip().split("=") for line in f])

rawDescription: Delineating a Read File

description: Delineating a Read File


code:
from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

rawDescription: How to calculate moving average in Python 3?

description: Calculate moving average in Python 3


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

y, x = np.mgrid[-10:10:20j, -10:10:20j]
land = np.hypot(x, y) < 7

erosion = scipy.ndimage.binary_erosion(land, structure=np.ones((3,3)))
coast = land != erosion

fig, ax = plt.subplots()
ax.pcolormesh(coast, cmap='gray', edgecolor='gray', antialiased=True)
plt.show()

rawDescription: Isolating coastal grids using convolving window (python)


code: soup.find_all(['a', 'link'], href=True)

rawDescription: BeautifulSoup4 - python: how to merge two bs4.element.ResultSet and get one single list?


code:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('input.csv', delimiter=',', index_col='x1')
df.plot(marker='s')
plt.show()

rawDescription: Read an undefined number of columns in Python and plot data with matplotlib


code:
params = {'apple': apple}
if orange is not None:
    params['orange'] = orange
params = urllib.urlencode(params)

rawDescription: Only add to a dict if a condition is met


code:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

rawDescription: How do you share data between a parent and forked child process in Python?

description: Share data between a parent and forked child process in Python


code: plt.gcf().set_facecolor('white') # Or any color

rawDescription: change a charts border area color

description: Change a charts border area color


code:
import re
line1 = "if  ( true )"
line2= "// if(true)"
line3= "/* if(true) */"
r = re.compile(r'^(?!/[/*]).*?if.*?\(.*?\).*')
r.search(line1)
r.search(line2)
r.search(line3)

rawDescription: Python - How to identify un-commented if statements lines in cpp file


code:
colorFunc = ctypes.windll.kernel32.SetConsoleTextAttribute
colorFunc(handle,AQUA)

rawDescription: Color Function in Python

description: Color Function in Python


code: pd.to_numeric(s, errors='coerce')

rawDescription: Remove non numeric values from a Series

description: Remove non numeric values from a Series


code: somespider = self._spiders['spname']()

rawDescription: How does Scrapy find Spider class by its name?


code:
res = scipy.sparse.coo_matrix(np.shape(r))
ma = np.where((r >= 0.5*dr) & (r <= 1.5*dr))  # Create first mask
res[ma] = ...

rawDescription: Avoid using for loop in np.array operations. Python


code:
for json_dict in data:
    for key,value in json_dict.iteritems():
        print("key: {} | value: {}".format(key, value))

rawDescription: python json dict iterate {key: value} are the same

description: Python json dict iterate {key: value} are the same


code: {'TTTT': {'sequences':['AGTG', 'AGGG'], 'additional':('string1', 'string2')}, 'AAAA': {'sequences':['AGAG', 'TGTG'], 'additional':('string3', 'string4')}}

rawDescription: Add multiple values to python dictionary


code:
def fast_impute(num_clusters, item_clusters, beta):

    # get counts
    cluster_counts = np.zeros(num_clusters)
    np.add.at(cluster_counts, item_clusters, 1)

    # get complete totals
    totals = np.zeros(num_clusters)
    np.add.at(totals, item_clusters, beta)

    # get number of zeros
    zero_counts = np.zeros(num_clusters)
    z = beta == 0
    np.add.at(zero_counts, item_clusters, z)

    # non-zero means
    cluster_means = totals / (cluster_counts - zero_counts)

    # perform imputations
    imputed_beta = np.where(beta != 0, beta, cluster_means[item_clusters])

    return imputed_beta

rawDescription: Missing value imputation in Python

description: Missing value imputation in Python


code:
ipdb.runcall(self, func, *args, **kwds)
ipdb.run(self, cmd, globals=None, locals=None)
# etc.

rawDescription: Is the python ipdb package available inside another package?


code:
# SConscript
Program('main.c')

rawDescription: Why does SCons VariantDir() not put output in the given directory?


rawDescription: Python Pandas compare two dataframes to assign country to phone number


code:
import numpy as np
np.sqrt(football[['wins', 'losses']].sum(axis=1))

rawDescription: Applying sqrt function on a column

description: Applying sqrt function on a column


code: current_task_resources = zip(current_task_resources_types, current_task_resources_names)

rawDescription: Dynamically populate template from two lists


code: score = 0

rawDescription: Python Help Again

description: Python Help Again


rawDescription: Python, context sensitive string substitution


code:
"in" in {"in": "out"}
"in" in {"out": "in"}

rawDescription: Use and meaning of "in" in an if statement in python


code:
a3 = np.load('a.npy', mmap_mode='r')
a3

rawDescription: Python memory mapping

description: Python memory mapping


code:
def __iadd__(self, other):
    for elem, count in other.items():
        self[elem] += count
    return self._keep_positive()

rawDescription: Which is faster Counter()+=Counter or Counter.update(Counter)?


code:
for ax in [ax1, ax2, ax3, ax4]:
   style_ax(ax)

rawDescription: Matplotlib subplots: legend and axis-scale


code:
myobj = imshow(first_image)
for pixel in pixels:
    addpixel(pixel)
    myobj.set_data(segmentedimg)
    draw()

rawDescription: How to update matplotlib's imshow() window interactively?

description: Update matplotlib's imshow() window interactively


rawDescription: python how to make a simple countdown program

description: Python how to make a simple countdown program


code:
from tastypie.serializer import Serializer

serializer = Serializer()

def my_view(request):

    #... do some other view stuff ...

    # prepare a queryset for serialization
    queryset = MyModel.objects.filter(is_cool=True)
    data = serialize_queryset(MyModel, queryset)

    # add in custom stuff, determined earlier in the view somewhere
    data['success'] = success
    data['message'] = message
    data['error'] = error

    # serialize and return response
    data = serializer.serialize(data)
    return HttpResponse(data, mimetype='application/json')

rawDescription: How to add data to tastypie resources in regular django views

description: Add data to tastypie resources in regular django views


code:
A2 = np.random.randint(-4, 10, size=(100000, 100))
A2c = A2.copy()

np.array_equal(accumulate_based(A2), cython_based(A2c))
# True

rawDescription: get the index of the last negative value in a 2d array per column

description: Get the index of the last negative value in a 2d array per column


code: df.columns = pd.MultiIndex.from_tuples([('_'.join(col.split('_')[:3]), col.split('_')[-1]) for col in df.columns], names=['Drug', 'Trial'])

rawDescription: Create Multiindex from pattern in column names


rawDescription: How to print Y axis label horizontally in a matplotlib / pylab chart?

description: Print Y axis label horizontally in a matplotlib / pylab chart


rawDescription: Circle and line collision detection in python tkinter


code:
a_test_case.py
import a_lib
import logging

logger = logging.getLogger()
logger.setLevel(50)
a_lib.main()

rawDescription: disable query logging - Google Appengine SDK Python

description: Disable query logging - Google Appengine SDK Python


code:
from pandas.stats.plm import PanelOLS
df

rawDescription: Fixed effect in Pandas or Statsmodels

description: Fixed effect in Pandas or Statsmodels


code: [f.name for f in br.forms()]

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

description: Select choices in a form using Python


rawDescription: Python - sparse vectors/distance calculation


code:
router = routers.SimpleRouter()
router.register(r'^users', UserViewSet)
urlpatterns = router.urls

rawDescription: How to delete a User with particular email using Django REST framework

description: Delete a User with particular email using Django REST framework


code:
f = Foo()
f.var = 'spam'
f.var = 'ham'
f.var
f.var = 'biggles'
f.var

rawDescription: Python class @property: use setter but evade getter?


code:
artifact = Artifact.objects.select_related().get(pk=pk)
serializers.serialize( "json", [ artifact ], indent = 4,
    relations = ('object_type', 'individual',))

rawDescription: Serializing Foreign Key objects in Django


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

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


code:
from numba import jit

df=pd.DataFrame( np.random.randn(10000,3), columns=['v','h','l'] )

df['vwap_pandas'] = (df.v*(df.h+df.l)/2).cumsum() / df.v.cumsum()

@jit
def vwap():
    tmp1 = np.zeros_like(v)
    tmp2 = np.zeros_like(v)
    for i in range(0,len(v)):
        tmp1[i] = tmp1[i-1] + v[i] * ( h[i] + l[i] ) / 2.
        tmp2[i] = tmp2[i-1] + v[i]
    return tmp1 / tmp2

v = df.v.values
h = df.h.values
l = df.l.values

df['vwap_numpy'] = np.cumsum(v*(h+l)/2) / np.cumsum(v)

df['vwap_numba'] = vwap()

rawDescription: Pandas Efficient VWAP Calculation

description: Pandas Efficient VWAP Calculation


code: vals_for_key = [val for source, val in the_dict[key]]

rawDescription: python data structure suggestion

description: Python data structure suggestion


code:
class Garage(models.Model):
    name     = models.CharField()

class Vehicle(models.Model):
    wheels   = models.IntegerField()
    gears    = models.IntegerField()
    garage   = models.ForeignKey(Garage)

rawDescription: Django advanced query

description: Django advanced query


code:
import hashlib
resultMD5 = hashlib.md5(open("myFile").read()).hexdigest()

rawDescription: Getting Python System Calls as string results


rawDescription: Python: Code to find a number where first N digits are divisible by N (from 0-9)


code:
for i, line in enumerate(c):
    line[:] = ownShuffle(line)

rawDescription: Subtlety accessing and modifying a multidimensionnal list


rawDescription: Numpy fancy indexing in multiple dimensions


code: x = zip(z, itertools.repeat(some_very_complex_computation(y)))

rawDescription: Python functional evaluation efficiency

description: Python functional evaluation efficiency


rawDescription: XPath for sub-element's text value in lxml


code:
...
conv[list] = lambda lst, cv: "(%s)" % ', '.join(cv[type(item)](item, cv) for item in lst)
con = MySQLdb.connect(..., conv=conv)
con.literal([1, "it's working...", 2])

rawDescription: Mysql named placeholders in python used in the IN clause


code:
class PersonSerializer(serializers.ModelSerializer):
    #                 vvvvvvvvv
    bar = serializers.CharField(
       source='foo', required=False
    )# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    class Meta:
        model = Person
        fields = ('id', 'foo', 'bar')

rawDescription: DRF expose model field in two separate read-write fields on the REST API


code:
lstLines = [((xb, yb, zb), (xe, ye, ze)) for i in range(Spar_Res.shape[0])
            for (xb, xe, yb, ye, zb, ze) in zip(Spar_Res[i,:-1,0], Spar_Res[i,1:,0],
                                                Spar_Res[i,:-1,1], Spar_Res[i,1:,1],
                                                Spar_Res[i,:-1,2], Spar_Res[i,1:,2])
           ]
lstLines = np.array(lstLines)

rawDescription: Line construction with double iteration

description: Line construction with double iteration


code:
import re

with open('in.txt') as intxt:
    data = intxt.read()

x = re.findall('[aA-zZ]+', data)
print(x)

rawDescription: Python program to extract text from a text file?


code: li = map(lambda x: "{0} - {1}".format(x, grade(x)), s)

rawDescription: Convert numbers to grades in python list


code:
from datetime import timedelta

# create a new record
record1 = TimeRecord.objects.create()
record1.duration
# output : datetime.timedelta(0, 2400)
# you can create an another
record2 = TimeRecord.objects.create(duration=timedelta(minutes=20))
record2.duration
# output : datetime.timedelta(0, 1200)

rawDescription: Set value for Django DurationField type in query


code: right = DataFrame(bf.values [1::2], index=left.index)

rawDescription: How can I join 2 rows in a dataframe into 1 row in a new one?

description: Join 2 rows in a dataframe into 1 row in a new one


code:
mySizer = wx.BoxSizer(wx.VERTICAL)
mySizer.Add(widget, 0, wx.CENTER|wx.ALL, 5)

rawDescription: Puting a BoxSizer in the middle of its panel


code:
connect_kwargs = dict(username="foo")
if authenticate:
   connect_kwargs['password'] = "bar"
   connect_kwargs['otherarg'] = "zed"
connect(**connect_kwargs)

rawDescription: Pythonic way to pass keyword arguments on conditional


rawDescription: Numpy C-Api array_equal

description: Numpy C-Api array_equal


code:
s = TaggedJSONSerializer()
data = OrderedDict((c, i) for i, c in enumerate('abcd'))
print(data)  # OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3)])
data = s.dumps(data)
print(data)  # {"OrderedDict":[["a",0],["b",1],["c",2],["d",3]]}
data = s.loads(data)
print(data)  # OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3)])

rawDescription: Flask session attribute loses typing after initial load


code:
Setup
from StringIO import StringIO
import pandas as pd

text = """id      date        item
1    2000-01-01     'foo'
1    2000-01-02     'pants'
1    2000-01-03     'bar'
2    2000-01-02     'organ'
2    2000-02-01     'beef'
3    2000-01-01     'pants'
3    2000-01-10     'oranges'
3    2000-02-20     'pants'"""

df = pd.read_csv(StringIO(text), delim_whitespace=True, parse_dates=[1])

rawDescription: Pandas check for future condition by group


code:
def generate_mix():
  c2 = np.random.uniform(0.1, 10.3)

rawDescription: Is there a more efficient route towards brute-forcing a random distirbution whilst implementing constraints?


a

b

c

rawDescription: make a increaseKey for list in python

description: Make a increaseKey for list in python


rawDescription: Speeding up outliers check on a pandas Series


code:
s = 'this is a sentence. this is one more sentence'
lst = s.split('. ')
[i.count(' ') for i in lst]

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


code:
from unittest.mock import patch
from io import StringIO

with patch("sys.stdin", StringIO("FOO")), patch("sys.stdout", new_callable=StringIO) as mocked_out:
    x = input()
    print("Read:", x)

assert mocked_out.getvalue() == "Read: FOO\n"

rawDescription: Python: equivalent of input using sys.stdin


code:
class Executor:
    def __init__(self, cmd):
        self.__cmd = cmd

    def __call__(self):
        gdb.execute(self.__cmd)

rawDescription: Continue after SIGNAL with a python script in gdb


code:
fig, ax = plt.subplots(subplot_kw=dict(aspect='equal'))
col = plot_polygon_collection(ax, s_poly.geometry)
# update the color
col.set_array( ... )

rawDescription: GeoPandas plotting - any way to speed things up?


code:
sorted_by_sum = [(name, sum(float(x) for x in items[1:6:2]), items)
                 for name, items in l]

rawDescription: Sum item inside a tuple

description: Sum item inside a tuple


rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching