code:
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

rawDescription: how to print keys and values of a dictionary in python

description: Print keys and values of a dictionary in python


code:
import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

rawDescription: Writing numerical values on the plot with Matplotlib


rawDescription: alternate for multiple constructors

description: Alternate for multiple constructors


code:
import tkFileDialog
filename = tkFileDialog.asksaveasfilename()
a = 1
b = []
c = {}
f = open(filename, 'wb') # wb is important
import pickle
pickle.dump((a,b,c), f)
f.close()

rawDescription: how to save and open variables to a file using tkFileDialog?

description: Save and open variables to a file using tkFileDialog


code:
plt.plot(results['ZR'])
plt.plot(firstIndex, firstset, "bo")
plt.plot(secondIndex, secondset, "ro")

rawDescription: Plot points in different colors

description: Plot points in different colors


rawDescription: Python : list index out of range error for filling in data set


code:
class InvoiceAdmin(admin.ModelAdmin):
    inlines = [
        SoldItemAdmin,
    ]

    def response_add(self, request, new_object):
        obj = self.after_saving_model_and_related_inlines(new_object)
        return super(InvoiceAdmin, self).response_add(request, obj)

    def response_change(self, request, obj):
        obj = self.after_saving_model_and_related_inlines(obj)
        return super(InvoiceAdmin, self).response_change(request, obj)

    def after_saving_model_and_related_inlines(self, obj):
        solditem_changed.send(obj)
        return obj

rawDescription: Post save process using ManyToMany with intermediary model in admin


code:
import jinja2
env = jinja2.Environment()
template_filter = map(env.compile_expression, template)

rawDescription: Django/Jinja2 : Generate (data for) CSV via template syntax


code:
pairs = list()
for (w1, tag1), (w2, tag2) in nltk.bigrams(posTagged):
    if t1.startswith("VB") and t2 == "RB":
        pairs.append((w1, w2))

rawDescription: How to extract the verbs and all corresponding adverbs from a text?

description: Extract the verbs and all corresponding adverbs from a text


code:
['mike', 'joe']
['nick', 'Janet']

rawDescription: Python get objects in list with matching attributes


code:
import heapq
heapq.nlargest(3, word_count.iteritems(), itemgetter(1))

rawDescription: Python: sort dict by values, print key and value


code:
from kivy.config import Config
Config.set('graphics', 'width', '1000')
Config.set('graphics', 'height', '500')
Config.set('graphics', 'resizable', 0)
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.graphics import Color, Ellipse, Line

Builder.load_file('hueLayout.kv')

class ColorLoopWidget(Widget):
    xlabel = ObjectProperty()
    ylabel = ObjectProperty()
    def on_touch_down(self, touch):
        with self.canvas:
            self.canvas.clear()
            d = 10
            Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d,d))
            touch.ud['line'] = Line(points=(touch.x, touch.y))
            self.xlabel.text = 'x: '+str(touch.x)
            self.ylabel.text = 'y: '+str(touch.y)

##    def on_touch_move(self, touch):
##        touch.ud['line'].points += [touch.x, touch.y]

class HueLayout(Widget):
    colorloopwidget = ObjectProperty()
    xlabel = ObjectProperty()
    ylabel = ObjectProperty()

##    def on_touch_down():
##        ColorLoopWidget.on_touch_down()
##
##    def on_touch_move():
##        ColorLoopWidget.on_touch_move()

    def clear_canvas(self):
        self.colorloopwidget.canvas.clear()

class HueApp(App):
    def build(self):
        return HueLayout()

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

rawDescription: Output touch position from custom kivy widget to labels


code: str = re.sub(r'\W|_', ' ', str, flags=re.UNICODE)

rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code:
source = open("PALTemplateData.csv","rb")

target = open("AnotherFile.csv","wb")

rawDescription: Writing with Python's built-in .csv module


code: listOneSorted, listTwoSorted = zip(*sorted(zip(listOne, listTwo), key = lambda x : x[0]))

rawDescription: generating a vector saying how a list should be sorted in python

description: Generating a vector saying how a list should be sorted in python


code:
import argparse
import shlex
response = raw_input('Enter repo PATHs (e.g. /path/to/repo1 /path/to/repo2)')
parser=argparse.ArgumentParser()
parser.add_argument('locations', nargs = '+')
args=parser.parse_args(shlex.split(response))
print(args.locations)

rawDescription: Python CLI Menu

description: Python CLI Menu


code:
for k in obj.__dict__:
    print(k, obj.__dict__[k])

rawDescription: how to reveal an object's attributes in Python?

description: Reveal an object's attributes in Python


code:
reduce(lambda x,y:(x<<8)+y,list(b"Hello World"[::-1]))
bits=bin(_)[2:]

rawDescription: Working with bit streams

description: Working with bit streams


code:
params_data = {
    'start_time': 1415134405,
}

stats = campaign.get_stats(
    params=params_data,
    fields=[
        'impressions',
        'clicks',
        ...
    ]
)

for stat in stats:
    ...

rawDescription: Filtering statistics from facebook ads api using the python sdk


code:
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime
cal = pdt.Calendar()
cal.parseDT("Oct 4") # today is Oct 25
cal.parseDT("Oct 4", datetime(2015, 1, 1))

rawDescription: Parse date with Python library "ParseDateTime"


code:
from itertools import chain
new_list = list(chain(a[0:2], [a[4]], a[6:]))

rawDescription: creating a new list with subset of list using index in python

description: Creating a new list with subset of list using index in python


code:
yourdistribution = Distribution(project_name='package.name')
yourdistribution._ep_map = {'myapp.myclasses', {
    'classentry1': entrypointinstance_for_classentry1,
    'classentry2': entrypointinstance_for_classentry2,
}}

rawDescription: How do I add a setuptools entry_point as an example in my main project?

description: Add a setuptools entry_point as an example in my main project


code:
import bs4

html = '''
<option value="674"> Example text here </option>
<option value="673"> Example text here</option>
<option value="672"> Example text here </option>
'''

soup  = bs4.BeautifulSoup(html)
mylst = [str(x.text).strip() for x in soup.find_all('option')]

rawDescription: Regular expression to return list in Python?


code:
N = 20

counter = 0
for a in range(1, N):
    if a%2 and a%3 and a%5:
        counter += 1

rawDescription: Count how many individual integers there are in a string, Python 3


code:
df = xa.join(xb, on='PersonID', how='inner')
df

rawDescription: pandas: vectorize counting rows in time interval

description: Pandas: vectorize counting rows in time interval


code:
hello[2]
hello[2] * 3

rawDescription: Creating multiple vectors

description: Creating multiple vectors


code:
class bFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, '2', size=(353,270), style=wx.CAPTION|wx.CLOSE_BOX|wx.SYSTEM_MENU|wx.MINIMIZE_BOX)
        self.parent = parent              # parent is the MainFrame instance (self --> parent)
        self.panel = wx.Panel(self)

        mainButton = wx.Button(self.panel, -1, '&Back to Main',pos=(100,100),size=(-1,30))
        self.Bind(wx.EVT_BUTTON, self.backMain,mainButton)

    def backMain (self, event):
        self.parent.Show()                # now I can show again Mainframe
        self.Destroy()

rawDescription: "Child frame inside Father frame inside Grandfather frame" wxPython


code:
integer = re.compile(r'\-?\d+')
for p in expression:
    if p.isdigit():
        # somehow find the current position in the string
        integer.match(expression, curpos)

rawDescription: Retrieving a full number

description: Retrieving a full number


code:
alphabet =  range(2)
base = 2
dict((x*base**2+y*base+z,(x,y,z)) for x in alphabet
                                  for y in alphabet
                                  for z in alphabet )

description: Python construct a dictionary {0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 0, 2], 3: [0, 0, 3], ...,999: [9, 9, 9]}


code:
voc=['C', 'D', '*']
list(product(voc,repeat=3))
list(i for i in product(voc,repeat=3)if len(set(i))>1)

rawDescription: Generate random element from list with no more than one repetition of one element


code:
for x,y in zipMap(get_handler, the_list):
    ...

rawDescription: Combine variable and for each loop python


code:
from itertools import islice

list(islice(infinite_counter(), 1000, 2000))

rawDescription: Get list of subset from infinite generator in Python


code:
from tkinter import *
import re
from tkinter import messagebox, filedialog

# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):
    # Define settings upon initialization. Here you can specify
    def __init__(self, master=None):

        # parameters that you want to send through the Frame class.
        Frame.__init__(self, master)

        # reference to the master widget, which is the tk window
        self.master = master

        # with that, we want to then run init_window, which doesn't yet exist
        self.init_window()

    # Load the gcode file in and extract the filament value
    def get_filament_value(self, fileName):
        with open(fileName, 'r') as f_gcode:
            data = f_gcode.read()
            re_value = re.search('filament used = .*? \(([0-9.]+)', data)

            if re_value:
                value = float(re_value.group(1))
                return 'Volume of the print is {} cm3'.format(value)
            else:
                return 'Filament volume was not found in {}'.format(fileName)

    def read_gcode(self):
        root.fileName = filedialog.askopenfilename(filetypes=(("GCODE files", "*.gcode"), ("All files", "*.*")))
        self.value.set(self.get_filament_value(root.fileName))

    def client_exit(self):
        exit()

    def about_popup(self):
        messagebox.showinfo("About",
                            "Small software created by Bartosz Domagalski to find used filament parameters from Sli3er generated GCODE")

    # Creation of init_window
    def init_window(self):

        # changing the title of our master widget
        self.master.title("Filament Data")

        # allowing the widget to take the full space of the root window
        self.pack(fill=BOTH, expand=1)

        # creating a menu instance
        menu = Menu(self.master)
        self.master.config(menu=menu)

        # create the file object)
        file = Menu(menu)
        help = Menu(menu)

        # adds a command to the menu option, calling it exit, and the
        # command it runs on event is client_exit
        file.add_command(label="Exit", command=self.client_exit)
        help.add_command(label="About", command=self.about_popup)

        # added "file" to our menu
        menu.add_cascade(label="File", menu=file)
        menu.add_cascade(label="Help", menu=help)

        # Creating the labels
        self.value = StringVar()
        l_instruction = Label(self, justify=CENTER, compound=TOP,
                              text="  Load GCODE file to find volume, \n weight and price of used filament.")
        l = Label(self, justify=CENTER, compound=BOTTOM, textvariable=self.value)
        #       l.place(x=85, y=45)
        l_instruction.pack()
        l.pack()

        l_instruction.pack()
        self.value = StringVar()
        l = Label(self, textvariable=self.value)
        l.pack()

        # Creating the button
        gcodeButton = Button(self, text="Load GCODE", command=self.read_gcode)
        gcodeButton.pack()
        #       gcodeButton.place(x=140, y=10)

        # status Bar
        status = Label(self, text="Waiting for file...", bd=1, relief=SUNKEN, anchor=W)
        status.pack(side=BOTTOM, fill=X)

# root window created. Here, that would be the only window, but you can later have windows within windows.
root = Tk()
root.resizable(width=False, height=False);
# root.geometry("400x300")

# creation of an instance
app = Window(root)

# mainloop
root.mainloop()

rawDescription: How to display the variable in a tkinter window?

description: Display the variable in a tkinter window


code:
import multiprocessing, sys, time

def f(icount, _sleepTime = 1):
    for i in range(icount):
        time.sleep(_sleepTime)
        print(_sleepTime)

def create_process():
    return multiprocessing.Process(target = f, args=(4, ))

def main(args):
    m = create_process()
    m.start()
    for i in range(15):
        time.sleep(.5)
        if not m.is_alive():
            # m.start throws an error after first run
            print("restarting")
            m.join()
            m = create_process()
            m.start()
        print("{}".format(m.is_alive()))
    m.join()

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

rawDescription: time.sleep hangs multithread function in python

description: Time.sleep hangs multithread function in python


code: Country('Africa', **dictionary)

rawDescription: Assign default arguments to Python class members


code:
Player.health.fset
Player.health.fget

rawDescription: How do I obtain the reference of a getter/setter method created through @property in Python?

description: Obtain the reference of a getter/setter method created through @property in Python


code:
G.add_edge(1, 3, weight=1)
G.add_edge(2, 3, weight=2)
G.edges()
nx.shortest_path(G, source=1, target=2, weight="weight")

rawDescription: Is it possible to add a weight/probability to a node in graph theory(using networkx)


rawDescription: Best way to split a string into elements and concat each element with a common value?

description: Split a string into elements and concat each element with a common value


rawDescription: How to plot a bar chart if the input data is of type list?

description: Plot a bar chart if the input data is of type list


code:
def recVowelCount(s):
    def loop(s, acc):
        if not s:
            return acc
        return loop(s[1:], (1 if s[0] in 'aeiouAEIOU' else 0) + acc)
    loop(s, 0)

rawDescription: Counting vowels in a string using recursion


code:
class Event(Base):
    __tablename__ = 'events'
    EventId = Column(Integer, primary_key=True)
    Session = Column(Integer)
    Type = Column(String)

rawDescription: SQLAlchemy - Select rows with the same column values, excluding those with values from different column


code: df['moving average'] = df['running total'] / df['count'].astype('float')

rawDescription: Spreadsheet Manipulation Tricks w/ Python's Pandas


code:
with valve_control(value, USE_VALVE):
  do_something()

rawDescription: Tips on using the with statement in Python


code: returns = {'file_|-/usr/bin/gen-motd.py_|-/usr/bin/gen-motd.py_|-managed': {'comment': 'File /usr/bin/gen-motd.py updated', 'pchanges': {'diff': PreservedScalarString('---\n+++\n@@ -1,5 +1,7 @@\n #!/usr/bin/env python\n\n+import sys\n+import urllib2\n import socket\n import json\n import time\n')}, 'name': '/usr/bin/gen-motd.py', 'start_time': '16:18:54.060168', 'result': True, 'duration': 99.663, '__run_num__': 1, 'changes': {'diff': PreservedScalarString('---\n+++\n@@ -1,5 +1,7 @@\n #!/usr/bin/env python\n\n+import sys\n+import urllib2\n import socket\n import json\n import time\n')}, '__id__': '/usr/bin/gen-motd.py'}}

rawDescription: python convert to yaml formatting issue

description: Python convert to yaml formatting issue


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


code:
arr1
arr2

rawDescription: Distance between numpy arrays, columnwise


code:
import yaml

file_name = 'test.yml'

with open(file_name) as infile:
    data = yaml.load(infile)

person = data['Person']
person['name'] = input('What is your name? ')
person['age'] = int(input('What is your age? '))
person['nationality'] = input('What is your nationality? ')
person['footed'] = input('What foot? ')
person['position'] = input('What is your position? ')

with open(file_name, 'w') as outfile:
    yaml.dump(data, stream=outfile, default_flow_style=False, indent=3)

rawDescription: Using Python with YAML

description: Using Python with YAML


code: print (np.may_share_memory(a, b))

rawDescription: How can I tell if NumPy creates a view or a copy?

description: Tell if NumPy creates a view or a copy


code:
example.py
from PIL import Image
import sample

im = Image.open('sample.gif')
im = im.convert('L')
si = sample.simple_image()
si.rows,si.cols = im.size
s = im.tostring() # Must keep a reference
si.imgdata = s
sample.some_func(si)

rawDescription: Marshaling a Python PIL Image using SWIG


code:
for req in self.parse(response):
    yield req

rawDescription: Multiple inheritance in scrapy spiders

description: Multiple inheritance in scrapy spiders


code:
result = grouped['Period'].apply(
    lambda x: x.loc[(x.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: isinstance('a', (str, list, tuple, int))

rawDescription: Elegant way to check if a list contains int, str, tuple and sub-list


code: np.savetxt('test.txt',x,fmt='%d %d %s')

rawDescription: How to realize a very big int matrix with 5 string columns in numpy (python3)?

description: Realize a very big int matrix with 5 string columns in numpy (python3)


code: c2.sort(key = lambda row: (row[2],row[1]))

rawDescription: Sorting a list of lists in Python

description: Sorting a list of lists in Python


rawDescription: python - filter minimum element for given condition

description: Python - filter minimum element for given condition


code:
import numpy as np
m = np.zeros((10, 4))
v = np.ones((10, 1))
c = np.c_[m, v]

rawDescription: How to append a vector to a matrix in python

description: Append a vector to a matrix in python


rawDescription: print sum of strings as float

description: Print sum of strings as float


code:
conversion_factors = {
    'foot': 0.3048,  # Google search '1 foot in m'
    'feet': 0.3048,
    'ft': 0.3048,
    'yard': 0.9144,
    # etc
}

rawDescription: Elegant list of conditions in Python

description: Elegant list of conditions in Python


code: send(ARP(op=ARP.is_at, psrc=victim_ip, hwdst=router_mac, pdst=router_ip))

rawDescription: Python 2.7 -scapy and ARP

description: Python 2.7 -scapy and ARP


code:
x = sparse.spdiags(np.arange(1,13).reshape(3,4), [-1, 0, 1], 5, 4)
x.A   # display as normal numpy array
x

rawDescription: spdiags() in MATLAB into Python

description: Spdiags() in MATLAB into Python


code:
def func(*args):
    return args
fields = ["A", "B", "C"]
func(*fields)
fields = ["A", "B", "C", "D"]
func(*fields)

rawDescription: Feed python function with a variable number of arguments


code:
with open("test.txt", "a") as myfile:
    myfile.write(str(VLT['V']))

rawDescription: Python files encoding

description: Python files encoding


code:
import re

invalid_escape = re.compile(r'\\[0-7]{1,3}')  # up to 3 digits for byte values up to FF

def replace_with_byte(match):
    return chr(int(match.group(0)[1:], 8))

def repair(brokenjson):
    return invalid_escape.sub(replace_with_byte, brokenjson)

rawDescription: Fixing invalid JSON escape

description: Fixing invalid JSON escape


code: soup = BeautifulSoup(urllib2.urlopen(url), "lxml", parse_only=required_part)

rawDescription: Trouble printing all items from a list in python


code:
def _get_deadline_date(self, cr, uid, context=None):
    val = self.pool.get('ir.config_parameter').get_param(cr, uid, 'key_value')
    try:
        val = int(val)
    except:
        # Just in case...
        val = 30
    return (datetime.now() + timedelta(days=val)).strftime('%Y,%m,%d')

_defaults = {
    'deadline_date': lambda s, cr, uid, c: s._get_deadline_date(self, cr, uid,     context=c),
}

rawDescription: Set default duration in res_config

description: Set default duration in res_config


rawDescription: Combine (3) 32-char hex hashes into a single unique 32-char hash?


code:
archive = ZipFile(self.archive_name, "r")
with archive:
    print(id(archive))
archive = ZipFile(self.archive_name, "r")
with archive:
    print(id(archive))

rawDescription: Python variables scope in loops example

description: Python variables scope in loops example


code:
def generate_strings(value, bound, alpha):
    yield value
    while value != bound: # run until we have reached bound
        for i, c in enumerate(reversed(value)): # loop over the string in reverse
            if c != alpha[-1]: # can this character be incremented?
                # construct an incremented value
                value = value[:-1-i] + alpha[alpha.index(c)+1] + alpha[0]*i
                break # exit the for loop
        else: # run only if for loop ended without breaking
            value = alpha[0]*(len(value) + 1) # make a longer string
        yield value

rawDescription: Generating a list of combinations with repetition... with a twist


code:
class SomeForm(ModelForm):
    def __init__(self, *args, **kwargs):
        if 'some_id' in kwargs:
            self.some_id = kwargs.pop('some_id')

        super(SomeForm, self).__init__(*args, **kwargs)

rawDescription: How to access id in modelform validation?

description: Access id in modelform validation


rawDescription: Python: Add strings to a list full of integers


code:
from pylab import *

x = arange(len(intList))
p = polyfit(x, intList, 2)
a, b, c = p
x0 = -0.5*b/a # x coordinate of vertex

# plot
x = arange(len(intList))
plot(x, intList)
plot(x, polyval(p, x))
axvline(x0, color='r', ls='--')

rawDescription: Python : fit a curve to a list of integers


code: f =  open('filename', 'rU')

rawDescription: Unable to read huge (20GB) file from CPython


code:
i=0
diffpath=os.path.join('diff/path',cr[i])
diff_file = open(diffpath, 'w')
for line in diff:
     diff_file.write(line)
diff_file.close()
i=i+1

rawDescription: Python-comparing mutliple files from different folders and generating diff files


rawDescription: Increase the data size

description: Increase the data size


code:
mylist = ['a', 'b', None, 'c', None]
mylist[:] = [0 if x is None else 1 for x in mylist]
mylist

rawDescription: How to convert a list of elements into a list with 0 or 1

description: Convert a list of elements into a list with 0 or 1


code:
d = {k:v if len(v) > 1 else v[0] for k,v in qd.iterlists()}
json.dumps(d)

rawDescription: QueryDict to string loses list within JSON


code:
iter = d.itervalues()
while True:
    try:
        x = next(iter)

        x = 5 # There is nothing in this line about changing the values of d
    except StopIteration:
        break

rawDescription: Why does python's dictionary iteration seemingly work with a copy?


code:
myarray = ['a', 'a', ['b', 'a', 'a'], ['a', 'c', 'd', 'a'], 'a', ['a', 'd']]

def nestremove(lst, what):
    new = []
    for item in lst:
        if isinstance(item,list):
            new.append(nestremove(item,what))
        elif item != what:
            new.append(item)
    return new

print(myarray)
myarray = nestremove(myarray, 'a')
print(myarray)

rawDescription: Remove all items of same name from list of sublists


rawDescription: Prime number finder - optimization

description: Prime number finder - optimization


code:
rdd = rdd.map(lambda x: pyspark.sql.Row(**x))
# ** is to unpack the dictionary since the Row constructor
# only takes keyword arguments

rawDescription: saving a list of rows to a Hive table in pyspark

description: Saving a list of rows to a Hive table in pyspark


code:
if data.count > 0:
    data.count = None
#continue with some stuff and lastly call .save()
productObj.save()

rawDescription: update an object after deleting a value from it

description: Update an object after deleting a value from it


code:
import shelve
from contextlib import closing

try: raw_input = raw_input
except NameError:
    raw_input = input # py3k

class phonebook:

    def __init__ (self, filename):
        self.allphones = shelve.open(filename, protocol=1, writeback=True)

    def adddata(self, name, phone):
        self.allphones[name] = phone # append to the dictionary
        self.allphones.sync()
        # confirm the input
        print ('A new phone book entry added - {0}:{1}'.format(name, phone))
        # dump the complete phonebook data
        print (dict(self.allphones.items()))

    def close(self):
        self.allphones.close()

with closing(phonebook('.phonebook')) as adding:
    name = raw_input('Type person\'s name --> ')
    phone = raw_input('Type person\'s phone number --> ')
    adding.adddata(name, phone)

rawDescription: Keeps only one entry instead of appending to the dictionary


code:
L1=['cat', 'dog', 'fish', 'rabbit', 'horse', 'bird', 'frog', 'mouse']
tuples = [(x,y) for x in L1 for y in L1 if x != y]
for entry in tuples:
    if (entry[1], entry[0]) in tuples:
        tuples.remove((entry[1],entry[0]))
for pair in tuples:
    input1= open('file_%s'%(pair[0]), 'r')
    file1= pickle.load(input1)
    input2= open('file_%s'%(pair[1]), 'r')
    file2= pickle.load(input2)

rawDescription: getting every possible combination in a list

description: Getting every possible combination in a list


code: res_list = [x[0] for x in rows]

rawDescription: Get the first element of each tuple in a list in Python


rawDescription: How to get the list of options that Python was compiled with?

description: Get the list of options that Python was compiled with


code:
# First go to the "/var/www/html" directory
os.chdir("/var/www/html" )

rawDescription: Python Script not creating file when run through Task Scheduler


code:
{
"_id" : ObjectId("534e0d346a1b7a0e48ff9076"),
"myoutput" : "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" ... /html>",
"myinput" : "http://www.exmaple.com/001"
}

rawDescription: Python send data over http

description: Python send data over http


code:
def f():pass

def g():pass

lambda x: f(), g()
lambda x: (f(), g())

rawDescription: Hide function not called

description: Hide function not called


code: slices_start = np.array([s.start for s in slices])

rawDescription: Python - slice array until certain condition is met


rawDescription: python 3 remove before and after on string

description: Python 3 remove before and after on string


rawDescription: Need help with BeautifulSoup(Python) and parsing HTML table


code:
foo
asdf
asdf
foo
foo
asdf
asdf
fooo

rawDescription: Python:How to split file into chunks by the occurrence of the header word


code:
def CLIENT_Overtime_Results(request):
    overtime_data = Overtime.objects.all()
    location = None
    if request.method == 'POST':
        form = OvertimeForm(data=request.POST)
        if form.is_valid():
            location = form.data['location']
            overtimeid = Location.objects.all()
            overtime_data = Overtime.objects.filter(location=location) #Added for filtering*
    else:
        form = OvertimeForm()
    template_name = "overtime/UBS_Overtime_Results.html"
    context = {
        'form': form,
        'location': location,
        'overtime_data': overtime_data,
    }
    return render(request, template_name, context)

rawDescription: Using queryset to 'filter' within form to display results from DB depending on option selected


code:
# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

rawDescription: Python : send data of form to one email address


code:
d = [{'feature_a':1, 'feature_b':'Jul', 'feature_c':100, 'feature_d':'A'},
 {'feature_a':2, 'feature_b':'Jul', 'feature_c':150, 'feature_d': 'B'},
 {'feature_a':1, 'feature_b':'Mar', 'feature_c':110, 'feature_d':'F'},
 {'feature_a':1, 'feature_b':'Mar', 'feature_c':110, 'feature_d':'G'}]
seen_set = set()
new_d = []
for i in d:
    if tuple([i['feature_a'],i['feature_b'],i['feature_c']]) not in seen_set:
        new_d.append(i)
        seen_set.add(tuple([i['feature_a'],i['feature_b'],i['feature_c']]))
pprint.pprint(new_d)

rawDescription: How to make values in list of dictionary unique?

description: Make values in list of dictionary unique


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(content, 'html.parser')
theories = ', '.join([li.text for li in soup.findAll('li')])

rawDescription: Django striptags, comma separated keywords


rawDescription: Python Pandas: How to read only first n rows of CSV files in?


code: numbers = map(int, raw_input().split())

rawDescription: Reading a line of integers in Python

description: Reading a line of integers in Python


code:
def sizeHint(self,option,index):
    parent = index.parent()
    if parent.isValid() and  not parent.parent().isValid():
        return QSize(32,32)
    return QSize(24,24)

rawDescription: How to set the icon-size in a QTreeWidget?

description: Set the icon-size in a QTreeWidget


code:
some_user = User.query.get(n)
some_user.department_assoc.append(UserDepartment(department_id=m,  is_manager=False))
db.session.commit()

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

description: Add value to join table with SQLAlchemy


code:
import re

text = """
  info = [ {
    Date = "YR-MM-DDT00:00:10",
    Date = "YR-MM-DDT01:02:03",
    Date = "YR-MM-DDT11:22:33"
  }
"""

new_text = re.sub('T.*"', '"', text)
print(new_text)

rawDescription: Delete a repeating pattern in a string using Python


code:
for i in range(0,100):
  if i != 0:
    pass

rawDescription: in python why if rank: is faster than if rank != 0:

description: In python why if rank: is faster than if rank != 0:


code:
def make_interleave(arr1, arr2, permutation):
    iters = [iter(arr1), iter(arr2)]
    return "".join(iters[i].next() for i in permutation)

make_interleave("ab", "cde", [1, 0, 0, 1, 1])

rawDescription: How can I interleave or create unique permutations of two stings (without recursion)

description: Interleave or create unique permutations of two stings (without recursion)


code:
IDs = np.unique(totalHigh_sliced)
counts = np.bincount(totalHigh_sliced.ravel(),prob_sliced.ravel())

rawDescription: Group and summarize matrix by value

description: Group and summarize matrix by value


code:
blob_info = blobstore.BlobInfo.get(resource)
type = blob_info.content_type
if type == 'application/pdf':
    self.response.headers['Content-Type'] = type
    self.send_blob(blob_info,save_as=False)
else:
    self.send_blob(blob_info,save_as=True)

rawDescription: Downloaded filename with Google App Engine Blobstore


code: Foo.query.join(Bar, and_(Foo.bar_no == Bar.bar_no, Bar.status == filters['status'])).all()

rawDescription: Sql filter query with join objects

description: Sql filter query with join objects


code:
it = iter(x)
a = next(it)

rawDescription: Python 2: someIterator.next() vs. next(someIterator) :Python 3


code:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from threading import Thread

class ThreadedHTTPServer(HTTPServer):
    def process_request(self, request, client_address):
        thread = Thread(target=self.__new_request, args=(self.RequestHandlerClass, request, client_address, self))
        thread.start()
    def __new_request(self, handlerClass, request, address, server):
        handlerClass(request, address, server)
        self.shutdown_request(request)

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write("hello world")

server = ThreadedHTTPServer(('', 80), Handler)
#server.serve_forever()

rawDescription: Threaded BaseHTTPServer, one thread per request


code:
if len(split_build_descriptor) == 1:
    buildfile = split_build_descriptor[0]
    target = ''
elif len(split_build_descriptor) == 2:
    buildfile, target = split_build_descriptor
else:
    pass  # handle error; there's two #s

rawDescription: Python how to handle split when delimiter not present?


code:
class MyConfigParser(ConfigParser.RawConfigParser):

    def get_list_of_tups(self, section, option):
        value = self.get(section, option)
        import re
        couples = re.finditer('\("([a-z0-9]*)", "([a-z0-9]*)"\)', value)
        return [(c.group(1), c.group(2)) for c in couples]

rawDescription: Python argparser. List of dict in INI

description: Python argparser. List of dict in INI


code:
function_type = type(lambda: None)
function_type
function_type(foo.__code__, globals(), 'bar')

rawDescription: Python 'Functions are objects'

description: Python 'Functions are objects'


code:
def transform_incoming_json_item(item, things=None):
    if things is None:
        things = []
    if isinstance(item, dict):    # <----
        item = [item]             # <----
    if isinstance(item, list):
        things.extend(process_thing(thing) for thing in item)
    return things

rawDescription: python instance-based type checking

description: Python instance-based type checking


code:
df
newdf = df.groupby(['x','y']).mean().reset_index()
newdf

rawDescription: Mean value by equality of rows

description: Mean value by equality of rows


code:
with open("inp1") as f:
    c = Counter(x.strip() for x in f)
with open("inp2") as f:
    c2 = Counter(x.strip() for x in f)
[(x, c[x], c2[x]) for x in set(c) | set(c2)]

rawDescription: store value into namedtuple in python

description: Store value into namedtuple in python


code:
from .custom_routers import HybridRouter

# The rest is from the `rest-framework` polls-tutorial.

rest_router = HybridRouter()
rest_router.register(r'users', UserViewSet)
rest_router.register(r'polls', PollViewSet)
rest_router.add_api_view("config", url(r'^config/$', configViews.SiteConfiguration.as_view(), name='site_configuration'))

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(rest_router.urls), name='rest_api'),
    url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^admin/', include(admin.site.urls), name='admin'),
]

rawDescription: django rest-framework singleton ViewSet

description: Django rest-framework singleton ViewSet


code:
def get_obj_quaternion ( mayaTransform, worldSpace=True ):
    '''
    gets the rotation quat for the supplied dag node in world or local space
    '''
    #convert from mMatrix to MTransformationMatrix....
    mMatrix = matrix_from_transform( mayaTransform, worldSpace=worldSpace )
    mTransformMtx = OpenMaya.MTransformationMatrix( mMatrix )

    # MscriptUtil. Sigh
    x = OpenMaya.MScriptUtil().asDoublePtr()
    y = OpenMaya.MScriptUtil().asDoublePtr()
    z = OpenMaya.MScriptUtil().asDoublePtr()
    w = OpenMaya.MScriptUtil().asDoublePtr()

    mTransformMtx.getRotationQuaternion( x, y, z, w )
    # getRotationQuaternion is an MTransformationMatrix method

    #convert them back to normal python floats
    x = OpenMaya.MScriptUtil().getDouble( x )
    y = OpenMaya.MScriptUtil().getDouble( y )
    z = OpenMaya.MScriptUtil().getDouble( z )
    w = OpenMaya.MScriptUtil().getDouble( w )

    return x, y, z, w

rawDescription: Maya Python API Scaling a matrix about another matrix


code:
if __name__ == '__main__':
    import proxy
    proxy.method()

rawDescription: Creating Python Façade Package

description: Creating Python Façade Package


code:
for _ in range(50):
    atoms.append(Element(group=16, valence=2, number=16, weight=32.066))

rawDescription: Is it possible to create unique instances that have the same input?


code: df['ts'] = pd.to_datetime(df.date, format='%m/%d/%Y %H:%M:%S')

rawDescription: Pandas group by several values in a single column


code:
import pylab
pylab.figure()
pylab.plot(range(10))
pylab.xticks([2,3,4], ['a','b','c'])
pylab.show()

rawDescription: customize ticks for AxesImage?

description: Customize ticks for AxesImage


code: f('a test', reversed, sorted, ''.join)

rawDescription: Better Function Composition in Python

description: Better Function Composition in Python


code:
piv.columns = ["tag_{}".format(x) for x in piv.columns]
piv = piv.reset_index()
piv

rawDescription: Denormalizing a column to a boolean matrix in Pandas?


code:
def natatime_25(itr, fillvalue=None, n=2):
  x = itertools.chain(iter(itr), (fillvalue,) * (n-1))
  return itertools.izip(*(x,)*n)

rawDescription: reading lines 2 at a time

description: Reading lines 2 at a time


code:
keywords = [keyword1, keyword2, ... ]
conditions = " or ".join(["contains(., '%s')" % keyword for keyword in keywords])
expression = "//*[%s]" % conditions

elm = driver.find_element_by_xpath(expression)

rawDescription: How to find element by multiple text strings?

description: Find element by multiple text strings


rawDescription: Sort List of Numbers according to Custom Number Sequence


code:
def common_fields(group):
    return dict(functools.reduce(set.intersection, (set(d.items()) for d in group)))

rawDescription: Correct use of a fold or reduce function to long-to-wide data in python or javascript?


rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
def todos_lista(lista, guarda):
    return all(map(guarda, lista))

rawDescription: Functional Python with Lists

description: Functional Python with Lists


code: hasattr(some_var, "username")

rawDescription: How to fake type with Python

description: Fake type with Python


code: numpy.dot(b, a.T)

rawDescription: Python/Numpy - Matrix Multiply a 2D Array and Each Row of another 2D Array


code:
for row_index, row in df.iterrows():
   convert_to_bib(row)

rawDescription: Python Pandas iterrows method

description: Python Pandas iterrows method


code: len(set(my_list)) == 1

rawDescription: boolean expression of a list

description: Boolean expression of a list


code:
for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)

rawDescription: python dictionary sorting in descending order based on values

description: Python dictionary sorting in descending order based on values


rawDescription: Regex include the negative lookbehind

description: Regex include the negative lookbehind


code:
passwords = []
with open('hash.txt', 'r') as f:
    passwords.extend(f.read().split('\n'))

rawDescription: Python: Exporting text list to a text file


code:
True
False

rawDescription: Is it possible to create a completely new instance of the members of a parent class?


code:
fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()

rawDescription: figure of imshow() is too small

description: Figure of imshow() is too small


rawDescription: Verifying arithmetic sequence python

description: Verifying arithmetic sequence python


rawDescription: Python Regex with duplicate field names but different values


code:
import fileinput
import sys

filename = 'test.txt'

# ----
# print the line user asked for
def printline(linenumber):
    handle = open(filename)
    for i, line in enumerate(handle):
        if (i+1) == int(linenumber):
            print (line)
            # find a keyword to type here to exit for loop as soon as the line of interest is printed
    handle.close()

# ----

# ask user for the line number
linenumber = input('Please enter line number: ')
print ('Line %s is: ' % linenumber)
printline(linenumber)

# ask if IN/OUT has to be changed
answer = input('Switch IN to OUT --OR-- OUT to IN? (y/n): ');
if answer == 'y':

    # use fileinput to change the file in place
    for line in fileinput.input(filename, inplace = True):

        # if it is the line of interest, switch IN to OUT if ,IN, is found
        # switch OUT to IN if ,OUT, is found
        if fileinput.filelineno() == int(linenumber):
            if ',IN,' in line:
                print ('%s' % line.strip().replace(',IN,', ',OUT,'))
            else:
                print ('%s' % line.strip().replace(',OUT,', ',IN,'))

        # if this is not the right line, just print the line back to file
        else:
            print (line.strip())

    fileinput.close()

print ('Line %s is: ' % linenumber)
printline(linenumber)

print ('Done')

rawDescription: File Manipulation in Python

description: File Manipulation in Python


rawDescription: How to programatically get the SDK version in Google Appengine (Python)?

description: Programatically get the SDK version in Google Appengine (Python)


code:
#!/usr/bin/env python
import urllib2
from lxml import html # $ apt-get install python-lxml or $ pip install lxml

page = urllib2.urlopen('http://stackoverflow.com/q/11939631')
doc = html.parse(page).getroot()

div = doc.get_element_by_id('question')
for tr in div.find('table').iterchildren('tr'):
    for td in tr.iterchildren('td'):
        print(td.text_content()) # process td

rawDescription: Is there an easy way to parse an HTML document and remove everything except a particular table?


rawDescription: ipython notebook pandas max allowable columns

description: Ipython notebook pandas max allowable columns


code: outfile.write('\n'.join(['%15s : %s' % key_value for key_value in dictionary.items()]))

rawDescription: How to use for loop in the write method?

description: Use for loop in the write method


code:
import numpy as np
np.random.permutation([x for x in range(5000, 5200) if not [t for t in range(2, x) if not x % t]])[0]

rawDescription: Creating only one random prime number in provided range


code:
circle_rad = 15  # This is the radius, in points
ax.plot(point[0], point[1], 'o',
        ms=circle_rad * 2, mec='b', mfc='none', mew=2)
ax.annotate('Midici', xy=point, xytext=(60, 60),
            textcoords='offset points',
            color='b', size='large',
            arrowprops=dict(
                arrowstyle='simple,tail_width=0.3,head_width=0.8,head_length=0.8',
                facecolor='b', shrinkB=circle_rad * 1.2)
)

rawDescription: How do I put a circle with annotation in matplotlib?

description: Put a circle with annotation in matplotlib


code: word_repeat_box.bind("<Key>", pressed)

rawDescription: Calculate the time between a range of key events in Python


rawDescription: How do I append values from a row in a CSV file into a list in python?

description: Append values from a row in a CSV file into a list in python


rawDescription: RGB Tuples to RGB Integers

description: RGB Tuples to RGB Integers


code:
from matplotlib import pyplot
steps = 10000
numwalks = 1000
walks = [makewalk(steps) for i in xrange(numwalks)]

rawDescription: how i can repeat loop for random walk?

description: How i can repeat loop for random walk


rawDescription: python list literal / initialization with dynamic number of elements

description: Python list literal / initialization with dynamic number of elements


code:
import threadtimer

timer = threadtimer.ThreadTimer(window)
timer.start(150)
window.Bind(threadtimer.EVT_THREAD_TIMER, function_to_call)

rawDescription: wxPython: wx.CallLater being very late

description: WxPython: wx.CallLater being very late


code:
def assign(lval, val):
     globals().update({lval:val})

rawDescription: Counting from 1 to infinity without assignment


rawDescription: Repeat Pandas dataframe row labels

description: Repeat Pandas dataframe row labels


code:
import string # This module holds lists of characters that you would find useful.

def encryptMessage(original_message):
    original_message = str(original_message)
    secret_message = []
    conversions = {"1": "@", "2": "#", "3": "$"}
    for letter in original_message:
        if letter in string.ascii_uppercase:
            secret_message.append(letter.lower() + "^")
        elif letter in '123':
            secret_message.append(conversions[letter])
        elif letter in string.ascii_lowercase:
            secret_message.append(letter)
        else:
            secret_message.append("*")
    return ''.join(secret_message)

rawDescription: Message "encryption" through a set of given rules returns incomplete result


code: xlbl = ax.set_xlabel(...)

rawDescription: How to access axis label object in matplotlib?

description: Access axis label object in matplotlib


code:
class ParentWithDocstring(object):
    """Parent docstring"""

class SubClassWithoutDocstring(ParentWithDocstring):
    __metaclass__ = inheritdocstring

SubClassWithoutDocstring.__doc__

rawDescription: Inherit a parent class docstring as __doc__ attribute


code:
class Test(object):
    @property
    def prop(self):
        return self.__dict__['prop']

    @property
    def prop(self):
        return "property"

rawDescription: Built-in function to read __slots__

description: Built-in function to read __slots__


code:
from splinter.browser import Browser
b = Browser('firefox')
b.visit('http://www.baidu.com')
b.fill('wd', 'test')
b.execute_script('document.getElementsByName("f")[0].submit()')

rawDescription: How do I click Enter using Splinter?

description: Click Enter using Splinter


code:
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13

rawDescription: How to print every third (or n-th) line from file in Python?

description: Print every third (or n-th) line from file in Python


code: from __future__ import print_function

rawDescription: How to use this for loop to get expected result in python

description: Use this for loop to get expected result in python


code:
print(np.dot(A,x))
# [ 5. -1.  3.]

assert np.allclose(np.dot(A,x), b)

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

description: Solve multivariable linear equation in python


code: #!/bin/env python

rawDescription: PYTHONPATH: command line calls on Windows 7


rawDescription: does python ctypes supports size-0 array?

description: Does python ctypes supports size-0 array


code:
for td in soup.find(text='Giraffe').parent.find_next_siblings():
    print(td.text)

rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function


code:
import struct, datetime
s = '\x07\xd8\t\x17\x03\x184\x00'
datetime.datetime(*struct.unpack('>HBBBBBB', s))

rawDescription: Convert snmp octet string to human readable date format


rawDescription: How to iterate over particular keys in a dict to get values

description: Iterate over particular keys in a dict to get values


code: hc.loc[hc["ID"].isnull(),'ID'] = hc["First Name"] + hc["Last Name"]

rawDescription: Fill empty cells in column with value of other columns


code: np.where(np.equal(Predictions, Labels))

rawDescription: How to find the set of indices where two vectors have equal elements in Python

description: Find the set of indices where two vectors have equal elements in Python


code:
lst = ['.ab.cd.ef.gh.', '.ij.kl.mn.op.']
['*' + item[1:-1] + '$' for item in lst]

rawDescription: Replacing selected parts of an item in Python list


code: (df.employee_id + df.customer_id + df.timestamp).apply(hash)

rawDescription: Creating a unique value per row in pandas?


code:
anotherdict = {(1, 2): 'a', (3, 4): 'b', (4, 2): 'c'}
{v for key in yourdict for v in key}
{v for key in anotherdict for v in key}

rawDescription: How to get all values from Python tuple keys from dictionaries into one list?

description: Get all values from Python tuple keys from dictionaries into one list


code:
from ConfigParser import RawConfigParser
parser = RawConfigParser({"myvar": "default_value"}) # Never use ConfigParser.ConfigParser!
parser.read("my_config")
myvar = parser.get("mysection", "myvar")

rawDescription: python: simple way to input python data from file

description: Python: simple way to input python data from file


code:
def find(x, L, seen=None):
    if seen is None:
        seen = set()
    if id(L) in seen:
        # Avoid infinite recursion
        return False
    seen.add(id(L))
    return x in L or any(find(x, sublist, seen)
                         for sublist in L
                         if isinstance(sublist, list))

rawDescription: Finding elements in list of lists

description: Finding elements in list of lists


rawDescription: Pythonic way to add datetime.date and datetime.time objects


code:
def area(a=None,b=None):

 if b is None:
    if a is None:
        return 'none'
    else:
        return a**3
 else:
    return a*b

print(area(2))
print(area(2,1))
print(area())

rawDescription: Python: giving answer according to given arguments


code:
import foo

foo.configure(42, 'bar')

rawDescription: Python: What is the recommended way to set configuration settings for a module when you import it?


code: arr[:, (1-slice_length):] = 0

rawDescription: Efficient 2d cumsum

description: Efficient 2d cumsum


code:
class MenuItem(object):
    def present(self, macromap):
        return macromap[type(self).__name__](self, macromap)

class TextLink(MenuItem):
    def __init__(self, url, text):
        self.url, self.text = url, text

class Section(MenuItem):
    def __init__(self, text, items):
        self.text, self.items = text, items

class ImageLink(MenuItem):
    ...

rawDescription: Polymorphic macros in Jinja

description: Polymorphic macros in Jinja


code:
sin_ele = []
dbl_ele = []
for i, ele in enumerate(arr[:-1], 1):
    dbl_ele.append(ele) if ele == arr[i] or ele == arr[i-2] else sin_ele.append(ele)
ele = arr[-1]
dbl_ele.append(ele) if dbl_ele and ele == dbl_ele[-1] else sin_ele.append(ele)
sin_ele.extend(dbl_ele)

rawDescription: arrange the elements in the sorted list so that all the redundant elements are at left/right side of the list

description: Arrange the elements in the sorted list so that all the redundant elements are at left/right side of the list


code: sorted_lists = [x for x in zip(*sorted(zip(sub_item), key=operator.itemgetter(0)))]

rawDescription: Sorting a list of the form [(single value), [(tuple 1), (tuple2), ...], (another value),[...]]


code: days = (df1['End Date'] - df1['START DATE']) / pd.offsets.Day(1)

rawDescription: How to find the number of days between two dates for dataframe manipulation

description: Find the number of days between two dates for dataframe manipulation


code:
over_tab = over(bitmap_rgba1, bitmap_rgba2)
over_tab[:, :, 0:3] = over_tab[:, :, ::-1][:, :, 1:4]
ax.imshow(over_tab)

rawDescription: Making figure transparent with colored background


rawDescription: Force integers of a given size with bin?

description: Force integers of a given size with bin


code:
t = time.time()
local = datetime.datetime.fromtimestamp(t)
utc = datetime.datetime.utcfromtimestamp(t)
offset = local - utc
sec = offset.total_seconds()

rawDescription: Time issues in Python

description: Time issues in Python


code:
[[uniform(lower_limit, upper_limit) if i > some_value else i
  for i in row]
  for row in Z]

rawDescription: Replace values in a 2D array with different random numbers


code:
import gc
gc.get_objects()

rawDescription: How to get the list of all initialized objects and function definitions alive in python?

description: Get the list of all initialized objects and function definitions alive in python


code:
for i in range(len(motifs[0])):
    seq = ''
    for j in range(len(motifs)):
            seq += motifs[j][i]
    profile.append([(best.count(bseq)+1)/float(len(seq)) for base in 'ACGT'])

rawDescription: How to break down an expression into for-loops

description: Break down an expression into for-loops


code: biography = contents[4:]

rawDescription: Python: How do you read a chunk of text from a file without knowing how long the file actually is?


code: (matching.groupby(['id', 'left', 'right'])['boolen'].sum() > 0).reset_index()

rawDescription: Conditional multi column matching (reviewed with new example)


code:
from pyspark.sql.types import *

schema = ArrayType(StructType([
    StructField("char", StringType(), False),
    StructField("count", IntegerType(), False)
]))

rawDescription: How to return a "Tuple type" in a UDF in PySpark?

description: Return a "Tuple type" in a UDF in PySpark


code:
my_list = [1,2,3,4,5]
flipped_list = my_list[::-1]

rawDescription: Specific Python reverse function questions


code:
def get_admin_absolute_url(self):
    if self.pk:
        return resolve_url('admin:checkAccounts_change', self.pk)

def admin_link(self):
    if not self.pk:
        return ''
    return ('{}').format(self.get_admin_absolute_url(),
                                        self.name)

rawDescription: django admin: How to get all values from 2 models with same FK

description: Django admin: How to get all values from 2 models with same FK


code: self.help_button = Button(text = "Help", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.1},on_press = self.update)

rawDescription: Update label's text when pressing a button in Kivy for Python


code:
from __future__ import print_function

import pandas as pd

df = pd.read_csv('data.csv', parse_dates=['DATE','CLOCKDATETIME'])

df.ix[(df['CLOCKDATETIME'].dt.hour <= 4), 'DATE'] -= pd.Timedelta('1 days')
print(df)

rawDescription: pandas combine_first resulting in more number of rows

description: Pandas combine_first resulting in more number of rows


code:
M *= 2
M.A
M.data

rawDescription: How do I get a scipy.csr sparse-matrix as a normal dense matrix without toDense()?

description: Get a scipy.csr sparse-matrix as a normal dense matrix without toDense()


rawDescription: Print binary then negate without ones complement in python


code:
def lrange_literal_eval(lst):
    return [ast.literal_eval(x) for x in lst]

r_server.set_response_callback('LRANGE', lrange_literal_eval)

r_list = r_server.lrange('test', 0, -1)
r_list.reverse()
r_server.delete('test')

rawDescription: How did you pop all valus in redis one time


code:
def sim(haystack, needle):
    index = haystack.index(needle) # throws ValueError when not found
    return (index, index + len(needle))

rawDescription: why the output is not good in some cases?

description: Why the output is not good in some cases


code:
#! /usr/bin/env python
import csv
try:
    from StringIO import StringIO   # Python 2.x
except ImportError:
    from io import StringIO         # Python 3.x

test_string = """name,value
foo,1
bar,2
"""

string_io = StringIO(test_string)
#
# Position is 0 i.e. the beginning of the string.
#
print("Position: {}".format(string_io.tell()))

dict_reader = csv.DictReader(string_io)
#
# Position is still 0. Nothing has been read.
#
print("Position: {}".format(string_io.tell()))
#
# Now we start reading from string_io
#
for row in dict_reader:
    print(row)
    #
    # Position increases every time you read
    # a row using dict_reader.
    #
    print("Position: {}".format(string_io.tell()))

description: Resetting csv.DictReader(StringIO.StringIO(some_string))


code:
l[:] = [";".join(line.split())for line in l]
print(l)

['48998.tyrone-cluster;gic1_nwgs;mbupi;18:45:44;R;qp32', '48999.tyrone-cluster;gic2_nwgs;mbupi;0;Q;batch', '49005.tyrone-cluster;...01R-1849-01_2;mcbkss;00:44:23;R;qp32', '49032.tyrone-cluster;gaussian_top.sh;chemraja;0;Q;qp32', '49047.tyrone-cluster;jet_egrid;asevelt;312:33:0;R;qp128']

rawDescription: insert a character into a list in python

description: Insert a character into a list in python


code:
import pygame
from random import randint

pygame.init()

#create a new event id called event_500ms
event_500ms = pygame.USEREVENT + 1

#set timer event to appear on the event queue every 500 number of milliseconds
pygame.time.set_timer(event_500ms, 500)

screen = pygame.display.set_mode((800,800))

while True:
    #get events from the event queue
    for ev in pygame.event.get():
        if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                pygame.quit()
                exit()

        #check for event_500ms event
        if ev.type == event_500ms:

            r = randint(0, 255)
            g = randint(0, 255)
            b = randint(0, 255)

            screen.fill((r, g, b))

            pygame.display.flip()

rawDescription: Python timer on randint

description: Python timer on randint


rawDescription: When will numpy copy the array when using reshape()


code: [(datetime.today().month - i - 1) % 12 + 1 for i in range(6)]

rawDescription: Last six months number in python

description: Last six months number in python


code:
import random

# '_' (underscore) is used for values that are generated, but that you do not
# care about - here we only want to repeat seven times and do not care about
# the actual loop count
for _ in range(7):
    # generate three random numbers between [1 and 6]
    # and store the values in a, b, c respectively (tuple unpacking)
    a, b, c = (random.randint(1, 6) for _ in range(3))

    # if one of the conditions holds, break out of the loop early
    if a == b or a == c or b == c or a == b == c:
        break

rawDescription: Python - calculate die rolls and count doubles


code:
from matplotlib import pyplot as plt
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

rawDescription: How to detect the nearest square to the image center points?

description: Detect the nearest square to the image center points


code: f = list(Comprehension(e)[2][1])

rawDescription: How to get a vector from a list in list in python?

description: Get a vector from a list in list in python


code:
# Merge clusters 0 and 1
union_find.union(0, 1)
# Add point 2 to the same set
union_find.union(0, 2)

rawDescription: Implementing Disjoint Set Data Structure in Python


code:
def reverse(PB=None):
    if PB is None:
        PB = {'l': 3, 'y':1, 'u':2}

rawDescription: problems with dict.keys not printing a list but printing the view of the list

description: Problems with dict.keys not printing a list but printing the view of the list


code:
def set_val(d, keys, val):
    out = d
    for k in keys[:-1]:
        out = out[k]
    out[keys[-1]] = val

rawDescription: Pythonic way of accessing recursively nested dict


rawDescription: Pandas: De-seasonalizing time-series data


code: [v for k,v in d1.items() if k[0]==111]

rawDescription: Listing all values from tuple key in dict


code:
chaine = 'some'

with open("test.txt", "r") as f:
    text = f.read()
    i = text.find(chaine)
    print(text[i:])

rawDescription: How to extract a text in a file python

description: Extract a text in a file python


code: toolbar.SetToolBitmapSize((24, 24))

rawDescription: How to make a wx Toolbar buttons larger?

description: Make a wx Toolbar buttons larger


rawDescription: Python - Find characters in list of strings that are not duplicates


code:
iso = datetime.date(2005, 1, 1).isocalendar()
iso
iso_to_gregorian(*iso)
iso = datetime.date(2010, 1, 4).isocalendar()
iso
iso_to_gregorian(*iso)
iso = datetime.date(2010, 1, 3).isocalendar()
iso
iso_to_gregorian(*iso)

rawDescription: What's the best way to find the inverse of datetime.isocalendar()?


code: nx.dijkstra_path(g, 'b', 'c')

rawDescription: How to do shortest path algorithm for unweighted graph?

description: Do shortest path algorithm for unweighted graph


code: return super(MessageResource, self).get_object_list(request).filter(Q(sender__user = request.user) | Q(recipient__user = request.user)).distinct('conversation_id').annotate(last_created=MAX(created)).order_by('-last_created')

rawDescription: Getting the latest distinct object in Django


rawDescription: Plotting ticks on the x axis with positive and negative values, in strange order -Python


code:
combined = {}
for d in yourlist:
    combined.setdefault(d['name'], {}).update(d)

output = combined.values()

rawDescription: Combine Dictionarys in a list based on a value


code:
regex_string = 'A.C'  # match an A, followed by any character, followed by C
regex_string = 'A\.C' # match an A, followed by a period, followed by C
regex_string = 'AsC'  # match an A, followed by s, followed by C
regex_string = 'A\sC'  # match an A, followed by a space character, followed by C

rawDescription: In programming, why are escape sequences for regex and escape sequences for string literals different?


code:
today = datetime.utcnow().date()
start = datetime(today.year, today.month, today.day, tzinfo=tz.tzutc()).astimezone(est)
end = start + timedelta(1)

rawDescription: Determine start and end time of current day (UTC -> EST -> UTC) ; Python


code:
import re
import bs4

soup = bs4.BeautifulSoup(html)
soup(attrs={'class' : re.compile(r'^prod')})

rawDescription: Find multiple words with regex in Beautifulsoup4


code:
class Databases(object):
    def __init__(self):
        for database in INSTALLED_DATABASES:
            setattr(self, database, __import__(database))

rawDescription: SQLAlchemy and Multiple Databases

description: SQLAlchemy and Multiple Databases


code:
mins = items[:n]
mins.sort()
for i in items[n:]:
    if i < mins[-1]:
        mins.append(i)
        mins.sort()
        mins= mins[:n]

rawDescription: Getting the lesser n elements of a list in Python


code: ' '.join(l).split().index('1word2')

rawDescription: Absolute position from relative

description: Absolute position from relative


code: labels = ["%f" % i for i in dayspeed['Download']]

rawDescription: Python variable to float list

description: Python variable to float list


code:
import subprocess
subprocess.call(['a.out'], stdin=file('a.inp'))

rawDescription: How to pipe parameter string to excutable in python?

description: Pipe parameter string to excutable in python


code:
counter = 0
for line in a.splitlines():
    if line.strip():
        counter += 1

rawDescription: How can I count the number of numbers in this line-separated string literal in python?

description: Count the number of numbers in this line-separated string literal in python


code:
def index(request):
    if request.session.get('current_user'):
        users = Follow.objects.following(request.user)
        questions = Question.objects.filter(user__in=users)
        return render(request, "welcome/index.html",locals())

rawDescription: how to get a list of questions posted by followed users

description: Get a list of questions posted by followed users


code:
from __future__ import print_function
import base64
import binascii
import os

def base64_encode_file(filename):
    filetype = os.path.splitext(filename)[1][1:]  # remove leading '.' from ext
    with open(filename) as file:
        data = file.read()
        return base64.b64encode(','.join((filename, filetype, data))), data

filename = 'C:/Users/martin/Desktop/img.PNG'
#filename = '/Users/user/Desktop/img.PNG'

encoded, data = base64_encode_file(filename)
print('encoded: {} (hex file data: {})'.format(encoded, binascii.hexlify(data)))

decoded = base64.b64decode(encoded).split(',', 2)
print('decoded:', decoded[0], decoded[1], binascii.hexlify(decoded[2]))

rawDescription: Prepend information in base64 encoding

description: Prepend information in base64 encoding


code: data = {"item1" : None, "item2":{"Book":none}}

rawDescription: Values assigned differently in seemingly identical dictionaries


code:
arraytarget=round(dist*analysisdist/intervalnumber)-1
spatialraw[arraytarget] += 1

rawDescription: Numpy/Python performing terribly vs. Matlab


code:
words = {'acheive':'achieve', 'achiev':'achieve','achieve':'achieve'}

s = "achiev acheive achieve"

from collections import Counter

from string import punctuation

cn = Counter()
for word in s.split():
    word = word.strip(punctuation)
    if word in words:
        wrd = words[word]
        cn[wrd] += 1

print(cn)
Counter({'achieve': 3})

rawDescription: Counting words in list using a dictionary


code: {{ a|todollars }}

rawDescription: How to add a character in Django template

description: Add a character in Django template


code:
[{'Germany': {"Luge - Men's Singles": 'Gold'}},
{'Germany': {"Luge - Men's Singles": 'Silver'}},
{'Italy': {"Luge - Men's Singles": 'Bronze'}}]

rawDescription: How would I merged nested dictionaries in a list in python?


code:
import time
from multiprocessing.dummy import Pool  # Thread Pool

NUM_WORKER_THREADS = 8

def worker(item):
    try:
        print("Processing {}".format(item))
        itemrec = getItemRecord(item) # external call to webservice ~3 second response.
    except Exception as inst:
        print("---------------EXCEPTION OCCURRED----------------")
        print(type(inst))
        print(inst.args)
        print(inst)

# start counter to monitor performance
start = time.perf_counter()

# get the items we need to work on for allocations
searchResults = getSearchResults() # external call to webservice
pool = Pool(NUM_WORKER_THREADS)
pool.map(worker, [item['id'] for item in searchResults
                    if item['recordtype'] == 'inventoryitem'])
pool.close()
pool.join()

# print end of execution performance counter
print('time:', time.perf_counter() - start)

rawDescription: Deadlock when calling task_done() as the task has been pulled by a new thread


code:
import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=20, backupCount=5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
    my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
    print(filename)

rawDescription: Is Python's logger able to rotate log files?


code: [k for k in result_dict if len(result_dict[k]) > 1 ]

rawDescription: Python:how to get keys with same values?

description: Python:how to get keys with same values


code:
a = np.array([
        [[1, np.nan], [np.nan, np.nan]],
        [[np.nan, 1], [np.nan, 2]],
        [[np.nan, np.nan], [np.nan, np.nan]]
    ])
get_nans_blocks_length(a)
array([1, 2, 1, 1, 2, 2], dtype=int64)

rawDescription: Finding start and stops of consecutive values block in Python/Numpy/Pandas


code:
data = {'B':['ADB','ACB','ADB','ARF','BCD'],
        'A':[125,189,148,789,789],
        'C':[['AF:12'],['AF:78', 'AF:85', 'AF:98'],[],
        ['AF:89', 'AF:85', 'AF:12'],['AF:76', 'AF:25']]}

df = pd.DataFrame(data)

def in_list(list_to_search,terms_to_search):
    results = [item for item in list_to_search if item in terms_to_search]
    if len(results) > 0:
        return 'True'
    else:
        return 'False'

df['D'] = df['C'].apply(lambda x: in_list(x, ['AF:12', 'AF:25']))

rawDescription: Pandas: Look if items are in a list in Series.series in a dataframe


code:
for line in all_blocks.splitlines():
    if MAC in line:
         print(line)

rawDescription: searching a string and printing the complete line containing that string

description: Searching a string and printing the complete line containing that string


code:
with open("file1") as infile, open("file2","w") as outfile:
    for i,line in enumerate(infile):
        if i==2:
            # 3rd line
            outfile.write("new line1\n")
            outfile.write("new line2\n")
            outfile.write("new line3\n")
        elif i==3:
            # 4th line
            pass
        else:
            outfile.write(line)

rawDescription: Remove and insert lines in a text file

description: Remove and insert lines in a text file


code: names = [s['name'].value() for s in nuke.selectedNodes()]

rawDescription: Get selected node names into a list or tuple in Nuke with Python


code:
import functools
mult_list = list(map(int, input("Enter numbers seperated by a comma: ").split(',')))
mult = functools.reduce(lambda x, y: x*y, mult_list)
print(mult)

rawDescription: Using lambda with user input list

description: Using lambda with user input list


code: import ConfigParser

rawDescription: How to read a config file using python

description: Read a config file using python


rawDescription: python mechanize follow_link fails

description: Python mechanize follow_link fails


code:
bullet.rect.x -= target[1] / dist * BULLET_SPEED
bullet.rect.y -= target[0] / dist * BULLET_SPEED

rawDescription: Pygame Sprite Moving at Constant Speed

description: Pygame Sprite Moving at Constant Speed


code:
from lxml import etree

xml = """
<root>
    <Maintag>
        <Change_type>NQ</Change_type>
        <Name>Atlas</Name>
        <Test>ATLS</Test>
        <Other>NYSE</Other>
        <Scheduled_E
"""
parser = etree.XMLParser(recover=True)
doc = etree.fromstring(xml, parser=parser)
print(etree.tostring(doc))

rawDescription: Python xml - handle unclosed token

description: Python xml - handle unclosed token


code:
averaged = reduce(lambda l, r: (l + r)/2,
    (misc.imread(f).astype(np.float32, copy = False) for f in files))

rawDescription: Averaged array calculation using numpy in Python


rawDescription: Find all submatrices of a given matrix

description: Find all submatrices of a given matrix


code:
class AClass(object):
      aprop = None
      def __init__(self):
           self.bprop = "bvalue"

rawDescription: Initialize object properties as class properties first in Python


code:
import bisect
def nearest(x, d):
    index = bisect.bisect(d, x)
    if not index:
        return d[index]  # left-most x coordinate
    if index == len(d):
        return d[-1]  # right-most x coordinate
    return min(d[index - 1:index + 1], key=lambda v: abs(v - x))

d = [-5, -3.5, -2.8, -0.6, 1.2, 3.4, 5.6]
nearest(10, d)
nearest(-10, d)
nearest(0, d)
nearest(3, d)

rawDescription: Python X-axis nearest point

description: Python X-axis nearest point


code:
f = open('file2', 'w')
f.write('Name: ' + name + '\n')

rawDescription: Take all lines from one txt file and copy them to a new text file with some extras


code:
import re
df = df.set_index('county')
df = df.rename(columns=lambda x: re.search(r'([a-zA-Z_]+)(\d{4})', x).groups())
df.columns = MultiIndex.from_tuples(df.columns, names=['label', 'year'])
s = df.unstack()
s.name = 'count'
print(s)

rawDescription: Creating a multi-index from csv census data


code: mark = {i: perc(i, len(comb)) for i in xrange(10, 100, 10)}

rawDescription: Getting indices for certain percent of a length of a list


code: import httpagentparser

rawDescription: Get user browser info in Python Bottle

description: Get user browser info in Python Bottle


code: sorted(set(item.split(':')[0] for item in l), key=int)

rawDescription: How can I split the strings and get only the first part of it?

description: Split the strings and get only the first part of it


code:
import logging

class LoggerWriter:
    def __init__(self, logger, level):
        self.logger = logger
        self.level = level

    def write(self, message):
        if message != '\n':
            self.logger.log(self.level, message)

def main():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger("demo")
    info_fp = LoggerWriter(logger, logging.INFO)
    debug_fp = LoggerWriter(logger, logging.DEBUG)
    print >> info_fp, "An INFO message"
    print >> debug_fp, "A DEBUG message"

if __name__ == "__main__":
    main()

rawDescription: Redirect stdout to logger in Python

description: Redirect stdout to logger in Python


code: 7 - days_as_num

rawDescription: How do I subtract from an array and an user input?

description: Subtract from an array and an user input


rawDescription: Pandas DF, conditional selection in unequal columns


rawDescription: Solve equation with a set of points

description: Solve equation with a set of points


code:
B.color
instance = B()
instance.color
instance.color = 3

rawDescription: Remove class attribute in inherited class Python


code: tuple(sorted(mytuple))

rawDescription: Sorting a tuple that contains lists

description: Sorting a tuple that contains lists


code:
class MessageModel(Base):
    __tablename__ = 'messages'
    player_id = Column(Integer,ForeignKey('chats.id'), nullable=False)
    message = Column(String(2000), nullable=False)
    time = Column(TIMESTAMP, server_default=func.now())
    player = relationship(PlayerModel, backref="messages")

rawDescription: How to achieve inner join using SQLAlchemy?

description: Achieve inner join using SQLAlchemy


code:
fields = ('firstName', 'lastName', 'age', 'class', 'city', )
filter_params = dict((field, value)
                        for field, value in request.GET.iteritems()
                        if value and field in fields)
students = Student.objects.filter(**filter_params)

rawDescription: How to find not null variables from URL query string? or can we get the variable in URL query string from request in python

description: Find not null variables from URL query string? or can we get the variable in URL query string from request in python


code:
from ctypes import *;
clib = cdll.LoadLibrary('/home/soltanmm/tmp/a.out');
print(clib.r2())

rawDescription: Using ctypes to grab a pointer from a nullary function (segfault) x64


code:
import matplotlib.pyplot as plt
p1 = plt.plot(data1)
p2 = plt.plot(data2)
plt.legend([p1, p2], ["Data 1", "Data 2"])

rawDescription: How can I stretch my pyplot to make markers more discernible?

description: Stretch my pyplot to make markers more discernible


code:
h = """

Kansas City KC"""

soup = BeautifulSoup(h)

print(soup.select_one("a.team-name abbr")["title"])

rawDescription: How to get a specific tag attribute text in Python with BeautifulSoup?

description: Get a specific tag attribute text in Python with BeautifulSoup


code:
fabric.operations.sudo(command, shell=True, pty=True,
                       combine_stderr=True, user=None,
                       quiet=False, stdout=None, stderr=None)

rawDescription: Fabric: do everything as a particular user


code:
s = 'this is some string with a lot of vowels'
vowels = 'aeiou'
{i : s.count(i) for i in vowels}

rawDescription: Python, counting from an inputted string. Needs to be returned in a specific order?


O(n) + O(n) = O(n)


code:
# http://plumberjack.blogspot.de/2010/10/supporting-alternative-formatting.html
class BraceMessage(object):
    def __init__(self, fmt, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

_F = BraceMessage

rawDescription: How to use modern string formatting options with Python's logging module?

description: Use modern string formatting options with Python's logging module


code: a = str(soup.find('body'))

rawDescription: Python 3 print() to a variable

description: Python 3 print() to a variable


code:
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    is_active = models.BooleanField(default=True)

rawDescription: How can I 'close' poll in Django

description: 'close' poll in Django


code:
shared_qs = Model.objects.filter(active=True)
german_entries = shared_qs.filter(language='de')
german_and_english = shared_qs.filter(Q(language='de') | Q(language='en'))

rawDescription: Django: Extending Querysets / Connect multiple filters with OR


code:
def select(df, substring):
    """Select by substring from Dataframe"""
    frames = []
    for i in substring:
        frames.append(df[df.index.to_series().str.contains(i)])
    return pd.concat(frames)

rawDescription: select Pandas Dataframe rows with for-loop for different substrings in index

description: Select Pandas Dataframe rows with for-loop for different substrings in index


code:
total = sum(counts.values())
dict((word, float(count)/total) for word,count in counts.items())

rawDescription: Count verbs, nouns, and other parts of speech with python's NLTK


code: reencoded_with_viewurl = json.dumps(json.loads(myString, object_hook = addImageKey))

rawDescription: Editing Existing JSON in Python

description: Editing Existing JSON in Python


code:
def inner_function(x):
    soma = 0

    for linf in range(1, x + 1):
        soma += linf

    return soma

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


rawDescription: Finding the consecutive zeros in a numpy array


code: np.repeat(a, a[::-1])

rawDescription: Generating repetitive data in numpy / pandas in a fast vectorized way


code:
def relations(v, vtype='a'):
    functions = {
        'a': lambda x: x, 'b': lambda x: x-1,
        'c': lambda x: x * 2, 'd': lambda x: x**2
    }

    a = functions[vtype](v)
    b = 1 + a
    c = 0.5 * a
    d = a ** 0.5
    return a,b,c,d

rawDescription: What’s the most Pythonic way of handling different, mutually-exclusive function inputs?


code:
from sympy import *
x1, y1, x2, y2, x, y, a = symbols('x1 y1 x2 y2 x y a')
xn  = (x - x1)/(x2 - x1)
yn1 = (1 - xn)/(1 - a*xn)
yn2 = (y - y1)/(y2 - y1)
eq0 = yn1 - yn2

solve(eq0, y)

rawDescription: Solving symbolically. Choosing the symbols in the final representation


code:
if value >= list[j]:
     numOfComp += 1
     j = j - 1

rawDescription: Number of comparisons in insertion sort

description: Number of comparisons in insertion sort


code:
import shapefile
from liblas import file as lasfile

pattr = {
    "i": 'intensity',
    "r": 'return_number',
    "n": 'number_of_returns',
    "s": 'scan_direction',
    "e": 'flightline_edge',
    "c": 'classification',
    "a": 'scan_angle',
    }

wattr = {
    "i": 'Intensity',
    "r": 'Return',
    "n": 'NumberRet',
    "s": 'ScanDir',
    "e": 'FlightEdge',
    "c": 'Class',
    "a": 'ScanAngle',
    }

def LAS2SHP(inFile, outFile=None, parse = 'irnseca'):
    w = shapefile.Writer(shapefile.POINT)
    w.field('Z','C','10')
    for key in parse:
        w.field(wattr[key],'C','10')
    for p in lasfile.File(inFile,None,'r'):
        w.point(p.x,p.y)
        pdata = [p.z] + [getattr(p, pattr[key]) for key in parse]
        pdata = map(float, pdata)
        w.record(*pdata)
    if outFile == None:
        inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))
        inFile_name = os.path.splitext(inFile_name_ext)[0]
        w.save("{0}\\{1}.shp".format(inFile_path,inFile_name))
    else:
        w.save(outFile)

rawDescription: Python: improve in elegant way (code saving) a function in order to avoid several Statements


rawDescription: Splitting up a string from a file and assigning variables


rawDescription: Python: mask a numpy.ndarray with another numpy.ndarray with elegant solution


code: return [e.lower() for e in temp if e]

rawDescription: Parsing text with regular expression into list with empty string in result


code: zip([1, 2, 3], "abc", [True, False, None])

rawDescription: Zipping multiple lists together?

description: Zipping multiple lists together


rawDescription: two dimensional array for encryption in python

description: Two dimensional array for encryption in python


code:
class noIdentifier(Exception):
    pass

rawDescription: Exit a Python Program (From a Function) with a Successful Run Result


code: ' '.join([word for word in words if a in word])

rawDescription: How to join strings with a space without adding an extra space at the end?

description: Join strings with a space without adding an extra space at the end


code:
def hex_to_dex(strng_of_hex):
    return int(strng_of_hex, 16)

rawDescription: Writing a function to convert hex to decimal


code:
c = sqlite3.connect('db_path.db')
cur = c.cursor()
cur.execute("SELECT column_name from table_name LIMIT 11")
test = cur.fetchall()

rawDescription: Displaying Sqlite3 results in a HTML table with python


rawDescription: Python slicing from last to first element?


code:
for row in data:
    row[-1] = int(row[-1])

rawDescription: How can I iterate through a python 2D list and delete/replace characters from a specific column?

description: Iterate through a python 2D list and delete/replace characters from a specific column


code:
def __init__(self, center, width, height):
    "Define a block by its center, width, and height"
    self.center = center
    self.width = width
    self.height = height

@classmethod
def from_corners(self, sw, ne):
    "Define a block by two corners"
    c, w, h = _convert_corners(sw, ne)
    return Block(c, w, h)

rawDescription: Groups of optional arguments for a function - python


code: MyClass = funkyDecorator(MyClass)

rawDescription: How do I add a method with a decorator to a class in python?

description: Add a method with a decorator to a class in python


code:
from datetime import date, datetime

today = date.today()
parsed = datetime.strptime(DATE_TO_COMPARE, '%b %d').date().replace(year=today.year)
if parsed > today:
    # last year
    parsed = parsed.replace(year=today.year - 1)

rawDescription: Is it possible to compare day + month(not year) against current day + month in python?


rawDescription: Python - test whether object is a builtin function


rawDescription: Read 2 lines of a file into a dataframe with two columns using pandas read_csv()


code:
def static_var(varname, value):
    def decorate(func):
        setattr(func, varname, value)
        return func
    return decorate

rawDescription: What is the Python equivalent of static variables inside a function?


rawDescription: element-wise operations of matrix in python

description: Element-wise operations of matrix in python


rawDescription: How do I create a namespace package in Python?

description: Create a namespace package in Python


code:
import pandas as pd
import numpy as np

year = np.arange(2010, 2020)
months = np.arange(1, 13)
days = np.arange(1, 29)

y, m, d = map(np.ravel, np.broadcast_arrays(*np.ix_(year, months, days)))

start = np.array(["0000-01-01"], dtype="M8[Y]")

r1 = start + y.astype("m8[Y]") + (m - 1).astype("m8[M]") + (d-1).astype("m8[D]")

def build_DatetimeIndex(*args):
    return pd.DatetimeIndex([pd.datetime(*tup)
                             for tup in np.broadcast(*args)])

r2 = build_DatetimeIndex(y, m, d)

np.all(pd.DatetimeIndex(r1) == r2)

rawDescription: Vectorized construction of DatetimeIndex in Pandas


code:
import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
     for line in f:
         out.write(line.split()[-1]+'\n')

rawDescription: Keep last word on each line of text file, delete rest


code:
def count_words(text, words):
    answer = 0
    for i in range(len(text)):
        if any(text[i:].startswith(word) for word in words):
            answer += 1
    return answer

rawDescription: Find particular words in a string, Python


code:
color = iter(list_of_colors)
acolor = next(color)

rawDescription: Color and Line writing using MatPlotLib

description: Color and Line writing using MatPlotLib


code:
import numpy as np
from scipy.spatial import cKDTree as kdtree

n = 100
k = 50

valid = False

while not valid:
    # generate k grid indices
    coords_flat = np.random.random_integers(0, n ** 2 - 1, size=k)
    coords = np.unravel_index(coords_flat, dims=(n, n))
    # test there are no adjacent cells
    valid = len(kdtree(coords).query_pairs(1.0)) == 0

print(coords)

rawDescription: Random sampling of non-adjacent cells in a pixel grid


rawDescription: How to create lists from csv files and cast columns to ints and floats

description: Create lists from csv files and cast columns to ints and floats


code:
import urllib
vars = {"id":"2", "test":"3"}
urllib.urlencode(vars)

rawDescription: Convert dict to string

description: Convert dict to string


code:
class One:
    def get(self):
        return 1

class Two:
    def __init__(self):
        one = One()
        val = one.get()

rawDescription: Python: How to call a class in the same file


code:
mydictionary={ 'ColumnName1':[dataRow1Col1, dataRow2Col1, dataRow3Col1],
               'ColumnName2':[dataRow1Col2, dataRow2Col2, dataRow3Col2],
               'ColumnName3':[dataRow1Col3, dataRow2Col3, dataRow3Col3] }

rawDescription: reading a CSV files columns directly into variables names with python

description: Reading a CSV files columns directly into variables names with python


code: variable['licenses']['mike']

rawDescription: Python: Retrieve result from inner dictionary


code: parser.add_argument('-m','--mode', type=str, required=True, choices=['add', 'del'])

rawDescription: Using argparse with a specified acceptable option


code:
import re
subject = "AA BB CC DD EE FF GG HH"
reobj = re.compile(r"(?=(\b\S+))(?=\b(\S+ \S+))?(?=\b(\S+(?: \S+){2}))?(?=\b(\S+(?: \S+){3}))?")
result = reobj.findall(subject)
tokens = []
for a in result:
    for b in a:
        if b != "":
            tokens.append(b)
print(tokens)

rawDescription: Use python regex to match all possible groups of 1, 2, 3, and 4 words


code:
def __iter__(self):
    return self

rawDescription: Establishing the number of values yielded by a generator


code:
def unique_values(iterable):
    seen = set()
    for item in iterable:
        if item not in seen:
            seen.add(item)
            yield item

rawDescription: Iterator Object for Removing Duplicates in Python


code:
import numpy
import theano
import theano.tensor as T

input_data = numpy.matrix([[28, 1], [35, 2], [18, 1], [56, 2], [80, 3]])
output_data = numpy.matrix([1600, 2100, 1400, 2500, 3200])

TS = theano.shared(input_data.astype('float32'), "training-set")
E = theano.shared(output_data.astype('float32'), "expected")
W1 = theano.shared(numpy.zeros((1, 2), dtype = 'float32'))

O = T.dot(TS, W1.T)
cost = T.mean(T.sqr(E - O.T))
gradient = T.grad(cost=cost, wrt=W1)
update = [[W1, W1 - gradient * 0.0001]]
train = theano.function([], cost, updates=update, allow_input_downcast=True, profile = True)

for i in range(1000):
    train()

train.profile.print_summary()

rawDescription: Theano simple linear regression runs on CPU instead of GPU


code: P = [0]*max ### make a list of zeros, length max

rawDescription: Euler's pentagonal number function in python


code:
if item not in mylist:
     mylist.append(item)

rawDescription: check if a number already exist in a list in python

description: Check if a number already exist in a list in python


code:
Da=random.choice(['1', '2', '3','4'])
if(Da=='1'):
    Fa=random.choice(clubs)
elif(Da=='2'):
    Fa=random.choice(hearts)
elif(Da=='3'):
    Fa=random.choice(spades)
elif(Da=='4'):
    Fa=random.choice(diamonds)

rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code:
def insertIntoDataStruct(name,startTime,endTime,aDict):
    if not name in aDict:
        aDict[name] = [(startTime,endTime)]
    else:
        aDict[name].append((startTime,endTime))

rawDescription: How to add values to existing dictionary key Python

description: Add values to existing dictionary key Python


rawDescription: Calculate the 3rd standard deviation for an array


rawDescription: Runtime Optimization of sympy code using numpy or scipy


rawDescription: Capturing negative matches in Python regular expressions


rawDescription: sqlite vacuum with django

description: Sqlite vacuum with django


code:
import re
import urllib.request

from bs4 import BeautifulSoup

r = urllib.request.urlopen('http://i.cantonfair.org.cn/en/ExpExhibitorList.aspx?k=glassware')
soup = BeautifulSoup(r, "html.parser")

links = soup.find_all("a", href=re.compile(r"expexhibitorlist\.aspx\?categoryno=[0-9]+"))
print([link["href"] for link in links])

rawDescription: How to find url through regex in python?

description: Find url through regex in python


rawDescription: Subclassing numpy ndarray problem

description: Subclassing numpy ndarray problem


code:
from sys import argv
quiet = '-d' in argv # True if '-d' in argv else False

rawDescription: How can I do really cheap command line parsing in Python?

description: Do really cheap command line parsing in Python


code:
class Dot11(Packet):
    name = "802.11"
    fields_desc = [
                    BitField("subtype", 0, 4),
                    BitEnumField("type", 0, 2, ["Management", "Control", "Data", "Reserved"]),
                    BitField("proto", 0, 2),
                    FlagsField("FCfield", 0, 8, ["to-DS", "from-DS", "MF", "retry", "pw-mgt", "MD", "wep", "order"]),
                    ShortField("ID",0),
                    MACField("addr1", ETHER_ANY),
                    Dot11Addr2MACField("addr2", ETHER_ANY),
                    Dot11Addr3MACField("addr3", ETHER_ANY),
                    Dot11SCField("SC", 0),
                    Dot11Addr4MACField("addr4", ETHER_ANY)
                    ]

rawDescription: SCAPY PYTHON - Get 802.11 DS Status

description: SCAPY PYTHON - Get 802.11 DS Status


code:
import os

def extract(name):
    with open(name, "rt") as f:
        a = []
        for line in f:
            line = line.rstrip("\r\n")
            if line.startswith("###### ") and line.endswith(" ######"):
                a.append(line[7:-7])
        return a

def create_dict(path):
    h = {}
    for name in os.listdir(path):
        a = extract(os.path.join(path, name))
        if a:
            h[name] = a
    return h

rawDescription: Python: extract strings between defined characters and store into a disctionary with lists


code:
A = {1,2,3}
B = A.copy()
A.remove(3)
print(B)

rawDescription: Python: How to store mutable variables like sets?


rawDescription: How to map the word in data frame to integer ID with python-pandas and gensim?

description: Map the word in data frame to integer ID with python-pandas and gensim


code:
func1d = lambda y, *args: optimize.curve_fit(f, xdata=x, ydata=y, *args)[0] #<-- [0] to get only popt
param = np.apply_along_axis( func1d, axis=2, arr=data )

rawDescription: Fitting a 3D array of data to a 1D function with numpy or scipy


code: df

rawDescription: How to convert pandas timezone aware timestamps to UNIX epoche?

description: Convert pandas timezone aware timestamps to UNIX epoche


code: array([3001], dtype='float16') - array([3000], dtype='float16')

rawDescription: Why does numpy.float16 break the OpenBlas/Atlas functionalities?


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

x = np.random.randn(60)
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

rawDescription: How to do a scatter plot with empty circles in Python?

description: Do a scatter plot with empty circles in Python


rawDescription: Using File IO to create matrix

description: Using File IO to create matrix


code:
def changelist_view(self, request, extra_context=None):
    if ('filters' in request.session):
        q = request.GET.copy()
        for filter in request.session['filters'].split('&'):
            key, value = urllib.splitvalue(filter)
            # check if the request does not already use the filter
            # and that the model has the attribute to filter for
            if (not request.REQUEST.has_key(key)) and (key in self.list_filter):
                q[key] = value
        request.GET = q
        request.META['QUERY_STRING'] = request.GET.urlencode()
    return super(PartAdmin,self).changelist_view(request, extra_context=extra_context)

rawDescription: Alternative to global variables in Django?


code:
from glob import glob
import os
pre = "xyz_"
[os.rename(f, "{}{}".format(pre, f)) for f in glob("*.html")]

rawDescription: Renaming multiple files in a folder by adding Prefix using python


code:
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)     # instantiate with positional or keyword arguments
p[0] + p[1]             # indexable like the plain tuple (11, 22)
x, y = p                # unpack like a regular tuple
x, y
p.x + p.y               # fields also accessible by name
p                       # readable __repr__ with a name=value style

rawDescription: Most pythonic way of ensuring a list of objects contains only unique items


rawDescription: Grouping by everything except for one index column in pandas


code:
B_notin_A = df['B'][~df['B'].isin(df['A'])]
B_notin_A

rawDescription: Merging two columns in a DataFrame while preserving first column values


code:
if __name__ == "__main__":
    result = testForThread1() # == 'ok', this is the blocking execution
    t1 = threading.Thread(name="Hello1", target=result)
    t1.start()

rawDescription: Python parallel threads

description: Python parallel threads


code:
import contextlib, io
zen = io.StringIO()
with contextlib.redirect_stdout(zen):
   import this
print(zen.getvalue())

rawDescription: How can I return python's "import this" as a string?

description: Return python's "import this" as a string


rawDescription: pymongo (python+mongodb) drop collection/gridfs?

description: Pymongo (python+mongodb) drop collection/gridfs


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(5, 5, figsize=(12, 10))
plt.show()

rawDescription: How do I set the matplotlib window size for the MacOSX backend?

description: Set the matplotlib window size for the MacOSX backend


code:
test = "single"
mysomething = condfunc(test)

rawDescription: Passing strings to functions

description: Passing strings to functions


code:
def main():
    name = input("Enter a name: ")
    n = int(input("How many lines? "))
    infilepath = 'blah'
    get(infilepath, name, n)

rawDescription: Python Copy specified lines from text file


code: {k : min(i for i in (h1.get(k), h2.get(k)) if i) for k in h1.keys() | h2}

rawDescription: Merge dictionaries with minimum value of common keys


code: self.ILCheck = False

rawDescription: Python2 PyQt4 Connect a bool Variable to a QCheckBox item


rawDescription: Python: Return hash values from hash table regarding to a searching keyword


rawDescription: Single process code performs faster than Multiprocessing - MCVE


code:
def move_file(new_path_to_file, file_to_move):
  file_name = file_to_move.split(os.path.sep)[-1]
  os.makedirs(new_path_to_file)
  os.rename(file_to_move, os.path.join(new_path_to_file, file_name))

rawDescription: Moving files to corresponding subdirectory in Python


rawDescription: python3 variable expansion "a"*x to add empty elements in a list

description: Python3 variable expansion "a"*x to add empty elements in a list


code: find_by_label(soup, "Mobile").strip()  # prints "021 427 399"

rawDescription: Extracting text outside of a <div> tag BeautifulSoup


code:
buttons = soup.findAll('span', {'class': 'button'})
for button in buttons:
  button.nextSibling

rawDescription: Python getting next line following a certain Condition


code: open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

rawDescription: Copying from one text file to another using Python


code: re.compile('SRR.*?\d{1,3}', re.DOTALL)

rawDescription: How to remove a string with varying numbers at the end

description: Remove a string with varying numbers at the end


rawDescription: javascript comparison operators

description: Javascript comparison operators


code:
B = np.random.random((10,4))
D0 = np.array([A[i]*B[i,:] for i in range(len(A))])
D2 = np.einsum('i,i...->i...', A, B)
np.allclose(D0, D2)

rawDescription: numpy array multiplication with arrays of arbitrary dimensions

description: Numpy array multiplication with arrays of arbitrary dimensions


rawDescription: Python - Trying to count instances of a string in SSH std.out


rawDescription: Compare lists, the order of content within a given column is unimportant


code:
def printPattern(n):
    return '*' + printPattern(n-1) + '!' if n > 0 else ''

rawDescription: python beginner recursion

description: Python beginner recursion


code:
gp = df.groupby('CloneID')
for g in gp.groups:
    path = 'CloneID' + str(g) + '.txt'
    gp.get_group(g).to_csv(path)

rawDescription: output multiple files based on column value python pandas

description: Output multiple files based on column value python pandas


code:
# Aligned with opening delimiter.
d = {'key1': 'value1',
     'key2': 'value2'}

longerVariableName = {'key1': 'value1',
                      'key2': 'value2'}

# Hanging indents should add a level.
d = {
    'key1': 'value1',
    'key2': 'value2'}

longerVariableName = {
    'key1': 'value1',
    'key2': 'value2'}

rawDescription: Correct layout for dictionary literals

description: Correct layout for dictionary literals


code:
text = "One of the values, I=1mV is used"
words = text.split()
words

rawDescription: Searching a string and returning only things I specify


code: from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)

rawDescription: How can I compare a date and a datetime in Python?

description: Compare a date and a datetime in Python


code:
d = dict() # key by `tax code`
for line in csv:
    l = [i.strip() for i in line.split(';')]

    d[l[3]] = l # update

lists = d.values()

rawDescription: Iterate through list in python and get highest value for a given element


rawDescription: GroupBy - How to extract seconds from DateTime with diff()


code:
from operator import add, sub, mul, div
opmap = {'+':add, '-':sub, '*':mul, '/':div}
opmap.get('+')(int('2'), int('3'))

rawDescription: Python- How to convert stringed operator back to its special meaning?


rawDescription: Populating a sparse list with random 1's


code: winner = max(cars, key=operator.attrgetter('Odometer'))

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


code:
class FooBarInterface(object):
    def f(self, foo, bar):
        raise NotImplementedError
class A(FooBarInterface):
    def f(self, foo, bar):
        return a()
class B(FooBarInterface):
    def f(self, foo, bar):
        return bb(bar=bar)
class C(FooBarInterface):
    def f(self, foo, bar):
        return ccc(foo=foo)

if funcname == 'a':
  obj = A()
elif funcname == 'b':
  obj = B()
elif funcname == 'c':
  obj = C()
# call it, uniformly
obj.f()

rawDescription: Python: Passing conditional parameters by name


code:
from subprocess import Popen, PIPE

p1 = Popen(["grep", "-v", "not"], stdin=PIPE, stdout=PIPE)
p2 = Popen(["cut", "-c", "1-10"], stdin=p1.stdout, stdout=PIPE, close_fds=True)
p1.stdin.write('Hello World\n')
p1.stdin.close()
result = p2.stdout.read()
assert result == "Hello Worl\n"

rawDescription: blocks - send input to python subprocess pipeline

description: Blocks - send input to python subprocess pipeline