code:
class A(Reference):
    def __init__(self):
        super(A, self).__init__()
        self.att = None

class B(Reference):
    def __init__(self):
        super(B, self).__init__()
        self.att = None

rawDescription: Python - how to get class instance reference from an attribute class?


code:
forms.py
class MenuForm(Form):
    zonas = forms.ModelChoiceField(queryset=Zonas.objects.all())

rawDescription: newbie Django Choicefield/Charfield display on html page

description: Newbie Django Choicefield/Charfield display on html page


code:
lis = [0,1,1,2,2,2,4,4,5,5,6,6,6,8,8,8]
maxx,minn = max(lis),min(lis)
from collections import Counter
c = Counter(lis)
[c[i] for i in xrange(minn,maxx+1)]

rawDescription: Get frequency count of elements in an array


code:
import sys
from subprocess import call

rc = call([sys.executable, 'path/to/run_app.py'])
cleanup()

rawDescription: Python losing control of subprocess?

description: Python losing control of subprocess


code:
while True:
    for a in range(10000):
        time.sleep(0.0001)
        for i in range(cntControl):
            barra[i].setValue(a)

rawDescription: Python PyQt4 progressbar Freezing GUI

description: Python PyQt4 progressbar Freezing GUI


rawDescription: Trying to get all image links of reddit.com using python and re


code:
from threading import Thread

class USBThingy(Thread):
    def __init__(self, reactor, device, protocol):
        self._reactor = reactor
        self._device = device
        self._protocol = protocol

    def run(self):
        while True:
            for line in self._device.streamData():
                self._reactor.callFromThread(self._protocol.usbStreamLineReceived, line)

rawDescription: Producing content indefinitely in a separate thread for all connections?


rawDescription: Force the Y axis to only use integers

description: Force the Y axis to only use integers


code:
class UserProfileUpdateView(generics.UpdateAPIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = UserProfileSerializer

    def get_object(self):
        return UserProfile.objects.get(user=self.request.user)

rawDescription: Update user profile and user in one request


code:
def foo(self, b=None):
    return bar(b or self.b)

rawDescription: Refactoring "x if x is not None else y" to "x or y"


code: cursor.execute(sql, params + (csv_path,))

rawDescription: How to add a header to an existing csv file?

description: Add a header to an existing csv file


code:
class Foo(object):
    list_of_all_foos = []

    def __init__(self):
        Foo.list_of_all_foos.append(self)

rawDescription: Loop over instances of a class to find attribute that equals a keyword


rawDescription: NumPy: Iterating over items to right, bottom of given element w/ its index


rawDescription: Ignore white spaces in a regular expression


code:
foo = 'value'
def change(name):
   globals()[name] = 'changed'

change('foo')
foo

rawDescription: How to streamline this script

description: Streamline this script


code:
#udp receive broadcast
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 1080))

while True:
    print(s.recv(1024))

rawDescription: python socket connecting to different subnet/domain

description: Python socket connecting to different subnet/domain


code:
# dylib in MacOSX, cdll.wincrt in Win, libc.so.? in Unix, ...
clib = ctypes.CDLL('libc.dylib')

_ = clib.memcpy(pixarray, im.tostring(), w_px * h_px * 4)

rawDescription: efficiently convert string (or tuple) to ctypes array

description: Efficiently convert string (or tuple) to ctypes array


code:
import collections

def get_iterable(x):
    if isinstance(x, collections.Iterable):
        return x
    else:
        return (x,)

rawDescription: Iterating over list or single element in python


code:
def getCommonLetters(a, b):
    return ''.join(sorted(set(a).intersection(set(b))))

rawDescription: To get the common letters in two words without repetition


code:
from dis import dis

def myfunc(recog, line):
    recog
    line.score

dis(myfunc)

rawDescription: Is there any performance difference between calling a local variable and calling an object's instance variable?


rawDescription: For loop inside a function

description: For loop inside a function


rawDescription: concat two dataframe using python

description: Concat two dataframe using python


code:
import os
import Image
import numpy as np

def rgb_to_hsv(rgb):
    # Translated from source of colorsys.rgb_to_hsv
    # r,g,b should be a numpy arrays with values between 0 and 255
    # rgb_to_hsv returns an array of floats between 0.0 and 1.0.
    rgb = rgb.astype('float')
    hsv = np.zeros_like(rgb)
    # in case an RGBA array was passed, just copy the A channel
    hsv[..., 3:] = rgb[..., 3:]
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    maxc = np.max(rgb[..., :3], axis=-1)
    minc = np.min(rgb[..., :3], axis=-1)
    hsv[..., 2] = maxc
    mask = maxc != minc
    hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask]
    rc = np.zeros_like(r)
    gc = np.zeros_like(g)
    bc = np.zeros_like(b)
    rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask]
    gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask]
    bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask]
    hsv[..., 0] = np.select(
        [r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc)
    hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0
    return hsv

def hsv_to_rgb(hsv):
    # Translated from source of colorsys.hsv_to_rgb
    # h,s should be a numpy arrays with values between 0.0 and 1.0
    # v should be a numpy array with values between 0.0 and 255.0
    # hsv_to_rgb returns an array of uints between 0 and 255.
    rgb = np.empty_like(hsv)
    rgb[..., 3:] = hsv[..., 3:]
    h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
    i = (h * 6.0).astype('uint8')
    f = (h * 6.0) - i
    p = v * (1.0 - s)
    q = v * (1.0 - s * f)
    t = v * (1.0 - s * (1.0 - f))
    i = i % 6
    conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5]
    rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v)
    rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t)
    rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p)
    return rgb.astype('uint8')

def hueChange(img, hue):
    arr = np.array(img)
    hsv = rgb_to_hsv(arr)
    hsv[..., 0] = hue
    rgb = hsv_to_rgb(hsv)
    return Image.fromarray(rgb, 'RGB')

filename = 'image.png'
basename, ext = os.path.splitext(filename)
img = Image.open(filename).convert('RGB')
for hue in np.linspace(0, 360, 8):
    img2 = hueChange(img, hue/360.)
    out_name = '{}_hue{:03d}.jpg'.format(basename, int(hue))
    img2.save(out_name)

rawDescription: RGB to HSV Python, change Hue continuously


rawDescription: Locating region between a confidence interval in data using Python


code:
from itertools import product
import operator
var1, var2, var3 = 42, 13, 81
unary_op = operator.pos, operator.neg
for ops in product(unary_op, repeat=3):
    vars = [op(var) for op, var in zip(ops, (var1, var2, var3))]
    print('{:=3d} + {:=3d} + {:=3d} = {sum:=4d}'.format(*vars, sum=sum(vars)))

rawDescription: Pythonic way to iterate and/or enumerate with a binary 'switch'


code:
re.__file__
shlex.__file__

rawDescription: What is the difference between shlex.split() and re.split()?


code:
current_players = (dict((k,v)            # dict comprehension:

    for k,v in list(team.items())        #   let’s filter the team member dict...
        for player in v['player']        #   for players...
            if player['year'] == 2013))  #   who are playing this year

rawDescription: How to format list and dictionary comprehensions

description: Format list and dictionary comprehensions


code: [index for index, item in enumerate(a) if item == "foo"]

rawDescription: Subarray from lists of strings

description: Subarray from lists of strings


code: import pdb; pdb.set_trace()

rawDescription: Getting a request object as in a view function but called from `manage.py shell`


rawDescription: Check if number is made of both 0 and 1 using regex


code:
import matplotlib.pyplot as plt
data = [[6, 2, 3], [1, 2, 3]]

plt.plot(data[0] + [data[0][0]], data[1] + [data[1][0]], marker='o', color='blue')
plt.show()

rawDescription: Plotting random points with Python in Linux


rawDescription: Sending hex packets in python

description: Sending hex packets in python


code:
Py_INCREF(Py_None);
result = Py_None;

rawDescription: How to return a tuple containing a None value from the C API?

description: Return a tuple containing a None value from the C API


code:
import os

(_, _, my_files) = os.walk('some_directory').next()
if len([f for f in my_files if f.endswith('.txt')]) > 10:
    for f in my_files[9:]:
        os.remove(os.path.join('some_directory', f))

rawDescription: Count how many text files in a directory using python 2.7 and edit them


code: remainder_list = [v for i,v in enumerate(tuple_list) if (i % 3) != 0]

rawDescription: Why is using a dict so much faster to exclude one list from another?


code:
for dummy in range(10):
    name()

rawDescription: Calling a function n times with two parameters


code: super(Form, self).__init__(parent = None)

rawDescription: uncheck radiobutton - PyQt4

description: Uncheck radiobutton - PyQt4


rawDescription: variable number of digit in format string

description: Variable number of digit in format string


code: grouped = rdd.reduceByKey(max)

rawDescription: Get the max value for each key in a Spark RDD


code: [list(filter(lambda x: x > thresholds[idx],qts)) for idx,qts in enumerate(quotes)]

rawDescription: compare elements of list to elements of list of lists and conditionally create new lists

description: Compare elements of list to elements of list of lists and conditionally create new lists


code:
from Tkinter import *
from twisted.internet import tksupport, reactor
master = Tk()
tksupport.install(master)

def send_message():
    message = e1.get()
    reactor.connectTCP("localhost", 8080, MessageCFactory(message))
    print("message: %s" % (message))

Label(master, text="Message").grid(row=0)
e1 = Entry(master)
e1.grid(row=0, column=1)
Button(master, text='Send', command=send_message).grid(row=3, column=1, sticky=W, pady=4)

from twisted.internet.protocol import ClientFactory, Protocol
from twisted.internet import reactor

class MessageCProto(Protocol):
    def connectionMade(self):
        self.transport.write(self.factory.message)
        self.transport.loseConnection()

class MessageCFactory(ClientFactory):
    protocol = MessageCProto

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

master.protocol("WM_DELETE_WINDOW", reactor.stop)
reactor.run()

rawDescription: Initiating TCP Client after running reactor.run()


code: count = len(re.findall(r'\b'+ word + r'\b', line, re.IGNORECASE))

rawDescription: Count the occurrence of a word in a txt file in python


code:
post = BlogPost.objects.get(...)
url = post.get_absolute_url()

rawDescription: Why is the get_absolute_url() defined in the models.py?


rawDescription: Selecting sublevels of Multiindex columns in pandas


code:
for k in range(1024):
    name = 'category_option_{0}'.format(k)
    # Use request.POST.get(name,None) to build a `Q` object

rawDescription: In Django, searching and filter by searchbox and categories in one go?


code:
#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime

cal = pdt.Calendar()
print(datetime.now())
for time_str in ["8 seconds ago", "5 minutes ago", "11 hours ago",
                 "11:34 AM yesterday"]:
    dt, flags = cal.parseDT(time_str)
    assert flags
    print(dt)

rawDescription: How to convert unformatted time to a python time object

description: Convert unformatted time to a python time object


code:
import datetime
from functools import partial
list1 = [datetime.time(10, 20), datetime.time(13, 14)]
list2 = [datetime.time(2, 15), datetime.time(4, 21)]
comb = partial(datetime.datetime.combine, datetime.date.min)
[comb(t1) - comb(t2) for t1, t2 in zip(list1, list2)]

rawDescription: Subtract datetime.time objects stored in two separate lists


rawDescription: How to pass a lambda expression to a C# constructor from an IronPython script?

description: Pass a lambda expression to a C# constructor from an IronPython script


code:
def count(n):
    return sum(i//2 for i in range(n, 0, -1))

rawDescription: Python -- divisibility and count

description: Python -- divisibility and count


rawDescription: How to extract sublists from a string in Python?

description: Extract sublists from a string in Python


code: v = [ {} for _ in range(2)]

rawDescription: Creating distinct objects in a function

description: Creating distinct objects in a function


code:
for line in file_text.splitlines():
    if not any(i in line.casefold() for i in li.split(",")):
        print(line)

rawDescription: if not a string in a file text

description: If not a string in a file text


rawDescription: How can I separate the numeric parts of filenames using Python?

description: Separate the numeric parts of filenames using Python


rawDescription: Element-wise logical AND on indeterminate number of Pandas Series


code:
timeit('c = dfL["path"].str.split(",").apply(create_dict); d = pd.DataFrame({n: c.apply(lambda x: x[n]) for n in wordlist})', 'from __main__ import dfL, wordlist, create_dict; import pandas as pd; from collections import defaultdict', number=100)
wordlist = wordlist + list(lowercase) + list(uppercase)
timeit('c = dfL["path"].str.split(",").apply(create_dict); d = pd.DataFrame({n: c.apply(lambda x: x[n]) for n in wordlist})', 'from __main__ import dfL, wordlist, create_dict; import pandas as pd; from collections import defaultdict', number=100)

rawDescription: pandas dataframe count row values

description: Pandas dataframe count row values


code: fahad

rawDescription: python read text file to array and edit the array

description: Python read text file to array and edit the array


code: result_list = [word.replace('t', 'T') for word in word_list]

rawDescription: Change all specific letters in a list in python


rawDescription: Python: Why can't I unpack a tuple into a dictionary?


rawDescription: incrementing key,value pair inside for loop iterating over dictionary

description: Incrementing key,value pair inside for loop iterating over dictionary


rawDescription: Repeating calculations in Python

description: Repeating calculations in Python


code:
import threading
import sys
import RPi.GPIO as GPIO
import time

class StopThread(StopIteration): pass

threading.SystemExit = SystemExit, StopThread

class Thread2(threading.Thread):

    def stop(self):
        self.__stop = True

    def _bootstrap(self):
        if threading._trace_hook is not None:
            raise ValueError('Cannot run thread with tracing!')
        self.__stop = False
        sys.settrace(self.__trace)
        super()._bootstrap()

    def __trace(self, frame, event, arg):
        if self.__stop:
            raise StopThread()
        return self.__trace
#############################################################

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)

def led_flash():
    while TRUE:
        GPIO.output(25, ON)
        time.sleep(1)
        GPIO.output(25, OFF)
        time.sleep(1)

# x gets defined somewhere

while True:
    if x == 1:
        flashing_thread = Thread2(target=led_flash)
        flashing_thread.start()
        #continue doing stuff
    else:
        if flashing_thread and flashing_thread.isAlive():
            flashing_thread.stop()

rawDescription: How to continuously flash LED (or other while loop) while Python code continues to run

description: Continuously flash LED (or other while loop) while Python code continues to run


rawDescription: Challenge: Creating a list of tuples of different combinations with different value 'options' in each location of the tuple.


code:
with open('dict.obj', 'rb') as fh:
    return pickle.load(fh)

rawDescription: Python fast dictionary creation with Pickle?


code: prediction = tf.argmax(y, 1)

rawDescription: Using TensorFlow to classify Handwritten Digits without validation labels


rawDescription: How to define radius for blur with Python Pillow?

description: Define radius for blur with Python Pillow


rawDescription: How to copy all python instances to a new class?

description: Copy all python instances to a new class


code:
def get_user_object(name, role, shell):
    return {
        'user': {
            'name': name,
            'full_name': name
        },
        'password': {
            'is_encrypted': True,
            'password': 'letmein'
        },
        'perms': [{
            'partition': '/Common',
            'role': role
        }],
        'login_shell': shell
    }

rawDescription: Creating a mixed python data structure by iterating over a list of lists


code:
import PIL.EpsImagePlugin
PIL.EpsImagePlugin.Ghostscript = mioGhostscript

rawDescription: convert Ghostscript from os.popen to subsession.popen python

description: Convert Ghostscript from os.popen to subsession.popen python


code:
def vertical_mean_line(x, **kwargs):
    plt.axvline(x.mean(), **kwargs)

rawDescription: Customizing annotation with Seaborn's FacetGrid


code:
def binary_search(li, targetValue):
    low, high = 0, len(li) - 1
    while low <= high:
        mid = (high + low) / 2
        if li[mid] < targetValue: low = mid + 1
        elif li[mid] > targetValue: high = mid - 1
        elif li[mid] == targetValue: return mid
    return None

rawDescription: Not printing output ? python

description: Not printing output ? python


code: sum(map(lambda x: x.pop(which_column), triangle))

rawDescription: Python - Delete column from a matrix without numPy


code:
@register.inclusion_tag('mylist.html')
def my_list():
    q = MyModel.objects.all()
    return {'my_list': q}

rawDescription: Django: is this possible to call view from template like ASP.NET MVC


code:
import re

i = open("in.txt")
o = open("out.txt", "w")

for line in i:
    if re.search("ENTRY|VERSION", line):
       o.write(line)

o.close()
i.close()

rawDescription: python sed not working

description: Python sed not working


code:
class CommercialPack(object):
    def __init__(self, pack):
        self.__dict__ = pack.__dict__

rawDescription: Object type casting in Python (design suggestion)


code:
obj = RealisticInfoArray([1, 2, 3], info='foo')
obj.__reduce__()

rawDescription: Preserve custom attributes when pickling subclass of numpy array


code:
{u'cmd': u'get-records',
 u'limit': 100,
 u'offset': 0,
 u'search': {0: {u'field': u'number',
                 u'operator': u'contains',
                 u'type': u'text',
                 u'value': u'Mike Jones'},
             1: {u'field': u'name',
                 u'operator': u'contains',
                 u'type': u'text',
                 u'value': u'Mike Jones'},
             2: {u'field': u'role', u'type': u'text'},
             6: u'SEARCH6'},
 u'searchLogic': u'OR'}

rawDescription: Parse the following query string into json using python


rawDescription: Python list of lists -> make sublists of element n


code:
res = {}

a=open('a.csv')
for line in a:
    (id, rest) = line.split(',', 1)
    res[id] = rest
a.close()

b=open('b.csv')
for line in b:
    (id, rest) = line.split(',', 1)
    res[id] = rest
b.close()

c=open('c.csv', 'w')
for id, rest in res.items():
    f.write(id+","+rest)
f.close()

rawDescription: How to merge two csv files?

description: Merge two csv files


code:
def natural_key(self):
  return self.name

rawDescription: how to convert the foreign key id to the value - Django

description: Convert the foreign key id to the value - Django


code:
app_conf = {'/': {'request.dispatch': d}}
cherrypy.config.update({
    'global': {
       'engine.autoreload.on' : False
     }
 })
cherrypy.tree.mount(root=None, config=app_conf)

rawDescription: Prevent CherryPy from automatically reloading


rawDescription: How to convert JavaScript dictionary into Python syntax

description: Convert JavaScript dictionary into Python syntax


rawDescription: Python: Is there a way to update the keys (columns) of a DictWriter before calling writerow()?


code: A.ix[A.index - B.index]

rawDescription: Python Pandas GroupBy equivalent of  If A and not B  where clause in SQL


rawDescription: numpy tile without memory allocation

description: Numpy tile without memory allocation


code:
@low_priority
def test():
    pass # Or whatever you want to do.

rawDescription: Is there a way to "nice" a method of a Python script


code: np.genfromtxt(dat, dtype=dat_dtype)

rawDescription: How to convert an array of strings to a record array?

description: Convert an array of strings to a record array


rawDescription: Pandas read multiindexed csv with blanks


rawDescription: python pandas time series year extraction

description: Python pandas time series year extraction


code:
def foo(x):
    return lambda f: f*x

rawDescription: How to run an operation on a collection in Python and collect the results?

description: Run an operation on a collection in Python and collect the results


code:
import lxml.etree as ET
filename = "file1.xml"
appendtoxml = "file2.xml"
output_file = appendtoxml.replace('.xml', '') + "_editedbyed.xml"

parser = ET.XMLParser(remove_blank_text=True)
tree = ET.parse(filename, parser)
root = tree.getroot()

out_tree = ET.parse(appendtoxml, parser)
out_root = out_tree.getroot()
for path in [".//Device", ".//Speaker"]:
    for elt in root.findall(path):
        out_root.append(elt)

out_tree.write(output_file, pretty_print=True)

rawDescription: LXML add an element into root

description: LXML add an element into root


code: (str(x) for x in l)

rawDescription: Why use the map() function?

description: Why use the map() function


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

rawDescription: How can I attach a pyplot function to a figure instance?

description: Attach a pyplot function to a figure instance


rawDescription: Pygame draw anti-aliased thick line

description: Pygame draw anti-aliased thick line


code:
def processDataLine(arg1, arg2):
    def _processDataLine(dataline):
        return ... # Do something with dataline, arg1, arg2
    return _processDataLine

json_data_rdd.flatMap(processDataLine(arg1, arg2))

rawDescription: Spark RDD - Mapping with extra arguments


code:
class mymodel(models.Model):
    name = models.CharField(max_length=50)
    my_image = models.ImageField(blank=True, null=True,upload_to='/home/user/webapps/project/uploads/')

rawDescription: Django 1.6 image upload and media path

description: Django 1.6 image upload and media path


rawDescription: Extract Only Unicode Characters from a String using Regular Expressions


code: ['mark', 'bill', '#special#', '#special method#', 'johni']

rawDescription: Regex does not remove the special chars in split function


code:
import json
from http import client

# Connect to the client
conn = client.HTTPConnection("geoip.nekudo.com")

# Make the request and extract the data
conn.request("GET","/api/172.217.3.110/full")
json_data = conn.getresponse().read().decode()

# Convert the JSON to a Python object
data = json.loads(json_data)

rawDescription: Python reads data from webpages

description: Python reads data from webpages


code:
def genFn(a, b, c):
    # some initialisation / pre-computation
    startPt = fn(a, b, c)
    def gen():  # actual generator function
        data = (yield None)
        while True:
            # perform some computation
            data = (yield result)
    return gen(), startPt  # returns generator and startPt

f, startPt = genFn(5, 6, 7)
f.send(None)
for data in dataseries[startPt:]:
    k = f.send(data)

rawDescription: How to store and retrieve meta-information in generator function object instance?

description: Store and retrieve meta-information in generator function object instance


code:
import matplotlib
matplotlib.use("wx")
from pylab import *
figure(1)
plot([1,2,3,4,5])
thismanager = get_current_fig_manager()
thismanager.window.SetPosition((500, 0))
show()

rawDescription: How do you set the absolute position of figure windows with matplotlib?

description: Set the absolute position of figure windows with matplotlib


code:
class AllServersHandlerTest(AsyncHTTPTestCase):

    def tearDown(self):
        pass

    def get_app(self):
        return Application([('/rest/test/', AllServersHandler)])

    def test_server_status_with_advertiser(self):
        on_new_host(None, '127.0.0.1')
        response = self.fetch('/rest/test/', method='GET')
        result = json.loads(response.body, 'utf8').get('data')
        self.assertEquals(['127.0.0.1'], result)

rawDescription: Getting Bad file descriptor when running Tornado AsyncHTTPTestCase


code:
import another_module

result = another_module.some_function(args)

rawDescription: Getting return infromation from another python script


rawDescription: How to convert a url string to safe characters with python?

description: Convert a url string to safe characters with python


rawDescription: Plotting two objects using a 4-item list


code:
frame =  pd.DataFrame({
    'home'    : ['CHI', 'ATL', 'SEA', 'DET', 'STL','HOU' ,'CHI','CHI'],
    'away'    : ['DET', 'CHI', 'HOU', 'TOR', 'DAL', 'STL', 'MIA', 'SEA'],
    'awayPTS' : [88, 75, 105, 99, 110, 85, 95, 100],
    'homePTS' : [92, 88, 95, 97, 100, 74, 98, 110],
})

score = collections.defaultdict(int)
def calculate(row):
    away = row['away']
    home = row['home']
    score[away] += row['awayPTS']
    score[home] += row['homePTS']
    return pd.Series([score[away], score[home]],
                     index=['awayteam_totalPTS', 'hometeam_totalPTS'])
frame = pd.concat([frame, frame.apply(calculate, axis=1)], axis=1)

rawDescription: calculating running totals in separate columns in Pandas DF

description: Calculating running totals in separate columns in Pandas DF


rawDescription: sort names in alphabitical order in mysql using python

description: Sort names in alphabitical order in mysql using python


code:
import PIL

# The conversion should work equally with a bitmap
img = PIL.Image.open("blackline.jpg")
rgb_im = img.convert('RGB')

rgb_im.size

rawDescription: How to analyse bitmap image in python, using PIL?

description: Analyse bitmap image in python, using PIL


code:
for i in itertools.count(100, -5):
    print(i)

rawDescription: Easy way to keep counting up infinitely

description: Easy way to keep counting up infinitely


code:
def make_streams_binary():
    sys.stdin = sys.stdin.detach()
    sys.stdout = sys.stdout.detach()

rawDescription: python/cgi - serves distorted images

description: Python/cgi - serves distorted images


code:
cols = zip(*stock.values())
converted = [dict(zip(stock, column)) for column in cols]

rawDescription: How to convert lists in a dictionary to dictionaries in a lists (Python)

description: Convert lists in a dictionary to dictionaries in a lists (Python)


code:
class Restaurant(db.Model):
    ...

    dishes = db.relationship('Dish', secondary=restaurant_dish,
        backref=db.backref('restaurants'))

rawDescription: SqlAlchemy and Flask, how to query many-to-many relationship


rawDescription: Django: Efficient model for ordered list of objects


code:
"""
command1
command2
command3
"""

rawDescription: Execute Commands Sequentially in Python

description: Execute Commands Sequentially in Python


code:
myset = set(A)
myset.update(B)
myset.update(C)

rawDescription: What is the preferred way to compose a set from multiple lists in Python


code:
import pygame
pygame.init()
red = (200,0,0)
white = (255,255,255)
gameDisplay=pygame.display.set_mode((800,600))

FPS=30
clock=pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            quit()
    cur = pygame.mouse.get_pos() #taking click events every time
    click=pygame.mouse.get_pressed() ##again, every time
    if click[0] == 1: #if left-clicked
        pygame.draw.rect(gameDisplay,red, (100,200,100,200)) #draw a red rectangle
        pygame.display.update() #and update the display

    clock.tick(FPS)

rawDescription: after i click on image for blit when MOUSEBUTTONDOWN the new blit then disappear in pygame

description: After i click on image for blit when MOUSEBUTTONDOWN the new blit then disappear in pygame


code: [(i, i+len(b)) for i in range(len(a)) if a[i:i+len(b)] == b]

rawDescription: find indexes of sequence in list in python

description: Find indexes of sequence in list in python


rawDescription: rethinkdb: get rows created no later than two weeks from now with unique id

description: Rethinkdb: get rows created no later than two weeks from now with unique id


rawDescription: Java's TreeSet equivalent in Python?

description: Java's TreeSet equivalent in Python


rawDescription: how to make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger

description: Make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger


code:
import Tkinter as tk
import tkFont

class DynamicLabel(tk.Label):
    def __init__(self, *args, **kwargs):
        tk.Label.__init__(self, *args, **kwargs)

        # clone the font, so we can dynamically change
        # it to fit the label width
        font = self.cget("font")
        base_font = tkFont.nametofont(self.cget("font"))
        self.font = tkFont.Font()
        self.font.configure(**base_font.configure())
        self.configure(font=self.font)

        self.bind("<Configure>", self._on_configure)

    def _on_configure(self, event):
        text = self.cget("text")

        # first, grow the font until the text is too big,
        size = self.font.actual("size")
        while size < event.width:
            size += 1
            self.font.configure(size=size)

        # ... then shrink it until it fits
        while size > 1 and self.font.measure(text) > event.width:
            size -= 1
            self.font.configure(size=size)

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.label = DynamicLabel(self, text="Resize the window to see the font change", width=20)
        self.label.pack(fill="both", expand=True, padx=20, pady=20)

        parent.geometry("300x200")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: TkInter Label Change Font Size by Text Length


code:
from multiprocessing import Process, Semaphore
from cat import *
from dog import *
from rabbit import *

semaphore = Semaphore(2)   # at most 2 processes running concurrently
p1 = cat(semaphore)
p2 = dog(semaphore)
p3 = rabbit(semaphore)
p1.start()
p2.start()
p3.start()
p1.join()
p2.join()
p3.join()

rawDescription: How to control the maximum concurrently running processes?

description: Control the maximum concurrently running processes


code: instance.method(arg1, arg2, arg3, ...)

rawDescription: Python Recursion within Class

description: Python Recursion within Class


code:
from itertools import chain

result = {k: list(chain.from_iterable(data_on_tetrahedron[x] for x in v)) for k, v in tets_sharing_vertex.items()}

pprint(result, width=100)

rawDescription: Complicated referencing with dictionaries, python


rawDescription: Python - split list of lists by value

description: Python - split list of lists by value


code:
import cgi

s = cgi.escape( """& < >""" )   # s = "& < >"

rawDescription: Escape special HTML characters in Python


rawDescription: Indexing a nested list in python

description: Indexing a nested list in python


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fg = plt.figure(1); fg.clf()
axx = [fg.add_subplot(4,1,1+i, projection='3d') for i in range(4)]
for ax,azel in zip(axx, [(115,10), (115,-10), (-115,10), (-115,-10)]):
    ax.set_title(u"Azim, elev = {}°, {}°".format(*azel))
    ax.set_zlabel('label text')
    ax.azim, ax.elev = azel

fg.canvas.draw()
plt.show()

rawDescription: Rotating axes label text in 3D matplotlib


rawDescription: parsing pandas data frame base on conditions and save it to a csv

description: Parsing pandas data frame base on conditions and save it to a csv


code:
df = (pd.read_csv('tales-01.txt',header=None)
      .groupby(level=0).apply(
        lambda x : pd.DataFrame ([[x.iloc[0,0],v]
                                  for v in x.iloc[0,1:]]))
      .reset_index(drop=True)
      .dropna()
      .rename_axis({0:'text',1:'word'},axis=1)
      )

rawDescription: Python: create edge list for bipartite graph using pandas


code: this_year = str(this_year)

rawDescription: Python SQLITE3 SELECT query with datetime calculated string not working


code:
import numpy as np
timepoints = [1,3,7,15,16,17,19]
myarray = np.array(timepoints)
def mypolynomial(bins, pfinal):   #pfinal is just the estimate of the final array (i'll do quadratic)
    a,b,c = pfinal  # obviously, for a*x^2 + b*x + c
    return (a*bins**2) + b*bins + c
mypolynomial(myarray, (1,1,0))

rawDescription: Obtaining Legendre polynomial form once Legendre coefficients are determined


rawDescription: Finding the index of the second match of a regular expression in python


code:
f = open('fname')
header = [next(f) for _ in range(header_len)]

rawDescription: Pythonic way to ignore for loop control variable


rawDescription: Find max since condition in pandas timeseries dataframe


rawDescription: How do I telescope the columns of a numpy array?

description: Telescope the columns of a numpy array


code: path = testWindow.openFileDialog()

rawDescription: How to read an attribute in another class?

description: Read an attribute in another class


rawDescription: Convert numpy array to numpy record array


code:
def f(x):
    return 1 < x ** 2 < 100

dis.dis(f)

rawDescription: How to see the assembly code of a Python file?

description: See the assembly code of a Python file


code:
def mainLoop():
    pygame.event.pump()
    keyboard(pygame.key.get_pressed())
    events = pygame.event.get()
    mouse(events)
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            return False

    if time.time() - obj.last_move > obj.move_after:
        obj.last_move = time.time()
        objMove(obj, obj.path.pop())

    return True

rawDescription: Continuously capture mouse events with pygame


rawDescription: List of tuples deletion

description: List of tuples deletion


code: for k in dict: ...

rawDescription: Learn Python The Hard Way - Exercise 39

description: Learn Python The Hard Way - Exercise 39


code:
def myRange(start, stop, step):
    s = start
    if step < 0:
        while s > stop:
            yield s
            s += step
            s = round(s, 15)
    if step > 0:
        while s < stop:
            yield s
            s += step
            s = round(s, 15)

r = myRange(1,0,-0.1)
for n in r:
    print(n)

rawDescription: Range with floating point numbers and negative steps


rawDescription: Beginner Python: Calculation Formatting

description: Beginner Python: Calculation Formatting


code:
def filter_plus_print(row):
    result = not row[0].startswith('#') and str(row[0]).isdigit()
    print("Keeping:" if result else "Removing:", row)
    return result

rawDescription: Python - Use a print/debug statement within a Lambda


rawDescription: python find minimum value in dictionary iteratively

description: Python find minimum value in dictionary iteratively


code:
hello = get_template_attribute('_cider.html', 'hello')
return hello('World')

rawDescription: Render part of the template in Flask

description: Render part of the template in Flask


code: startdata = raw_input('enter_input:')

rawDescription: I want to have raw_input and nohup together in python


code:
def list_expand(x):
    new_list = []
    while True:
        if len(x) < 2:
            new_list.append(x[0])
            break

        m = min(x)
        x.remove(m)
        if abs(m - min(x)) < 100:
            new_list.extend(range(m, min(x)))
        else:
            new_list.append(m)
    return new_list

rawDescription: How to expand a list of integer based on a threshold?

description: Expand a list of integer based on a threshold


code:
from datetime import datetime
from csv import reader

with open('onlyOnce.txt', 'r') as fp:
    for f_time, sec_time, dte in filter(None, reader(fp, delimiter="_")):
        check_stime = datetime.strptime(f_time,"%H:%m").time()
        check_etime = datetime.strptime(f_time,"%H:%m").time()
        # check every minute if current information = desired information
        now = datetime.now()

        if now.strftime("%Y-%d-%m") == dte and check_etime  <= now.time() <= check_etime:
            print("this line in range time: " + f_time)
        else:
            print("")

rawDescription: How to split each line from file using python?

description: Split each line from file using python


code:
HAYSTACK_CONNECTIONS = {
'My_Testing':
{
    'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
    'URL': 'http://127.0.0.1:9200/',
    'INDEX_NAME': 'my_testing',
    'INCLUDE_SPELLING': True,
    'EXCLUDED_INDEXES': ['talks.search_indexes.NoteIndex'],

},
'Note':
{
    'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
    'URL': 'http://127.0.0.1:9200/',
    'INDEX_NAME': 'note',
    'INCLUDE_SPELLING': True,
    'EXCLUDED_INDEXES': ['talks.search_indexes.My_TestingIndex'],

},
'default': {
    'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
    'URL': 'http://127.0.0.1:9200/',
    'INDEX_NAME': 'haystack',
    # 'INCLUDE_SPELLING': True,

},
}

HAYSTACK_ROUTERS = ['talks.routers.My_TestingRouter',
                'talks.routers.NoteRouter']

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

rawDescription: Is it possible to have multiple index in haystack elastic using real-time signal for auto-update


code: map( lambda l: l[0], lists )

rawDescription: manipulating lists to find different variables

description: Manipulating lists to find different variables


code: df['population_summed'] = df.groupby([df.index, 'city_name'])['population'].transform('sum')

rawDescription: Groupby using column and index and then sum to create new column in Pandas


code:
import csv

with open('csvfile.csv') as infile, open('outputfile.txt', 'w') as outfile:
    outfile.write(','.join("'{}'".format(row['location']) for row in csv.DictReader(infile)))
    outfile.write("\n")

rawDescription: Handling last line in Python CSV file reading


code:
class IndexedList(list):
    def __init__(self, items, attrs):
        super(IndexedList,self).__init__(items)
        # do indexing
        self._attrs = tuple(attrs)
        self._index = {}
        _add = self._addindex
        for obj in self:
            _add(obj)

    def _addindex(self, obj):
        _idx = self._index
        for attr in self._attrs:
            _idx[getattr(obj, attr)] = obj

    def _delindex(self, obj):
        _idx = self._index
        for attr in self._attrs:
            try:
                del _idx[getattr(obj,attr)]
            except KeyError:
                pass

    def __delitem__(self, ind):
        try:
            obj = list.__getitem__(self, ind)
        except (IndexError, TypeError):
            obj = self._index[ind]
            ind = list.index(self, obj)
        self._delindex(obj)
        return list.__delitem__(self, ind)

    def __delslice__(self, i, j):
        for ind in xrange(i,j):
            self.__delitem__(ind)

    def __getitem__(self, ind):
        try:
            return self._index[ind]
        except KeyError:
            return list.__getitem__(self, ind)

    def __getslice__(self, i, j):
        return IndexedList(list.__getslice__(self, i, j))

    def __setitem__(self, ind, new_obj):
        try:
            obj = list.__getitem__(self, ind)
        except (IndexError, TypeError):
            obj = self._index[ind]
            ind = list.index(self, obj)
        self._delindex(obj)
        self._addindex(new_obj)
        return list.__setitem__(ind, new_obj)

    def __setslice__(self, i, j, newItems):
        _get = self.__getitem__
        _add = self._addindex
        _del = self._delindex
        newItems = list(newItems)
        # remove indexing of items to remove
        for ind in xrange(i,j):
            _del(_get(ind))
        # add new indexing
        if isinstance(newList, IndexedList):
            self._index.update(newList._index)
        else:
            for obj in newList:
                _add(obj)
        # replace items
        return list.__setslice__(self, i, j, newList)

    def append(self, obj):
        self._addindex(obj)
        return list.append(self, obj)

    def extend(self, newList):
        newList = list(newList)
        if isinstance(newList, IndexedList):
            self._index.update(newList._index)
        else:
            _add = self._addindex
            for obj in newList:
                _add(obj)
        return list.extend(self, newList)

    def insert(self, ind, new_obj):
        # ensure that ind is a numeric index
        try:
            obj = list.__getitem__(self, ind)
        except (IndexError, TypeError):
            obj = self._index[ind]
            ind = list.index(self, obj)
        self._addindex(new_obj)
        return list.insert(self, ind, new_obj)

    def pop(self, ind=-1):
        # ensure that ind is a numeric index
        try:
            obj = list.__getitem__(self, ind)
        except (IndexError, TypeError):
            obj = self._index[ind]
            ind = list.index(self, obj)
        self._delindex(obj)
        return list.pop(self, ind)

    def remove(self, ind_or_obj):
        try:
            obj = self._index[ind_or_obj]
            ind = list.index(self, obj)
        except KeyError:
            ind = list.index(self, ind_or_obj)
            obj = list.__getitem__(self, ind)
        self._delindex(obj)
        return list.remove(self, ind)

rawDescription: python list/dict property best practice

description: Python list/dict property best practice


code:
[(s, st1.find(s)) for s in (' '.join(li[i:i+n]) for i in range(len(li)-n+1))
    if s in st1]

rawDescription: Check if string contains a certain amount of words of another string


code:
import cloudpickle
cloudpickle.dumps(set.union)
f = pickle.loads(pickle.dumps(set.union))
f({1, 2, 3}, {5})

rawDescription: Pickling method descriptor objects in python


code:
f = lambda j: processDataLine(dataline, arg1, arg2)
json_data_rdd.flatMap(f)

rawDescription: Spark RDD - Mapping with extra arguments


code:
for i in range(num_to_run):
    inqueue.put(i)

rawDescription: python multiprocessing - select-like on running processes to see which have one have finished

description: Python multiprocessing - select-like on running processes to see which have one have finished


code: df.to_excel('output.xlsx', index=False)

rawDescription: Need to create upper column for many lower columns and filling the existing data in it


code:
x1 += dx
y1 += dy

x2 += dx
y2 += dy

rawDescription: How to move a line diagonally (on a canvas) in python?

description: Move a line diagonally (on a canvas) in python


code:
['foobar/bar/', 'foobar/bar/b.txt', 'foobar/bar/c.txt', 'foobar/foo/',
 'foobar/foo/a.txt', 'foobar/foo/b.txt', 'foobar/']

rawDescription: Selective extracting and opening for zipfile in python


rawDescription: I Wish to Save Configuration With System IP Address


code:
import collections
d = collections.defaultdict(list)
for item in visa:
    comm, node = item.split('::')[0:2]
    d[comm].append(node)

rawDescription: Create a dictionary with different length for values using dictionary comprehension


code:
with open('num.txt') as nums:
    lines = re.findall(r'\w+\.txt\s+\d+', nums.read())

numbers = {}
for line in lines:
    line_split = re.split(r'\.txt\s+', line)
    count = line_split[1]
    numbers[line_split[0]] = int(line_split[1])

rawDescription: Length cutting through file handling

description: Length cutting through file handling


code:
import numpy as np
x, y = np.loadtxt('data.txt', unpack=True)
bins = np.arange(10+1)
totals, edges = np.histogram(x, weights=y, bins=bins)
totals

rawDescription: python average bitrate per second

description: Python average bitrate per second


code:
test="working جنگ test  بندی کروانا not good"
test
import re
re.findall(r'[\u0600-\u06ff]',test)

rawDescription: How to find urdu words in a string using python

description: Find urdu words in a string using python


rawDescription: running average of items list in python in reverse order

description: Running average of items list in python in reverse order


code: [s[:2] + s[-2:] if len(s) > 4 else s for s in lst]

rawDescription: How do I loop through each string in my list?

description: Loop through each string in my list


rawDescription: find key value based on value field python dictionary

description: Find key value based on value field python dictionary


code:
from django.conf.urls import patterns, include, url

urlpatterns = patterns('mainsite.views',
    url(r'^$', 'index'),
    url(r'^someOtherPage/$', 'someOtherPage'),
    url(r'^anotherPage/$', 'anotherPage'),
    url(r'page1/$', 'page_1'), # page 1 url
    url(r'page2/$', 'page_2'), # page 2 url
    url(r'page3/$', 'page_3'), # page 3 url
    url(r'page4/$', 'page_4'), # page 4 url
)

rawDescription: How Do I Properly Set Up URLConf in Django (RegEx?)


code:
lst = [-1, 3, -8]
results = map(cmath.sqrt, lst)

rawDescription: Square root of a negative array Python

description: Square root of a negative array Python


code:
class New(models.Model):
    title = models.CharField(max_length=100,unique=True)
    body = models.TextField()
    editable = models.BooleanField(default=True)

    def __unicode__(self):
        return self.title

rawDescription: State Control/Workflow in Django

description: State Control/Workflow in Django


rawDescription: Reshaping arrays in an array of arrays

description: Reshaping arrays in an array of arrays


code:
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)

rawDescription: scipy: savefig without frames, axes, only content

description: Scipy: savefig without frames, axes, only content


rawDescription: swap one element list to int

description: Swap one element list to int


code:
R
t

rawDescription: Numpy matrix combination

description: Numpy matrix combination


rawDescription: integer extraction from list of lists in python

description: Integer extraction from list of lists in python


code:
theJSON['tuc'][0]['meanings'][-1]
theJSON = process(theJSON)
theJSON['tuc'][0]['meanings'][-1]

rawDescription: When accessing a website (Glosbe.com) via json API special characters don't decode


code: [dict(child, child_father_id=d['father_id']) for child in d['a_have_list']]

rawDescription: In python how can I hoist key from a dict without loop?


code:
seqs = [x.split("=")[1] for x in ['sequence=AGATGG',
                                  'sequence=AGCTAG',
                                  'sequence=TGCTAG',
                                  'sequence=AGGTAG',
                                  'sequence=AGCTAG',
                                  'sequence=AGAGAG']]

rawDescription: Total Mismatches between two strings

description: Total Mismatches between two strings


code:
from bokeh.embed import components
script, div = components(plot)
return render_template('page.html', script=script, div=div)

rawDescription: Embed "Bokeh created html file" into Flask "template.html" file


code:
def compare_my_tuples(lhs, rhs):
    if rhs[1] > lhs[0]: return 1
    elif rhs[1] < lhs[0]: return -1
    elif rhs[0] > lhs[0]: return -1
    elif rhs[0] < rhs[0]: return 1
    else: return 0

sorted_list_of_tuples = sorted(list_of_tuples,
                               key=functools.cmp_to_key(compare_my_tuples))

rawDescription: Sort a list of tuples with two tuple entries in opposite order


code:
import scrapy
from scrapy.spiders import Spider

class YellowPages(Spider):
    name = "yellow"
    allowed_domains = ["yellowpages.com"]
    start_urls = [
        "http://www.yellowpages.com/"
    ]

    def parse(self, response):
        return scrapy.FormRequest.from_response(
            response,
            formxpath="//form[@id='search-form']",
            formdata={
                "search_terms":"business",
                "geo_location_terms" : "78735"},
            callback=self.after_results
        )

    def after_results(self, response):
        for result in response.css("div.result a[itemprop=name]::text").extract():
            print(result)

rawDescription: Scrapy web crawling going bad

description: Scrapy web crawling going bad


code: print ("So your name is {}? Awesome.".format(name.title()))

rawDescription: How do I force the player in a text-based game to use an alphabet-only name?

description: Force the player in a text-based game to use an alphabet-only name


code:
with open("file.txt", "w") as file:
    for line in lines:
        file.write(line)

rawDescription: Python: How to 'write' on the second line of a text file ignoring the first line


rawDescription: How to generate permutations of a list without "reverse duplicates" in Python using generators

description: Generate permutations of a list without "reverse duplicates" in Python using generators


rawDescription: Android: Emulator: Python: Tabbing between Fields in a Form


rawDescription: Slicing URL with Python

description: Slicing URL with Python


rawDescription: Change numpy array under condition from another array


code:
type(a).__name__ # Returns class name as a string
a.__class__      # Same as type(a)

rawDescription: How to get Qt widget type

description: Get Qt widget type


rawDescription: Python3 strange list reversal

description: Python3 strange list reversal


code:
import weakref
def foo():
    pass
w = weakref.ref(foo)
w() == foo

rawDescription: Testing that I have connected to a particular signal in Django


code: conn.execute("SELECT COUNT(*) FROM cat_table;")

rawDescription: Have sqlalchemy count how many rows are in the table and print it out


rawDescription: Centering a Numpy array of images

description: Centering a Numpy array of images


rawDescription: Transform numpy ndarray from a column list to row list


rawDescription: Average Iterating through list

description: Average Iterating through list


code:
radio_uno = Radiobutton(Main,text='Config1', value=1,variable = radio_var)
radio_due = Radiobutton(Main,text='Config2', value=2,variable = radio_var)
radio_tre = Radiobutton(Main,text='Config3', value=3,variable = radio_var)

rawDescription: Python Tkinter - get selection on Radiobutton


code:
for one_enemy in enemies:
    print("x:", one_enemy.x)
    print("y:", one_enemy.y)

rawDescription: appending code to create multiple random moving sprites - python tkinter

description: Appending code to create multiple random moving sprites - python tkinter


code:
f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

rawDescription: Python write to CSV line by line

description: Python write to CSV line by line


code: return None or file

rawDescription: What is wrong with my custom model field?


code:
# Extract values and keys
dv = np.array(list(d.values()))
dk = np.array(list(d.keys()))

# Get positions of keys in first column of x and thus change the first column
_,C = np.where(x[:,0][:,None] == dk)
x[:,0] = dv[C]

rawDescription: Numpy broadcast through dictionary

description: Numpy broadcast through dictionary


code:
df = pd.read_csv("toolong.csv")
df
df["b"] = df["b"].str[:10]
df

rawDescription: Truncating column width in pandas

description: Truncating column width in pandas


code:
from testso_app.models import StreamItem
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
a = User.objects.all()[0]
cctt = ContentType.objects.all()
si = StreamItem(user=a, content_type=cctt[0], object_id=1)
si.content_type.model

rawDescription: How to get the class name of a ContentType in django

description: Get the class name of a ContentType in django


code:
a = [[1, 'test', 12, 'toronto'], [2, 'test', 145, 'montreal']]
shorten = {1: 2, 3: 4} #shorten column 1 to length 2, and col 3 to len 4
a = [[e[:shorten[i]] if i in shorten else e for i, e in enumerate(line)] for line in a]
print (a)

rawDescription: re-size elements in a list based on index

description: Re-size elements in a list based on index


code:
def open_student_form(self, cr, uid, ids, context=None):
    this = self.browse(cr, uid, ids, context=context)[0]
    return {
        'type': 'ir.actions.act_window',
        'name': 'Student',
        'view_mode': 'form',
        'view_type': 'form',
        'res_model': 'school.student',
        'nodestroy': 'true',
        'res_id': this.student.id, # assuming the many2one is (mis)named 'student'
        'views': [(False, 'form')],
    }

rawDescription: openerp context in act_window

description: Openerp context in act_window


rawDescription: Order record array by unique occurances

description: Order record array by unique occurances


code: [x for x in filename if not re.match(r'.*(\.jpg|\.png|...).*',x)]

rawDescription: Pythonic way invert matching

description: Pythonic way invert matching


code:
name_list = [['John', 'Smith'], ['Sarah', 'Nichols'], ['Alex', 'Johnson']]

color_list = ['Red', 'Green', 'Blue']

from itertools import cycle, islice

i = 2
cyc =  cycle(islice(color_list, 0, i))
for  sub in name_list:
    sub.append(next(cyc))

print(name_list)

rawDescription: Python append value at array increment to a list


rawDescription: Do I underestimate the power of NumPy.. again?


code:
import numpy as np
a = np.array([[1, 1],
              [0, 1]])
n = 2
np.kron(a, np.ones((n,n)))

rawDescription: How to "scale" a numpy array?

description: "scale" a numpy array


code:
M = pd.Series([1, 0, 15])
M2 = M.apply(lambda x: dateutil.relativedelta.relativedelta(months=x))
M2

rawDescription: Python & Pandas: series to timedelta

description: Python & Pandas: series to timedelta


code:
def g():
    return inspect.currentframe().f_back.f_locals

rawDescription: Lambdify works with Python, but throws an exception with Cython


rawDescription: Pandas rename/transpose column using value from another column


code:
fig = plt.figure( figsize=(8, 6) )
ax = fig.add_axes( [.05, .05, .9, .9] )

ts1.plot( ax, color='DarkBlue' )
ts2.plot( ax, color='DarkRed' )

# reindex ts2 like ts1
ts2 = ts2.reindex_like( ts1 )
(ts1 - ts2).plot( ax, color='DarkGreen' )

rawDescription: Subtracting two interleaved, differently based time-series arrays with numpy?


code:
# Scott Daniels, http://code.activestate.com/recipes/52902-function-composition/
# Lightly edited for style.
class Compose(object):
    '''Compose functions. compose(f,g,x...)(y...) = f(g(y...),x...))'''
    def __init__(self, f, g, *args, **kwargs):
        self.f = f
        self.g = g
        self.pending = args[:]
        self.kwargs = kwargs.copy()

    def __call__(self, *args, **kwargs):
        return self.f(self.g(*args, **kwargs), *self.pending, **self.kwargs)

class Starcompose:
    '''Compose functions. Starcompose(f,g,x...)(y...) = f(*g(y...),x...))'''
    TupleType = type(())

    def __init__(self, f, g, *args, **kwargs):
        self.f = f
        self.g = g
        self.pending = args[:]
        self.kwargs = kwargs.copy()

    def __call__(self, *args, **kwargs):
        mid = self.g(*args, **kwargs)
        if isinstance(mid, self.TupleType):
            return self.f(*(mid + self.pending), **self.kwargs)
        return self.f(mid, *self.pending, **self.kwargs)

rawDescription: Python avoiding lambda for key which needs two callables (function composition)


rawDescription: Performance comparison of OpenCV-Python interfaces, cv and cv2


code:
import itertools
def logsplit(lst):
    iterator = iter(lst)
    for n, e in enumerate(iterator):
        yield itertools.chain([e], itertools.islice(iterator, n))

rawDescription: Split a Python list logarithmically

description: Split a Python list logarithmically


code: ['ooo', 'aaaa']

rawDescription: Regex: How to match sequence of SAME characters?


rawDescription: Sklearn SVM: SVR and SVC, getting the same prediction for every input


code:
def to_number(s):
    """Converts a string to a number."""
    f = float(s)
    return int(f) if f.is_integer() else f

rawDescription: Converting float strings with 0 tenths and hundredths to integers in python 2.7


code:
msilib.add_data(self.db, "Shortcut",
        [("S_APP_%s" % index, executable.shortcutDir,
                executable.shortcutName, "TARGETDIR",
                "[TARGETDIR]%s" % baseName, None, None, None,
                None, None, None, None)])

rawDescription: How to set shortcut working directory in cx_freeze msi bundle?

description: Set shortcut working directory in cx_freeze msi bundle


code:
import gviz_api

scheme = [('col1','string','SURNAME'),('col2','number','ONE'),('col3','number','TWO')]
data_table = gviz_api.DataTable(scheme)

#  --- lines in surnames.csv are : ---
#  surname,percent,cumulative percent,rank\n
#  SMITH,1.006,1.006,1,\n
#  JOHNSON,0.810,1.816,2,\n
#  WILLIAMS,0.699,2.515,3,\n

with open('surnames.csv') as f:

    f.readline()
    # to skip the first line surname,percent,cumulative percent,rank\n

    datdata_table.LoadData( [el if n==0 else float(el) for n,el in enumerate(line.split(',')[0:3])] for line in f )
    # to populate the data table by iterating in the CSV file

rawDescription: Fastest way to do data type conversion using csv.DictReader in python


code:
def f():

    ...
    yield
    ...
    yield
    ...

for step, value in enumerate(f()):
    try:
        time.sleep(2)
    except KeyboardInterrupt:
        print(step) # step holds the number of the last executed function

rawDescription: Python Generators and yield : How to know which line the program is at


code:
import re

name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'

def get_name(string):
    return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]

rawDescription: Extracting part of a string with irregular delimiters in python


code:
# Tested with Django 1.9.2
import sys

import django
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.db import connections, models, DEFAULT_DB_ALIAS
from mock import Mock
from contextlib import contextmanager

NAME = 'udjango'

def main():
    setup()

    class City(models.Model):
        class Meta:
            app_label = NAME  # This line is needed for EVERY model
        name = models.CharField(max_length=100)

    class Person(models.Model):
        class Meta:
            app_label = NAME  # This line is needed for EVERY model
        name = models.CharField(max_length=50)
        city = models.ForeignKey(City, related_name='residents')
        health = models.IntegerField()

        def spawn(self):
            for i in range(self.health):
                self.children.create(name='Child{}'.format(i))

    class Child(models.Model):
        class Meta:
            app_label = NAME  # This line is needed for EVERY model
        parent = models.ForeignKey(Person, related_name='children')
        name = models.CharField(max_length=255)

    syncdb(City)
    syncdb(Person)
    syncdb(Child)

    # A typical unit test would start here.
    # The irrelevant set up of a city and name is no longer required.
    with mock_relations(Person):
        dad = Person(health=2)
        dad.spawn()

        # Validation
        num_children = len(Person.children.create.mock_calls)
        assert num_children == 2, num_children

        Person.children.create.assert_called_with(name='Child1')

    # End of typical unit test.
    print('Done.')

@contextmanager
def mock_relations(model):
    model_name = model._meta.object_name
    model.old_relations = {}
    model.old_objects = model.objects
    try:
        for related_object in model._meta.related_objects:
            name = related_object.name
            model.old_relations[name] = getattr(model, name)
            setattr(model, name, Mock(name='{}.{}'.format(model_name, name)))
        setattr(model, 'objects', Mock(name=model_name + '.objects'))

        yield

    finally:
        model.objects = model.old_objects
        for name, relation in model.old_relations.iteritems():
            setattr(model, name, relation)
        del model.old_objects
        del model.old_relations

def setup():
    DB_FILE = NAME + '.db'
    with open(DB_FILE, 'w'):
        pass  # wipe the database
    settings.configure(DEBUG=True,
                       DATABASES={
                            DEFAULT_DB_ALIAS: {
                                'ENGINE': 'django.db.backends.sqlite3',
                                'NAME': DB_FILE}},
                       LOGGING={'version': 1,
                                'disable_existing_loggers': False,
                                'formatters': {
                                    'debug': {
                                        'format': '%(asctime)s[%(levelname)s]%(name)s.%(funcName)s(): %(message)s',
                                        'datefmt': '%Y-%m-%d %H:%M:%S'}},
                                'handlers': {
                                    'console': {
                                        'level': 'DEBUG',
                                        'class': 'logging.StreamHandler',
                                        'formatter': 'debug'}},
                                'root': {
                                    'handlers': ['console'],
                                    'level': 'WARN'},
                                'loggers': {
                                    "django.db": {"level": "WARN"}}})
    app_config = AppConfig(NAME, sys.modules['__main__'])
    apps.populate([app_config])
    django.setup()

def syncdb(model):
    """ Standard syncdb expects models to be in reliable locations.

    Based on https://github.com/django/django/blob/1.9.3/django/core/management/commands/migrate.py#L285
    """
    connection = connections[DEFAULT_DB_ALIAS]
    with connection.schema_editor() as editor:
        editor.create_model(model)

main()

rawDescription: Simplify Django test set up with mock objects


rawDescription: List comparison failing

description: List comparison failing


code: d = dict(entry.split('=') for entry in inputstring.split(','))

rawDescription: Python - Convert a key-value string to a dictionary


code:
from collections import defaultdict
from operator import itemgetter
from itertools import count

def cmp_getters(ig1, ig2):
   if any(not isinstance(x, itemgetter) for x in (ig1, ig2)):
      return False
   d1 = defaultdict(count().next)
   d2 = defaultdict(count().next)
   ig1(d1)                                 # populate d1 as a sideeffect
   ig2(d2)                                 # populate d2 as a sideeffect
   return d1==d2

rawDescription: comparing itemgetter objects

description: Comparing itemgetter objects


code:
from queue import Queue
from threading import Thread
import copy

# Object that signals shutdown
_sentinel = object()

# increment function
def increment(i):
    i += 1
    return i

# A thread that produces data
def producer(out_q):
    i = 0
    while True:
        # Produce some data
        i = increment( i )
        print(i)
        out_q.put(i)
        if i > 5:
            out_q.put(_sentinel)
            break

# A thread that consumes data
def consumer(in_q):
    for data in iter(in_q.get, _sentinel):
        # Process the data
        pass

# Create the shared queue and launch both threads
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()

rawDescription: Using Queues in Multi-Thread Python, Passing the queue to a subfunction as reference


code:
import ast

def load_sections(filename):
    with open(filename, 'r') as infile:
        for line in infile:
            if not line.startswith('header'):
                continue  # skip to the next line until we find a header

            sectionname = line.split(None, 1)[-1].strip()
            section = {}
            for line in infile:
                if line.startswith('header'):
                    break  # end of section
                line = line.strip()
                key, value = line.split(' = ', 1)
                section[key] = ast.literal_eval(value)

            yield sectionname, section

rawDescription: How can I parse a formatted file into variables using Python?

description: Parse a formatted file into variables using Python


code: {{ request.user.referal.y }}

rawDescription: Accessing an additional profile from templates


code: x, y = m(longitude, latitude)

rawDescription: Lines not plotting on graph using Python/Basemap


rawDescription: Find the first tuple in anything that is or might contain a tuple?


code:
def student_data(name, age, number, enrolled):
    return str([name, age, number, enrolled])

rawDescription: Putting biographical data in order from 4 parameters using python 3.3


code: arr2.T[numpy.array(zip(range(0, 3), range(1, 4)))]

rawDescription: Distance between numpy arrays, columnwise


rawDescription: Numpy: Column dependent slicing

description: Numpy: Column dependent slicing


code: variable_name = (ctypes_type * length)(initial_values)

rawDescription: How to use malloc and free with python ctypes?

description: Use malloc and free with python ctypes


code:
total = 0
for key, value in month_dictionary.iteritems():
    total += value
    month_dictionary[key] = total

rawDescription: accumulating an orderedDict

description: Accumulating an orderedDict


code:
lines_1=par1.plot(ind + 0.5*width, perform_1,linestyle='', marker='H', markerfacecolor ='k')
lines_2=par1.plot(ind + 1.5*width, perform_2,linestyle='', marker='*',markerfacecolor ='m')
ax.legend((rects1[0], rects2[0],lines_1[0],lines_2[0]), ('Current time period', 'Next time Period','Current Period Performance', 'Next Period Performance'),prop=dict(size=10), numpoints=1 )

rawDescription: Aligning markers for individual points in matplotlib and removing "double" legend for markers in matplotlib in Python


code:
(df['Period'].diff() > 1).cumsum()
(df['Period'].diff() > 1).cumsum() == 0

rawDescription: How to filter a Dataframe based on a criteria using .shift()

description: Filter a Dataframe based on a criteria using .shift()


code:
@delegate('__len__', '_content')
@delegate('__getitem__', '_content')
class MyList(object):
    def __init__(self, content):
        self._content = content

spam = MyList([1,2,3,4,5])

len(spam) # prints "5"

spam[0] # prints "1"

rawDescription: Easy way of overriding default methods in custom Python classes?


rawDescription: Indexing column values in pandas

description: Indexing column values in pandas


code: FIREFOX_CMD="cd /path/to/some/place && python selenium-example.py"

rawDescription: Remote executing of program via xterm run using paramiko python ssh library


code: csv_dict_writer(filePath + 'textFirst.csv', setAndSpike, [second])

rawDescription: String explosion when using Dict(zip(fieldnames, data)) function and csv.DictWriter


rawDescription: print sum of strings as float

description: Print sum of strings as float


code:
user = '0'
xml = '<int>%s</int>'

def foo():
    return xml % (user,)

rawDescription: modifying a variable from python module in second script for function in first script

description: Modifying a variable from python module in second script for function in first script


code:
def prepare(self):
        if self.navigation:
            self.context['navigation']={
                #building navigation
                #in your case based on request.args.get('page')
            }
        else:
            self.context['navigation']=None
        #added another if to point on changes, but you can combine with previous one
        if self.navigation:
            self.context['extends_with']="templates/page_with_navigation.html"
        else:
            self.context['extends_with']="templates/main_page.html"

rawDescription: Dynamic navigation in Flask

description: Dynamic navigation in Flask


rawDescription: Why does python allow you to create dictionaries with duplicate keys


code:
TrueXor(1, 0, 0)
TrueXor(True, False, False)

rawDescription: Check if only one variable in a list of variables is set


code:
class TorProxyDownloadHandler(HTTP11DownloadHandler):

    def download_request(self, request, spider):
        """Return a deferred for the HTTP download"""
        agent = ScrapyTorAgent(contextFactory=self._contextFactory, pool=self._pool)
        return agent.download_request(request)

class ScrapyTorAgent(ScrapyAgent):
    def _get_agent(self, request, timeout):
        bindaddress = request.meta.get('bindaddress') or self._bindAddress
        proxy = request.meta.get('proxy')
        if proxy:
            _, _, proxyHost, proxyPort, proxyParams = _parse(proxy)
            scheme = _parse(request.url)[0]
            omitConnectTunnel = proxyParams.find('noconnect') >= 0
            if  scheme == 'https' and not omitConnectTunnel:
                proxyConf = (proxyHost, proxyPort,
                             request.headers.get('Proxy-Authorization', None))
                return self._TunnelingAgent(reactor, proxyConf,
                    contextFactory=self._contextFactory, connectTimeout=timeout,
                    bindAddress=bindaddress, pool=self._pool)
            else:
                _, _, host, port, proxyParams = _parse(request.url)
                proxyEndpoint = TCP4ClientEndpoint(reactor, proxyHost, proxyPort,
                    timeout=timeout, bindAddress=bindaddress)
                agent = SOCKS5Agent(reactor, proxyEndpoint=proxyEndpoint)
                return agent

        return self._Agent(reactor, contextFactory=self._contextFactory,
            connectTimeout=timeout, bindAddress=bindaddress, pool=self._pool)

rawDescription: How to write a DownloadHandler for scrapy that makes requests through socksipy?

description: Write a DownloadHandler for scrapy that makes requests through socksipy


code:
cond1 = (df.index.get_level_values('b').isin(['foo'])) & (df.index.get_level_values('c').isin(['can']))
cond2 = (df.index.get_level_values('b').isin(['bar'])) & (df.index.get_level_values('c').isin(['baz']))
df[cond1 | cond2]

rawDescription: How to slice one MultiIndex DataFrame with the MultiIndex of another

description: Slice one MultiIndex DataFrame with the MultiIndex of another


code:
def itemsetter(*items):
    if len(items) == 1:
        item = items[0]
        def g(obj, value):
            obj[item] = value
    else:
        def g(obj, *values):
            for item, value in zip(items, values):
                obj[item] = value
    return g

rawDescription: Reverse itemgetter (itemsetter?): inserting a list of items into specific positions in a larger list


code:
df = pd.DataFrame({'phone_number': ['555-111-2222', '555-111-3333']})

df.phone_number.to_csv('phone_numbers.csv')

rawDescription: How to save a Data Frame column as a list? [Pandas]

description: Save a Data Frame column as a list? [Pandas]


code:
import datetime
datetime.datetime.strptime(sample, pattern)

rawDescription: Epoch time is one hour out from UTC, should be UTC+1


code:
def neighbours(comp0, cand0):
    comp = deque([i for i in comp0])
    cand = deque([i for i in cand0])
    for i in range(len(cand)):
        elem = cand.popleft()
        comp.append(elem)
        yield list(comp), list(cand)
        comp.pop()
        cand.append(elem)

n = neighbours([2], [1,4,5])
res = []
for i in n:
    print(i)
    res.append(i)

res

rawDescription: python `list` and `for` return different results

description: Python `list` and `for` return different results


code:
from PyQt4.QtCore import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

my_array = [['00','01','02'],
            ['10','11','12'],
            ['20','21','22']]

def main():
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

class MyWindow(QTableView):
    def __init__(self, *args):
        QTableView.__init__(self, *args)

        tablemodel = MyTableModel(my_array, self)
        self.setModel(tablemodel)

class MyTableModel(QAbstractTableModel):
    def __init__(self, datain, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.arraydata = datain

    def rowCount(self, parent):
        return len(self.arraydata)

    def columnCount(self, parent):
        return len(self.arraydata[0])

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        # vvvv this is the magic part
        elif role == Qt.BackgroundRole:
            if index.row() % 2 == 0:
                return QBrush(Qt.yellow)
            else:
                return QBrush(Qt.red)
        # ^^^^ this is the magic part
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.arraydata[index.row()][index.column()])

if __name__ == "__main__":
    main()

rawDescription: pyqt - Change row~cell collor in TableView

description: Pyqt - Change row~cell collor in TableView


rawDescription: python dict to numpy structured array

description: Python dict to numpy structured array


code:
points = [Point(i, i) for i in xrange(500)]
for point in points:
    assert isinstance(point, Point)

rawDescription: Dynamically define variable names

description: Dynamically define variable names


code:
class Asset_Analysis(Base):
    #Tell SQLAlchemy what the table name is and if there's any table-specific arguments it should know about
    __tablename__ = 'Asset_Analysis'
    __table_args__ = {'sqlite_autoincrement': True}
    #tell SQLAlchemy the name of column and its attributes:
    id = Column(Integer, primary_key=True, nullable=False)
    fid = Column(Integer, ForeignKey('Price_History.id'))

rawDescription: using sqlalchemy to load csv file into a database

description: Using sqlalchemy to load csv file into a database


code:
class SingleRelatedObjectDescriptorReturnsNone(SingleRelatedObjectDescriptor):
    def __get__(self, instance, instance_type=None):
        try:
            return super(SingleRelatedObjectDescriptorReturnsNone, self).__get__(instance=instance, instance_type=instance_type)
        except ObjectDoesNotExist:
            return None

class OneToOneOrNoneField(models.OneToOneField):
    """A OneToOneField that returns None if the related object doesn't exist"""
    related_accessor_class = SingleRelatedObjectDescriptorReturnsNone

rawDescription: Django: Return 'None' from OneToOneField if related object doesn't exist?


rawDescription: Convert a long string into a matrix, cleaning it


code: df.columns = df.iloc[0:2].apply(lambda x: '.'.join([y for y in x if y]), axis=0)

rawDescription: Pandas: parse merged header columns from Excel


code:
def triangle_sum(n):
    start = sum(range(n))+1
    return sum(range(start,start+n))

rawDescription: Sum of all numbers

description: Sum of all numbers


code:
args = link['href'].partition('(')[-1].rpartition(')')[0]
args = [v.rstrip(',').strip("'") for v in args.split()]

rawDescription: python BeautifulSoup getting variables from a garbage page

description: Python BeautifulSoup getting variables from a garbage page


code: x = a or b

rawDescription: Python operator that mimic javascript || operator


code: os.environ["PATH"] += os.pathsep + os.pathsep.join(pathlist)

rawDescription: Python: Platform independent way to modify PATH environment variable


code:
import operator
from collections import Counter
from math import factorial
def npermutations(l):
    num = factorial(len(l))
    mults = Counter(l).values()
    den = reduce(operator.mul, (factorial(v) for v in mults), 1)
    return num / den

rawDescription: Counting permuations in Python

description: Counting permuations in Python


code:
def check(s):
    subs = (s[i:i+5] for i in xrange(len(s)-4))
    for sub in subs:
        if sub.count('0') < 2:
            return "REJECT"
    return "ACCEPT"

rawDescription: Deterministic Finite Automata for {0,1} Every5-Two0


code:
class Matrix(object):
    def __init__(self, *dims):
        self._shortcuts = [i for i in self._create_shortcuts(dims)]
        self._li = [None] * (self._shortcuts.pop())
        self._shortcuts.reverse()

    def _create_shortcuts(self, dims):
        dimList = list(dims)
        dimList.reverse()
        number = 1
        yield 1
        for i in dimList:
            number *= i
            yield number

    def _flat_index(self, index):
        if len(index) != len(self._shortcuts):
            raise TypeError()

        flatIndex = 0
        for i, num in enumerate(index):
            flatIndex += num * self._shortcuts[i]
        return flatIndex

    def __getitem__(self, index):
        return self._li[self._flat_index(index)]

    def __setitem__(self, index, value):
        self._li[self._flat_index(index)] = value

rawDescription: Multidimensional array in Python

description: Multidimensional array in Python


code:
def create_global_function():
    global foo
    def foo(): return 'bar'

rawDescription: How to define global function in Python?

description: Define global function in Python


code: return dell(2,k) (2,1)

rawDescription: I am stuck at the process of retrieving a value from a matrix


rawDescription: Complicated Django annotation with self reference


code: np.dot(result.model.X, result.params)

rawDescription: How to get constant term in AR Model with statsmodels and Python?

description: Get constant term in AR Model with statsmodels and Python


rawDescription: Reshape 1-D Numpy Array to 2-D

description: Reshape 1-D Numpy Array to 2-D


code:
class UserDepartment(db.Model): # Since we're using Flask-SQLAlchemy
    __tablename__ = 'users_departments'

    user_id        = db.Column(db.Integer, ForeignKey('users.id'), primary_key=True)
    department_id  = db.Column(db.Integer, ForeignKey('departments.id'), primary_key=True)

    is_manager     = db.Column(db.Boolean)

    user       = relationship('User', back_populates='department_assoc')
    department = relationship('Department', back_populates='user_assoc')

rawDescription: How to add value to join table with SQLAlchemy?

description: Add value to join table with SQLAlchemy


code:
import pandas as pd
import re

file = 'filepath' #this is the file path to the saved text file
music = open(file, 'r')
lines = music.readlines()
# split the lines by comma
lines = [line.split(',') for line in lines]
# capturing the column line
columns = lines[9]
# capturing the actual content of the data, and dismissing the header info
content = lines[10:]

musicdf = pd.DataFrame(content)
# assign the column names to our dataframe
musicdf.columns = columns
# preview the dataframe
musicdf.head(10)

# the final column had formatting issues, so wanted to provide code to get rid of the "\n" in both the column title and the column values

def cleaner(txt):
    txt = re.sub(r'[\n]+', '', txt)
    return txt

# rename the column of issue
musicdf = musicdf.rename(columns = {'var_timbre12\n' : 'var_timbre12'})

# applying the column cleaning function above to the column of interest
musicdf['var_timbre12'] = musicdf['var_timbre12'].apply(lambda p: cleaner(p))

# checking the top and bottom of dataframe for column var_timbre12
musicdf['var_timbre12'].head(10)
musicdf['var_timbre12'].tail(10)

rawDescription: How to load in txt file as data in Python?

description: Load in txt file as data in Python


rawDescription: Python - Merge lists in a row from a list


code:
body_text = soup.findAll("body")
if len(body_text) == 0:
    return []

rawDescription: What is the fastest, most error-free method of extracting and cleaning the HTML body text in Python?


code:
from collections import defaultdict
d = defaultdict(list)

def process(filename, line):
    if line[0] == '#':
        return

    fields = line.split('\t')
    key = tuple(fields[0:5]) # Fields that makes lines similar/same
    d[key].append((filename, line))

for filename in filenames:
    with gzip.open(filename) as fh:
        for line in fh:
            process(filename, line.strip())

rawDescription: Multiple file comparison

description: Multiple file comparison


code:
y = np.ascontiguousarray(y)
y2 = np.ascontiguousarray(y2)

rawDescription: Numpy create two arrays using fromiter simultaneously


rawDescription: Python: When I have a if statement and a print assigned to 3 integers, and I type one higher, it gives both that, and the correct print


code: rows = [row.split() for row in your_tuple]

rawDescription: What are the equivalents of .split() and .rstrip() for a tuple?


rawDescription: save os.walk() in variable

description: Save os.walk() in variable


rawDescription: Python csv writer: write a string in front of an array, all in individual columns


code:
while True:

    hero.draw()

    keysPressed = pygame.key.get_pressed()

    if keysPressed[K_a]:
        hero.x = hero.x - 3
    if keysPressed[K_d]:
        hero.x = hero.x + 3
    if keysPressed[K_w]:
        hero.y = hero.y - 3
    if keysPressed[K_s]:
        hero.y = hero.y + 3

    screen.fill((0, 255, 0))

rawDescription: Can't draw rect in python pygame

description: Can't draw rect in python pygame


code:
class FunctionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Function
    name = factory.Sequence(lambda n: "Function %d" % n)

class FunctionParameterFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.FunctionParameter
    name = factory.Sequence(lambda n: "Function %d" % n)
    function = factory.SubFactory(FunctionFactory)

class ParameterSettingFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.ParameterSetting
    name = factory.Sequence(lambda n: "Function %d" % n)

    function_instantiation = factory.SubFactory(FunctionInstantiationFactory)
    function_parameter = factory.SubFactory(FunctionParameterFactory,
        function=factory.SelfAttribute('..function_instantiation.function'))

class DatasetAnd2ColumnsFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Function
    dataset = factory.SubFactory(DatasetFactory,
        name=factory.Sequence(lambda n: "Custom dataset %d" % n))
    column_1 = factory.SubFactory(ColumnFactory, dataset=dataset,
        name=factory.Sequence(lambda n: "Column 1 %d" % n))
    column_2 = factory.SubFactory(ColumnFactory, dataset=dataset,
        name=factory.Sequence(lambda n: "Column 2 %d" % n))

# I found it neater not to inherit in the end, due to needing quite a lot of
# additional complexity not included in my original question.
class FunctionToParameterSettingsFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.FunctionInstantiation

    name = factory.Sequence(lambda n: "Custom instantiation name %d" % n)
    # You can call Sequence to pass values to SubFactories
    function = factory.SubFactory(FunctionFactory,
        name=factory.Sequence(lambda n: "Custom function %d" % n))

    parameter_setting_1 = factory.RelatedFactory(ParameterSettingFactory,
        'function_instantiation',
        # Note the __ syntax for override values for nested objects:
        parameter__name='Parameter 1',
        name='Parameter Setting 1')
    # Possible to use Sequence here too, and makes looking at data easier
    parameter_setting_2 = factory.RelatedFactory(ParameterSettingFactory,
        'function_instantiation',
        parameter__name=factory.Sequence(lambda n: "Param 1 for fn %d" % n),
        name=factory.Sequence(lambda n: "Param Setting 1 for fn %d" % n))

rawDescription: Getting id of associated child records in factory_boy


code: my_dict = {frozenset(['key1', 'key2']): 'foo'}

rawDescription: 2D Dictionary or other data structure where order of keys doesn't matter


code:
import subprocess
import warnings
import re

NM = 'x86_64-w64-mingw32-nm'
DLLTOOL = 'x86_64-w64-mingw32-dlltool'
EXPORT_PATTERN = r'^[_]{1,2}imp_(?P<export>.*) in python\d+\.dll'

def build_libpython(ver, nm=NM, dlltool=DLLTOOL,
                    export_pattern=EXPORT_PATTERN):
    pylib = 'python%s.lib' % ver
    pydef = 'python%s.def' % ver
    pydll = 'python%s.dll' % ver
    libpy = 'libpython%s.a' % ver
    warning = '%s failed - ' + '%s not built' % libpy
    match_export = re.compile(export_pattern).match
    cmd_nm = [nm, '-Cs', pylib]
    cmd_dlltool = [dlltool,
                   '--dllname', pydll,
                   '--def', pydef,
                   '--output-lib', libpy]
    with open(pydef, 'w') as f:
        f.write('LIBRARY %s\nEXPORTS\n' % pydll)
        p_nm = subprocess.Popen(cmd_nm,
                                stdout=subprocess.PIPE,
                                universal_newlines=True)
        for line in sorted(p_nm.stdout):
            m = match_export(line)
            if m:
                f.write(m.group('export') + '\n')
        if p_nm.wait() != 0:
            warnings.warn(warning % nm)
            return False
    if subprocess.call(cmd_dlltool) != 0:
        warnings.warn(warning % dlltool)
        return False
    return True

rawDescription: Link to Python with MinGW

description: Link to Python with MinGW


code:
s=smoke_machine()
list(next(s))
list(next(s))
list(next(s))
list(next(s))
list(next(s))
list(next(s))
list(next(s))

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
class Injured(models.Model):
     players = models.ManyToManyField(Player)

class Banned(models.Model):
    players = models.ManyToManyField(Player)

rawDescription: Django: How to write groups and where those groups live?


code:
from SOAPpy import WSDL
wsdlFile = 'http://data.opensolution.se/index.php?wsdl'
server = WSDL.Proxy(wsdlFile)
server.methods.keys()
callInfo = server.methods['GetTables']
callInfo.inparams
callInfo.inparams[0].name
callInfo.inparams[0].type
callInfo.outparams
callInfo.outparams[0].name
callInfo.outparams[0].type

rawDescription: suds.TypeNotFound error

description: Suds.TypeNotFound error


code: # apt-get install python-pyside

rawDescription: Add possibility to launch commands from browser


code:
import os
from zipfile import Zipfile

dirpath = '/users/matthew/documents/school/assignments/a1'

with open("A1_my_upi.zip", 'w') as outfile:
    for fname in os.listdir(dirpath):
        if not fname.endswith('.py'):
            continue
        outfile.write(os.path.join(dirpath, fname))

rawDescription: How to convert IDLE python files into a ZIP folder?

description: Convert IDLE python files into a ZIP folder


code:
import maya.OpenMaya as OpenMaya
import maya.cds as cmds

def APIMatrix ( valList ):  # where vallist is a list of floats
    mat = OpenMaya.MMatrix()
    OpenMaya.MScriptUtil.createMatrixFromList( valList, mat )
    return mat

rawDescription: Maya Python API Scaling a matrix about another matrix


rawDescription: Python: A complete list of modules

description: Python: A complete list of modules


code:
# contrib.auth.middleware.py:

def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user

class AuthenticationMiddleware(object):
    def process_request(self, request):
        assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."

        request.user = SimpleLazyObject(lambda: get_user(request))

# django.contrib.auth.__init__.py (auth.get_user)

def get_user(request):
    from django.contrib.auth.models import AnonymousUser
    try:
        user_id = request.session[SESSION_KEY]
        backend_path = request.session[BACKEND_SESSION_KEY]
        backend = load_backend(backend_path)
        user = backend.get_user(user_id) or AnonymousUser()
    except KeyError:
        user = AnonymousUser()
    return user

rawDescription: Get the user object from session

description: Get the user object from session


rawDescription: Search app in Django

description: Search app in Django


rawDescription: How could all combinations of a set of possible arguments of a function be tried and the resultant values be collected?


code:
from functools import reduce
import datetime

items = [[datetime.datetime(2000, 12, 10, 0, 0), 0.0011], [datetime.datetime(2000, 12, 11, 0, 0), 0.0013 ], [datetime.datetime(2000, 12, 12, 0, 0), 0.0014]]

def add_printing_result(a, b):
    total = a+b
    print(total)
    return total

reduce(add_printing_result, (item[1] for item in items))

rawDescription: adding elements in nested lists

description: Adding elements in nested lists


rawDescription: International Date "String" Is Subtracting Instead of Remaining in Its Original Format


code: pd.cut(df['play_count'], bins=bins, include_lowest=True, labels=[1, 2, 3, 4, 5]).astype(int)

rawDescription: python pandas dataframe index match

description: Python pandas dataframe index match


code: log_file = open(log_file_path, 'a+')

rawDescription: python subprocess is overwriting file used for stdout - I need it to append to the file (windows)

description: Python subprocess is overwriting file used for stdout - I need it to append to the file (windows)


code:
from multiprocessing import Process, Value

class AsyncTimer():

    def __init__(self):
        self._proc = None
        self._do_count = Value('b',True)
        self._count = Value('i', 0)

    def _count_seconds(self):

        while self._do_count.value:
            self._count.value += 1

    def start(self):
        self._proc = Process(target=self._count_seconds)
        self._proc.start()

    def stop(self):
        self._do_count.value = False
        self._proc.join()

    def get_seconds(self):
        return self._count.value

rawDescription: While loop is breaking passing of values to a variable within a python process


rawDescription: Python: append last word from lines in input file to to end of lines of output file


code: (ip_hl, ip_v) = (value >> 4, value & 15)

rawDescription: How to read packet saved in a file with Python?

description: Read packet saved in a file with Python


code:
strs = "abc+bcd+cdf"
re.sub(r'\+|;','\n',strs)

rawDescription: Python - In a string find a character and print remaining part of string in a new line


code:
mY = np.abs(Y) # Find magnitude
peakY = np.max(mY) # Find max peak
locY = np.argmax(mY) # Find its location
frqY = frq[locY] # Get the actual frequency value

rawDescription: Print highest peak value of the frequency domain plot


code:
from ast import literal_eval
with open('data.txt') as f:
    sale = [literal_eval(line) for line in f]
    data = {'Sale': sale}
    print(data)

rawDescription: Convert following data to JSON format in python


code:
for encrypt_rounds in range(101):  # 0 -> 100 inclusive
    decrypt_rounds = 100 - encrypt_rounds
    encrypted_s = encrypt(some_string, encrypt_rounds)
    decrypted_s = decrypt(some_string, decrypt_rounds)

rawDescription: Python: How to run two loops simultaneously and pass iterative arguments to them?


code:
# -*- mode: python -*-
a = Analysis(['Collector.py'],
             pathex=['C:\\Users\\vijay\\Python\\Collector'],
             hiddenimports=[],
             hookspath=None,
             runtime_hooks=None)
a.datas += [('logo.png','C:\\Users\\vijay\\System\\icon\\logo.png','DATA')]
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='Collector.exe',
          debug=False,
          strip=None,
          upx=True,
          console=False , icon='C:\\Users\\vijay\\System\\icon\\logo.ico')

rawDescription: Add image to .spec file in Pyinstaller

description: Add image to .spec file in Pyinstaller


rawDescription: Running a function from a string

description: Running a function from a string


code: zip(matrix[0], matrix[1], matrix[2], ...)

rawDescription: check whether an element is in list or not

description: Check whether an element is in list or not


code:
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

rawDescription: Matplotlib connect scatterplot points with line - Python


code:
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.lang import Builder

from jnius import autoclass
PythonActivity = autoclass('org.renpy.android.PythonActivity')
View = autoclass('android.view.View')

from android.runnable import run_on_ui_thread

root = Builder.load_string('''
BoxLayout:
    orientation: 'vertical'
    Button:
        text: 'Dim'
        on_press: app.dim()
    Button:
        text: 'Undim'
        on_press: app.undim()
''')

class DimTestApp(App):
    def build(self):
        return root

    @run_on_ui_thread
    def set_systemui_visibility(self, options):
        PythonActivity.mActivity.getWindow().getDecorView().setSystemUiVisibility(options)

    def dim(self, *args):
        self.set_systemui_visibility(View.SYSTEM_UI_FLAG_LOW_PROFILE)

    def undim(self, *args):
        self.set_systemui_visibility(0)

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

rawDescription: Kivy: dimming Android navigation buttons


code:
class AB(bpy.types.Operator):
    bl_idname = "wm.simple_multi_operator"
    bl_label = "Multi Purpose Operator"

    param_one = StringProperty()
    # param_two = StringProperty()

    def execute(self,context):

        if self.param_one == 'A':
            self.some_functionality(context)

        elif self.param_one == 'B':
            # some other code
            self.some_functionality(context)

        return {'FINISHED'}

    def some_functionality(self, context):
        ...

rawDescription: Call a function in a class from different class


code:
lst = [1,2,3,4]
sorted(lst) == lst
lst = [1,2,4,3]
sorted(lst) == lst

rawDescription: How do I tell if a list is in ascending order? Just needs to return True or False

description: Tell if a list is in ascending order? Just needs to return True or False


code:
def __setitem__(self, key, item):
    putenv(key, item)
    self.data[key.upper()] = item
def __getitem__(self, key):
    return self.data[key.upper()]

# ...

def has_key(self, key):
    return key.upper() in self.data
def __contains__(self, key):
    return key.upper() in self.data
def get(self, key, failobj=None):
    return self.data.get(key.upper(), failobj)

rawDescription: Why python uppercases all environment variables in windows


code: temps = comm.bcast(temps,root=0)

rawDescription: How to share data between processes in Python using MPI?

description: Share data between processes in Python using MPI


code:
import numpy as np

data_file_name = 'in.txt'

data=np.loadtxt(data_file_name)

unique = np.unique(data[:,0])
out = []
for i in unique:
    ind = np.where(data[:,0]==i)
    out.append(data[ind,2]-data[ind,1])
outarray = np.hstack(out)[0]

print(outarray)

rawDescription: While loops with certain array conditions


rawDescription: Pandas TimeGrouper: .median() behaves differently to .quantile(0.5)


code:
class AnnotatedIPv4PoolManager(models.Manager):
    def get_queryset(self):
        query = super(AnnotatedIPv4PoolManager, self).get_queryset()
        return query.annotate(available_ips=Count('ip_ranges'),
                              num_subscribers=Count('subscribers'),
                              )

class IPv4Pool(models.Model):
    name = models.CharField(max_length=255)
    annotated = AnnotatedIPv4PoolManager()

rawDescription: Field calculated from Foreign Keys, need to save twice?


rawDescription: How can I solve multivariable linear equation in python?

description: Solve multivariable linear equation in python


code:
import re

# inside your for i in range(posts_to_show) loop:
value = feed['entries'][i].content[0]['value']
image_url = re.search('(?P<url>http?://[^\s]+(png|jpeg|jpg))', value).group("url")

rawDescription: I would like to catch the image from RSS feed


code:
arr = ctypes.cast(t.contents.arr,POINTER(c_byte))
for i in range(t.contents.size):
    print(arr[i])

rawDescription: does python ctypes supports size-0 array?

description: Does python ctypes supports size-0 array


code: [u'katab']

rawDescription: how to remove all staff by using regular Expression

description: Remove all staff by using regular Expression


rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function