code:
def complex_array_to_rgb(X, theme='dark', rmax=None):
    '''Takes an array of complex number and converts it to an array of [r, g, b],
    where phase gives hue and saturaton/value are given by the absolute value.
    Especially for use with imshow for complex plots.'''
    absmax = rmax or np.abs(X).max()
    Y = np.zeros(X.shape + (3,), dtype='float')
    Y[..., 0] = np.angle(X) / (2 * pi) % 1
    if theme == 'light':
        Y[..., 1] = np.clip(np.abs(X) / absmax, 0, 1)
        Y[..., 2] = 1
    elif theme == 'dark':
        Y[..., 1] = 1
        Y[..., 2] = np.clip(np.abs(X) / absmax, 0, 1)
    Y = matplotlib.colors.hsv_to_rgb(Y)
    return Y

rawDescription: Mapping element-wise a NumPy array into an array of more dimensions


code:
men = j['men_rankings'].keys()
women = j['women_rankings'].keys()

rawDescription: Reading a nested json file

description: Reading a nested json file


code:
import subprocess
def psql_copy_from(filename, tablename, columns = None):
    """Warning, this does not properly quote things"""
    coltxt = ' (%s)' % ', '.join(columns) if columns else ''
    with open(filename) as f:
        subprocess.check_call([
            'psql',
            '-c', 'COPY %s%s FROM STDIN' % (tablename, coltxt),
            '--set=ON_ERROR_STOP=true', # to be safe
            # add your connection args here
        ], stdin=f)

rawDescription: psycopg2 COPY using cursor.copy_from() freezes with large inputs

description: Psycopg2 COPY using cursor.copy_from() freezes with large inputs


code:
from heapq import heappush, heappop

def heapsort(iterable):
    h = []
    for value in iterable:
        heappush(h, value)
    return [heappop(h) for i in range(len(h))]

rawDescription: Soting lists using Heap? Python

description: Soting lists using Heap? Python


code:
zxor = reduce(lambda a, b: a ^ b, z, 0)

import operator
zxor = reduce(operator.xor, z, 0)

rawDescription: Python equivalent of sum() using xor()

description: Python equivalent of sum() using xor()


code:
# cmdline = ['vlc', '--demux', 'h264', '-'] #pick a media player
# cmdline = ['mplayer', '-fps', '25', '-cache', '1024', '-']
player = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
while True:
    data = sock.recv(1024)
    if not data:
        break
    player.stdin.write(data)

rawDescription: Python: Play Video file from a Buffer

description: Python: Play Video file from a Buffer


rawDescription: Any simple python package providing dict merge?


rawDescription: Creating a boolean array by testing if each element in numpy array is between 2 numbers


code:
class C:
    def __init__(self):
        self.attr1 = 12345

    @property
    def synonym(self):
        return self.attr1

    @synonym.setter
    def synonym(self, value):
        self.attr1 = value

rawDescription: Point two variables to the same value in Python


rawDescription: Create python string with fill char and counter


code:
# create query order by monthly price
base_query = Contract.query.order_by(Contract.monthly_price)

# build subqueries for each network
queries = []
for n in networks.all():
    queries.append( base_query.filter(Contract.network_id==n.id).\
                        limit(3).subquery().select() )

# get contracts using union_all
contracts = Contract.query.select_entity_from(union_all( *queries )).all()

rawDescription: SQLalchemy top 3 results from each category


code:
newurl = '/my/new/route?' + urllib.urlencode(self.request.params)
self.redirect(newurl)

rawDescription: How to make a redirect and keep the query string?

description: Make a redirect and keep the query string


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
for tag in soup():
    del tag['style']
    del tag['class']
    if tag.name == 'div':
        tag.name = 'p'
return soup.body.encode_contents()

rawDescription: Replace HTML tags preserving their content using lxml


code: variable = int(variable)

rawDescription: How do I make my program acknowledge that a variable contains an integer in Python

description: Make my program acknowledge that a variable contains an integer in Python


code: [x for x in xrange(First_Number, Last_Number+1) for y in xrange(Repeat_Count)]

rawDescription: List Comprehension Instead of Nested For Loops for Repeated Number List


code:
class MyGame:          # define the class
    def play(self):    # each method gets an instance passed as "self"
        self.p1 = input("Enter player 1's name ")    # attributes can be assigned on self
        self.p2 = input("Enter player 2's name ")
        self.round1()
        self.round2()

    def random_weapons(self):
        weapons = ["Stick", "Baseball bat", "Golf club", "Cricket bat", "Knife"]
        self.w1 = random.choice(weapons)
        self.w2 = random.choice(weapons)
        print(self.p1 + " has found a " + self.w1) # and looked up again in other methods
        print(self.p2 + " has found a " + self.w2)

    def round1(self):
        print("Lets pick weapons for Round 1")
        self.random_weapons()

    def round2(self):
        print("Lets pick weapons for Round 2")
        self.random_weapons()

def main():
    game = MyGame()  # create the instance
    game.play()      # call the play() method on it, to actually start the game

rawDescription: How do I pass variables around in python

description: Pass variables around in python


rawDescription: Django: How to programatically change superuser and/or staff status of a user


code:
import pythoncom
import win32com.client as wc
from win32com.axcontrol import axcontrol
import win32com.server as ws
from win32com.server import util
from win32com.server.exception import COMException
import winerror
import pywintypes

# Windows Media Player Custom Interface IWMPRemoteMediaServices
IWMPRemoteMediaServices = pywintypes.IID("{CBB92747-741F-44FE-AB5B-F1A48F3B2A59}")

class OleClientSite:
    _public_methods_ = [ 'SaveObject', 'GetMoniker', 'GetContainer', 'ShowObject', 'OnShowWindow', 'RequestNewObjectLayout', 'QueryService' ]
    _com_interfaces_ = [ axcontrol.IID_IOleClientSite, pythoncom.IID_IServiceProvider ]

    def SaveObject(self):
        print("SaveObject")
        raise COMException(hresult=winerror.E_NOTIMPL)

    def GetMoniker(self, dwAssign, dwWhichMoniker):
        print("GetMoniker ")
        raise COMException(hresult=winerror.E_NOTIMPL)

    def GetContainer(self):
        print("GetContainer")
        raise COMException(hresult=winerror.E_NOTIMPL)

    def ShowObject(self):
        print("ShowObject")
        raise COMException(hresult=winerror.E_NOTIMPL)

    def OnShowWindow(self, fShow):
        print("ShowObject" + str(fShow))
        raise COMException(hresult=winerror.E_NOTIMPL)

    def RequestNewObjectLayout(self):
        print("RequestNewObjectLayout")
        raise COMException(hresult=winerror.E_NOTIMPL)

    def QueryService(self, guidService, riid):
        print("QueryService",guidService,riid)
        if riid == IWMPRemoteMediaServices:
            print("Known Requested IID, but can't implement!")
            raise COMException(hresult=winerror.E_NOINTERFACE)
        else:
            print("Requested IID is not IWMPRemoteMediaServices" )
            raise COMException(hresult=winerror.E_NOINTERFACE)

if __name__=='__main__':
    wmp = wc.Dispatch("WMPlayer.OCX")
    IOO = wmp._oleobj_.QueryInterface(axcontrol.IID_IOleObject)
    pyOCS = OleClientSite()
    comOCS = ws.util.wrap(pyOCS, axcontrol.IID_IOleClientSite)
    IOO.SetClientSite(comOCS)

rawDescription: Heavily confused by win32api + COM and an answer from SO


code:
d = {'user':'amarillion', 'pass':'*****' }
server.login(**d)

rawDescription: SOAPpy - reserved word in named parameter list


code:
def startCallBack():
    myJob.start()

rawDescription: Stopping a python thread from a tkinter gui


code:
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider

auth_provider = PlainTextAuthProvider(username='cassandra',
                                      password='cassandra')
cluster = Cluster(auth_provider=auth_provider)

rawDescription: Python Cassandra 2 authentication with SASL


code:
foo = 'Stackoverflow is best '
import re
foo = re.sub(r'^\s*|\s*$', r'"""', foo)
foo

rawDescription: Python : How to insert special character


code:
if len(products_to_sync) != 0:
        for product in data:
            # pdb.set_trace()
            Store_Name = str('voylla retail pvt ltd')
            sku = str(product[2])
            size = str(product[3])
            threep_number =  str(product[1])
            qty = int(product[7])
            leadtime = int(product[8])
            mod = str(product[11])
            none = str('None')
            if mod == none:
                leadtime = 2
            replicable = str('Yes')
            product_obj = Product.objects.get(threep_number=threep_number)
            channel_sku = self.threep_sku_mapping_method(channel,product_obj)
            # pdb.set_trace()
            if channel_sku != 0:
                sku=str(channel_sku)
                if qty == 0:
                    continue
                else:
                    csvresultwriter.writerow(['%s'%Store_Name,'%s'%sku,'%s'%size,'%s'%threep_number,'%d'%qty,'%d'%leadtime,'%s'%replicable])
        email = EmailMessage(subject='CBazaar Quantity Sync Details File', body='PFA CSV File attached with this mail.', from_email='help@voylla.com',
            to=['abhishek.g@qa.voylla.com'],
            headers = {'Reply-To': '3pcatalogging@voylla.in'})
        # Attach csv file
        email.attach("cbazaar_quantity_sync_"+task_start_time+".csv", csvresult.getvalue(), 'text/csv')
        # Send message with built-in send() method
        email.send()
else:
     self.stdout.write('No products to sync with CBazaar.')

rawDescription: How to stop mails to be sent if the attachment data is empty in python?

description: Stop mails to be sent if the attachment data is empty in python


code:
# xedges, yedges as returned by 'histogram2d'

# create an array for the output quantities
avgarr = np.zeros((nbins, nbins))

# determine the X and Y bins each sample coordinate belongs to
xbins = np.digitize(x, xedges[1:-1])
ybins = np.digitize(y, yedges[1:-1])

# calculate the bin sums (note, if you have very many samples, this is more
# effective by using 'bincount', but it requires some index arithmetics
for xb, yb, v in zip(xbins, ybins, verification):
    avgarr[yb, xb] += v

# replace 0s in H by NaNs (remove divide-by-zero complaints)
# if you do not have any further use for H after plotting, the
# copy operation is unnecessary, and this will the also take care
# of the masking (NaNs are plotted transparent)
divisor = H.copy()
divisor[divisor==0.0] = np.nan

# calculate the average
avgarr /= divisor

# now 'avgarr' contains the averages (NaNs for no-sample bins)

rawDescription: find mean bin values using histogram2d python

description: Find mean bin values using histogram2d python


code:
from glob import iglob
import shutil
import os

PATH = r'C:\music'

destination = open('everything.mp3', 'wb')
for filename in iglob(os.path.join(PATH, '*.mp3')):
    shutil.copyfileobj(open(filename, 'rb'), destination)
destination.close()

rawDescription: How do I concatenate files in Python?

description: Concatenate files in Python


code:
length = int(input())
s = input()
count = 0
# i: the head index of substring
# j: the tail index of substring, and len(substring) <=length
for i in range(len(s)):
    for j in range(min(length, len(s) - i)):
        if s[i] == s[i + j]:
            count += 1

print(count)

rawDescription: speed up python nested loop

description: Speed up python nested loop


code:
def steps1d(self, ns):
    return 2*sc.random.random_integers(0, 1, size=ns)-1

def Walk1d(self, ns=None):
    if ns is None:
        ns = self.ns
    return sc.cumsum(self.steps1d(ns))

rawDescription: python how to overload maybe?? the constructor

description: Python how to overload maybe?? the constructor


code:
l = [[1, 2], [2, 3], [4, 5]]

out = open('out.csv', 'w')
for row in l:
    for column in row:
        out.write('%d;' % column)
    out.write('\n')
out.close()

rawDescription: How do I write data to csv file in columns and rows from a list in python?

description: Write data to csv file in columns and rows from a list in python


code:
class PostDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.ui = Ui_Dialog() #code from designer!!
        self.ui.setupUi(self)

        self.ui.plainTextEdit.installEventFilter(self)

    def eventFilter(self, event):
        if event.type() == QtCore.QEvent.KeyPress:
            # do some stuff ...
            return True # means stop event propagation
        else:
            return QtGui.QDialog.eventFilter(self, event)

rawDescription: PyQt: how to receive keyboard events in a subclassed QWidget?


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.website.com/a2b.php")

def find_by_xpath(locator):
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, locator))
    )

    return element

class FirstFormPage(object):
  def fill_form(self):
    find_by_xpath('//input[@name="t1"]').send_keys('200')
    find_by_xpath('//input[@name="t2"]').send_keys('250')
    find_by_xpath('//input[@name="t3"]').send_keys('300')

    return self # makes it so you can call .submit() after calling this function

  def submit(self):
    find_by_xpath('//input[@value = "ok"]').click()

class SecondFormPage(object):
  def fill_form(self):
    find_by_xpath('//input[@name="timestamp"]').send_keys('1445368847')
    find_by_xpath('//input[@name="timestamp_checksum"]').send_keys('JEN8mj')
    find_by_xpath('//input[@name="ckey"]').send_keys('20040')
    find_by_xpath('//input[@name="id"]').send_keys('39')
    find_by_xpath('//input[@name="a"]').send_keys('533374')
    find_by_xpath('//input[@name="c"]').send_keys('3')

    return self # makes it so you can call .submit() after calling this function

  def submit(self):
    find_by_xpath('//input[@value = "ok"]').click()

FirstFormPage().fill_form().submit()
SecondFormPage().fill_form().submit()
driver.quit() # closes the webbrowser

rawDescription: Python mechanize - Submit form twice

description: Python mechanize - Submit form twice


rawDescription: how to add all of these values in a python dictionary

description: Add all of these values in a python dictionary


code:
offset = len(lines) / 2

if offset % 2 != 0:
    # ensure that the second col does not contain more than the first one
    offset += 1

lines_col0 = lines[:offset]
lines_col1 = lines[offset:]

rawDescription: How to get the half part of forloop in django template

description: Get the half part of forloop in django template


code: a, b, c = shareVars['a'], shareVars['b'], shareVars['c']

rawDescription: Pass variables back to the invoker of a Python interactive console session


rawDescription: Extracting a URL's in Python from XML

description: Extracting a URL's in Python from XML


code:
while True:
    num = input('your number please :')
    if isinstance(num, int) and num > 17:
        print('your abs value is : {0}'.format((num-17)*2))
        break
    else:
        print ('bad value')

rawDescription: invalid syntax in while loop

description: Invalid syntax in while loop


code: foreign_key_field = models.ForeignKey("keyname", default=1)

rawDescription: Default for dropdown menu in Django admin


code:
import wx

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)

        for i in range(5):
            self.test.InsertColumn(i, 'Col %d' % (i + 1))
            self.test.SetColumnWidth(i, 200)

        for i in range(0, 100, 5):
            index = self.test.InsertStringItem(self.test.GetItemCount(), "")
            for j in range(5):
                self.test.SetStringItem(index, j, str(i+j)*30)

        self.Show()

app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()

rawDescription: wxpython - Expand list control vertically not horizontally

description: Wxpython - Expand list control vertically not horizontally


code:
a3 = f.iloc[:, 8] - f.iloc[:, 9]
a4 = 100 * f.iloc[:, 2]
a5 = f.iloc[:, 10] - f.iloc[:, 11]
toappend = pd.concat([a3, a4, a5], axis=1).rename(columns=dict(zip(range(3), list('abc'))))
toappend.tail()
res = m.append(f.iloc[:, [0, 3, 4, 5, 1, 6, 7]].join(toappend))
res.tail()[['a', 'b', 'c']]

rawDescription: Append to dataframe from another with calculations


code:
import locale
import string
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
string.letters
locale.setlocale(locale.LC_ALL, 'de_DE')
string.letters

rawDescription: How to find out which chars are defined as alphanumeric for a given locale

description: Find out which chars are defined as alphanumeric for a given locale


code: from dbapi2 import *

rawDescription: 'from sqlite3 import dbapi2 as sqlite3' vs 'import sqlite3'?


code:
s=np.argsort(X)
np.take(Y,s)

rawDescription: Sort 2D numpy array (by row) based on another 2D array of same shape


code:
import wx
class DisplayText(wx.Dialog):

    def __init__(self, parent, text="", displayMode=0):

        # Initialize dialog
        wx.Dialog.__init__(self, parent, size=(480,320), style=( wx.DIALOG_EX_METAL | wx.STAY_ON_TOP ) )

        # Center form
        self.Center()

        # (For Mac) Setup a panel
        self.panel = wx.Panel(self)

        # Create text field
        self.txtField = wx.StaticText(self.panel, label=text, pos=(80,120), size=(320,200), style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ST_NO_AUTORESIZE)
        self.txtField.SetFont(wx.Font(24, wx.DEFAULT, wx.BOLD, 0))
        self.txtField.SetAutoLayout(False)

app = wx.App(False)

c = DisplayText(None, text="Now is the time for all good men to come to the aid of their country.")
c.Show()
app.MainLoop()

rawDescription: Python/WXWidgets: ST_NO_AUTORESIZE not being honored for wx.StaticText


code:
import shutil

src = "Folder1/Folder2/file1"
dst = "Folder3"+src
dstfolder = os.path.dirname(dst)
shutil.copytree(src,dstfolder)

rawDescription: How to copy all the files in certain Directory and recreate the directory structure dynamically using python

description: Copy all the files in certain Directory and recreate the directory structure dynamically using python


code:
from django.contrib import admin
from myapp.models import Contestant

def send_mail(modeladmin, request, queryset):
    for obj in queryset:
        obj.send_registration_email()

make_published.short_description = "Resend activation mails for selected users"

class ContestantAdmin(admin.ModelAdmin):
    list_display = [...]
    ordering = [...]
    actions = [send_mail]

admin.site.register(Contestant, ContestantAdmin)

rawDescription: Django: Exposing model method to admin

description: Django: Exposing model method to admin


code:
import wx
import cv2

#----------------------------------------------------------------------

class webcamPanel(wx.Panel):

    def __init__(self, parent, camera, fps=10):
        wx.Panel.__init__(self, parent)

        self.camera = camera

        ret_value, frame = self.camera.read()
        height, width = frame.shape[:2]

        # resize panel with camera image
        self.SetSize( (width, height) )

        # resize main window
        self.GetParent().GetParent().SetSize( (width, height+75) )

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame = cv2.flip(frame, 1)
        self.bmp = wx.BitmapFromBuffer(width, height, frame)

        self.timer = wx.Timer(self)
        self.timer.Start(1000./fps)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_TIMER, self.NextFrame)

    def OnPaint(self, e):
        dc = wx.BufferedPaintDC(self)
        dc.DrawBitmap(self.bmp, 0, 0)

    def NextFrame(self, e):
        ret_value, frame = self.camera.read()
        if ret_value:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.flip(frame, 1)
            self.bmp.CopyFromBuffer(frame)
            self.Refresh()

#----------------------------------------------------------------------

class webcamWindow(wx.Frame):

    def __init__(self, camera, fps=10):
        wx.Frame.__init__(self, None)

        self.panel = wx.Panel(self, -1)

        # add panel with webcam image
        self.webcampanel = webcamPanel(self.panel, camera)

        # get size of webcam panel
        webcampanelsize = self.webcampanel.GetSize()

        # put button below webcam panel
        self.but = wx.Button(self.panel, label="Capture", pos=(0, webcampanelsize.height), size=(webcampanelsize.width,75))

#----------------------------------------------------------------------

camera = cv2.VideoCapture(0)

app = wx.App()
cap = webcamWindow(camera)
cap.Show()
app.MainLoop()

rawDescription: wxPython button widget won't move

description: WxPython button widget won't move


code: i, j, k, l = (collections.deque() for _ in xrange(4))

rawDescription: Copy an empty deque

description: Copy an empty deque


code:
from flask_classy import FlaskView

class TaskView(FlaskView):
    def index(self):
        """Return a list of all tasks."""
        pass

    def get(self, id):
        """Get a specific task."""
        pass

    def delete(self, id):
        """Delete the task."""
        pass

TaskView.register(app)

rawDescription: How to define a base route in Flask API routing system

description: Define a base route in Flask API routing system


code:
vs = Operator.objects.filter(DisplayName="Jimmy",
                             TransactionSummary__StartTime__gte=tz.localize(datetime(year=2013, month=10, day=1)),
                             AlertSummary__StartTime__gte=tz.localize(datetime(year=2013, month=10, day=1)))\
    .values("DisplayName")\
    .annotate(TotalTransactions=Sum("TransactionSummary__TransactionCount"),
              TotalAlerts=Sum("AlertSummary__AlertScore"))

rawDescription: Avoiding cartesian product with Django

description: Avoiding cartesian product with Django


code:
import tkinter as tk
from tkinter import *
from tkinter import ttk

LARGE_FONT = ("Times New Roman", 12)
NORM_FONT = ("Times New Roman", 10)

class DIS(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default="")
        tk.Tk.wm_title(self, "program")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)

        self.name = StringVar()
        self.frames = {}

        for F in (StartPage, contactQues, nameVerify):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row = 0, column = 0, sticky = "nsew")

            self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        button2 = ttk.Button(self, text = "Name Select",
                        command=lambda:           controller.show_frame(contactQues))
        button2.pack()

class contactQues(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        label1 = tk.Label(self, text = "Select Your Name", font = LARGE_FONT)
        label1.pack(pady=10, padx=10)

        button2 = ttk.Button(self, text = "Bojangles", command = self.bojangles)
        button2.pack(pady=5)

    def bojangles(self):

        self.controller.name.set("Mr. Bojangles")
        self.controller.show_frame(nameVerify)
    #
    #Many other names to select
    #

class nameVerify(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        label5 = tk.Label(self, text = "Your Name:", font = LARGE_FONT)
        label5.pack(pady=10, padx=10)
        labelcontact = tk.Label(self, textvariable = self.controller.name, font = NORM_FONT)
        labelcontact.pack()

app = DIS()
app.mainloop()

rawDescription: Can't access variable from other class - tkinter


code:
frozenset(Counter([1, 1, 1, 2, 3, 3, 4]).iteritems())
hash(frozenset(Counter([1, 1, 1, 2, 3, 3, 4]).iteritems()))
hash(frozenset(Counter([1, 1, 1, 2, 3, 4]).iteritems()))

rawDescription: Hashing an immutable dictionary in Python


code:
set_db = set( (row.rev,row.revision) for row in exists_row )
for k,v in files.items():
    if (v['rev'],v['revision']) in set_db:
        del(files[k])

rawDescription: Python list/dict comparisons performance


code:
import binascii
binascii.unhexlify("02")
'\x3c' + _

rawDescription: Python String of Hex to Hex (with leading zeros)


code:
words = ['xoo', 'dsd', 'xdd']
sorted(words, key=lambda x: (x[0] != 'x', x))

rawDescription: A more pythonic way to write this expression?


code:
from google.appengine.ext.ndb import model

class User(model.Model):
   name = model.StringProperty()

users, cursor, more = User.query(User.name == "Jon").fetch_page(25)

if more:
    # Do next page logic
    next_users = User.query(User.name == "Jon").fetch_page(25, start_cursor=cursor)

rawDescription: cursor and with_cursor() in GAE

description: Cursor and with_cursor() in GAE


code:
tokens = ("LBRACKET", "RBRACKET",
          "INTEGER", "FLOAT", "COMMA") # So we can add other tokens
t_LBRACKET = r'\('
t_RBRACKET = r'\)'
t_INTEGER = r'\d+'
t_FLOAT = r'\d+\.\d+'
t_COMMA = r','

def p_list(p):
    """list : LBRACKET sequence RBRACKET
            | LBRACKET RBRACKET"""
    if len(p) == 4:
        p[0] = p[2]
    else:
        p[0] = None

def p_number(p):
    """number : INTEGER
              | FLOAT"""
    p[0] = p[1]

def p_sequence(p):
    """sequence : list_el COMMA sequence
                | list_el"""
    if len(p) == 4:
        p[0] = p[1] + p[3]
    else:
        p[0] = p[1]

def p_list_el(p):
    """list_el : number
               | list"""
    p[0] = p[1]

rawDescription: Recursive Descent Parser using Python and PLY


code:
from azure.servicebus import ServiceBusService
import json;

sbs = ServiceBusService("your_namespace",
                        shared_access_key_name="your_policy_name",
                        shared_access_key_value="your_policy_secret")

# build dictionary and send value
temp = {'DeviceId': 'dev-01', 'Temperature': str(i)}
sbs.send_event('woodstove2', json.dumps(temp))

rawDescription: How do you send a variable to Azure Event Hubs using Python SDK

description: Send a variable to Azure Event Hubs using Python SDK


code:
import urllib

data = self.request.GET.copy() # or data = urlparse.parse_qs(self.request.query)
data['channel_pageno'] = 1

uri = urllib.urlencode(data)

rawDescription: How to manipulate query string?

description: Manipulate query string


code:
ax.annotate('line1 \n line2', xy=(timeNow, y),  xycoords='data',
            xytext=(-50, 30), textcoords='offset points',
            arrowprops=dict(arrowstyle="->"),
            verticalalignment='center',
            horizontalalignment='center'
            )

rawDescription: matplotlib multiple line annotation

description: Matplotlib multiple line annotation


code:
import re
s = 'Hello, my name is [name] and I am [age] years old'
re.split(r'(\[|\])', s)

rawDescription: Splitting stings but keeping "split" character


code:
lst = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
idx, maxLenStr = max(enumerate(lst), key=lambda x:len(x[1]))
sublist = lst[:idx]

rawDescription: Python:How can i get all the elements in a list before the longest element?


code: [(i, j) for i in range(3) for j in range(3) if board[i][j] == 0]

rawDescription: Python List Indexes

description: Python List Indexes


code:
from datetime import datetime
import pytz

tz = pytz.timezone('US/Eastern') #NOTE: deprecated timezone name

naive_utc_dt = datetime.utcnow()                # naive datetime object
utc_dt = naive_utc_dt.replace(tzinfo=pytz.utc)  # aware datetime object
east_dt = utc_dt.astimezone(tz)                 # convert to Eastern timezone
naive_east_dt = east_dt.replace(tzinfo=None) #XXX use it only if you have to

rawDescription: Convert UTC native datetime to Eastern tine native datetime for pymongo


code:
from pprint import pprint
my_var = ['one', 'two', ('red','green'), {'state' : 'Oregon', 'city' : 'Portland'}]
pprint(my_var, width=1)

rawDescription: How to force pprint to print one list/tuple/dict element per line?

description: Force pprint to print one list/tuple/dict element per line


code:
import subprocess
import os
p = Popen(os.path.join(os.path.expanduser('~'), os.path.expandvars('%Test%'),
    'helper.chm'), shell=True)

rawDescription: python import system variable path to working script to work with subprocess.Popen

description: Python import system variable path to working script to work with subprocess.Popen


code:
import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

rawDescription: urllib2 with cookies

description: Urllib2 with cookies


code:
x = np.random.randint(0, 4, 32)
x
(x + np.random.randint(1, 4, 32)) % 4

rawDescription: How can I create a subset of the 'most dissimilar' arrays from a set of possible combinations?

description: Create a subset of the 'most dissimilar' arrays from a set of possible combinations


code: re.sub(r'[^a-zA-Z]', '', mystring)

rawDescription: Replace any character outside of the English alphabet in Python?


code:
m = 0xFFFFFF00
allf = 0xFFFFFFFF
~m & allf

rawDescription: Python: unsigned 32 bit bitwise arithmetic


code: results_patientalerts = db.GqlQuery("SELECT * FROM PatientAlerts WHERE patientinfo_ID = :1 AND alert_type != :2", data_key, 3)

rawDescription: app engine python gql query not running

description: App engine python gql query not running


code:
# these are all of your j values
inds = np.arange(0,SRpixels)

# these are the j values you don't want to skip
sel = np.invert((abs(SR_pointCloud[inds,0]) > SR_xMax) | (SR_pointCloud[inds,2] > SR_zMax) | (SR_pointCloud[inds,2] < 0))

RIGrid1_Location[sel,0] = np.floor(((SR_pointCloud[sel,0] + xPosition + 5) - xGrid1Center) / gridSize)
RIGrid1_Location[sel,1] = np.floor(((SR_pointCloud[sel,2] + yPosition) - yGrid1LowerBound) / gridSize)
RIGrid2_Location[sel,0] = np.floor(((SR_pointCloud[sel,0] + xPosition + 5) - xGrid2Center) / gridSize)
RIGrid2_Location[sel,1] = np.floor(((SR_pointCloud[sel,2] + yPosition) - yGrid2LowerBound) / gridSize)

rawDescription: For loop speed with Numpy

description: For loop speed with Numpy


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

fig = plt.figure()
ax = fig.add_subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)

coords_to_annote = [(2,1),(3,1),(4,1)]

for coords in coords_to_annote:
    ax.annotate('local max', xy=coords, xytext=(3, 1.5),
                arrowprops=dict(facecolor='black', shrink=0.05),
                )

ax.set_ylim(-2,2)
plt.show()

rawDescription: How can I have one annotation pointing to several points in matplotlib?

description: Have one annotation pointing to several points in matplotlib


code:
db.collection.aggregate([
    { "$group": {
        "_id": None,
        "client_timestamp": { "$min": "$client_timestamp" }
    }}
])

rawDescription: Returning minimum value for a ISODate value in a collection


code:
import re
s = "CPP" # to C++
rx = r"(?<=\bC)P+\b"
res = re.sub(rx, (lambda m: "%s"%("+" * len(m.group(0)))), s)
print(res)

rawDescription: Replace characters and wrap them in a tag, using one regular expression


code:
import random

# You can do this once in your program
lines = open('filename').read().splitlines()

# Whenever you need a new random line, you do this
randomline = random.choice(lines)

rawDescription: (Python) How to make python program take a random line from a .txt file?


code:
import shlex
s = shlex.shlex("command 'my \'ugly\' argument' other \"arguments\" and options", posix=True)
s.whitespace_split = True
s.commenters = ''
next(s)
next(s)
s.instream.read()

rawDescription: Split into N elements a string by spaces preserving quoted substrings


code:
# alpha is increasing. This is because the updates of Cov are
# bringing in too much numerical error that is greater than
# than the remaining correlation with the
# regressors. Time to bail out

description: Sklearn.linear_model.LassoLarsIC Early stopping


code:
try:
    from Tkinter import *
except ImportError:
    from tkinter import *

def print_entry_value(*args):
    print(v.get())

root = Tk()
v = StringVar()
v.trace('w', print_entry_value)
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

rawDescription: How to change order for tkinter binds

description: Change order for tkinter binds


code: final_list = zip(list1, list2, list3)

rawDescription: creating a special kind of merged list within a list in django

description: Creating a special kind of merged list within a list in django


code:
import copy

class ProjectViewSet(viewsets.ModelViewSet):

      ...

      def create(self, request, *args, **kwargs):
          data = copy.deepcopy(request.data)
          data['creator_id'] = request.user.id
          request._data = data

          return super(ProjectViewSet, self).create(request, *args, **kwargs)

rawDescription: Python Django RestFramework route trigger


code:
like_button = driver.find_element_by_css_selector(".single_like_button.btn3-wrap > div.btn3")
like_button.click()

rawDescription: Social Exchange bot Stuck at button click


code:
import mayavi.mlab as mlab
import matplotlib.pyplot as plt

# create and capture a mlab object
mlab.test_plot3d()
img = mlab.screenshot()
mlab.close()

# create a pyplot
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.plot([0,1], [1,0], 'r')

# add the screen capture
ax2 = fig.add_subplot(122)
ax2.imshow(img)
ax2.set_axis_off()

rawDescription: Combining mayavi and matplotlib in the same figure


rawDescription: Python: change labels of a plot using matplotlib


code:
class beer(models.Model):
    tapStatus = models.BooleanField(_('tap status'), default=False,
            help_text=_('decide whether or not this item gets pasted onto the website'))
    def __unicode__(self):
        return str(self.tapStatus)
    beerdescription = models.CharField(max_length=400)
    def __unicode__(self):
        return self.beerdescription
    beerStyle = models.CharField(max_length=5)
    def __unicode__(self):
        return self.beerStyle
    beerabv = models.CharField(max_length=5)
    def __unicode__(self):
        return self.beerabv
    beername = models.CharField(max_length=40)
    def __unicode__(self):
        return self.beername

rawDescription: How do i replace the charfield with a checkbox in django admin

description: Replace the charfield with a checkbox in django admin


code:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("outlook")
shell.AppActivate("Outlook")
shell.SendKeys("^o", 0) # 1 für Pause = true 0 für nein
shell.SendKeys("^a", 0)
shell.SendKeys("^c", 0)

rawDescription: how to open a program in python and send keystrokes?

description: Open a program in python and send keystrokes


code:
# loop continuously
while True:
    # get the input and store it in the variable inp
    inp = int(input("Input an integer (0 terminates): "))
    # break the loop if inp equals 0
    if inp == 0:
        break
    # do stuff to the input

rawDescription: Get input for a while statement

description: Get input for a while statement


code:
tps = df5.pivot_table(values=['Total_Products_Sold'],
                      index='Week_Days',
                      columns='Category',
                      aggfunc='sum')

tps = tps.div(tps.sum(1), axis=0)
tps.plot(kind='bar', stacked=True)

rawDescription: Python Pandas: Plotting 100% stacked graph issue


code:
class Id_Class(object):
    new_id   = itertools.count(1000).next
    order_id = itertools.count(1000).next
    person_id= itertools.count(1000).next

    @staticmethod
    def new_id(t):   # t = type of id required
        if t == "Order":
            return Id_Class.order_id()
        elif t == "Person":
            return Id_Class.person_id()

rawDescription: Creating a Class to generate IDs

description: Creating a Class to generate IDs


code:
from datetime import datetime
import pandas.io.data as web
from pandas.tseries.offsets import BDay

df = pd.read_csv(path_to_file).loc[:, ['symbols']].dropna().squeeze()

symbols = []
for ticker in df.tolist():
    r = web.DataReader(ticker, "yahoo",
                   start= datetime.now() - BDay(20),
                   end= datetime.now())

    r['Symbol'] = ticker
    symbols.append(r)
df = pd.concat(symbols).drop('Close', axis=1)
cell= df[['Symbol','Open','High','Low','Adj Close','Volume']]
cell.reset_index().sort_values(['Symbol', 'Date'], ascending=[1,0]).set_index('Symbol').to_csv(path_to_file, date_format='%d/%m/%Y')

rawDescription: Saving to_csv read just the columns, not the rows


code:
existing = {"a": 1, "b": 2, "c": 3}
inbound = {"b": 3, "c": 4, "d": 5}
permitted = {"a","b","c"}
existing.update((key, val) for (key, val) in inbound.items() if key in permitted)

rawDescription: What's the most pythonic way to copy JSON fields to another JSON structure?


code:
import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
if y == x:
    print(1)
elif y == 1:         # see georg's comment
    print(x)
elif y > x:          # will be executed only if y != 1 and y != x
    print(0)
else:                # will be executed only if y != 1 and y != x and x <= y
    a = math.factorial(x)
    b = math.factorial(y)
    c = math.factorial(x-y)  # that appears to be useful to get the correct result
    div = a // (b * c)
    print(div)

rawDescription: Python Binomial Coefficient

description: Python Binomial Coefficient


code:
import numpy as np

arr = np.eye(3)
np.apply_along_axis(np.count_nonzero, 0, arr)

rawDescription: How to apply a function to all the column of a numpy matrix?

description: Apply a function to all the column of a numpy matrix


code:
def send_mail(large=True):
    """Send 5 emails, 1 minute apart."""
    for _ in range(5):
        # send an email here, large or small.
        if large:
            send_large_email()
        else:
            send_small_email()
        wait()  # 1 minute

def wait(mins=1):
    time.sleep(mins * 60)

def main():
    start = time.time()
    day = 24 * 60 * 60
    while time.time() - start < day:
         send_mail()
         wait(5)  # wait 5 minutes
         send_mail(large=False)
         wait(5)

rawDescription: How do I create this loop of sending large email and small email every 1min within a 5min interval

description: Create this loop of sending large email and small email every 1min within a 5min interval


code:
class MyModel(models.Model):
    pass

for label in labels:
    MyModel.add_to_class(label, models.CharField(max_length=255))

rawDescription: Django - Creating model fields from list with for loop


code:
from itertools import takewhile
input = '123abc456def'
''.join(takewhile(str.isdigit, input))

rawDescription: Cleanest way to obtain the numeric prefix of a string


code:
@classmethod
def entity_from_dict(cls, parent_key, dict):
    valid_properties = {}
    for cls_property in cls._properties:
        if cls_property in dict:
            valid_properties.update({cls_property: dict[cls_property]})
    #logging.info(valid_properties)
    # Update the id from the dict
    if 'id' in dict: # if creating a new entity
            valid_properties['id'] = dict['id']
    # Add the parent
    valid_properties['parent'] = parent_key
    try:
        entity = cls(**valid_properties)
    except Exception as e:
        logging.exception('Could not create entity \n' + repr(e))
        return False
    return entity

rawDescription: GAE converting dictionary to NDB datastore entity


code:
class EditedAddress(models.Model):
    class Meta:
        verbose_name = 'Edited Address'
        verbose_name_plural = 'Edited Addresses'

rawDescription: Label name for ModelAdmin in Django

description: Label name for ModelAdmin in Django


code:
def update_ball(self, dx, dy, screen_w, screen_h):  #added screen width and height parameters
    self.x += self.dx
    self.y += self.dy
    if self.y > screen_h:
        self.y -= 5
        self.dy *= -1
    elif self.y < 0:
        self.y += 5
        self.dy *= -1
    if self.x > screen_w:
        self.x -= 5
        self.dx *= -1
    elif self.x < 0:
        self.x += 5
        self.dx *= -1

rawDescription: How to make the ball bounce from top to bottom?

description: Make the ball bounce from top to bottom


code:
url = "https://manager.gimbal.com/api/" # Note you'll need to customize this
headers = {'Authorization': 'Token <server api key>'}
r = requests.get(url, headers=headers)

rawDescription: Python API connnection issue/ not sure what they are asking


code: result = sum(data.values())

rawDescription: JSON Object parsing: Loop through dynamic data


code:
import json, os
from django.core.urlresolvers import resolve
from your_project_dir.settings import BASE_DIR

local_file_path = '{0}/{1}/{2}'.format(resolve(request.path).app_name, 'statics', 'd.json')
global_file_path = os.path.join(BASE_DIR, local_file_path)

with open(global_file_path, 'w') as outfile:
   json.dump(data, outfile)

rawDescription: How to store json data in static file in Django view, and call this function from another function ?

description: Store json data in static file in Django view, and call this function from another function


code:
from collections import Counter

text = open("test_file.txt").read().lower()
letter_freqs = Counter(text)

word_freqs = Counter(text.split())

rawDescription: Text file probability calculation (Markov Chain) - Python


code:
d ={}
for i in tup : d[li.index(i[0])] = i
list(d.values())

rawDescription: Sort a list of tuples using index position of items in another list


code: np.einsum( "ik,ikl->il", A,B )

rawDescription: Pairwise product between array of vectors and array of matrices


code:
nums = [1, 2, 3]
interp = [num + (dec / 10.)
          for num in nums
          for dec in range(10)
          if num + (dec / 10.) <= max(nums)]

rawDescription: Interpolating integer list by fixed decimal increments in Python


code:
mydict={"fork" : True, "form" : True, "fold" : True, "fame" : True}
[k for k in mydict if k.startswith("for")]

rawDescription: autocomplete-like feature with a python dict

description: Autocomplete-like feature with a python dict


rawDescription: Python equivalent to Matlab function 'ellipke'


code:
header_row = 0

# build list of lists that represents row values in worksheet,
# including column names from header row
rows = [worksheet.row_values(row) for row in range(worksheet.nrows)]

# extract list of column names to use for insert statement, values to be inserted remain
columns = rows.pop(header_row)

cnxn = pyodbc.connect(r"DRIVER={SQL Server};SERVER=XXXXXXXXXX\DEV_CON1;DATABASE=GGG;UID=AAA_dbo;PWD=XXXXXXXXX;")
cursor = cnxn.cursor()

# list of column names used to build SQL statement, including parameter placeholders (?)
populate_db = "insert into tblSnap_TEST ({}) values ({})".format(', '.join(columns),
                                                                 ', '.join('?' * len(columns)))

# insert is executed once for each sequence of parameter values
cursor.executemany(populate_db, rows)
cnxn.commit()
cnxn.close()

rawDescription: Assigning Values to Variables from List in Python 2.7


code:
# initialize correct vectors
l1=Lat[:-1]      # all points but last
l2=Lat[1:]       # all points but first
lg1=Long[:-1]
lg2=Long[1:]
t1=Time[:-1]
t2=Time[1:]

speed(l1,lg1,t1,l2,lg2,t2)    # call the function which will run over your arrays

rawDescription: Repeating a function throughout a dataset


code:
import subprocess
subprocess.call(["shutdown", "-f", "-r", "-t", "10", "-c", '"MESSAGE HERE"'])

rawDescription: How to change the shutdown message for Windows using python?

description: Change the shutdown message for Windows using python


code:
with open("output.csv", "ab") as f:
    for ind1,key1 in enumerate(file1):
        for ind2,key2 in enumerate(file2):
            ques1 = file1[key1]
            ques2 = file2[key2]
            match_ratio = difflib.SequenceMatcher (None, ques1, ques2).ratio()
            n = csv.writer(f)
            n.writerow([key1, ques1, key2, ques2, match_ratio])

rawDescription: Python 2.7.10 csv how to write each version of an iterating output in a new row


code:
try:
    # Win32
    from msvcrt import getch
except ImportError:
    # UNIX
    def getch():
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            return sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)

rawDescription: How to do "hit any key" in python?

description: Do "hit any key" in python


code:
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(your_dates, your_data)

# format your data to desired format. Here I chose YYYY-MM-DD but you can set it to whatever you want.
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# rotate and align the tick labels so they look better
fig.autofmt_xdate()

rawDescription: Format of datetime in pyplot axis

description: Format of datetime in pyplot axis


code:
import subprocess
import sys

def open_folder(path):
    if sys.platform == 'darwin':
        subprocess.check_call(['open', '--', path])
    elif sys.platform == 'linux2':
        subprocess.check_call(['gnome-open', '--', path])
    elif sys.platform == 'win32':
        subprocess.check_call(['explorer', path])

open_folder(path=".") # open current directory

rawDescription: How to open current working directory (OS X/Linux/Win)

description: Open current working directory (OS X/Linux/Win)


code:
sentence = input('Please Enter a Sentence: ')
number   = input('Please Enter a Number: ')

shift   = int(number)
letters = list(sentence)
cipher  = ''

ceasar = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

for letter in letters:
    if letter in ceasar:
        oldindex = ceasar.index(letter)
        newindex = (oldindex + shift) % len(ceasar)
        newletter = ceasar[newindex]
    else:
        newletter = letter

    print(letter, end="")
    cipher += newletter

rawDescription: How to make a caesar cipher work with input that has spaces in Python

description: Make a caesar cipher work with input that has spaces in Python


code:
import pygame
from itertools import cycle

pygame.init()

screen = pygame.display.set_mode((300, 300))
# move inside the screen (or any other Rect)
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()

speed = 5
up, down, left, right = (0, -speed), (0, speed), (-speed, 0), (speed, 0)
dirs = cycle([up, right, down, left])
dir = next(dirs)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    # move player
    player.move_ip(dir)
    # if it's outside the screen
    if not s_r.contains(player):
        # put it back inside
        player.clamp_ip(s_r)
        # and switch to next direction
        dir = next(dirs)

    screen.fill(pygame.color.Color('Black'))
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

    pygame.display.flip()
    timer.tick(25)

rawDescription: Moving the image in a square fashion with pygame


rawDescription: Python regular expression that matches floating point numbers


code:
def __setstate__(self, state):
    self.__dict__.update(state)
    # do other things that need to be set on unpickling.

rawDescription: __new__ not calling __init__ when correct class


code:
from Tkinter import *

class Example:
    def __init__(self, master):
        self.startButton = Button(master,text='Start', command=self.start)
        self.startButton.grid(row=0, column=0)

        self.stopButton = Button(master, text='Stop', command=self.stop)
        self.stopButton.grid(row=0, column=1)

        self.textBox = Text(master, bd=2)
        self.textBox.grid(row=1, columnspan=2)

    def start(self):
        self.count = 0
        self.cancel_id = None
        self.counter()

    def counter(self):
        self.textBox.delete("1.0", END)
        if self.count < 10:
            self.count += 1
            self.textBox.insert(END, str(self.count)+'\n\n')
            self.cancel_id = self.textBox.after(1000, self.counter)

    def stop(self):
        if self.cancel_id is not None:
            self.textBox.after_cancel(self.cancel_id)
            self.cancel_id = None

root=Tk()
Example(root)
root.mainloop()

rawDescription: How to stop a running function without exiting the Tkinter window entirely?

description: Stop a running function without exiting the Tkinter window entirely


code:
from Crypto.Cipher import AES
import base64

AES.key_size=128
iv="your iv"
key="your key"
crypt_object=AES.new(key=key,mode=AES.MODE_CBC,IV=iv)

decoded=base64.b64decode(plain) # your ecrypted and encoded text goes here
decrypted=crypt_object.decrypt(decoded)

rawDescription: Encrypt in PHP, Decrypt in Python

description: Encrypt in PHP, Decrypt in Python


code:
import plistlib
import pprint
import subprocess

output = subprocess.check_output(('/usr/sbin/diskutil', 'list', '-plist'))
diskutil = plistlib.readPlistFromString(output)
pprint.pprint(diskutil)

rawDescription: Python - identify the type of device

description: Python - identify the type of device


code:
func_list = [func1, func2, func3]
random.choice(func_list)()

rawDescription: Is there a better way to run a randomly chosen function?


code:
def __init__(self, **kwargs):
    self.__dict__.update( kwargs )

rawDescription: setattr with kwargs, pythonic or not?

description: Setattr with kwargs, pythonic or not


rawDescription: Simpler way to break a list of comma separated values into many lists in Python 3


rawDescription: Python port binding

description: Python port binding


code:
import markdown2
rawtext = "Getting the Gist of Markdown's Formatting Syntax\n------------------------------------------------\nThis page offers a brief "
markdown2.markdown(rawtext)

rawDescription: not getting expected result from python markdown

description: Not getting expected result from python markdown


code:
if pygame.key.get_pressed()[pygame.K_ESCAPE]:
     pygame.quit()

rawDescription: Pygame event queue

description: Pygame event queue


code:
with open('test.csv','r') as input_csv, open('output.csv','w',newline='') as output_csv:
    reading = csv.reader(input_csv)
    writing = csv.writer(output_csv)
    data = [next(reading)]
    previous_row = next(reading)
    for row in reading:
            if row[0] == '':
                    previous_row.append(row[2])
            else:
                    previous_row = ["'{}'".format(previous_row[0]), "'{}'".format(previous_row[1]),"'{}'".format(', '.join(previous_row[2:]))]
                    data.append(previous_row)
                    previous_row = row
    previous_row = ["'{}'".format(previous_row[0]), "'{}'".format(previous_row[1]),"'{}'".format(', '.join(previous_row[2:]))]
    data.append(previous_row)
    writing.writerows(data)

rawDescription: python: changing variable in a row based on previous line

description: Python: changing variable in a row based on previous line


code:
def pw_gen():
    key = zip(string.digits, string.ascii_uppercase)

    cruft, x = str(random.random()).split('.')

    def f(i,e):
      Q = random.random()
      if Q > 0.7:
        return e[1].lower()
      else:
        return e[1]

    return [ f(item,element) for item in x for element in key if item in element ]

rawDescription: Better way to write this "double-barreled list" in Python


code: print (results[0][0])

rawDescription: How to print postgresql timestamp in python

description: Print postgresql timestamp in python


code:
ds = [dict(w.split('=', 1) for w in x) for x in s]
pd.DataFrame.from_records(ds)

rawDescription: Parsing key-value pairs into DataFrame columns


code:
weekNum = "week" + str(i)               #i is either 2, 3, 4, 5
query = "select {0} from golden_table where nGram = %s and hash_tag = %s".format(weekNum)
cur.execute(query, (tup[0], tup[1]))

rawDescription: python StringBuilder for MySQL query execution

description: Python StringBuilder for MySQL query execution


code: iter(fileobj.readline, '')

rawDescription: Why is iter not a method of an instance and __iter__ is?


code:
from selenium import webdriver
from selenium.webdriver.phantomjs.service import Service
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver

class PhantomJSService(webdriver.PhantomJS):
    def __init__(self, executable_path="phantomjs", port=0,
                 desired_capabilities=DesiredCapabilities.PHANTOMJS,
                 service_args=None, service_log_path=None):

        self.service = Service(executable_path,
                               port=port, service_args=service_args,
                               log_path=service_log_path)
        self.service.start()

        try:
            RemoteWebDriver.__init__(self,
                command_executor=self.service.service_url,
                desired_capabilities=desired_capabilities)
        except:
            self.quit()
            raise

rawDescription: Webdriver phantomjs no longer following link on click


code: {{ json.key1 }}

rawDescription: Accessing dictionary by key in Django template


code:
with open('myfile.text') as f:
    lines = islice(f, 5, 11)

rawDescription: Python - grab lines from text file, lines x-y


code:
INSTALLED_APPS = [
  # always on apps
]

from gargoyle import gargoyle
if gargoyle.is_active('my_switch'):
    INSTALLED_APPS.append('my_conditional_app')

rawDescription: Use Disqus' gargoyle for whole apps

description: Use Disqus' gargoyle for whole apps


rawDescription: Refining Re Search

description: Refining Re Search


code:
for r in res:
    r.update(r.pop('some_key', {}))

rawDescription: Python loops vs comprehension lists vs map for side effects (i.e. not using return values)


rawDescription: Game ai Line of Sight Python

description: Game ai Line of Sight Python


code:
import wx

########################################################################
class TestPopup(wx.PopupWindow):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, style):
        """Constructor"""
        wx.PopupWindow.__init__(self, parent, style)

        panel = wx.Panel(self)
        self.panel = panel
        panel.SetBackgroundColour("CADET BLUE")

        st = wx.StaticText(panel, -1,
                           "This is a special kind of top level\n"
                           "window that can be used for\n"
                           "popup menus, combobox popups\n"
                           "and such.\n\n"
                           "Try positioning the demo near\n"
                           "the bottom of the screen and \n"
                           "hit the button again.\n\n"
                           "In this demo this window can\n"
                           "be dragged with the left button\n"
                           "and closed with the right."
                           ,
                           pos=(10,10))
        sz = st.GetBestSize()
        self.SetSize( (sz.width+20, sz.height+20) )
        panel.SetSize( (sz.width+20, sz.height+20) )

        panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
        panel.Bind(wx.EVT_MOTION, self.OnMouseMotion)
        panel.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
        panel.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)

        st.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
        st.Bind(wx.EVT_MOTION, self.OnMouseMotion)
        st.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
        st.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)

        wx.CallAfter(self.Refresh)

    def OnMouseLeftDown(self, evt):
        self.Refresh()
        self.ldPos = evt.GetEventObject().ClientToScreen(evt.GetPosition())
        self.wPos = self.ClientToScreen((0,0))
        self.panel.CaptureMouse()

    def OnMouseMotion(self, evt):
        if evt.Dragging() and evt.LeftIsDown():
            dPos = evt.GetEventObject().ClientToScreen(evt.GetPosition())
            nPos = (self.wPos.x + (dPos.x - self.ldPos.x),
                    self.wPos.y + (dPos.y - self.ldPos.y))
            self.Move(nPos)

    def OnMouseLeftUp(self, evt):
        if self.panel.HasCapture():
            self.panel.ReleaseMouse()

    def OnRightUp(self, evt):
        self.Show(False)
        self.Destroy()

########################################################################
class TestPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        btn = wx.Button(self, label="Open Popup")
        btn.Bind(wx.EVT_BUTTON, self.onShowPopup)

    #----------------------------------------------------------------------
    def onShowPopup(self, event):
        """"""
        win = TestPopup(self.GetTopLevelParent(), wx.SIMPLE_BORDER)

        btn = event.GetEventObject()
        pos = btn.ClientToScreen( (0,0) )
        sz =  btn.GetSize()
        win.Position(pos, (0, sz[1]))

        win.Show(True)

########################################################################
class TestFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Test Popup")
        panel = TestPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = TestFrame()
    app.MainLoop()

rawDescription: wxPython popup window bound to a wxButton

description: WxPython popup window bound to a wxButton


rawDescription: Python regex example

description: Python regex example


rawDescription: Get list from pandas DataFrame column headers


code:
from itertools import takewhile

h3s = soup('h3') # find all <h3> elements
for h3, h3next in zip(h3s, h3s[1:]):
  # get elements in between
  between_it = takewhile(lambda el: el is not h3next, h3.nextSiblingGenerator())
  # extract text
  print(''.join(getattr(el, 'text', el) for el in between_it))

rawDescription: Retrieve all content between a closing and opening html tag using Beautiful Soup


code:
import Image, io, base64

data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

im = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))
im.save("image.jpg")

rawDescription: base64 URI to PNG-Python

description: Base64 URI to PNG-Python


code:
from bs4 import BeautifulSoup
import re

soup = BeautifulSoup('
 blabla
 and
blabla
')
soup.find_all('p', onclick=re.compile('.'))

rawDescription: BeautifulSoup webscrape, isolate specific tag with random html class


code:
from collections import Counter

counts = Counter()
for d in data:
    k, v = d['addr'], d['cnt']
    counts[k] += v

relevant = counts.most_common(50)

rawDescription: find and sum repeating repeating dictionary elements

description: Find and sum repeating repeating dictionary elements


code: vmin, vmax = plt.gci().get_clim()

rawDescription: How to get current plot's clim in matplotlib

description: Get current plot's clim in matplotlib


code: matrix[j, min(max(0,lim1),n):min(max(0,lim2),n)] = 0

rawDescription: Arrays indexing

description: Arrays indexing


rawDescription: How do I "randomly" select numbers with a specified bias toward a particular number


rawDescription: Python: how to compute covariance matrix and export data like a map structure


code:
import networkx as nx

n1, n2 = 10, 10

# Define two random graphs
g1 = nx.gnm_random_graph(n1,20)
g2 = nx.gnm_random_graph(n2,20)
pos1 = nx.graphviz_layout(g1,prog='dot')
pos2 = nx.graphviz_layout(g2,prog='dot')

# Shift graph2
shift = 400
for key in pos2:
    pos2[key] = (pos2[key][0]+shift, pos2[key][1])

# Combine the graphs and remove all edges
g12 = nx.disjoint_union(g1,g2)
for i,j in g12.edges():
    g12.remove_edge(i,j)

# Add the conjoined edges
g12.add_edge(5, 7+n1)
g12.add_edge(2, 3+n1)
g12.add_edge(8, 7+n1)

# Set the new pos for g12
pos12 = pos1.copy()
for node in pos2:
    pos12[node+n2] = pos2[node]

# Show the results, make the conjoined edges darker

import pylab as plt
nx.draw_networkx(g1,pos=pos1,alpha=0.5)
nx.draw_networkx(g2,pos=pos2,alpha=0.5)
nx.draw_networkx_edges(g12,pos=pos12,width=5)
plt.axis('off')
plt.show()

rawDescription: Drawing a graph partition with the networkX package in Python


rawDescription: Django: Sort database import by the last entry first and so on


code:
#!/usr/bin/env python
import sys
n = int(sys.argv[1])
data = sys.stdin.read()
print(data[::n])

rawDescription: Output every nth byte of stdin

description: Output every nth byte of stdin


rawDescription: Numpy minimum in (row, column) format

description: Numpy minimum in (row, column) format


code:
class BaseHandler(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)
        country = self.request.headers.get('X-AppEngine-Country')
        if not country == "US" and not country == "" and not country == None: # The last two handle local development
            self.redirect('international_holding_page')
            logging.info(country)

rawDescription: Is there a way to handle requests with locale-dependant wsgi handlers?


code:
list_of_dicts = []

dict1 = {'Source': 'Log1', 'Type': 'Connection', 'Datetime': '2014-02-13 14:10:00', 'fullpath':'N/A'}
dict2 = {'Source': 'Log2', 'Type': 'Disconnect', 'Datetime': '2014-05-13 11:00:00', 'fullpath':'N/A'}
dict3 = {'Source': 'Log4', 'Type': 'Other', 'Datetime': '2014-05-10 02:50:00', 'fullpath':'N/A'}

list_of_dicts.append(dict1)
list_of_dicts.append(dict2)
list_of_dicts.append(dict3)

d = {d['Datetime']:d for d in list_of_dicts} # dictionary comprehension

for k in sorted(d.keys()):
    print(d[k])

rawDescription: Python list of Dictionaries, sort and print values by chronological order


code:
import numpy as np

mask = (z['b'] != 0)
z_valid = z[mask]

z['c'] = 0
z.loc[mask, 'c'] = z_valid['a'] / np.log(z_valid['b'])

rawDescription: Pandas apply but only for rows where a condition is met


code:
import os
import pandas as pd

def get_data():
    current_directory=os.getcwd()
    workbook_clients=pd.ExcelFile(current_directory+"/Documents/clients.xlsx")
    data=pd.io.excel.ExcelFile.parse(workbook_clients)
    return data

clients = get_data()
print(clients)

rawDescription: Calculating python variable only once

description: Calculating python variable only once


code:
def MasterTab():
    btn = cmds.button(label='Press Me')
    # use a '#' in the name to get a unique number suffix....
    edit_me = cmds.text('edit_me#', label='Hello')

    # define the handler here, when you know what 'edit_me' is...
    def change_text(_):
        cmds.text(edit_me, e=True, label = 'bye')

    # now attach the command...
    cmds.button(btn, e=True, c=change_text)

rawDescription: Maya UI - A master in every Tab

description: Maya UI - A master in every Tab


code:
#!/usr/bin/python

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from_adr='foo@example.com'
to_adr='bar@example.com'

msg = MIMEMultipart('alternative')
msg['Subject'] = "Emailing a link"
msg['From'] = from_adr
msg['To'] = to_adr

html = """

Link:

    Link Text

"""

part1=MIMEText(html, 'html')
part2=MIMEText("Link:\nhttp://www.somewhere.com/whatever.foo", 'text')

msg.attach(part1)
msg.attach(part2)

s = smtplib.SMTP('localhost')
s.sendmail(from_adr, to_adr, msg.as_string())
s.quit()

rawDescription: How to make link in message body with Python

description: Make link in message body with Python


code:
foo = __import__('foo')
for attr in dir(foo):
    if not attr.startswith('_'):
        globals()[attr] = getattr(foo, attr)

rawDescription: Dynamically importing Python modules

description: Dynamically importing Python modules


code:
counts = {}
for f in filenames:
    for val in [s.strip() for s in open(f).readlines()]:
        counts[val] = counts.get(val, 0) + 1

rawDescription: How do i make a Histogram spanning multiple files?

description: Make a Histogram spanning multiple files


code:
order_of_3rd = [3,0,1,2]
My_table.sort(key=lambda a: (a[0], order_of_3rd.index(a[2])))

rawDescription: python: sort table (list of lists) according to specific ordered list (and other options)

description: Python: sort table (list of lists) according to specific ordered list (and other options)


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

def get_main_screen_text():
    text = "\n       [Anyfusion Monitoring System]\n\n"
    return text

class Tom(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)
        vbox1 = wx.BoxSizer(wx.VERTICAL)
        vbox2 = wx.BoxSizer(wx.VERTICAL)
        self.message = get_main_screen_text()

        self.write = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE, value=self.message)
        System_Checkup = wx.Button(panel, 1, label='System_Checkup')
        Open_the_Web = wx.Button(panel, 1, label=' Open_the_Web ')
        Help_Desk = wx.Button(panel, 1, label=' Help_Desk ')
        Exit = wx.Button(panel, 1, label=' Exit ')

        vbox1.Add(self.write, 1, wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT | wx.BOTTOM, 15)
        vbox2.Add(System_Checkup, 0, wx.TOP | wx.TOP  | wx.RIGHT, 15)
        vbox2.Add(Open_the_Web, 0, wx.TOP | wx.RIGHT, 15)
        vbox2.Add(Help_Desk, 0, wx.TOP, 230)
        vbox2.Add(Exit, 0, wx.TOP | wx.RIGHT, 15)
        vbox.Add(vbox1, 1, wx.EXPAND)
        vbox.Add(vbox2, 0, wx.TOP)
        self.Bind(wx.EVT_BUTTON, self.EventHandler, id=1)
        panel.SetSizer(vbox)
        self.Centre()

    def EventHandler(self, event):
        b=event.GetEventObject().GetLabel()
        if b.endswith('System_Checkup'):
            self.message = self.message+"\nABC"
            self.write.SetValue(self.message)
            self.write.SetEditable(False)
            self.write.SetScrollPos(wx.VERTICAL,0)
            self.write.SetFocus()
            self.write.SetInsertionPointEnd()
            self.write.Refresh()

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

if __name__ == "__main__":
    app = MyApp()
    app.MainLoop()

rawDescription: WxPython[TextCtrl] : The way of locate the cursor to end of text using TextCtrl function.


code:
import re
regex = re.compile(r'#[0-9A-F]+')

test_string = '#4A#61#76#61#53#63#72#69#70#74'
for hex_string in re.findall(regex, test_string):
  test_string = test_string.replace(hex_string, chr(int(hex_string.replace('#', ''), 16)))

test_string

rawDescription: Search for word that may have hex characters


code:
g = gevent.spawn_later(5, function)
g.kill()

rawDescription: Is there a way to cancel gevent.spawn_later()?


code:
import pandas as pd
from datetime import datetime
d = {'ru' : pd.Series([1., 1., 1.,1, 3]),
   'case' : pd.Series([2., 2., 2., 2., 2]),
      'opdate' : pd.Series([datetime(2012, 5, 2), datetime(2012, 5, 2), datetime(2012, 5, 2),datetime(2012, 5, 2), datetime(2012, 5, 2)]),
   'lst_svc' : pd.Series([datetime(2012, 5, 2), datetime(2012, 5, 3), datetime(2012, 5, 5),datetime(2012, 5, 5),datetime(2012, 6, 5)])}

df=pd.DataFrame(d)

def f(s):
    s2 = pd.Series(0, index=s.index)
    s2.iloc[-1] = 1
    return s2

df["lastMark"] = df.groupby(['ru','case','opdate'])['lst_svc'].apply(f)
df

rawDescription: mark last record in group by date pandas python

description: Mark last record in group by date pandas python


code:
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

if settings.DEBUG:
    urlpatterns += patterns(
        '',
        url(
            r'^media/(?P<path>.*)$',
            'django.views.static.serve', {
                'document_root': settings.MEDIA_ROOT,
            }
        ),
    )

urlpatterns += staticfiles_urlpatterns()

rawDescription: Django Ckeditor image browser not finding images


code:
with open('file1.json', 'r') as f:
    data2 = {tuple(int(x) for x in k.split(',')): v
        for (k, v) in json.load(f).items()}

rawDescription: Reading numeric keys from JSON file

description: Reading numeric keys from JSON file


code: list(range(1, 2))

rawDescription: openpyxl - populating a column using a list

description: Openpyxl - populating a column using a list


code:
n = netaddr.IPNetwork('10.10.8.0/22')
list(n.subnet(24))
[str(sn) for sn in n.subnet(24)]

rawDescription: Need to break down a IP subnet

description: Need to break down a IP subnet


code: plotfile(os.path.join(pathname,'foo.csv'), names=['a', 'b', 'c', 'd', 'e', 'f'], cols=(3,5), skiprows=0, delimiter=',', label='Series')

rawDescription: Pylab plotfile() skips the first row of a file with no header - how to stop this?


code:
class MixinAB(object):

    def test_autoslug_generaton(self):
        """ test automatically generated slug """
        assert self.object.code == self.slug

    def test_return_correct_name(self):
        """ test the __unicode__() method """
        assert self.object.__unicode__() == self.name

class TestA(MixinAB, TestCase):
    """ Test the A model """

    def setUp(self):
        self.name = 'A'
        self.slug = 'a'
        self.object = A.objects.create(name=self.name)

rawDescription: Django: optimize test that violates DRY

description: Django: optimize test that violates DRY


code:
number_unigrams = tokens.count(k[0])
prob = v / number_unigrams

rawDescription: how can I divide the frequency of bigram pair by unigram word?

description: Divide the frequency of bigram pair by unigram word


code:
def retrieve_input():
    global vehicle_registration
    global vehicle_time
    global vehicle_distance
    vehicle_registration = veh_reg_text_box.get()
    vehicle_time = time_text_box.get()
    vehicle_distance = distance_text_box.get()
    number_checker()

rawDescription: How do I store a text entry as a variable in Tkinter?

description: Store a text entry as a variable in Tkinter


code:
import site
site.addsitedir("x:/path/to/perforce/directory")
# you can add more folders the same way

rawDescription: Add enviroment variable for python with batch


code:
def save(self, *args, **kwargs):
    # save the instance, do this first so that we have an id
    super(MyModelClass, self).save(*args, **kwargs)
    # if it was a new instance fid is not set yet
    if self.id and not self.fid:
        self.fid = encode(self.id)
        # save the instance again now that we've set fid
        super(MyModelClass, self).save(*args, **kwargs)

rawDescription: Django Save method needs to update model instance twice


code:
# setup.py

from setuptools import find_packages, setup

setup(
    #...
    packages=find_packages(exclude='tests'),
    #...
)

rawDescription: Is there an easier way to package with Python?


code: test_dict = dict((x, dict()) for x in ['k1', 'k2'])

rawDescription: Passing in a new value to each key using Python's `dict.fromkeys`


code:
starter = tf.constant(0)
z_initial = tf.constant([], dtype=tf.int32)

def body(hops, z_prev):
    hops = tf.add(hops, 1)
    z_next = tf.concat(0, [z_prev, tf.expand_dims(hops, 0)])
    return hops, z_next
def condition(hops, z):
    return tf.logical_and(tf.less(tf.gather(
        argmax_ep_gate_array_concat, hops), story_len), tf.less(hops, tf.constant(20)))

self.gate_index, self.z = tf.while_loop(condition,body,[starter, z_initial])

rawDescription: TensorFlow stuck into endless loop using tf.while_loop()


code:
from collections import Counter

items = Counter()
with open('data_file.txt', 'r') as f:
    for line in f:
        items.update(line.split())

print("Total Unique Items: {0}".format(len(items)))

for item, count in items.most_common(5):
    print("Item {0} was purchased {1} times".format(item, count))

rawDescription: how to find unique items in a total data set

description: Find unique items in a total data set


code: int("".join(str(X) for X in x))

rawDescription: Converting a list of integers into a single value


code:
from datetime import datetime, timedelta

query = MyModel.gql("WHERE date > :1 ORDER BY plays DESC", datetime.now() - timedelta(days=7))
count = query.count()
if count < 50:
   query = MyModel.gql("WHERE date > :1", datetime.now() - timedelta(days=10))
value = query.fetch()

rawDescription: get entities for last 7 days in datastore

description: Get entities for last 7 days in datastore


code:
from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')

rawDescription: Capturing a single image from my webcam in Java or Python


rawDescription: how to switch into a single database among multiple databases at run time in django?

description: Switch into a single database among multiple databases at run time in django


code:
from random import choice

solider_long = ['1', '2', '3']

solider_speed = [ '4', '5', '6']

solider_block = [ '4', '5', '6']

# save the choices in a variable
choice_solider_close = choice(solider_close)
choice_solider_long = choice(solider_long)
choice_solider_speed = choice(solider_speed)
choice_solider_block = choice(solider_block)

print ("You choose solider")
print ("Your stats: close combat : " + choice_solider_close)
print ("            long range combat : " + choice_solider_long)
print ("            long range combat : " + choice_solider_speed)
print ("            long range combat : " + choice_solider_block)
print ("Press Y to continue")

rawDescription: Saving a random choice and using it later


code:
re.search("brown fox\W+(?:\w+\W+){1,4}lazy dog", s)
re.search("brown fox\W+(?:\w+\W+){1,3}lazy dog", s)
re.search("brown fox\W+(?:\w+\W+){1,2}lazy dog", s)

rawDescription: counting number of words between two strings python regexp

description: Counting number of words between two strings python regexp


code:
p = subprocess.Popen(['path/to/long/runnning/process', 'arg1', 'arg2'])
...
p.terminate()  # kill the process.

rawDescription: Is there a way I can close an exe from python


code:
out_char = ctypes.c_char()
result = lib.test(ctypes.byref(out_char))

rawDescription: Define array type in Python to be filled by C function


code:
def scrub(table_name):
    return ''.join( chr for chr in table_name if chr.isalnum() )

scrub('); drop tables --')  # returns 'droptables'

rawDescription: variable table name in sqlite

description: Variable table name in sqlite


code:
from ctypes import *
import numpy as np

__all__ = ['GetImage']

# WinDLL is stdcall; use CDLL for cdecl.
Wlib = WinDLL(r'C:\...\Wsl.dll')

Wlib.GetImage.argtypes = ([c_char_p, c_int, c_char_p] +
                          [c_int] * 6 +
                          [c_void_p])

def GetImage(name, ID, strLibPath, Lvl=0,
             rbeg=100, rend=1099,
             cbeg=5500, cend=6499,
             ZLayer=0, nBpp=24):
    roiW = cend - cbeg + 1
    roiH = rend - rbeg + 1
    nch = nBpp // 8
    img = np.zeros([roiW, roiH, nch], dtype=np.uint8)
    ImgBuffer = img.ctypes
    status = Wlib.GetImage(name, ID, strLibPath, Lvl,
                           rbeg, rend, cbeg, cend,
                           ZLayer, ImgBuffer)
    # test status
    return img

rawDescription: Python Numpy Array Ctypes Pointer

description: Python Numpy Array Ctypes Pointer


code:
class GetFoosAndResponses(generics.ListAPIView):
    # init stuff here

    def list(self, request):
        foo_queryset = Foo.objects.filter(owner=request.user)
        foo_serializer = FooSerializer(foo_queryset, many=True)

        foo_response_queryset = FooResponse.objects.filter(owner=request.user)
        foo_response_serializer = FooResponseSerializer(foo_response_queryset, many=True)

        return Response(foo_serializer.data + foo_response_serializer.data, status=status.HTTP_200_OK)

rawDescription: How to combine two similar views into a single response?

description: Combine two similar views into a single response


code:
reform = {(outerKey, innerKey): values for outerKey, innerDict in dictionary.iteritems() for innerKey, values in innerDict.iteritems()}
reform
pandas.DataFrame(reform)

rawDescription: Nested dictionary to multiindex dataframe where dictionary keys are column labels


code:
#!/usr/bin/python

from socket import *
#import re

HOST = 'localhost'  # server IP
PORT = 21567        # port
BUFSIZ = 1024
ADDR = (HOST, PORT)
#ip = re.compile(r'([0-9\.]{1,3}){4}')

def validate_ip(ip):
    try:
        if inet_aton(ip):
           return True
    except:
        return False

def query():
    while True:
        hostc = raw_input('Host: ')
        portc = raw_input('Port: ')
        if (portc and validate_ip(hostc)):
            try:
                tcpCliSock.connect(hostc, int(portc))
                break
            except:
                pass
            #print("\nInvalid Entry.\n")
        else:
            tcpCliSock.connect(ADDR)
            break

tcpCliSock = socket(AF_INET, SOCK_STREAM)   # allocate client's socket
query()

rawDescription: Taking input for HOST/PORT else connect with default HOST/PORT


rawDescription: How to show multiple plots with big differences in y-values in matplotlib?

description: Show multiple plots with big differences in y-values in matplotlib


code:
import tempfile, smtplib, os, sys

# Find an available file descriptor
t = tempfile.TemporaryFile()
available_fd = t.fileno()
t.close()

# now make a copy of stderr
os.dup2(2,available_fd)

# Now create a new tempfile and make Python's stderr go to that file
t = tempfile.TemporaryFile()
os.dup2(t.fileno(),2)

# Now run the task that logs to stderr
s = smtplib.SMTP("mx10.comcast.com")
s.set_debuglevel(1)
s.sendmail("no-such-sender@comcast.com",["no-such-receiver@comcast.com"],"""
from: no-such-sender@comcast.com
to: no-such-receiver@comcast.com
subject: no such message

This message won't be delivered to anybody.
""")

# Grab the stderr from the temp file
sys.stderr.flush()
t.flush()
t.seek(0)
stderr_output = t.read()
t.close()

# Put back stderr
os.dup2(available_fd,2)
os.close(available_fd)

# Finally, demonstrate that we have the output:
print("STDERR:")
count = 0
for line in stderr_output.decode('utf-8').split("\n"):
    count += 1
    print("{:3} {}".format(count,line))

rawDescription: capture debug output from python smtplib

description: Capture debug output from python smtplib


code:
def findval(str):
    val = []
    for x in str.split(','):
        if '-' in x:
           lnum, rnum = x.split('-')
           lnum, rnum = int(lnum), int(rnum)
           val.extend(range(lnum, rnum + 1))
        else:
           lnum = int(x)
           val.append(lnum)
    return val
findval('001,008-011,020')

rawDescription: Expand a string describing a set of numbers noted as a list of numbers and/or ranges


code:
my_dict = {'ABC': True}
'ABC' in [my_dict]  # False
'ABC' in my_dict  # True

rawDescription: How do I compare a string to a unicode dictionary?

description: Compare a string to a unicode dictionary


code:
def send_mail_multi(headers, text, msgHtml="", orig=None):
    """
    """

    msg = MIMEMultipart('mixed')
    # Create message container - the correct MIME type is multipart/alternative.
    body = MIMEMultipart('alternative')

    for k,v in headers.items():
        if isinstance(v, list):
            v = ', '.join(v)
        msg.add_header(k, v)

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    if orig is not None:
        text, msgHtml2 = append_orig_text(text, msgHtml, orig, False)

        # Fix subject
        msg["Subject"] = "RE: "+orig["Subject"].replace("Re: ", "").replace("RE: ", "")
        msg['In-Reply-To'] = orig["Message-ID"]
        msg['References'] = orig["Message-ID"]#+orig["References"].strip()
        msg['Thread-Topic'] = orig["Thread-Topic"]
        msg['Thread-Index'] = orig["Thread-Index"]

    body.attach(MIMEText(text, 'plain'))
    if msgHtml != "":
        body.attach(MIMEText(msgHtml2, 'html'))
    msg.attach(body)

    send_it(msg)

def append_orig_text(text, html, orig, google=False):
    """
    Append each part of the orig message into 2 new variables
    (html and text) and return them. Also, remove any
    attachments. If google=True then the reply will be prefixed
    with ">". The last is not tested with html messages...
    """
    newhtml = ""
    newtext = ""

    for part in orig.walk():
        if (part.get('Content-Disposition')
            and part.get('Content-Disposition').startswith("attachment")):

            part.set_type("text/plain")
            part.set_payload("Attachment removed: %s (%s, %d bytes)"
                        %(part.get_filename(),
                        part.get_content_type(),
                        len(part.get_payload(decode=True))))
            del part["Content-Disposition"]
            del part["Content-Transfer-Encoding"]

        if part.get_content_type().startswith("text/plain"):
            newtext += "\n"
            newtext += part.get_payload(decode=False)
            if google:
                newtext = newtext.replace("\n","\n> ")

        elif part.get_content_type().startswith("text/html"):
            newhtml += "\n"
            newhtml += part.get_payload(decode=True).decode("utf-8")
            if google:
                newhtml = newhtml.replace("\n", "\n> ")

    if newhtml == "":
        newhtml = newtext.replace('\n', '
')

    return (text+'\n\n'+newtext, html+'
'+newhtml)

rawDescription: Reply to email using python 3.4

description: Reply to email using python 3.4


code:
from Tkinter import *

root = Tk()
root.wm_title("Title:D")

root.geometry('{}x{}'.format(500, 300))

##photo = PhotoImage(file="spaz.gif")
label = Label(root, text="Label 1")
label.grid(row=1, column=1)

root.grid_columnconfigure(2, weight=1)

w = Label(root, text="This label", fg="red", font=("Helvetica", 16))
w.grid(row=5, column=20)

root.mainloop()

rawDescription: Python tkinter grid manager not working, columns


code:
from __future__ import print_function

import json

r = ...
data = json.loads(r)

latlng = data['results'][0]['locations'][0]['latLng']
latitude = latlng['lat']
longitude = latlng['lng']

print(latitude, longitude)  # 33.663512 -111.958849

rawDescription: Flask python json parsing

description: Flask python json parsing


code:
from bitstring import BitString
s = BitString(filename='somefile')

# replace byte range with new values
# The step of '8' signifies byte rather than bit indicies.
s[10:15:8] = '0x001122'

# Search and replace byte value with two bytes
s.replace('0xcc', '0xddee', bytealigned=True)

# Different interpretations of the data are available through properties
if s[5:7:8].int > 1000:
    s[5:7:8] = 1000

# Use the bytes property to get back to a Python string
open('newfile', 'wb').write(s.bytes)

rawDescription: Alternatives to using pack_into() when manipulating a list of bytes?


code: [x for x in itertools.product("01",repeat=2)]

rawDescription: Print all of the possible combinations with numbers


code:
# you should probably store person records in a data structure
persons = []

def read_persons_config_file(filename):
    # this method will read the line separated person records from the persons file
    # it will use methods like [open][4] to access the file and [readlines][5] to use data
    # it should probably call read_person_file() on each record
    # this method can maintain a list of persons
    pass

def read_person_file(filename):
    # this method should read a single person record and store it in a [data structure][6]
    # of your choice. I'd recommend you go with [dictionaries][7], but there are many
    # alternatives
    # this method should either return a result to the caller (the data structure you chose)
    # or append the data structure to a list of data structures (persons) you've created
    pass

rawDescription: building a boolean array from many text files using python

description: Building a boolean array from many text files using python


code:
# in /a/b/c/d/e/file.py
import os
os.path.dirname(os.path.abspath(__file__)) # /a/b/c/d/e

rawDescription: Get location of the .py source file

description: Get location of the .py source file


code:
def compose(f, g):
    return lambda x: f(g(x))

def do(func):
    print (func(6))

def a(x):
    return x*2

def b(x):
    return x*3

combinedAB = compose(a,b)
do(combinedAB)

rawDescription: Pass function of function as parameter

description: Pass function of function as parameter


code:
def fib(n):
    if n < 2:
        return 1
    return fib(n-1) + fib(n-2)

def centrecoords(max_n):
    # initial values
    k = 0
    l = 1
    result=(0,-1)
    # note fib(0) == fib(1) == 1
    for n in range(2,max_n):
        if n % 2 == 0:
            result = (result[0], result[1] + ((-1) ** k) * fib(n - 2))
            yield result
            if k % 2 == 0:
                k += 1
        else:
            result = (result[0] + ((-1) ** l) * fib(n - 2), result[1])
            yield result
            if l % 2 == 0:
                l += 1

cen_coords = list(centrecoords(21))

rawDescription: Alternating counters in Python (Fibonacci Plot)


code:
from mpl_toolkits.axes_grid1 import make_axes_locatable

ax1 = plt.subplot2grid((1,1), (0,0))
divider = make_axes_locatable(ax1)
ax2 = divider.append_axes("bottom", size="100%", pad=0.5)
ax3 = divider.append_axes("bottom", size="100%", pad=1)

rawDescription: Adjust the distance only between two subplots in matplotlib


code:
import re

def tryint(s):
    try:
        return int(s)
    except:
        return s

def alphanum_key(s):
    """ Turn a string into a list of string and number chunks.
        "z23a" -> ["z", 23, "a"]
    """
    return [ tryint(c) for c in re.split('([0-9]+)', s) ]

def sort_nicely(l):
    """ Sort the given list in the way that humans expect.
    """
    l.sort(key=alphanum_key)

rawDescription: How do you sort files numerically?

description: Sort files numerically


code:
import base64
encoded = base64.b64encode(open("filename.png", "rb").read())

rawDescription: How do you base-64 encode a PNG image for use in a data-uri in a CSS file?

description: Base-64 encode a PNG image for use in a data-uri in a CSS file


code:
x = linspace(0, 2*pi, 1000)
plot(x, sin(x)), plot(x, cos(x))

rawDescription: ipython qtconsole: drawing multiple functions inside one plot

description: Ipython qtconsole: drawing multiple functions inside one plot


code:
#! /usr/bin/python3
import time

m = [ [c for c in line] for line in '''............................
..XXXXXXXXXX...........XXX..
..X........X...........X.X..
..XXXXXX...X....XXXXXXXX.X..
.......X...X....X........X..
....XXXX...XXXXXX........X..
....X....................X..
....X.................XXXX..
....XXXXXXXXXXXXXXXXXXX.....'''.split ('\n') ]

def flood (matrix, start):
    maxX = len (matrix [0] )
    maxY = len (matrix)
    tbf = [start]
    while tbf:
        x, y = tbf [0]
        tbf = tbf [1:]
        if x < 0 or x >= maxX or y < 0 or y >= maxY: continue
        if matrix [y] [x] == 'X': continue
        matrix [y] [x] = 'X'
        tbf += [ (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) ]
        print ('\x1b[0J\x1b[1;1H') #Clear screen and position cursor top left
        for line in matrix: print (''.join (line) )
        time.sleep (.2)

#flood (m, (0, 0) )
flood (m, (4, 2) )

rawDescription: Animate flood fill in python

description: Animate flood fill in python


code:
with open('filename.csv') as csvfile:
    data = [(int(x), int(y)) for x, y in csv.reader(csvfile, delimiter= ',')]

rawDescription: Importing coordinates from CSV - Python

description: Importing coordinates from CSV - Python


code:
@fields.computed_field(db.KVField(db.StringField(), db.ListField(db.TupleField(db.StringField()))), deps=[feedname, location])
def getFeedContent(a=[feedname, location]):
    return readRSS(a['feedname'], a['location'])

rawDescription: Get field value within Flask-MongoAlchemy Document


code:
# Reshape array
r = np.reshape(v, 621)
date = np.arange(r.shape[0])  # assume that delta time between data is 1 hour
date1 = date/24.  # use days instead of hours

# plot asthetics
plt.plot(date1, r, linestyle='-', linewidth=5.0, c='c')

rawDescription: Divide Numpy array by constant to make hours days


code:
def values_incremented(some_data):
    return [{'value': current_sum, 'date': element['date']}
      for element, current_sum
      in zip(some_data,
           reduce(lambda x, y: [y['value']] if not x else x + [x[-1] + y['value']], some_data, []))]

rawDescription: Python compute running sum of values in one-line


code: adict = dict(cp.items('foo'))

rawDescription: Python: storing settings in dictionary vs argparse.Namespace


code:
def upgradeUserRank(playerScore):
    # :param playerscore: whatever variable
    # which contains the players newest time
    # after adding the 20 seconds
    #
    # returns the new player rank if they should
    # be upgraded, else None
    serverGroups = {
        "Rookie": ("9", "3600"),
        "Member": ("10", "43200"),
        "Veteran": ("11", "172800")
    }

    # invert the dictionary because we want to reference by times
    # scoreDict = {serverGroups[i][1]:i for i in serverGroups.keys()}
    scoreDict = {j[1]:i for i, j in serverGroups.items()}

    # iterate through the required times from greatest to least
    # so you don't return the lower ranks
    for i in sorted(scoreDict, key=lambda x:int(x), reverse=True):
        # Check if they've entered the new rank in the last 20 seconds
        # Otherwise, you'd suggest they should be updated
        # every 20s interval you check after the pass the
        # threshold
        if 0<=playerScore-int(i)<20:
            return scoreDict[i]

rawDescription: If else statements using dict to select the right value


code:
min_pos = current_cost.argmin()
min_val = current_cost[min_pos]

rawDescription: minimum and argmin in numpy

description: Minimum and argmin in numpy


code:
# read file into array of lines
lines = open("data.txt").readlines()

# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[2])

rawDescription: How to sort an entire file on a specifc data/column?

description: Sort an entire file on a specifc data/column


code:
from pyelasticsearch import ElasticSearch
import json
import os

es = ElasticSearch(ES_CLUSTER)

json_docs = []
for filename in os.listdir(os.getcwd()):
    if filename.endswith('.json'):
        with open(filename) as open_file:
            json_docs.append(json.load(open_file))

es.bulk(ES_INDEX, ES_TYPE, json_docs)

rawDescription: how do you add multiple json files to elasticsearch

description: Add multiple json files to elasticsearch


code:
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate

nodes = np.array( [ [1, 2], [6, 15], [10, 6], [10, 3], [3, 7] ] )

x = nodes[:,0]
y = nodes[:,1]

tck,u     = interpolate.splprep( [x,y] ,s = 0 )
xnew,ynew = interpolate.splev( np.linspace( 0, 1, 100 ), tck,der = 0)

plt.plot( x,y,'o' , xnew ,ynew )
plt.legend( [ 'data' , 'spline'] )
plt.axis( [ x.min() - 1 , x.max() + 1 , y.min() - 1 , y.max() + 2 ] )
plt.show()

rawDescription: Matplotlib draw Spline from multiple points


code:
def field_by(self, field_name, user):
    return self.filter(**{field_name + '__user': user})

rawDescription: Django QuerySet is too redundant

description: Django QuerySet is too redundant


code:
import random
from pylab import *
from datetime import *
N = 60
t0 = datetime.combine(date.today(), time(7,0,0))
delta_t = timedelta(minutes=1)
x_axis = t0 + arange(N)*delta_t
plot(x_axis, random(N))
show()

rawDescription: Assigning dates to samples in matplotlib


code:
import pickle

class Player:
    def __init__(self, name):
        self.name = name
        self.base_defe = 0
        self.weap = "Rusty Sword"
        self.wbow = "None"
        self.armH = "Worn Helmet"
        self.armB = "Worn Shirt"
        self.armA = "Worn Gloves"
        self.armL = "Worn Pants"
        self.armF = "Worn Boots"
        self.gold = 1000
        self.orichalcum = 0
        self.base_stre = 1
        self.base_magi = 1
        self.base_rang = 1
        self.maxmana = 100
        self.mana = self.maxmana
        self.level = 1
        self.exp = 0
        self.maxexp = 100
        self.expdiff = 50
        self.pots = 0
        self.arrows = 0
        self.q1c = False
        self.q2c = False
        self.q3c = False
        self.q1 = False
        self.q2 = False
        self.q3 = False
        self.QuestActive = False
        self.qtitle = "None"
        self.maxhealth = 100 + self.base_defe
        self.health = self.maxhealth
        self.inventory = ["Rusty Sword",
                          "Worn Shirt",
                          "Worn Pants",
                          "Worn Boots",
                          "Worn Helmet",
                          "Worn Gloves"]
        self.spells = []

p = Player('Fred')
p.exp = 100
p.gold = 5000

with open('fred.player', 'wb') as f:
    pickle.dump(p, f)

with open('fred.player', 'rb') as f:
    p2 = pickle.load(f)

print('Loaded player "%s" with %d exp and %d gold.' % (p2.name, p2.exp, p2.gold))

rawDescription: Save/Load System in Python Text-Based RPG


code: a, b = d.keys() - {key}  # On Py3; on Python 2.7, you'd use d.viewkeys()

rawDescription: How to swap 2 values in a dictionary, given the 3rd's key?

description: Swap 2 values in a dictionary, given the 3rd's key


code:
import numpy as np
import numba

@numba.guvectorize(['(float64[:], float64[:], float64[:], float64[:], float64[:])'], '(),(),(n),() -> (n)', nopython=True)
def _gpcm(theta, a, thresh, D, res):

    tmp = np.zeros(thresh.shape, dtype=np.float64)
    tmp[0] = a[0] *  D[0] * (theta[0] - thresh[0])
    bot = 0

    for j in range(1, thresh.shape[0]):
        if not np.isnan(thresh[j]):
            tmp[j] = tmp[j - 1] + a[0] * D[0] * (theta[0] - thresh[j])

    for j in range(thresh.shape[0]):
        if not np.isnan(thresh[j]):
            tmp[j] = np.exp(tmp[j])
            bot += tmp[j]

    for j in range(thresh.shape[0]):
        if not np.isnan(thresh[j]):
            res[j] = tmp[j] / bot
        else:
            res[j] = 0

rawDescription: Why can't I use `nopython=True` with `numba.guvectorize` on this function?


code:
import operator
ScorePoint(60, operator.le)

rawDescription: Python comparison functions

description: Python comparison functions


code:
def get_color():
    color = askcolor()
    print(color[1])

rawDescription: Is there another way to do this?

description: Is there another way to do this


code:
u'*{nbsps}{text}*{delimiter}'.format(nbsps=4*nbsp,
                                     text=data['text'],
                                     delimiter=delimiter)

rawDescription: Most pythonic way for formatting strings


code: [nonzero(abs(x-a)<0.5) for x in b]

rawDescription: Python: finding indices

description: Python: finding indices


code:
list_of_numbers = [1,2,4,5]
list_of_numbers.insert(2,3)

rawDescription: How to add to the middle of a list without removing anything?

description: Add to the middle of a list without removing anything


code:
def fun1(ax):
    ax.plot(range(5))

def fun2(ax):
    ax.plot(range(5)[::-1])

fig, ax = plt.subplots(1, 1)

fun1(ax)
fun2(ax)

plt.draw()

rawDescription: How to plot 2 subplots from different functions in the same window(figure)?

description: Plot 2 subplots from different functions in the same window(figure)


code:
class CustomList(list):
    def __init__(self, *args, **kwargs):
        list.__init__(self, args[0])

    def foobar(self):
        return 'foobar'

rawDescription: Create a python class that is treated as a list, but with more features?


code:
def tearDown(self):
    self.tearDownHelper()
    super(ServerTest, self).tearDown()

@tornado.testing.gen_test
def tearDownHelper(self):
    conn = yield r.connect()
    yield r.db("test").table("test_table").delete().run(conn)
    conn.close()

rawDescription: tearDown not called for unittesting with Tornado

description: TearDown not called for unittesting with Tornado


code:
# Python 2.X
def is_sortable(obj):
    return hasattr(obj, "__cmp__") or \
           hasattr(obj, "__lt__") or \
           hasattr(obj, "__gt__")

# Python 3.X
def is_sortable(obj):
    cls = obj.__class__
    return cls.__lt__ != object.__lt__ or \
           cls.__gt__ != object.__gt__

rawDescription: Check if an object is order-able in python?


code:
class Set(models.Model):
    @property
    def thumbnail(self):
        try:
            return self.photos.get(is_thumbnail=True)
        except Photo.DoesNotExist:
            # You can either use the first photo or just return None.
            # Note that if the set has no photos self.photos.first()
            # will actually return None anyway
            return self.photos.first()

class Photo(models.Model):
    set = models.ForeignKey(Set, related_name='photos')
    is_thumbnail = models.BooleanField(default=False)

    # cf  https://docs.djangoproject.com/en/1.8/ref/models/instances/#validating-objects
    def clean(self):
        if self.is_thumbnail:
           qs = self.set.photos.filter(is_thumbnail=True)
           if self.pk:
               qs = qs.exclude(pk=self.pk)
           if qs.exists():
               raise ValidationError("Only one thumbnail per set")

rawDescription: Django - cycle relations between models

description: Django - cycle relations between models


code:
html='
arya starkahahah
'
a=PyQuery(html)
a.outerHtml()
for img in a('img'):
    PyQuery(img).attr('src', "whatever")
a.outerHtml()

rawDescription: how to use pyquery to modify a node attribute in python

description: Use pyquery to modify a node attribute in python