code:
p = []
while len(l) > 0:
  p.append(min(l))
  l.remove(min(l))

rawDescription: Move every element from list l to list p


code:
def asInt(v): return None if v is None else int(v)

value1 = asInt(kwargs['par1'])

rawDescription: How to rewrite this pattern with a simpler structure

description: Rewrite this pattern with a simpler structure


rawDescription: Python Pandas idiom for converting TimeSeries with lists as values into a DataFrame


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

G = nx.DiGraph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_color = values)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

rawDescription: how to draw directed graphs using networkx in python?

description: Draw directed graphs using networkx in python


code:
import pandas as pd
from pandas import DataFrame
from matplotlib import pyplot as plt
import pandas.io.data as web
import datetime as dt

end = dt.datetime.today()
df = web.DataReader('GMCR', 'yahoo', '2007-01-01', end)
sp = web.DataReader('^GSPC', 'yahoo', '2007-01-01', end)

fig, ax1 = plt.subplots()
df['Close'].plot(ax=ax1,color='g')
sp['Close'].plot(secondary_y=True, ax=ax1,color='b')

plt.show()

rawDescription: How to get two line charts (using seperate y-axis), to share the same date x-axis?

description: Get two line charts (using seperate y-axis), to share the same date x-axis


code:
#!/usr/bin/python
import wx

class ex2(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(400, 420))

        panel = wx.Panel(self, -1)
        vbox = wx.BoxSizer(wx.HORIZONTAL)
        self.sl_qZone1 = wx.Slider(panel, -1, 50, 0, 100, size=(20,200), style=wx.SL_HORIZONTAL)
        self.tc_qZone1 = wx.TextCtrl(panel, -1, value="", style=wx.TE_CENTER|wx.TE_PROCESS_ENTER)

        self.sl_qZone1.Bind(wx.EVT_SLIDER, lambda event: self.sliderUpdate(event, self.sl_qZone1,self.tc_qZone1))
        self.tc_qZone1.Bind(wx.EVT_TEXT_ENTER, lambda event: self.tcVolUpdate(event, self.sl_qZone1,self.tc_qZone1))

        vbox.Add(self.sl_qZone1, 1, wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT | wx.BOTTOM, 15)
        vbox.Add(self.tc_qZone1, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 20)
        panel.SetSizer(vbox)
        self.Centre()

    def sliderUpdate(self, event, slider, textctrl):
        textctrl.SetValue(str(slider.GetValue()))

    def tcVolUpdate(self, event, slider, textctrl):
        slider.SetValue(int(textctrl.GetValue()))

class MyApp(wx.App):
    def OnInit(self):
        frame = ex2(None, -1, 'Example 2')
        frame.ShowModal()
        frame.Destroy()
        return True

rawDescription: wxSlider updating wxTextCtrl and Visa Versa

description: WxSlider updating wxTextCtrl and Visa Versa


code:
from subprocess import Popen, PIPE
import time

def keypress(sequence):
    p = Popen(['xte'], stdin=PIPE)
    p.communicate(input=sequence)

time.sleep(2)
keypress("key Right ")
time.sleep(2)
keypress("key Right ")
time.sleep(2)
keypress("key Right ")
time.sleep(2)
keypress("key Right ")

rawDescription: application to fake keybord strike (for slides' scroll) with python?

description: Application to fake keybord strike (for slides' scroll) with python


code:
def subtotals_as_table(self):
    format_args = self.data.copy()
    format_args['taxes'] = self.format_taxes()
    return '
...
 ${taxes}
...
'.format(**format_args)

rawDescription: Call function from HTML table data tags

description: Call function from HTML table data tags


rawDescription: Webdriver. How to retrieve the xpath of found element?


code:
with open(file_path, 'r') as fh:
  for line in fh:
    process(line)

rawDescription: What is the optimal way to process a very large (over 30GB) text file and also show progress


code:
import random

num = 3
print(num)

message=""
end = False #set a valid condition to end the program
for n in range(num):
#   while message =="":
    while end == False:
        newnum= random.randint(48,122)
        if newnum > 47 and newnum < 58:
            val=chr(newnum)
            val = newnum
            message +=chr(val)
        elif newnum > 64 and newnum <91:
            val=chr(newnum)
            val = newnum
            message +=chr(val)
        elif newnum > 97 and newnum < 123:
            val=chr(newnum)
            val = newnum
            message +=chr(val)

        else:
            newnum -= random.randint(7,10)
            val=chr(newnum)
            val = newnum
            message +=chr(val)
        if (any(x.isupper() for x in message)
             and any(x.islower() for x in message)
             and any(x.isdigit() for x in message)):

            print(message)
            end=True
#       else:
#           message =""

rawDescription: While Loop not working in Python

description: While Loop not working in Python


code:
def fetch(url):
    return (url, urllib2.urlopen(url).read())

rawDescription: Order of files downloaded by a multithreaded program is not constant


code:
from decimal import Decimal
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)()
Base = declarative_base(bind=engine)

class Product(Base):
    __tablename__ = 'product'

    id = Column(Integer, primary_key=True)
    type = Column(String, nullable=False)
    name = Column(String, nullable=False, default='')
    price = Column(Numeric(7, 2), nullable=False, default=Decimal(0.0))

    __mapper_args__ = {
        'polymorphic_on': type,  # subclasses will each have a unique type
    }

class Motorcycle(Product):
    __tablename__ = 'motorcycle'

    # id is still primary key, but also foreign key to base class
    id = Column(Integer, ForeignKey(Product.id), primary_key=True)
    manufacturer = Column(String, nullable=False, default='')
    model = Column(String, nullable=False, default='')
    max_speed = Column(Integer, nullable=False, default=0)

    __mapper_args__ = {
        'polymorphic_identity': 'motorcycle',  # unique type for subclass
    }

class Book(Product):
    __tablename__ = 'book'

    id = Column(Integer, ForeignKey(Product.id), primary_key=True)
    author = Column(String, nullable=False, default='')
    pages = Column(Integer, nullable=False, default=0)

    __mapper_args__ = {
        'polymorphic_identity': 'book',
    }

Base.metadata.create_all()

# insert some products
session.add(Book())
session.add(Motorcycle())
session.commit()

print(session.query(Product).count())  # 2 products
print(session.query(Book).count())  # 1 book

rawDescription: sqlalchemy: non-trivial one-to-one relationship with multiple tables

description: Sqlalchemy: non-trivial one-to-one relationship with multiple tables


code: d = {x: 1 for x in d}

rawDescription: Python: Replace All Values in a Dictionary


code:
from __future__ import unicode_literals
import youtube_dl

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['http://www.youtube.com/watch?v=BaW_jenozKc'])

rawDescription: download only audio from youtube video using youtube-dl in python script

description: Download only audio from youtube video using youtube-dl in python script


code:
users = [1,2,3]

for user in users:
   row = MyModel.objects.filter(user__id = user).order_by("order")[0]

rawDescription: Filter data using max value

description: Filter data using max value


code:
from itertools import product
from string import ascii_lowercase
[''.join(p) for p in product(ascii_lowercase, repeat=3)]

rawDescription: Generate continuous character strings in a range


code:
import Tkinter as tk
import random

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        self._running = False
        self._relx = None

        tk.Tk.__init__(self, *args, **kwargs)

        self.pack_propagate(False)
        self.configure(width=400, height=400)
        self.label = tk.Label(self, text="hello, world", background="red")
        self.button = tk.Button(self, text="Start", command=self.toggle)
        self.button.pack(side="top")

    def toggle(self):
        '''toggle animation on or off'''
        self._running = not self._running
        if self._running:
            self.button.configure(text="Stop")
            self.moveit()
        else:
            self.button.configure(text="Start")

    def moveit(self):
        '''Animate the label'''
        if not self._running:
            # animation has been stopped
            # hide the label from view.
            self.label.place_forget()

        if self._running:
            if not self.label.winfo_viewable():
                # not visible; establish future locations
                self._relx = [.5, .4, .3, .2, .1, 0]
            relx = self._relx.pop(0)
            self._relx.append(relx)
            self.label.place(relx=relx, rely=0.7)
            self.after(1000, self.moveit)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: Get rid of a label inside a thread?

description: Get rid of a label inside a thread


code:
from ctypes import *
from ctypes.util import find_library

#linkmap structure, we only need the second entry
class LINKMAP(Structure):
    _fields_ = [
        ("l_addr", c_void_p),
        ("l_name", c_char_p)
    ]

libc = CDLL(find_library('c'))
libdl = CDLL(find_library('dl'))

dlinfo = libdl.dlinfo
dlinfo.argtypes  = c_void_p, c_int, c_void_p
dlinfo.restype = c_int

#gets typecasted later, I dont know how to create a ctypes struct pointer instance
lmptr = c_void_p()

#2 equals RTLD_DI_LINKMAP, pass pointer by reference
dlinfo(libc._handle, 2, byref(lmptr))

#typecast to a linkmap pointer and retrieve the name.
abspath = cast(lmptr, POINTER(LINKMAP)).contents.l_name

print(abspath)

rawDescription: Get absolute path of shared library in Python


code:
from random import randint

def randGen(n, x, ignore=[]):
    index = 0
    while index < x:
        temp = randint(0, n-1)
        if temp not in ignore:
            index += 1
            # yield the temp value and wait for
            # the next call
            yield temp

# you could now create your list
# myList = [i  for i in randGen(5, 2, [2,3])]
# or as Mark pointed out
myList = list(randGen(5,2,[2,3]))
print(myList)

# or use the generator items when you need them
for i in randGen(5, 2, [2,3]):
    # do something with i
    print(i)

rawDescription: Python: create list of random integers where state space is limted


code:
class DistributorGroup(Distributor):
    distributor_links = GenericRelation(DistributorLink, related_query_name="distributor_groups")

class DistributorPerson(Distributor):
    distributor_links = GenericRelation(DistributorLink, related_query_name="distributor_persons")

class Link(models.Model):
    pass

class DistributorLink(models.Model):
    link = models.ForeignKey(Link);

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

rawDescription: through model for an Abstract model

description: Through model for an Abstract model


code:
import numpy
from scipy import ndimage

array = numpy.zeros((100, 100), dtype=np.uint8)
x = np.random.randint(0, 100, 2000)
y = np.random.randint(0, 100, 2000)
array[x, y] = 1

pl.imshow(array, cmap="gray", interpolation="nearest")

s = ndimage.generate_binary_structure(2,2) # iterate structure
labeled_array, numpatches = ndimage.label(array,s) # labeling

sizes = ndimage.sum(array,labeled_array,range(1,numpatches+1))
# To get the indices of all the min/max patches. Is this the correct label id?
map = numpy.where(sizes==sizes.max())[0] + 1
mip = numpy.where(sizes==sizes.min())[0] + 1

# inside the largest, respecitively the smallest labeled patches with values
max_index = np.zeros(numpatches + 1, np.uint8)
max_index[map] = 1
max_feature = max_index[labeled_array]

min_index = np.zeros(numpatches + 1, np.uint8)
min_index[mip] = 1
min_feature = min_index[labeled_array]

rawDescription: Isolate greatest/smallest labeled patches from numpy array


code:
def wrapper(*args):
    process = Popen(list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return stdout, stderr

rawDescription: How to capture information from executable jar in Python?

description: Capture information from executable jar in Python


code: data = {i.split()[0]: i.split()[1:] for i in open('PID.txt').read().split('\n\n')}

rawDescription: How to get text between 2 lines with PYthon

description: Get text between 2 lines with PYthon


code:
#!/usr/bin/env python
from __future__ import print_function

import concurrent.futures
import time
import sys

quit = False
def wait_a_bit(name):
    while not quit:
        print("{n} is doing work...".format(n=name))
        time.sleep(1)

def setup():
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
    future1 = executor.submit(wait_a_bit, "Jack")
    future2 = executor.submit(wait_a_bit, "Jill")

    # main thread must be doing "work" to be able to catch a Ctrl+C
    # http://www.luke.maurits.id.au/blog/post/threads-and-signals-in-python.html
    while (not (future1.done() and future2.done())):
        time.sleep(1)

if __name__ == "__main__":
    try:
        setup()
    except KeyboardInterrupt:
        quit = True

rawDescription: How do you kill Futures once they have started?

description: Kill Futures once they have started


code:
import urllib
tlds = urllib.urlopen("http://data.iana.org/TLD/tlds-alpha-by-domain.txt").readlines()

rawDescription: Converting a cURL command to Python's urllib2


code:
count = 0
for key, value in lmdb_env.cursor():
        count = count + 1

rawDescription: Count number of records in lmdb databse with python


code: c.execute('INSERT INTO  table_name(first_column_name, second_column_name) VALUES(?, ?)',var)

rawDescription: write python list of tuples to sqlite

description: Write python list of tuples to sqlite


code:
import hashlib
value1 = "value1"
value2 = "value2"
value3 = "value3"
hashlib.md5(value1 + value2 + value3).hexdigest()

rawDescription: MD5 with more than one parameter

description: MD5 with more than one parameter


code:
import re
a = '/afolder_l/location/folder_l/file.jpg'
p= re.compile("/.+/location/.+_([lr])/")
m = p.match(a)
m.span()
m.span(1)

rawDescription: Python regex get group position

description: Python regex get group position


code:
with plt.rc_context({"axes.grid": True, "grid.linewidth": 0.75}):
    f, ax = plt.subplots()  # Will make a figure with a grid
    ax.plot(x, y)

f, ax = plt.subplots()  # Will make a figure without a grid
ax.plot(x, y)

rawDescription: how to set local rcParams or rcParams for one figure in matplotlib

description: Set local rcParams or rcParams for one figure in matplotlib


rawDescription: How do I boolean mask an array using chained comparisons?

description: Boolean mask an array using chained comparisons


code:
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api', methods = ['GET'])
def this_func():
    """This is a function. It does nothing."""
    return jsonify({ 'result': '' })

@app.route('/api/help', methods = ['GET'])
def help():
    """Print available functions."""
    func_list = {}
    for rule in app.url_map.iter_rules():
        if rule.endpoint != 'static':
            func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
    return jsonify(func_list)

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: List all available routes in Flask, along with corresponding functions' docstrings


code:
from datetime import datetime as dt
dr = p.DateRange(dt(2009,1,1),dt(2010,12,31), offset=p.datetools.Hour())
hr = dr.map(lambda x: x.hour)
dt = p.DataFrame(rand(len(dr),2), dr)
dt
dt[(hr >= 10) & (hr <=16)]

rawDescription: pandas, python - how to select specific times in timeseries

description: Pandas, python - how to select specific times in timeseries


code:
# GOOD
import pkg_resources

try:
    pkg_resources.get_distribution('numpy')
except pkg_resources.DistributionNotFound:
    HAS_NUMPY = False
else:
    HAS_NUMPY = True
    # You can also import numpy here unless you want to import it inside the function

rawDescription: PEP 8 and deferred import

description: PEP 8 and deferred import


code:
class MyModelForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = ('title', )

    def clean_title(self):
        title = self.cleaned_data['title']
        try:
            name = client.search(title).name
        except HTTPError:
            raise ValidationError("Can't validate the name. Try again later")
        if title != name:
            raise ValidationError("This name is not supported")
        return title

rawDescription: django form validation - compare inserted data

description: Django form validation - compare inserted data


code:
class Add(tk.Frame):
    def __init__(self, parent, controller):
        ...
        # initialize after_id to none
        self.after_id = None
        ...

def time_start(self):
    # kill the old timer
    if self.after_id is not None:
        self.after_cancel(self.after_id)
    ...
...
def countdown(self, remaining = None):
    ...
    if self.remaining <= 0:
        ...
        self.after_id = None
    else:
        ...
        self.after_id = self.after(1000, self.countdown)

rawDescription: How to reset countdown timer in python with button(tkinter)

description: Reset countdown timer in python with button(tkinter)


code:
from Tkinter import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.parent = master
        self.initUI()

    def initUI(self):
        self.outputBox = Text(self.parent, bg='yellow', height= 10, fg='green', relief=SUNKEN, yscrollcommand='TRUE')
        self.outputBox.pack(fill='both', expand=True)
        self.button1 = Button(self.parent, text='button1', width=20, bg ='blue', fg='green', activebackground='black', activeforeground='green')
        self.button1.pack(side=RIGHT, padx=5, pady=5)
        self.button2 = Button(self.parent, text='button2', width=25, bg='white', fg='green', activebackground='black', activeforeground='green')
        self.button2.pack(side=LEFT, padx=5, pady=5)

def main():
    root = Tk()
    app = Application(root)
    app.parent.geometry('300x200+100+100')
    app.parent.configure(background = 'red')
    app.mainloop()

main()

rawDescription: Python/Tkinter root window background configuration


code:
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:  #to check whether user is available or not?
    # the password verified for the user
    if user.is_active:
        print("User is valid, active and authenticated")
    else:
        print("The password is valid, but the account has been disabled!")
else:
    # the authentication system was unable to verify the username and password
    print("The username and password were incorrect.")

rawDescription: Django: How do I use is_active of auth_user table?


code:
class SampleModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(SampleModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(objectAdmin = request.user)

rawDescription: Object level permissions django

description: Object level permissions django


code:
import glob

dir_to_search = '/some/path/to/images/'

files_in_dir = glob.glob("{}{}".format(dir_to_search,'*.jpg'))

list_of_files = ['1.jpg','2.jpg','3.jpg']

missing_files = [x for x in list_of_files if x not in files_in_dir]

rawDescription: How to compare a list and directory to check for missing files?

description: Compare a list and directory to check for missing files


rawDescription: Python negative zero slicing

description: Python negative zero slicing


code:
import SCons.Environment
SCons.Environment.Environment._copy_from_cache = link_or_copy_file
SCons.Environment.Environment._copy2_from_cache = link_or_copy_file

rawDescription: Overriding SCons Cache Copy Function

description: Overriding SCons Cache Copy Function


rawDescription: How to split the file content by space and end-of-line character?

description: Split the file content by space and end-of-line character


code: foo_bar = __import__("foo bar")

rawDescription: How do you import a file in python with spaces in the name?

description: Import a file in python with spaces in the name


rawDescription: Extract value from single row of pandas DataFrame


code:
import sys
from PySide import QtCore
from PySide import QtGui
from PySide import QtWebKit

class MainWindow (QtGui.QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setGeometry(300,300,800,600)
        self.setWindowTitle('QtPlayer')
        web = QtWebKit.QWebView(self)
        web.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled, True)
        web.load(QtCore.QUrl("http://youtu.be/Dys1_TuUmI4"))
        web.show()
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    win = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: python cross platform apps

description: Python cross platform apps


code:
import matplotlib.pyplot as plt
import pandas as pd
pd.Series(randn(1000)).hist(by=randint(0, 4, 1000), figsize=(6, 4),
                            sharex=True, sharey=True)

ax = plt.gca()
ax.set_xlim(-10, 10)
ax.set_ylim(0, 100)

rawDescription: Force all subplots to use the same axis range when plotting with Pandas


code:
with open('file','r') as file:
    groups = [] # Will contain the final data
    current_group = [] # Temporary

    line = file.readline()
    while line != "":
        if line == "XXXX":
            # Store the current group and start a new one
            groups.append(current_group)
            current_group = []
        else:
            # Add the number to the current group
            current_group.append(int(line.split()[2]))
        line = file.readline()

rawDescription: Moving Average plot

description: Moving Average plot


code:
import sqlite3
import pandas as pd

#access the database created
db = sqlite3.connect('database')

df = pd.read_sql("select ID, Name, count(*) from table1 as t1 join table2 as t2 on t1.ID=t2.ID group by ID", db)

df.to_sql('table1', db, if_exists='replace', index=False)

rawDescription: How to insert one column in an existing DataFrame into a new column in a table in existing database

description: Insert one column in an existing DataFrame into a new column in a table in existing database


code:
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')
driver.execute('executePhantomScript', {'script': '''phantom.setProxy("10.0.0.1", 12345);''', 'args' : [] })

rawDescription: PhantomJS Proxy when using Remote Webdriver?


code:
import datetime
a = datetime.datetime.now()
b = datetime.datetime.now()
c = b - a
divmod(c.days * 86400 + c.seconds, 60)

rawDescription: How do I find the time difference between two datetime objects in python?

description: Find the time difference between two datetime objects in python


code:
from django.db import models

class MyModel(models.Model):
    STATUSES = (
        ('i', 'Initiated'),
        ('a', 'Accepted'),
        ('d', 'Delivered'),
        ('c', 'Cancelled'),
    )
    status = models.CharField(choices=STATUSES, default='i')

rawDescription: Subclassing the Models.Charfield for my Own Custom model Field


code:
def forgottenPwdEmail(request):
    if request.method == 'POST':
        form = PasswordResetRequestForm(request.POST)
        user = User.objects.get(username=request.user.username)
        user.confirmed = True
        user.save()
        return sendResetPasswordMail(user, request.META['HTTP_HOST'])
    else:
        form = PasswordResetRequestForm()
        return render(request, 'front/reset_password_form.html', {'form': form})

rawDescription: Django - didn't return an HTTPResponse Object


rawDescription: How to draw non-transparent text on an icon (not bitmap) using wxpython?

description: Draw non-transparent text on an icon (not bitmap) using wxpython


code: bytes = struct.pack( 'h', some_data )

rawDescription: How can i convert Integer to Signed Word in Python (for use with PySerial)?

description: Convert Integer to Signed Word in Python (for use with PySerial)


code: cites = cities.filter(distance_lt=101)

rawDescription: Filtering a django queryset based on computed values


code:
class FooAdminForm(forms.ModelForm):
    name = forms.CharField(max_length=100,
                widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    def __init__(self, *args, **kwargs):
        super(FooAdminForm, self).__init__(*args, **kwargs)
        self.fields['name'].required = False
        if kwargs.has_key('instance'):
            instance = kwargs['instance']
            # do something with the instance here if you want

    class Meta:
        model = Foo

class FooAdmin(admin.ModelAdmin):
    form = FooAdminForm

    fieldsets = (
        (None, {
            'fields': ('id', 'name',),})
    )
    readonly_fields = ('id',)

rawDescription: Add custom html between two model fields in Django admin's change_form


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

rawDescription: What adjustment can I make to my code so that it prints the second matrix without replacing the first? Python


code:
def checkNeighbours(x,y,matrix):
    neighbourValues = [matrix[x_][y_] for x_ in range(x-1,x+2) for y_ in range(y-1,y+2)
                       if (0 <= x_ < len(matrix) and 0 <= y_ < len(matrix) and (x_ != x or y_ != y))]
    return neighbourValues.count('O')

rawDescription: Efficiently read values around another value in a 2D Array?


code:
import sys
from gi.repository import Gtk, Gdk

def callBack(*args):
    print("Clipboard changed. New value = " + clip.wait_for_text())

clip = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clip.connect('owner-change',callBack)
Gtk.main()

rawDescription: How to catch the clipboard event (onChangeClipboard equivalent) from any application in Python

description: Catch the clipboard event (onChangeClipboard equivalent) from any application in Python


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

df = pd.read_csv('/home/Jian/Downloads/real_data.csv')

# processing
# ==========================
fig, ax = plt.subplots()
ax.set_ylim([0, 1.2])
count = 0

def func(group):
    group.sort('value', inplace=True)
    x = np.linspace(0, 1, len(group))
    global ax, count
    if count > 0:
        ax.plot(x, group.value, label=group.groups.values[0])
    count += 1
    return group

df.groupby('groups').apply(func)
ax.legend(loc='best')

rawDescription: Plotting Pandas: Grouped line chart

description: Plotting Pandas: Grouped line chart


code:
y = 'anything'

bool(y == 'n' or 'no')

rawDescription: How come my program does not quit?

description: How come my program does not quit


code:
import Tkinter as tk

class Display:
    def __init__(self, master):
        self.label = None
        self.master = master
        self.tick()

    def tick(self):
        if self.label:
            self.label.destroy()
        self.label = tk.Label(self.master, text = 'a')
        self.label.place(x=0,y=0)
        self.master.after(50, self.tick)

root = tk.Tk()
disp = Display(root)

rawDescription: Leak in updating label

description: Leak in updating label


code:
class MyObj(object):
    def __init__(self):
        self.thread = threading.Thread(target=self.run)
    def run(self):
        ...

rawDescription: Restarting thread in python. Why needs the instance to be recreated?


code:
def StringToHexString(s):
    return ''.join( map(lambda param:hexLoookup[param], map(ord,s) ) )

rawDescription: Efficient string to hex function

description: Efficient string to hex function


code:
f = open('coordfile', 'r')
newcontents=""
linecounter=-1
for line in f:
    if linecounter>=0:
       linecounter+=1
    if "Oil Pool" in line:
       linecounter+=1
    if linecounter>6:
       linecounter=-1
    if linecounter==-1:
       newcontents+=line
f.close()

f=open('coordfile', 'w')
f.write(newcontents)
f.close()

rawDescription: How to search and remove lines in Python

description: Search and remove lines in Python


code:
from collections import OrderedDict
a = {'foo': 1, 'bar': 2}
a
b = OrderedDict(sorted(a.items()))
b
b['foo']
b['bar']

rawDescription: sorting dictionary python 3

description: Sorting dictionary python 3


code:
import numpy as np
from scipy import ndimage
b = np.array([True,True,True,False,False,True,True,False,False,False,True,False,True])
ndimage.binary_erosion(ndimage.binary_dilation(b), border_value=1)

rawDescription: numpy: to exclude single and double saltuses in an array

description: Numpy: to exclude single and double saltuses in an array


code:
from ggplot import *
qplot(meat.beef)

rawDescription: Is there a way to plot a pandas series in ggplot?


rawDescription: django Queryset with year(date) = '2010'

description: Django Queryset with year(date) = '2010'


code:
class App:

    def __init__(self, master):
            frame = Frame(master)
            frame.pack()
            Label(frame, text='Turn LED ON').grid(row=0, column=0)
            Label(frame, text='Turn LED OFF').grid(row=1, column=0)

            self.button = Button(frame, text='LED 0 ON', command=self.convert0)
            self.button.grid(row=2, column=0)

            self.LED = Label(frame, image=logo)
            self.LED.grid(row=2, column=1)

    def convert0(self, tog=[0]):

        tog[0] = not tog[0]
        if tog[0]:
            print('LED 0 OFF')
            self.button.config(text='LED 0 OFF')
            self.LED.config(image = logo2)
        else:
            print('LED 0 ON')
            self.button.config(text='LED 0 ON')
            self.LED.config(image = logo)

rawDescription: Python GUI toggle button trying to toggle a label image


code:
from rpy2.robjects.packages import importr
base = importr('base')
base.eval(expr)

rawDescription: Evaluating code after parsing it

description: Evaluating code after parsing it


code:
import jupyter_core
import os,glob,json

jrd = jupyter_core.paths.jupyter_runtime_dir()
with open(glob.glob(jrd+'/nbserver-*.json')[0]) as json_file:
    root_dir = json.load(json_file)['notebook_dir']

rawDescription: Accessing Root in Jupyter Notebook

description: Accessing Root in Jupyter Notebook


rawDescription: How to match 2 out of 3 groups with a non-password-related regular expression in Python?

description: Match 2 out of 3 groups with a non-password-related regular expression in Python


rawDescription: How to collapse a list into a string in python?

description: Collapse a list into a string in python


code:
class DocTest(unittest.TestCase):
    source_dir = u'docs/source'
    config_dir = u'docs/source'
    output_dir = u'docs/build'
    doctree_dir = u'docs/build/doctrees'
    all_files = 1

    def test_html_documentation(self):
        app = Sphinx(self.source_dir,
                     self.config_dir,
                     self.output_dir,
                     self.doctree_dir,
                     buildername='html',
                     warningiserror=True,
        )
        app.build(force_all=self.all_files)
        # TODO: additional checks here if needed

    def test_text_documentation(self):
        # The same, but with different buildername
        app = Sphinx(self.source_dir,
                     self.config_dir,
                     self.output_dir,
                     self.doctree_dir,
                     buildername='text',
                     warningiserror=True,
        )
        app.build(force_all=self.all_files)
        # TODO:  additional checks if needed

    def tearDown(self):
        # TODO: clean up the output directory
        pass

rawDescription: How to test the validity of your Sphinx documentation?

description: Test the validity of your Sphinx documentation


code:
def clean_dash_array(self):
    data = self.cleaned_data['dash_array']
    try:
        data_cleaned = [tuple(float(i) for i in el.strip('()').split(',')) for el in data.split('),(')]
    except:
        raise forms.ValidationError("You must enter tuple(s) of int or float delimited with commas - Ex: (1,1),(2,2)")
    return data

rawDescription: Django - Field validation to ensure the data is a list of tuples of float


rawDescription: Add optional part in python regular expression


code:
import csv
import sys

masterlst = open('masterlist.csv')
comparelst = open(sys.argv[1])

masterrdr = csv.DictReader(masterlst, dialect='excel')
comparerdr = csv.DictReader(comparelst, dialect='excel')

headers = comparerdr.fieldnames

with open('callcounts.csv', 'w') as outfile:
    wrtr = csv.DictWriter(outfile, fieldnames=headers, dialect='excel', quoting=csv.QUOTE_MINIMAL, delimiter=',', escapechar='\n')
    wrtr.writerow(dict((fn,fn) for fn in headers))
    for line in masterrdr:
        found = False
        with open(sys.argv[1]) as loopfile:
            looprdr = csv.DictReader(loopfile, dialect='excel')
            for row in looprdr:
                if row['Names'] == line['Names']:
                    line['Calls'] = row['Calls']
                    wrtr.writerow(line)
                    found = True
                    break

        if found == False:
            line['Calls'] = '0'
            wrtr.writerow(line)

masterlst.close()
comparelst.close()

rawDescription: How do I iterate through 2 CSV files and get data from one and add to the other?

description: Iterate through 2 CSV files and get data from one and add to the other


code:
image_set_label = Label(self, text="Image Set Type: ") # made self parent
image_set_label.grid(row=1, column=0, pady=10)
self._image_set_type = Entry(self) # made self parent
self._image_set_type.insert(0, "Ramp")
self._image_set_type.grid(row=1, column=1, pady=10, columnspan=2)

rawDescription: Why do Python Tkinter Radio Buttons align left?


code:
galleries = Galleries.objects.get(id=1)
values = galleries.gallery_type.values_set.filter(language='language')

rawDescription: Django: follow relations backwards

description: Django: follow relations backwards


code: [datetime.datetime.strptime(d, '%Y-%m-%d').strftime("%B %Y") for d in my_list]

rawDescription: Convert date to month and day python?

description: Convert date to month and day python


code:
# combined the filters, no need to separate into two steps
v = Action.objects.filter(game=1, step=2, type=3)
v = v.annotate(count=Count('to_player'))
v = v.latest('count') # will return Action with the highest count

rawDescription: Count and Max after values() method on Django query


code:
p = re.compile("\([^()]*\)")
count = 1
while count:
    s, count = p.subn("", s)

rawDescription: python string manipulation

description: Python string manipulation


code:
# Instruction
# I changed the instructions to make them more precise and get rid of the unneccesarily awkward operators
print("Instructions: Please enter a simple equation of the form 'integer [operator] integer', where [operator] is '+', '-', '*' or '/'.")
print("Instructions: Make sure to put spaces between each element.")

# Read user's equation as a string
equation = input("\nPlease, enter your equation by following the syntax expressed above: ")

# Echo to the screen what the user has entered
print('The equation you entered is "%s".' % equation)

# Parse the equation into a list
theParts = equation.split() # default is whitespace

# print("Here is a list containing the operands and operator of the equation: ", theParts) # For debugging purposes

if len(theParts) == 0 :
    print("\nHave you simply pressed the Enter key? Please, enter an equation next time! :)")
# Since the two conditions warranted the same response, I just condensed them.
elif len(theParts) == 1 or len(theParts) == 2:
    print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")

elif len(theParts) == 3 :
    #print("\nThe equation entered by the user is %s %s %s." % (theParts[0], theParts[1], theParts[2]))
    # I set the answer before the conditions to a float, so division can result in more meaningful answers
    theAnswer = 0.0
    # I cast the input strings to integers
    p1 = int(theParts[0])
    p2 = int(theParts[2])
    if theParts[1] is str("+"):
        theAnswer = p1 + p2
    elif theParts[1] is str("-"):
        theAnswer = p1 - p2
    elif theParts[1] is str("*"):
        theAnswer = p1 * p2
    elif theParts [1] is str("/"):
        theAnswer = p1 / p2
    print('The anwser of the input equation is "{}".'.format(theAnswer))

print("\nBye!")

rawDescription: Parts of my code won't show in shell. (if/elif statement)


code:
neg = -100*numpy.random.rand(20e6)
pos = -neg
combined = numpy.zeros(len(neg)+len(pos))
combined[::2] = neg
combined[1::2] = pos

rawDescription: Long (>20million element) array summation in python numpy


code: checkins.objects.filter( location_id__in = list(flagged_checkins.objects.values_list('location_id', flat=True)) ).delete()

rawDescription: Remove rows with same ID from two lists in Django


rawDescription: How to escape number in regex

description: Escape number in regex


code:
reader = open('input.txt')
writer = open('output.txt', 'w')
names, nums = [], []
row = reader.read().split(' ')
x = len(row)/2
for (a, b) in [(n, v) for n, v in zip(row[:x], row[x:]) if v!='na']:
    names.append(a)
    nums.append(b)
writer.write(' '.join(names))
writer.write(' ')
writer.write(' '.join(nums))
#writer.write(' '.join(names+nums)) is nicer but cause list to be concat

rawDescription: Removing values from a list in python

description: Removing values from a list in python


code:
def runTest():
    # pack your arguments in a tuple
    mainArgs = (testName.get(), name.get(), float(duration.get()))
    # create a thread object armed with your function and the args to call it with
    thread = Thread(target=controller.main, args=mainArgs)
    # launch it
    thread.start()
    #and remember, never set state (directly or indirectly) from separate threads without taking appropriate precautions!

rawDescription: How do I make a timer run in a Tkinter widget while a process, started by the widget, is running?

description: Make a timer run in a Tkinter widget while a process, started by the widget, is running


code:
for k, v in inventory.items():
    item_total = item_total + v
    print(v + ' ' + k)

rawDescription: Automate the Boring Stuff, Chapter 5 Practice Project


code:
class Conditional_Singleton(object):
    saved_insances = {}
    def __new__(cls, condition = None):
        if not condition in cls.saved_instances:
            cls.saved_instances[condition] = super(
                Conditional_Singleton, cls).__new__(cls)
        return cls.saved_instances[condition]
    def __init__(self, condition = None):
        if not getattr(self, 'initialization'):
            self.initialization = some_func_of(condition)

rawDescription: How to create a singleton class based on its input?

description: Create a singleton class based on its input


code:
import os

for root, dirs, files in os.walk('/path/to/dir', topdown=False):
    for name in files:
        f = os.path.join(root, name)
        if os.path.getsize(f) == filesize:
            os.remove(f)

rawDescription: Iterating through directories and checking the file's size


code: odd_numbers = ifilterfalse(is_even, range(10))

rawDescription: Idiomatically negate a filter

description: Idiomatically negate a filter


code: groupby(..., lambda x: my_normal_function(x, other, arguments))

rawDescription: How can I pass an argument to a keyfunc being passed to itertools.groupby?

description: Pass an argument to a keyfunc being passed to itertools.groupby


code:
words = query.split()
not_found = True

for each in words:
    if each in rsp_dict:
        print(rsp_dict[each])
        not_found = False

if not_found:
    print("The phrase was not found!")

rawDescription: How to test if none of the iterables are true in Python 3

description: Test if none of the iterables are true in Python 3


code:
def __init__(self, *args, **kwargs):
    super(self.__class__, self).__init__(*args, **kwargs)
    CHOICES = []
    for notice in NoticeType.objects.all():
        CHOICES.append( (notice.label, notice.display) )
    self.fields['notifications'].choices = CHOICES

rawDescription: Django: form values not updating when model updates


code:
from scipy.weave import converters

def inlineTimeStep(self, dt=0.0):
    """Takes a time step using inlined C code -- this version uses
    blitz arrays."""
    g = self.grid
    nx, ny = g.u.shape
    dx2, dy2 = g.dx**2, g.dy**2
    dnr_inv = 0.5/(dx2 + dy2)
    u = g.u

    code = """
           #line 120 "laplace.py" (This is only useful for debugging)
           double tmp, err, diff;
           err = 0.0;
           for (int i=1; i<nx-1; ++i) {
               for (int j=1; j<ny-1; ++j) {
                   tmp = u(i,j);
                   u(i,j) = ((u(i-1,j) + u(i+1,j))*dy2 +
                             (u(i,j-1) + u(i,j+1))*dx2)*dnr_inv;
                   diff = u(i,j) - tmp;
                   err += diff*diff;
               }
           }
           return_val = sqrt(err);
           """
    # compiler keyword only needed on windows with MSVC installed
    err = weave.inline(code,
                       ['u', 'dx2', 'dy2', 'dnr_inv', 'nx', 'ny'],
                       type_converters=converters.blitz,
                       compiler = 'gcc')
    return err

rawDescription: MEX equivalent for Python ( C wrapper functions)


code:
app = wx.App(0)
imagePath = "my_splash_image.png"
bitmap = wx.Bitmap(imagePath, wx.BITMAP_TYPE_PNG)
shadow = wx.WHITE
splash = AS.AdvancedSplash(None, bitmap=bitmap, timeout=5000,
                           agwStyle=AS.AS_TIMEOUT |
                           AS.AS_CENTER_ON_PARENT |
                           AS.AS_SHADOW_BITMAP,
                           shadowcolour=shadow)
frame = wx.Frame(None, -1, "AdvancedSplash Test")
frame.Center()
frame.Show()
app.MainLoop()

rawDescription: Advanced splash sreen how can i use it in my code


code:
from mako.template import Template

mytemplate = Template(filename='email.html')
sendemail("text@example.com", "me@example.com", mytemplate.render())

rawDescription: How to use Pylons / Mako templates to make an HTML email from a stand alone python script?

description: Use Pylons / Mako templates to make an HTML email from a stand alone python script


code:
try:
    articles = Article.objects.all().order_by('-created')[1:]
except IndexError:
    articles = Article.objects.none()

rawDescription: Querying all objects in order of creation except for the latest one


code:
globals()['x'] = 42
x

rawDescription: Python: Is it possible to create a global variable with the name given as string?


code:
from flask.ext.login import user_logged_in

@user_logged_in.connect_via(app)
def on_user_logged_in(sender, user):
    log_auth_token(user.get_auth_token()) # or whatever.

rawDescription: How to run custom code at login with flask-security

description: Run custom code at login with flask-security


code:
def job_expired(self):
    time=self.time
    date=self.purchased
    end=date+timedelta(days=time)
    #now is defined globally
    if now > end:
        self.expired = True
        self.pending = False
        self.save()

        ex = self.expired
    else:
        ex=self.expired=False
    return ex

rawDescription: Django model method wont update model field


code:
my_list = ['apple', 'orange', 'dragon', 'panda']
my_list.reverse()
while my_list:
    print(my_list.pop())

rawDescription: Python loop through list and shorten by one


code:
old = None
while True:
    var = s.recv(30)
    if var != old:
        old = var
        url = "magnet://myhost.com/{0}".format(var)
        os.startfile(url)

rawDescription: Pass statement if previous magnet URL is the same


code:
def __repr__(self):
  return repr(self.i)

rawDescription: Python __repr__ for numbers?

description: Python __repr__ for numbers


code:
class CheckResponse(webapp2.RequestHandler):   # webapp2

    def get(self):

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write(self.request.GET['resp'])

application = webapp2.WSGIApplication([
        ('/mail', MainPage),
        ('/', ShowHome),
        ('/checkResponse', CheckResponse)      # changed
    ], debug=True)

rawDescription: Unable to pass url parameters into the class method in GAE python


code:
cities = ["detroit" , "chicago" , "portland"]
if cities == ["detroit" , "chicago" , "portland"]:
    for city in cities:
        exec("{} = [\"\"]".format(city))

rawDescription: python: creating list of each element of list

description: Python: creating list of each element of list


code:
import webbrowser as ac

chrome = webbrowser.get('chrome')
chrome.open('istihza.com')

rawDescription: Python 3 - webbrowser module - open() function


rawDescription: Returning a composite graphics object in python/matplotlib


rawDescription: Median across multiple axes

description: Median across multiple axes


code:
#!/usr/bin/env python
import pyglet
from pyglet.gl import *

window = pyglet.window.Window()
glEnable(GL_DEPTH_TEST)

image = pyglet.image.load('imgs/appfolio.png')
texture = image.get_texture()
glEnable(texture.target)
glBindTexture(texture.target, texture.id)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height,
             0, GL_RGBA, GL_UNSIGNED_BYTE,
             image.get_image_data().get_data('RGBA', image.width * 4))

rect_w = float(image.width) / image.height
rect_h = 1

@window.event
def on_draw():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    glTranslatef(0, 0, -10)
    glBindTexture(texture.target, texture.id)
    glBegin(GL_QUADS)
    glTexCoord2f(0.0, 0.0); glVertex3f(-rect_w, -rect_h, 0.0)
    glTexCoord2f(1.0, 0.0); glVertex3f( rect_w, -rect_h, 0.0)
    glTexCoord2f(1.0, 1.0); glVertex3f( rect_w,  rect_h, 0.0)
    glTexCoord2f(0.0, 1.0); glVertex3f(-rect_w,  rect_h, 0.0)
    glEnd()

def on_resize(width, height):
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(65.0, width/float(height), 0.1, 1000.0)
    glMatrixMode(GL_MODELVIEW)

window.on_resize = on_resize # we need to replace so can't use @window.event
pyglet.app.run()

rawDescription: Moving an image around in 3D space

description: Moving an image around in 3D space


code:
df = []
for key, value1 in exp1_dict.iteritems():
    if key in exp2_dict:
        dict_union = list(set(value1).intersection(exp2_dict[key]))
        col1 = key
        col2 = str(f_exp1_dict[key])
        col2 = str(f_exp2_dict[key])
        col3 = str('|'.join(value1))
        col4 = str(len(exp1_dict[key]))
        col5 = str(len(exp1_corr.index))
        col6 = str('|'.join(exp2_dict[key]))
        col7 = str(len(exp2_dict[key]))
        col8 = str(len(exp2_corr.index))
        col9 = str('|'.join(dict_union))
        col10 = str(dict_union)
        df.append([col1, col2, col3, col4, col5, col6, col7, col8, col9, col10])

df = pd.DataFrame(df)

rawDescription: Convert an iteration over dictionaries into a pandas dataframe


code: np.bincount(n * (Ytrue - 1) + (Ypred -1), minlength=n*n).reshape(n, n)

rawDescription: Python one-liner for a confusion/contingency matrix needed


code: last_five = somesequence[-5:]

rawDescription: Is there a Python idiom for the last n elements of a sequence?


code: (c for c in s if c in '+-/*()_')

rawDescription: python how to extract operators from string

description: Python how to extract operators from string


code: cur.execute('insert into tempPDBcode (PDBcode) values (%s);', s)

rawDescription: Python: inserting double or single quotes around a string


code:
from bisect import bisect_left
def bi_contains(lst, item):
    """ efficient `item in lst` for sorted lists """
    # if item is larger than the last its not in the list, but the bisect would
    # find `len(lst)` as the index to insert, so check that first. Else, if the
    # item is in the list then it has to be at index bisect_left(lst, item)
    return (item <= lst[-1]) and (lst[bisect_left(lst, item)] == item)

rawDescription: Most efficient way for a lookup/search in a huge list (python)


code:
start_time = datetime.datetime.strptime(stop_date[0], "%Y%m%d%H%M%S")
stop_time = datetime.datetime.strptime(stop_date[1], "%Y%m%d%H%M%S")
current_time = datetime.datetime.now()

if current_time < start_time:
    # not yet started
    do_something()
elif current_time > start_time + (stop_time - start_time) / 2:
    # past half-way
    do_something_else()

rawDescription: How to compare the current time with date format

description: Compare the current time with date format


code:
count = df.loc[:, 'start station id'].value_counts()
tuples = [tuple((x, y)) for x, y in count.items()]

rawDescription: Separate out value_counts values

description: Separate out value_counts values


code:
from functools import partial
x = partial(filter, is_even)  # lambda lst: filter(is_even, lst)
new_list = x(list_of_ints)
# or just new_list = partial(filter, is_even)(list_of_ints)

rawDescription: Python's filter functions arguments order


code:
class Case:
    def __init__(self, id, formtype, age, fever=None, cough=None, gender=None):
        self.case_id = id
        self.form_type = formtype
        self.age = age
        self.fever = fever
        self.cough = cough
        self.gender = gender

    def __iter__(self):
        for ele in ["case_id", "form_type", "age",
                    "fever", "cough", "gender"]:
            yield ele

caselist = [
    Case(id="12345", formtype="A", age=12, fever=1, gender="female"),
    Case(id="12345", formtype="B", age=12, cough=0),
    Case(id="67890", formtype="A", age=34, fever=0, gender="male"),
    Case(id="67890", formtype="B", age=34, cough=1),
    Case(id="75321", formtype="A", age=2, fever=0, gender="male")
]

d = {}

for c in caselist:
    if c.case_id not in d:
        d[c.case_id] = c
    elif d[c.case_id].form_type != "B" and c.form_type == "B":
        tmp = d[c.case_id]
        for attr in c:
            if getattr(c, attr) is None:
                setattr(c, attr, getattr(tmp, attr))
        d[c.case_id] = c

caselist[:] = d.values()
print(caselist)

rawDescription: Merge list of objects into consistent list based on common matching attribute in Python


code:
to_translate = 'Hola como estas?'
print("%s >> %s" % (to_translate, translate(to_translate)))
print("%s >> %s" % (to_translate, translate(to_translate, 'fr')))

rawDescription: Translation Languages Python

description: Translation Languages Python


code:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy

def H(n, f, l, delta, H_abs, H_ph):
    c0 = 2.99796e8
    n0 = 1.00027 + 0j
    n1 = n[0] + 1j * n[1]

    Sum = 0
    for i in range(1, delta+1):
        Sum = Sum + ((n0-n1)*numpy.exp(-1*2*numpy.pi*f*n1*l/c0)/(n1+n0))**i

    H_Theo = 4*n0*n1*numpy.exp(2*numpy.pi*f*l*(n0-n1)/c0)*(1+Sum)/(n0+n1)

    M = numpy.abs(H_Theo) - H_abs
    A = numpy.angle(H_Theo) - H_ph

    return abs(M) + abs(A)

freq = 1213188709257.4814
l_real = 6.77e-4
d = 0
H_abs = 0.798653104536778
H_ph = 2.1845744701729926

n_test = numpy.arange(1.5, 2.5, 0.01).tolist()
k_test = numpy.arange(-0.05, 0.05, 0.001).tolist()

X = n_test
Y = k_test
X, Y = numpy.meshgrid(X, Y)

errore = []
for i in range(len(n_test)):
    errore.append(H([X[i],Y[i]], freq, l_real, d, H_abs, H_ph))

Z = errore

fig2 = plt.figure()
az = fig2.gca(projection='3d')
az.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = az.contour(X, Y, Z, zdir='z', offset=numpy.min(Z)-1, cmap=cm.coolwarm)
cset = az.contour(X, Y, Z, zdir='x', offset=numpy.min(X)-1, cmap=cm.coolwarm)
cset = az.contour(X, Y, Z, zdir='y', offset=numpy.max(Y)+0.05, cmap=cm.coolwarm)

az.set_xlabel('n')
az.set_xlim(numpy.min(X)-1, numpy.max(X)+1)
az.set_ylabel('k')
az.set_ylim(numpy.min(Y)-0.05, numpy.max(Y)+0.05)
az.set_zlabel('Err')
az.set_zlim(numpy.min(Z)-1, numpy.max(Z)+1)

plt.show()

rawDescription: Problemw with python surface plot

description: Problemw with python surface plot


code:
# write a decorator function taking the function to decorate as only parameter:
def timer_decorator(func):

    # define an inner function as wrapper with a flexible signature as your target function:
    def wrapper(*args, **kwargs):

        # set up timing:
        start_time = time.time()

        # call the wrapped function (passed as 'func' argument):
        return_value = func(*args, **kwargs)

        # check the timer and evaluate the time span:
        end_time = time.time()
        time_span = end_time - start_time
        print("Function '{}' took {:.3}s to run.".format(func.__name__, time_span))

        # return the decorated function's return value:
        return return_value

    # return the constructed wrapper function (don't call it --> no brackets "()" !):
    return wrapper

# Decorate your original function with your decorator:
@timer_decorator
def breadth_first_tree_search(problem):
    "Search the shallowest nodes in the search tree first."
    return tree_search(problem, FIFOQueue())

# Call your decorated function just like a normal function without any decoration:
breadth_first_tree_search("however you specify a problem...")

rawDescription: using timer to get runtime of a funtion

description: Using timer to get runtime of a funtion


code:
obj
obj.Sizer
obj.Sizer.Children
obj.Sizer.Children[0]
obj.Sizer.Children[0].Window

rawDescription: wxpython: How do you access the objects which you've placed inside of a wx.Sizer object?

description: Wxpython: How do you access the objects which you've placed inside of a wx.Sizer object


code:
s = "x=y"
key,value = s.split('=', 1)
print(key, "==", value)
x == y

items = ["x=y","i=j","a=b"]

for ele in items:
   key, value = ele.split('=', 1)
   print(key, "==", value)

rawDescription: python: dictionary from "key=value"

description: Python: dictionary from "key=value"


rawDescription: Create independent objects using operator * on list


code:
import struct
from mmap import mmap

class FileVector:

    number_size = len(struct.pack("<i", 0))

    def __init__(self, file_name, initial_size, default_value=0):
        try:
            self.f = open(file_name, "r+b")
        except FileNotFoundError:
            self.f = open(file_name, "w+b")
            fill = self._number_to_bytes(default_value)
            for i in range(initial_size):
                self.f.write(fill)
            self.f.flush()
        self.m = mmap(self.f.fileno(), 0)

    def close(self):
        self.m.close()
        self.f.close()

    def update(self, position, value):
        self.m.seek(self.number_size * position)
        self.m.write(self._number_to_bytes(value))

    def read(self, position):
        self.m.seek(self.number_size * position)
        return self._bytes_to_number(self.m.read(self.number_size))

    def _number_to_bytes(self, n):
        return struct.pack("<i", n)

    def _bytes_to_number(self, b):
        return struct.unpack("<i", b)[0]

fv = FileVector("data", 10**9)
print(fv.read(1000))
fv.update(1000, -42)
print(fv.read(1000)) # should return -42

rawDescription: What is the fastest approach of having a list stored on drive in python?


code:
from random import shuffle

finput = 'path/input.txt'
foutput = 'path/output.txt'

with open(finput, 'r') as fin, open(foutput, 'w') as fout:
    sentences = fin.readlines()

    #add the order using enumeration
    sentences = list(enumerate(sentences))
    shuffle(sentences)
    for i, sentence in sentences:
        fout.write("{0}: {1}".format(i + 1, sentence))

rawDescription: Scrambling sentences on Python

description: Scrambling sentences on Python


code:
while guessesMade < 6:
    guess = int(input('Take a guess'))

    if guess < number:
        print('Your guess is too low.')
        guessesMade += 1

    elif guess > number:
        print('Your guess is too high.')
        guessesMade += 1

    else:
        break

rawDescription: Stuck in a while loop while using if statement


code:
from types import NoneType
n = NoneType()

rawDescription: Other unique-instance objects besides None in python?


rawDescription: how do you put text into an array in python

description: Put text into an array in python


code:
bools = [False, False, False, True, False]
# we're using constants here but you can use variables

# find first True value
whichbool = bools.index(True)

# now call a function based on that value
[func0, func1, func2, func3, func4][whichbool]()

rawDescription: Quick way to find a true boolean, given several boolean variables?


code:
import sys
def get_module_name(mod):
    for path, module in sys.modules.items():
        if mod == module:
            return path
    raise ValueError('module not found')

from foo.bar import bar
print(get_module_name(bar))
# foo.bar.bar

rawDescription: How to get the full namespace of a module after its imported in python

description: Get the full namespace of a module after its imported in python


code:
import copy

class A:

    def __init__(self):
        self.x = 1

    def changeX(self,num):
        self.x = num

class B:

    def __init__(self,classA):
        self.x = classA

class C:
    def __init__(self,classA):
        self.x = classA

    def ChangeA(self,num):
        self.x.changeX(num)

c_a = A()
c_b = B(c_a)
c_c = copy.deepcopy(C(c_a))

c_c.ChangeA(2)

c_a.x #1
c_b.x.x #1
c_c.x.x #2

rawDescription: Python Object Reference

description: Python Object Reference


code:
class NameMixinMeta(type):
    def _get_name(self):
        return getattr(self, '_name', self.__name__)

    def _set_name(self, name):
        self._name = name

    name = property(_get_name, _set_name)

class NameMixin(object):
    __metaclass__ = NameMixinMeta
    def _get_name(self):
        return getattr(self, '_name', self.__class__.__name__)

    def _set_name(self, name):
        self._name = name

    name = property(_get_name, _set_name)

class A(NameMixin):
    _name = 'Class A'

class B(NameMixin):
    pass

rawDescription: Python properties also as class properties


rawDescription: Loading in python png image made in gimp as rgb image


code:
from flask import Flask
from flask import request
from flask.ext.cors import CORS

import os

app = Flask(__name__)
CORS(app, resources={r'/': {"origins": "*"}}, headers='Content-Type')
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route('/')
def index():
    return "
Hello Stupid
"

@app.route('/ruby/test', methods=['GET'])
def runRubyScript():
    return os.system("ruby script.rb")

if __name__ == "__main__":
    app.run(host='0.0.0.0')

rawDescription: Error connecting to python server running in boot2docker (centos container | Windows 7.1 host)


code:
d = \
[y for x in d for y in x[1].values()]

rawDescription: How can i make the list form list of tuples

description: Make the list form list of tuples


code:
for filename in os.listdir("."):
    with open(filename) as csv_file:
        for row in csv.reader(csv_file):
            d['Order %s' % row[1]] = {'tag': row[1], 'prodcode': row[2], 'qty': row[3]}

rawDescription: Parsing Multiple CSV (.txt) Files in Python


code:
proxymodels = {"Foo": FooModel, "Bar": BarModel}

for o in BaseModel.objects.all():
    proxymodels[o.type].method_name(o, *args, **kwargs)

rawDescription: Django - get instances of base model as corresponding proxy models


code:
import os.path
import glob
import shutil

source = "My Source Path" # Replace these variables with the appropriate data
dest = "My Dest Path"
command = "My command"

# Find the files that need to be copied
files = glob.glob(os.path.join(source, "swale-*"))

# Copy the files to the destination
for file in files:
     shutil.copy(os.path.join(source, "swale-*"), dest)

# Create a sorted list of files - using the file sizes
# biggest first, and then use the 1st item
biggest = sorted([file for file in files],
        cmp=lambda x,y : cmp(x,y),
        key=lambda x: os.path.size( os.path.join( dest, x)),  reverse = True)[0]

# Rename that biggest file to swale.dat
shutil.move( os.path.join(dest,biggest), os.path.join(dest,"swale.date") )

# Run the command
os.system( command )
# Only use os.system if you know your command is completely secure and you don't need the output. Use the popen module if you need more security and need the output.

rawDescription: Python, Copy, Rename and run Commands

description: Python, Copy, Rename and run Commands


code:
import numpy as np
import cv2

im = cv2.imread('image.jpg')
row, col= im.shape[:2]
bottom= im[row-2:row, 0:col]
mean= cv2.mean(bottom)[0]

bordersize=10
border=cv2.copyMakeBorder(im, top=bordersize, bottom=bordersize, left=bordersize, right=bordersize, borderType= cv2.BORDER_CONSTANT, value=[mean,mean,mean] )

cv2.imshow('image',im)
cv2.imshow('bottom',bottom)
cv2.imshow('border',border)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: how to add border around an image in opencv python

description: Add border around an image in opencv python


code:
a = np.arange(9).reshape((3,3))
a
np.random.shuffle(a.flat)
a

rawDescription: Shuffle a numpy array

description: Shuffle a numpy array


code:
row = ['string1', 'string2']
row.extend(t.string3[-7:] for t in tobject)

rawDescription: python list from both strings and for loop

description: Python list from both strings and for loop


code:
from lxml import etree as ET

os.chdir("/Users/paulsallen/workspace/fforce/FForce Dev Account/config/objects/")
objs = glob.glob("*.object")

fields_dict = {}

for filename in objs:
    root = ET.parse(filename).getroot()
    required = root.xpath('.//n:fullName[../n:required/text()="true"]/text()',
        namespaces={'n': tree.nsmap[None]})
    fields_dict[os.path.splitext(filename)[0]] = required

rawDescription: How to use python to parse XML to required custom fields

description: Use python to parse XML to required custom fields


code:
data = "this this this %this %this"

data = ' '.join(data.split('%')[::2])

data # => "this this this  this"

rawDescription: search a file using python

description: Search a file using python


code:
import math
import matplotlib.pyplot as plt

#This function does the maths - turns co-ordinates into angles
#with 0 on +ve x axis, increasing anti-clockwise
def get_theta(x,y):
    theta = math.atan(y*1.0/x) / (2*math.pi) * 360
    if x < 0:
        theta += 180
    if theta < 0:
        theta += 360
    return theta

def visualize(val,ar):
    ax = plt.gca()
    ax.plot([val-5],[ar-5], marker='o', color='r')
    ax.set_xlim([-5,5])
    ax.set_ylim([-5,5])
   #insert the following to calculate the angles and
   #then annotate them on the plot
    x,y = val-5,ar-5
    label = get_theta(x, y)
    ax.annotate(str(label)+' degrees', xy = (x, y), xytext = (-20, 20),textcoords = 'offset points')

if __name__ == '__main__':
    plt.figure()
    x = [6,4,4,6]
    y = [6,6,4,4]
    for (val, ar) in zip(x,y):
        visualize(val,ar)

    plt.draw()
    plt.grid()
    plt.show()

rawDescription: Finding angle using matplotlib

description: Finding angle using matplotlib


code:
text = "'I wonder how many miles I've fallen by this time?' she said aloud."
import string
words = [x.strip(string.punctuation) for x in text.split()]
words

rawDescription: A better way to exclude punctuation/non-alphabet characters from a string?


rawDescription: Shuffling numpy array without commas

description: Shuffling numpy array without commas


rawDescription: How do I convert local time to UTC in Python?

description: Convert local time to UTC in Python


code:
from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    (r'^docs/$', direct_to_template, {
        'template': 'index.html'
    }),
)

rawDescription: Django - redirect to a static html file

description: Django - redirect to a static html file


code:
a = range(20)
a
a[7:] #seventh term and forward
a[:11] #everything before the 11th term
a[::2] # even indexed terms.  0th, 2nd, etc
a[4:17]
a[4:17:2]
a[::-1]
a[19:4:-5]
a[1:4] = [100, 200, 300] #you can assign to slices too
a

rawDescription: Unable to reverse lists in Python, getting "Nonetype" as list


code:
struct.unpack('i', b'\xdb\x0fI@')
struct.unpack('f', b'\xdb\x0fI@')

rawDescription: Python interpretation of bytes. (C memcpy)


code:
for i in xrange(len(list_1)-1):
    l1 = list_1[:]
    l2 = list_2[:]
    var_list_1_1 = l1.pop(i)
    var_list_1_2 = l1
    var_list_2_1 = l2.pop(i)
    var_list_2_2 = l2

rawDescription: Python: two list iteration inside for loop for index


code:
with open ('sampleID.txt', 'r') as inF:
        for line in inF:
            if 'Sample ID:' in line:

                SID = line.split(':')[1].strip()

rawDescription: Using line.split until white space

description: Using line.split until white space


code:
import sqlite3
db = sqlite3.connect("<path_to>/places.sqlite")
urls = db.execute("select url from moz_places").fetchall()

rawDescription: How can i grab the domain name from the firefox's places.sqlite file with python script

description: Grab the domain name from the firefox's places.sqlite file with python script


code:
class Device(models.Model):
    ...
    gcm_device = models.OneToOneField(GCMDevice)

rawDescription: Django multiple model inheritance, django-push-notifications


rawDescription: A 'related content' list with DetailView in Django


code:
import pymssql

conn = pymssql.connect(server='', user='', password='', database='')

cur = conn.cursor()
cur.execute('SELECT Top 1 LastUpdate FROM tbl_Date')

myDate = 20160426

for row in cur:
    print(row[0])

if row[0] == myDate:
    print('true')
    #then do something
else:
    print('false')

conn.close()

rawDescription: comparing an int variable to MSSQL query results Python via pymssql

description: Comparing an int variable to MSSQL query results Python via pymssql


rawDescription: Line Disappears When Using Contours in MatPlotLib


code:
s = '-5 5 3 5'
sum(map(int, s.split()))

rawDescription: How to add inputed numbers in string.(Python)

description: Add inputed numbers in string.(Python)


code:
import curses

def Main(screen):
   while True:
      ch = screen.getch()
      if ch == ord('q'):
         break
      elif ch == 27: # ALT was pressed
         screen.nodelay(True)
         ch2 = screen.getch() # get the key pressed after ALT
         if ch2 == -1:
            break
         else:
            screen.addstr(5, 5, 'ALT+'+str(ch2))
            screen.refresh()
         screen.nodelay(False)

curses.wrapper(Main)

rawDescription: How to detect curses ALT + key combinations in python

description: Detect curses ALT + key combinations in python


code:
import re

bulk_data = '''F0142514RM/JRSE1420 Mod/4758
F0144758RM/JRSE935 Mod/23
F014GS4RM/JRSE10 Mod/445
'''

ptrn1 = re.compile(r'''
    ^       #matches the start of the string
    .*      #matches 0 or more of anything
    RM\/    #matches "RM" followed by "/"
    (\w+)   #matches one or more alphanumeric character and the undescore
    \b      #matches empty string
    .*      #matches anything
    $       #matches the end of string
''', re.MULTILINE | re.VERBOSE)

ptrn2 = re.compile(r'''
    ^       #matches the start of the string
    .*      #matches 0 or more of anything
    \s      #matches a space character
    (Mod.*) #matches "Mod" follow by 0 or more of anything
    $       #matches the end of string
''', re.MULTILINE | re.VERBOSE)

typeA1, typeA2, typeA3 = ptrn1.findall(bulk_data)
typeB1, typeB2, typeB3 = ptrn2.findall(bulk_data)

rawDescription: Copy value in var from structured data

description: Copy value in var from structured data


code:
from django import forms
class MyForm(forms.Form):
    check = forms.BooleanField(required = True)
    # your other form fields

rawDescription: Django: Require Checkbox to be ticked to Submit Form


code: x[np.asarray(x > 0)] = 0

rawDescription: How to index 0-d array in Python?

description: Index 0-d array in Python


code:
import matplotlib as mpl

ax_cb1 = fig.add_axes((0.85, 0.125, 0.03, 0.75))
BW_cdict = {
    'red':    ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0)),
     'green': ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0)),
     'blue': ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0))
    }
black_white = mpl.colors.LinearSegmentedColormap('BlackWhite', BW_cdict)
norm = mpl.colors.Normalize(vmin=z_min, vmax=z_max)
cb1 = mpl.colorbar.ColorbarBase(
    ax_cb1, cmap=black_white, norm=norm, orientation='vertical'
)

ax_cb2 = fig.add_axes((0.125, 0.95, 0.75, 0.03))
BR_cdict = {
    'red':    ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0)),
     'green': ((0.0, 0.0, 0.0),
               (1.0, 0.0, 0.0)),
     'blue':  ((0.0, 1.0, 1.0),
               (1.0, 0.0, 0.0))
    }
blue_red = mpl.colors.LinearSegmentedColormap('BlueRed', BR_cdict)
norm = mpl.colors.Normalize(vmin=w_min, vmax=w_max)
cb2 = mpl.colorbar.ColorbarBase(
    ax_cb2, cmap=blue_red, norm=norm, orientation='horizontal'
)

rawDescription: Matplotlib: How to add two custom colorbars to an image map


code:
import pandas as pd
df = pd.concat(list_of_dataframes)

rawDescription: Combine a list of pandas dataframes to one pandas dataframe


rawDescription: Flask SqlAlchemy 2 table join : how to retrieve rows with both objects


code:
config.add_route('all_orders', '/order')
config.add_route('order_detail', '/order/{id}')

@view_config(route_name='all_orders', renderer='all_orders.mako')
def all_orders_view(request):
    all_orders = {} # query the DB?
    return {'orders': all_orders}

@view_config(route_name='order_detail', renderer='order_detail.mako')
def order_detail_view(request):
    order_id = request.matchdict['id']
    order = None # query the db for order
    if order is None:
        raise HTTPNotFound
    return {'order': order}

rawDescription: How to map two views with the same route in pyramid?

description: Map two views with the same route in pyramid


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

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

class browser(QWebView):
    def __init__(self, parent=None):
        super(browser, self).__init__(parent)

        self.timerScreen = QTimer()
        self.timerScreen.setInterval(2000)
        self.timerScreen.setSingleShot(True)
        self.timerScreen.timeout.connect(self.takeScreenshot)

        self.loadFinished.connect(self.timerScreen.start)
        self.load(QUrl("http://www.google.com/ncr"))

    def takeScreenshot(self):
        image   = QImage(self.page().mainFrame().contentsSize(), QImage.Format_ARGB32)
        painter = QPainter(image)

        self.page().mainFrame().render(painter)

        painter.end()
        image.save(self.title() + ".png")

        sys.exit()

if __name__ == "__main__":
    import  sys
    app  = QApplication(sys.argv)
    main = browser()
    app.exec_()

rawDescription: Wait for a delay before capture website image with PyQt


code:
response = self.client.post('/api/token/',
       {'grant_type': 'password', 'username': username, 'password': password})

rawDescription: Testing in Django Rest Framework, reproduce this curl request?


code:
import numpy as np
a = np.array(['hi','hello'])
a.dtype
a = np.array(['hi','hello'], dtype='S2')
a

rawDescription: Adding a row (header) to a numpy matrix issue using np.vstack in python


code:
file_in  = open('input.txt', 'r')
file_out = open('output.txt', 'w')

for line in file_in:
    line = line.rstrip()
    line = line.split('\t')

    CATEGORY = ' '.join(line[:-3]) ##set variable as beginning of line
                                   ##to before 3rd last column
    NUMBER_1 = line[-3] ##set variable as 3rd last column
    TOTAL = line[-1]    ##set variable as last column

    file_out.write('%s\t%s\t%s\n' % (CATEGORY, NUMBER_1, TOTAL))

file_in.close()
file_out.close()

rawDescription: Read text file and write file from specific contents


code:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://kozbeszerzes.ceu.hu/searchresults.xhtml?q=1998&page=0')

for e in driver.find_elements_by_class_name('result'):
    link = e.find_element_by_tag_name('a')
    print(link.text.encode('ascii', 'ignore'), link.get_attribute('href').encode('ascii', 'ignore'))

driver.quit()

rawDescription: how to scrape search results if returned in javascript (using python)

description: Scrape search results if returned in javascript (using python)


code:
import tkinter as tk

root1 = tk.Tk()

def new_window():
    root2 = tk.Toplevel()
    # click the last button and all tk windows close
    def shutdown():
        root1.destroy()
        root2.destroy()
    background_image2 = tk.PhotoImage(file = '...')
    background_button2 = tk.Button(root2, image = background_image2, command = shutdown)
    background_button2.pack()
    root2.mainloop()

background_image1 = tk.PhotoImage(file = '...')
# have used a button not a label for me to make another tk window
background_button1 = tk.Button(root1, image = background_image1, command = new_window)
background_button1.pack()

root1.mainloop()

rawDescription: Python Tkinter: How do I apply a new background image when opening a new tk window?


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

# load bluemarble with PIL
bm = PIL.Image.open('bluemarble.jpg')
# it's big, so I'll rescale it, convert to array, and divide by 256 to get RGB values that matplotlib accept
bm = np.array(bm.resize([d/5 for d in bm.size]))/256.

# coordinates of the image - don't know if this is entirely accurate, but probably close
lons = np.linspace(-180, 180, bm.shape[1]) * np.pi/180
lats = np.linspace(-90, 90, bm.shape[0])[::-1] * np.pi/180

# repeat code from one of the examples linked to in the question, except for specifying facecolors:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.outer(np.cos(lons), np.cos(lats)).T
y = np.outer(np.sin(lons), np.cos(lats)).T
z = np.outer(np.ones(np.size(lons)), np.sin(lats)).T
ax.plot_surface(x, y, z, rstride=4, cstride=4, facecolors = bm)

plt.show()

rawDescription: Creating a rotatable 3D earth

description: Creating a rotatable 3D earth


code:
import glob
with open('countfile' , 'w') as out:
    list_of_files = glob.glob('./*.linear')
    for file_name in list_of_files:
        with open(file_name, 'r') as f:
            count = sum(1 for line in f)
            out.write('{c} {f}\n'.format(c = count, f = file_name))

rawDescription: count lines in multiple files and output along with file names

description: Count lines in multiple files and output along with file names


code:
import win32gui
win32gui.IsWindow(handle)
win32gui.IsWindowVisible(handle)

rawDescription: Close Python when Parent is closed

description: Close Python when Parent is closed


code:
from tkinter import *

root = Tk()

enable = {'jack': 0, 'john': 0}
checkvalues = {}

def actright(x):
    print(x,  checkvalues[x].get())

for machine in enable:
    myvar = IntVar()
    myvar.set(enable[machine])
    checkvalues[machine] =myvar
    l = Checkbutton(root, text=machine, onvalue=1, offvalue=0, variable = myvar,
                    command = lambda machine=machine: actright(machine))
    l.pack(anchor = W)

root.mainloop()

rawDescription: Using two individual check buttons in tkinter with the same value


code:
from comtypes.client import CreateObject

access = CreateObject('Access.Application')

from comtypes.gen import Access

DBEngine = access.DBEngine
db = DBEngine.CreateDatabase('test.mdb', Access.DB_LANG_GENERAL)
      # For me, test.mdb was created in my My Documents folder when I ran the script

db.BeginTrans()

db.Execute("CREATE TABLE test (ID Text, numapples Integer)")
db.Execute("INSERT INTO test VALUES ('ABC', 3)")

db.CommitTrans()
db.Close()

rawDescription: How do you create a mdb database file in Python?

description: Create a mdb database file in Python


code:
# Create the button and make it checkable
self.testButton = QtGui.QAction(QtGui.QIcon('images/icons/test.png'), 'Test', self)
self.testButton.setCheckable(True)

# Mark the button as checked
self.testButton.setChecked(True)

rawDescription: PyQt4 - Making a QIcon look active or "pressed down"


rawDescription: how to efficiently strip a string with delimiting characters on both ends?

description: Efficiently strip a string with delimiting characters on both ends


code:
from selenium.webdriver.support.ui import Select

# initialize the select instance
select = Select(driver.find_element_by_id('address'))

# get the list of options and choose a random one
options = [o.text for o in select.options]
option = random.choice(options)

# select it
select.select_by_visible_text(option)

rawDescription: Store dynamic dropdown options with Python and Selenium Webdriver


code:
from multiprocessing import Queue, Process
import multiprocessing

def worker(e, m):
    while True:
       e.wait() # Wait to be told the file has changed. This will block.
       e.clear()  # Clear the flag so the main thread can set it again if changes happen while we process
       # Send request to server, retrieve data
       # Write to HTML files

def watch_file_for_changes():
    while True:
       if file_changed: # Use whatever watching mechanism you already have for this; inotify, etc.
          e.set() # Tell the worker to process the file. This unblocks e.wait()

if __name__ == "__main__":
   e = Event()
   # Start some workers. You can choose whatever number you want.
   p = multiprocessing.Process(target=worker, args=(e,))
   p.start()
   watch_file_for_changes()

rawDescription: Python: Always listen and execute data when passed


code:
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
pyplot.ioff()
fig = pyplot.figure()
# HERE your code to add things in the figure
pyplot.savefig('file.png')
pyplot.close()

rawDescription: Python: saving a plot and not opening it in a GUI


rawDescription: Output alternatives in Python

description: Output alternatives in Python


code:
import xml.etree.ElementTree as ET
r = ET.fromstring('''<MultiGeometry>
     <Polygon>
         <Altitude>
         </Altitude>
         <coordinates>
         </coordinates>
     </Polygon>
</MultiGeometry>''')
ET.tostring(r)
print(ET.tostring(r).decode())

rawDescription: how to use iterparse to get xml snippet

description: Use iterparse to get xml snippet


code:
class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        # custom stuff here
        obj.save()

rawDescription: Further customization of Django admin (add new object)


rawDescription: How can I convert a string with dot and comma into a float number in Python

description: Convert a string with dot and comma into a float number in Python


code:
stringifiedKey = str(key)
reconstitutedKey = db.Key(stringifiedKey)

rawDescription: gae Model get_by_id() vs get_by_key_name()

description: Gae Model get_by_id() vs get_by_key_name()


code:
with open(fileName, 'ab+') as c:
    writer = csv.writer(c ,dialect= 'excel', delimiter= ',')
    try :
         frist_row= next(csv.reader(c ,dialect= 'excel', delimiter= ','))
         for item in domainList:
                  writer.writerow([item, '', 'Related'])
    except StopIteration :
           writer.writerow(['domain','ip','identifier','relationship', 'related To'])
           for item in domainList:
               writer.writerow([item, '', 'Related'])

rawDescription: How can I check if the first line of a CSV file has been written to?

description: Check if the first line of a CSV file has been written to


rawDescription: Ending a comment in Python

description: Ending a comment in Python


code:
import cx_Oracle
from multiprocessing import managers
from multiprocessing import current_process
from multiprocessing import Process
import time

class Connection(cx_Oracle.Connection):

    def execute(self, sql):
        cursor = self.cursor()
        cursor.execute(sql)
        return list(cursor)

#function to setup the connection object in manager process
def setupConnection(user,password,dsn):
    conn = Connection(user=user,password=password,dsn=dsn)
    return conn

#proxy object for my connection
class connectionProxy(managers.BaseProxy):
    def close(self):
        return self._callmethod('close',args=())
    def ping(self):
        return self._callmethod('ping',args=())
    def execute(self, sql):
        return self._callmethod('execute', args=(sql,))

#connection manager
class connectionManager(managers.BaseManager):
    pass

#child process work function
def child(conn_proxy):
    print(str(current_process().name) + "Working on connection : " + str(conn_proxy), id(conn_proxy))
    result = conn_proxy.execute('select 1 from dual')
    print("Result:", result)

if __name__ == '__main__' :
    #db details
    user = 'user'
    password = 'pwd'
    dsn = 'tnsentry'

    #setup manager process and open the connection
    manager = connectionManager()
    manager.register('set_conn',setupConnection,proxytype=connectionProxy,exposed = ('close','ping','execute'))
    manager.start()

    #pass the connection to the child process
    conn_proxy = manager.set_conn(user=user,password=password,dsn=dsn)
    p = Process(target=child, args=(conn_proxy,),name='oraWorker')
    p.start()
    p.join()

rawDescription: python cx_Oracle.Connection proxying to share between process - I get an error when creating a cursor on a shared connection object

description: Python cx_Oracle.Connection proxying to share between process - I get an error when creating a cursor on a shared connection object


code:
import pandas as pd
df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
df
s = df.ix[:,0]
type(s)

rawDescription: How to get the first column of a pandas DataFrame as a Series?

description: Get the first column of a pandas DataFrame as a Series


code:
import json
import requests

metadata = json.dumps({"documentType": "application/msword"})
files = {
    'meta': ('', metadata, 'application/json'),
    'data': ('sample.docx', content, 'application/octet-stream'),
}

req = requests.post(
    "https://text.s4.ontotext.com/v1/twitie",
    auth=("user", "pass"),
    files=files)

rawDescription: Convert cURL request to Python-Requests request


code: re.findall('[A-Z][A-Za-z]*', text)

rawDescription: Python regular expressions, how to search for a word starting with uppercase?


code:
import numpy as np

var = np.array([10, 7, 4, 3, 2, 1]) # input array

np.percentile(var, np.arange(0, 100, 25)) # quartiles
array([ 1.  ,  2.25,  3.5 ,  6.25]) # output

np.percentile(var, np.arange(0, 100, 10)) # deciles
array([ 1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  5.5,  7. ,  8.5]) #output

rawDescription: Solving for quartile and decile using Python


code:
import urllib.request
from bs4 import BeautifulSoup

url_to_parse = 'http://www.myfxbook.com/members/fxgrowthbot/forex-growth-bot/71611'
response = urllib.request.urlopen(url_to_parse)
html = response.read()
soup = BeautifulSoup(html)
a = soup.find(id='history').find_all('td')

print(len(a))  # 300

rawDescription: Parse table <td> from remote HTML with BS4


code:
import selenium.webdriver as webdriver
import lxml.html as lh
import lxml.html.clean as clean

browser = webdriver.Chrome() # Get local session of Chrome
browser.get("http://www.webpage.com") # Load page

content=browser.page_source
cleaner=clean.Cleaner()
content=cleaner.clean_html(content)
doc=lh.fromstring(content)

rawDescription: Access Chrome DOM tree with python

description: Access Chrome DOM tree with python


code:
plt.yscale('log')
plt.xscale('log')

rawDescription: Vary the scale of x-axis with Matplotlib


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

data = [8,12,15,17,18,18.5]
perc = np.linspace(0,100,len(data))

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

ax.plot(perc, data)

fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
xticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)

plt.show()

rawDescription: Pyplot: using percentage on x axis

description: Pyplot: using percentage on x axis


rawDescription: Operation on two dicts

description: Operation on two dicts


rawDescription: Multi dimensional arrays in Python of a dynamic size


code: queryResults = Event.objects(title__icontains=q, end__gte=datetime.utcnow())

rawDescription: How to query mongoDB using Mongoengine with several "WHERE" arguments (what is AND)?

description: Query mongoDB using Mongoengine with several "WHERE" arguments (what is AND)


code:
import shlex
shlex.split('this is "a test"')

rawDescription: Split a string by spaces -- preserving quoted substrings -- in Python


rawDescription: How to extract a list from pandas?

description: Extract a list from pandas


code:
con.executemany("insert into stats(date, temperature) values (?, ?)",
                ((rec[0], rec[9]) for rec in stats))

rawDescription: Only import two columns from a CSV

description: Only import two columns from a CSV


code:
def addition(a,b):
    return [[a[i][j]+b[i][j] for j in range(len(a[i]))] for i in range(len(a))]

rawDescription: matrix manipulation using list comprehension

description: Matrix manipulation using list comprehension


code:
def flatten(lst):
    for dct in lst:
        key = dct["key"]
        if "tree" not in dct:
            yield [key] # base case
        else:
            for result in flatten(dct["tree"]): # recursive case
                yield [key] + result

rawDescription: Flatten a list of dictionaries and extract data along the way


code: [i for (i,e) in enumerate(list) if e==1][5]

rawDescription: Pythonic way to find index of n th occurance of a value in a list?


code:
import Tkinter
import threading
from Queue import Queue, Empty

class Gui(Tkinter.Tk):

    def __init__(self, parent=None):
        Tkinter.Tk.__init__(self, parent)
        self.ui_queue = Queue()
        self._handle_ui_request()
        self.title('Original Title')
        self.label = Tkinter.Label(self, text='Just a Label.',
            width=30, anchor='center')
        self.label.grid()

        self.bind('<<change_title>>', self.change_title)

        timer = threading.Timer(1, self.event_generate, ['<<change_title>>'])
        timer.start()

    def change_title(self, event=None):
        # Separate the function name, it's args and keyword args,
        # and put it in the queue as a tuple.
        ui_function = (self.title, ('New Title',), {})
        self.ui_queue.put(ui_function)

    def _handle_ui_request(self):
        '''
        Periodically services the UI queue to handles UI requests in the main thread.
        '''
        try:
            while True:
                f, a, k = self.ui_queue.get_nowait()
                f(*a, **k)
        except Empty:
            pass

        self.after(200, self._handle_ui_request)

G = Gui(None)
G.mainloop()

rawDescription: Python Tkinter: App hangs when changing window title via callback event


code:
import numpy, pylab, random

data = [ random.gauss(1, 0.2) for x in range(1000) ]

fig = pylab.figure()
weights = numpy.ones_like(data)/float(len(data))
n, bins, patches =pylab.hist(data, bins=20, histtype='bar',
                         weights=weights)
pylab.xlim(min(bins), max(bins))
pylab.ylim(0, 1)
pylab.show()

rawDescription: How can I get rid of the line in pylab histogram

description: Get rid of the line in pylab histogram


code:
import importlib
module = importlib.import_module(driver)
module.some_function()

rawDescription: Getting Module dynamically

description: Getting Module dynamically


code: slave = Popen(['ruby', 'slave.rb'], stdin=pipe, stdout=pipe, stderr=out, bufsize=0)

rawDescription: control stdin and stdout of a ruby program in python

description: Control stdin and stdout of a ruby program in python


rawDescription: Math Equations as Python Objects

description: Math Equations as Python Objects


code:
import tldextract
tldextract.extract('domainname.net.pl')
tldextract.extract('www.domainname.net.pl')
from publicsuffix import PublicSuffixList
psl = PublicSuffixList()
psl.get_public_suffix('domainname.net.pl')
psl.get_public_suffix('www.domainname.net.pl')

rawDescription: Python - regexp to check if string is TLD domain


code:
class MyClass:

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

a = MyClass(my_dataframe)
b = MyClass(my_dataframe)

rawDescription: Pass pandas dataframe into class

description: Pass pandas dataframe into class


code: new_matrix = matrix1 + matrix2

rawDescription: Python: Inserting a list of lists into another list of lists


code:
train = np.arange(20).reshape(4,5).T
target = np.hstack([np.arange(5).reshape(5,1), np.arange(100, 105).reshape(5,1)])
train
target
np.random.shuffle(train)
target[train[:,0]]
train

rawDescription: How to randomly shuffle data and target in python?

description: Randomly shuffle data and target in python


code:
import glob

for filename in glob.glob("somefolder/*.txt"):
    with open(filename, 'r') as inputFile:
        filecontent = inputFile.read();

rawDescription: How to import text files to fit this clustering algorithm?

description: Import text files to fit this clustering algorithm


code: df = df * MultFactor

rawDescription: Pandas DataFrame apply Specific Function to Each column


code: np.nonzero( np.logical_and( array1 == 2, array2 > array3 ) )

rawDescription: converting matlab "find" to "numpy" where

description: Converting matlab "find" to "numpy" where


code:
sql = "INSERT INTO tbltemplate (template_name) VALUES (%s)"
for template in dir_template_list:
    conn.query(sql, (template,))

rawDescription: Make a single insert query in python

description: Make a single insert query in python


rawDescription: How can I set Invitee in Google Calendar through Python?

description: Set Invitee in Google Calendar through Python


code:
@app.route('/update',  methods=['POST'])
def update():
    os.system('python update.py')
    return redirect(url_for('home'))

rawDescription: how to avoid flask insert duplicate entries?

description: Avoid flask insert duplicate entries


code:
def biggest():
    big_x, big_y, max_seen = 0, 0, 0
    for x in xrange(999,99,-1):
        if x*x < max_seen:
            break # breaks out of outer loop, as no later x value can be better
        for y in xrange(x, 99,-1):
            if x*y < max_seen:
                break # breaks out of inner loop, no later y value can be better
            if is_palindrome(x*y):
                big_x, big_y, max_seen = x,y, x*y
    return big_x, big_y, max_seen

rawDescription: Euler #4 in Python

description: Euler #4 in Python


code:
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

def SendMail(ImgFileName):
    img_data = open(ImgFileName, 'rb').read()
    msg = MIMEMultipart()
    msg['Subject'] = 'subject'
    msg['From'] = 'e@mail.cc'
    msg['To'] = 'e@mail.cc'

    text = MIMEText("test")
    msg.attach(text)
    image = MIMEImage(img_data, name=os.path.basename(ImgFileName))
    msg.attach(image)

    s = smtplib.SMTP(Server, Port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(UserName, UserPassword)
    s.sendmail(From, To, msg.as_string())
    s.quit()

rawDescription: Attachment Image to send by mail using Python


code:
from unittest import TestCase

class PotatoTestTemplate(TestCase):
    def setUp():
        pass

class PotatoTest1(PotatoTestTemplate):
    def test1(self):
        pass

class PotatoTest2(PotatoTestTemplate):
    def test1(self):
        pass

rawDescription: Why do tests in derived classes rerun the parent class tests?


code:
class Foo:
  SERIALIZABLE_ATTRIBUTES = {
    'belongings' : list,
    'net_worth' : float
  }

  def __init__(self):
    self.clear()

  def clear(self):
    for k, v in SERIALIZABLE_ATTRIBUTES.items():
      setattr(self, k, v())

rawDescription: Resetting class to default state

description: Resetting class to default state


code:
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_RIGHT

styles = getSampleStyleSheet()
style_right = ParagraphStyle(name='right', parent=styles['Normal'], alignment=TA_RIGHT)
doc = SimpleDocTemplate("my_doc.pdf", pagesize=A4)
Story=[]
# here you add your rows and columns, these can be platypus objects
tbl_data = [
    [Paragraph("Hello", styles["Normal"]), Paragraph("World (right)", style_right)],
    [Paragraph("Another", styles["Normal"]), Paragraph("Row (normal)", styles["Normal"])]
]
tbl = Table(tbl_data)
Story.append(tbl)
doc.build(Story)

rawDescription: python Reportlab two items in the same row on a Paragraph

description: Python Reportlab two items in the same row on a Paragraph


code:
l=['Name', 'AMAZON.COM - TOT RETURN IND', 'AMAZON.COM INC - NET CASH FLOW - FINANCING', 'AMAZON.COM INC - NET CASH FLOW - INVESTING', 'AMAZON.COM INC - NET CASH FLOW-OPERATING ACTIVS', 'AMAZON.COM INC - COST OF GOODS SOLD (EXCL DEP)', 'AMAZON.COM INC - EARNINGS BEF INTEREST & TAXES', 'AMAZON.COM INC - EBIT & DEPRECIATION', 'AMAZON.COM INC - GROSS INCOME', 'AMAZON.COM INC - NET SALES OR REVENUES', 'AMAZON.COM INC - OPERATING INCOME', 'AMAZON.COM INC - NET INCOME AVAILABLE TO COMMON', 'AMAZON.COM INC - ACCOUNTS PAYABLE', 'AMAZON.COM INC - CASH', "AMAZON.COM INC - COMMON SHAREHOLDERS' EQUITY", 'AMAZON.COM INC - CURRENT ASSETS - TOTAL', 'AMAZON.COM INC - CURRENT LIABILITIES-TOTAL', 'AMAZON.COM INC - TOTAL INVENTORIES', 'AMAZON.COM INC - LONG TERM DEBT', 'AMAZON.COM INC - TOTAL ASSETS']
companies, ratios =zip(*filter( lambda y: len(y) == 2, map(lambda x: tuple(x.split(" - ")), l)))
companies
ratios

rawDescription: Split list of lists in new list

description: Split list of lists in new list


code:
df['count'] = df.groupby('digits')['fsq'].transform(len)
df

rawDescription: DataFrame: add column with the size of a group


code: my_tuple = tuple([my_string] + my_list)

rawDescription: Create a tuple from a string and a list of strings


rawDescription: Python regex - cleaning markdown html

description: Python regex - cleaning markdown html


code:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as p
from scipy import zeros
import random
import threading

w,h = 320,200

black = zeros((h,w,3), dtype='uint8')
red = black.copy(); red[:,:,0] = 255
green = black.copy(); green[:,:,1] = 255
blue = black.copy(); blue[:,:,2] = 255

def ants():
    from scipy import rand, dstack
    return dstack([(255*rand(h,w)).astype('uint8')]*3)

fig = p.figure()
axs = [fig.add_subplot(1,3,i) for i in xrange(3)]
[ax.imshow(black) for ax in axs]

def update_image(ax):
    ## this takes some time
    import time
    time.sleep(3)
    ax.images[0].set_data(random.choice([red, green, blue]))
    ax.figure.canvas.draw()

def hit(event):
    if event.inaxes in axs:
        update_axs = [event.inaxes]
    else:
        update_axs = axs
    for ax in update_axs:
        ax.images[0].set_data(ants())
    p.draw()
    for ax in update_axs:
        t=threading.Thread(target=update_image,args=(ax,))
        t.daemon=True
        t.start()

cid = fig.canvas.mpl_connect('button_press_event', hit)
p.show()

rawDescription: how to stop the matplotlib GUI thread from freezing up?

description: Stop the matplotlib GUI thread from freezing up


code:
networkAdds = addresses.splitlines()[1:]
networkAdds = set(add.split(None,2)[1] for add in networkAdds if add.strip())
with open(sys.argv[1]) as infile: knownAdds = set(line.strip() for line in infile)

print("These addresses were in the file, but not on the network")
for add in knownAdds - networkAdds:
    print(add)

rawDescription: Python get list of mac addresses and compare them with list from file


code:
import numpy as np

A = np.array([1,2,3,4,5,6,7])
B = np.array([2,4,6])
C = np.searchsorted(A, B)

D = np.delete(np.arange(np.alen(A)), C)

D
#array([0, 2, 4, 6])

rawDescription: Check if each element in a numpy array is in another array


rawDescription: What's a simple way to hard code a 6x6 numpy matrix?


code:
def conj(self):
    return complex(self.re, - self.im)

rawDescription: how to construct a class for complex number in python?

description: Construct a class for complex number in python


code: args2 = (AsIs(schema), AsIs(table_name[0]), AsIs(new_owner))

rawDescription: Return SQL Query results as a variable in python


code:
import colorsys
from PIL import Image

def recolor(im, r, g, b):
    h, l, s = colorsys.rgb_to_hls(r/255.0, g/255.0, b/255.0)
    result = im.copy()
    pix = result.load()
    for y in range(result.size[1]):
        for x in range(result.size[0]):
            r2, g2, b2, a = pix[x, y]
            h2, l2, s2 = colorsys.rgb_to_hls(r2/255.0, g2/255.0, b2/255.0)
            r3, g3, b3 = colorsys.hls_to_rgb(h, l2, s)
            pix[x, y] = (int(r3*255.99), int(g3*255.99), int(b3*255.99), a)
    return result

recolor(im_flag, 255, 0, 0).save(r'c:\temp\red_flag.png')

rawDescription: Change/Overlay color on single-colored PNG image with transparent background?


code:
from collections import OrderedDict
OrderedDict([('method', 'constant'), ('data', '1.225')])
dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))

rawDescription: How to convert an OrderedDict into a regular dict in python3

description: Convert an OrderedDict into a regular dict in python3


code: maps_list = [[[[0 for i in range(4)] for z in range(100)] for y in range(100)] for x in range(100)]

rawDescription: Coordinates aren't being assigned correctly (Python 3.3)


code:
df2.mean(level=0)
df2.mean(level=1)

rawDescription: Pandas - access gouped levels in function


rawDescription: Create sibling file name in Python

description: Create sibling file name in Python


code:
def multiply(a, b):
  return a * b

rawDescription: Python function execution

description: Python function execution