code:
import math

# Input argument is the radius
circle_radius = 2.

# This is specified as 1, but doesn't have to be
tile_size = 1.

# Make a square box covering a quarter of the circle
tile_length_1d = int(math.ceil(circle_radius / tile_size ))

# How many tiles do you need?
num_complete_tiles = 0
num_partial_tiles = 0

# Now loop over all tile_length_1d x tile_length_1d tiles and check if they
# are needed
for i in range(tile_length_1d):
    for j in range(tile_length_1d):
        # Does corner of tile intersect circle?
        intersect_len = ((i * tile_size)**2 + (j * tile_size)**2)**0.5
        # Does *far* corner intersect (ie. is the whole tile in the circle)
        far_intersect_len = (((i+1) * tile_size)**2 + ((j+1) * tile_size)**2)**0.5
        if intersect_len > circle_radius:
            # Don't need tile, continue
            continue
        elif far_intersect_len > circle_radius:
            # Partial tile
            num_partial_tiles += 1
        else:
            # Keep tile. Maybe you want to store this or something
            # instead of just adding 1 to count?
            num_complete_tiles += 1

# Multiple by 4 for symmetry
num_complete_tiles = num_complete_tiles * 4
num_partial_tiles = num_partial_tiles * 4

print "You need %d complete tiles" %(num_complete_tiles)
print "You need %d partial tiles" %(num_partial_tiles)

rawDescription: number of complete and partial sqare tiles needed to fill a circle

description: Number of complete and partial sqare tiles needed to fill a circle


rawDescription: Python - How to remove duplicate tuples in a list of lists?


code: print '<input type="button" value="WRITE" id="{}"></input>	'.format(pinNo)

rawDescription: How to assign a python variable value to a html button's id?

description: Assign a python variable value to a html button's id


code:
import string

sans_S = [c for c in string.ascii_uppercase if c is not 'S']
user_choice = 3
alphabet = sans_S[0:user_choice] + ['S'] + sans_S[user_choice:]

print alphabet
# ['A', 'B', 'C', 'S', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
#  'O', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

# now create dictionary using modified list
alphadict = dict((x, i) for i, x in enumerate(alphabet))

# print out alphadict sorted by item values (not a necessary part of answer)
revdict = dict( (v,k) for k,v in alphadict.iteritems() )
print '{',
for v in sorted(alphadict.itervalues()):
    print "%r:%2d," % (revdict[v], v),
print '}'

# { 'A': 0, 'B': 1, 'C': 2, 'S': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8,
#   'I': 9, 'J':10, 'K':11, 'L':12, 'M':13, 'N':14, 'O':15, 'P':16, 'Q':17,
#   'R':18, 'T':19, 'U':20, 'V':21, 'W':22, 'X':23, 'Y':24, 'Z':25, }

rawDescription: Skip a letter in dictionary

description: Skip a letter in dictionary


code:
from collections import defaultdict
import glob

def get_site_files():
    sites = defaultdict(list)
    for fname in glob.glob('*.txt'):
        parts = fname.split('.')
        if len(parts)==6 and parts[2]=='WRFc36':
            sites[parts[0]].append(fname)
    return sites

def main():
    for site,files in get_site_files().iteritems():
        # you need to better explain what you are trying to do here!
        print site, files

if __name__=="__main__":
    main()

rawDescription: extract columns from multiple text file with Python

description: Extract columns from multiple text file with Python


code:
driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print element
print 'element.text: {0}'.format(element_text)
print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value)
driver.quit()

rawDescription: How can I get the current contents of an element in webdriver

description: Get the current contents of an element in webdriver


code:
i = ['abc', 'def', 'ghi']
j = [' ', 'rfd', ' ', ' ', 'qf']
cnt = 0
new = []
for item in j:
    if item == ' ':
            new.append(i[cnt])
            cnt += 1
    else:
            new.append(item)

print new

rawDescription: How to insert value from a list into other at position of space?

description: Insert value from a list into other at position of space


code:
def passwordToDigit(passToConvert):
    passLen = len(passToConvert) #puts the length of the password in a variable
    i = 0 #i is the selected character in the password
    j = 0 #j is the selected possible char, i.e. '0' is 'A' in possibleChars or '1' in possibleCharsToDigit
    while i < passLen:
        if passToConvert[i] == possibleChars[j]:
            passToConvert = passToConvert[0:i] + possibleCharsToDigit[j] + passToConvert[i + 1:]
            i += 1
            j = 0
            print passToConvert
        else:
            j += 1
    print passToConvert

rawDescription: Python IndexError: list index out of range with long string


code:
import requests
import sys

from requests.auth import HTTPBasicAuth, HTTPDigestAuth

AUTH_MAP = {
    'basic': HTTPBasicAuth,
    'digest': HTTPDigestAuth,
}

def auth_get(url, *args, **kwargs):
    r = requests.get(url)
    if r.status_code != 401:
        return r
    auth_scheme = r.headers['WWW-Authenticate'].split(' ')[0]
    auth = AUTH_MAP.get(auth_scheme.lower())
    if not auth:
        raise ValueError('Unknown authentication scheme')
    r = requests.get(url, auth=auth(*args, **kwargs))
    return r

if __name__ == '__main__':
    print auth_get(*sys.argv[1:])

rawDescription: Is there a python http-client which automatically performs authentication for several auth types?


code:
import time
from random import randint

def print_data():
    print "Hello World!"
    time.sleep(randint(30, 45))

def print_data_for(total_time):
    start_time = time.time()
    while time.time() < start_time + total_time:
        print_data()

print_data_for(60*60)  # 1 hour

rawDescription: Timers in Python

description: Timers in Python


code:
import httplib

try:
    url = httplib.HTTPConnection('yahoo.com')
    url.connect()
except httplib.HTTPException as ex:
    print "not connected"

rawDescription: Test to see if URL exists

description: Test to see if URL exists


code:
while True:
    # this will block until at least one socket is ready
    ready_socks,_,_ = select.select(socks, [], [])
    for sock in ready_socks:
        data, addr = sock.recvfrom(1024) # This is will not block
        print "received message:", data

rawDescription: Is there a way to listen to multiple python sockets at once


code:
a="Hello WORLD"

def toBigInt(s):
    ret=0
    for i,j in enumerate(s):
        ret+= ord(j)<<(i*8)
    return ret

def fromBigInt(i):
    s=""
    while i>0:
        s+=chr(i&0xff)
        i=i>>8
    return s

i = toBigInt(a)
print i
print fromBigInt(i)

rawDescription: How do I convert a string into a unique decimal number in python?

description: Convert a string into a unique decimal number in python


code:
from itertools import groupby
data = [[1],[3],[2],[2]]
sorted_data = sorted(data, reverse=True)
for rank, (_, grp) in enumerate(groupby(sorted_data, key=lambda xs: xs[0]), 1):
    for x in grp:
        x.append(rank)
print data

rawDescription: Ranking a list without breaking ties in Python


code:
import copy

# Returns a list of all permutations of the given list.
def permutate(s):
    # A list of all found permutations, to be returned
    permutations = []

    # Takes a set which has all elements below index i fixed and finds all permutations
    def recurse(s, i):
        # If all elements are fixed, store the current permutation
        if i == len(s):
            # append a deepcopy of s
            permutations.append(copy.deepcopy(s))
        else:
            # Swap the "first" element with each other element to generate new permutations
            for element in xrange(i, len(s)):
                s[element], s[i] = s[i], s[element]
                recurse(s, i + 1)
                s[element], s[i] = s[i], s[element]

    # Use the recursive algorithm to find all permutations, starting with no fixed elements
    recurse(s, 0)
    return permutations

print permutate([1, 2, 3])

rawDescription: What is the average case performance of this permutation-generating algorithm?


code:
cmd = 'print "Hello, world!"'
exec cmd
cmd = """
x = 4
y = 3
z = x*y + 1
print 'z = {0}'.format(z)
"""
exec cmd

rawDescription: Run Python script saved as variable

description: Run Python script saved as variable


code:
import operator
def weightingfun(cost, weights, volumes):
    return cost*sum(weights)/sum(map( operator.mul, weights, volumes))

weights = (1, 0.5, 0.33, 2)
volumes = (100, 20, 10, 5)
print weightingfun(70, weights, volumes)

rawDescription: How can I create a Python function with variable arguments

description: Create a Python function with variable arguments


code:
class Character(object):

    """All Characters have a name and some hit points."""

    def __init__(self, name, hit_points):
        self.name = name # assigned in __init__ so instance attribute
        self.hit_points = hit_points

class Player(Character):

    """Players are Characters, with added attack and defence attributes."""

    def __init__(self, name, hit_points, attack, defence):
        super(Player, self).__init__(name, hit_points) # call superclass
        self.attack = attack
        self.defence = defence

    def _attack(self, other, chance, damage):
        """Generic attack function to reduce duplication."""
        if random.random() <= chance:
            other.hit_points -= damage # works for any Character or subclass

    def quick_attack(self, other):
        """Attack with 80% chance of doing 10 damage."""
        self._attack(other, 0.8, 10)

dragon = Character("Dragon", 25) # dragon is a Character instance
ranger = Player("Ranger", 100, 80, 50) # ranger is a Player instance
ranger.quick_attack(dragon)
print dragon.hit_points

rawDescription: How can I use variables from another class in python?

description: Use variables from another class in python


code:
tn.write("tar -xvf a.tar")
while True:
    resp = tn.read_until("#", 1.0)
    if 0 == len(resp): break
    print resp
print "done"

rawDescription: How to print out the output of "tar" execution until it finishes using telnetlib?

description: Print out the output of "tar" execution until it finishes using telnetlib


code:
from traits.api import Instance, Str, HasTraits

class Person(HasTraits):
    name = Str("hooked")

class Chair(HasTraits):
    sitting = Instance(Person, kw = {})

t = Chair()
print t.sitting.name

rawDescription: Instantiating a default instance for an Enthought trait


code:
urllist = ['http://example.com', 'http://example1.com']
hero_id = []
for url in urllist:
    db = re.findall('(\d{3})/">(\w+\s-\s\w+)</a>', urllib.urlopen(url).read(), re.DOTALL)
    for j in db:
        hero_id.append(tuple(filter(None, j))[0])
print hero_id

rawDescription: Appending numbers to a list

description: Appending numbers to a list


code:
import libxml2
libxml2.loadCatalog('catalog.xml')
print libxml2.catalogResolveURI('file:///common/logo.xml')

rawDescription: Python LXML catalog lookup

description: Python LXML catalog lookup


code:
## myModule.py
def printHello():
   print "hello"

## otherModule
import myModule
print myModule.printHello()  ## prints hello

def otherPrint():
   print "Hello world"

myModule.printHello = otherPrint
myModule.printHello()  ## prints Hello world

rawDescription: Can I change the attributes of a module at runtime in the active python shell?

description: Change the attributes of a module at runtime in the active python shell


code:
import urllib2
import re
from BeautifulSoup import BeautifulSoup
from os.path import basename
from urlparse import urlsplit

#get content of a url and save (not necessary) the originalhtml
url = "http://www.someDomain.com"
urlContent = urllib2.urlopen(url).read()
page = BeautifulSoup(urlContent)
f = open("originalHtml",'w')
f.write(urlContent)
f.close()
#Find all images in the file, put them in imgUrls
imgUrls = page.findAll('img')
imagesDict = {}

# download all images
for image in imgUrls:
    try:
        #get src tag and download file, save link and local link in dict
        imgUrl = image['src']
        imgData = urllib2.urlopen(imgUrl).read()
        fileName = basename(urlsplit(imgUrl)[2])
        location = "images/" + fileName;
        imagesDict[location] = imgUrl
        print "loc=" + location
        output = open(location,'wb')
        output.write(imgData)
        output.close()
    except:
        #not so clean solution to catch hard-linked images ('http://somedomain.com/img/image.jpg
        try:
            imgData = urllib2.urlopen(url + imgUrl).read()
            fileName =  basename(urlsplit(imgUrl)[2])
            location = "images/" + fileName
            imagesDict[location] = imgUrl
            print "loc=" + location
            output = open(location,'wb')
            output.write(imgData)
            output.close()
        except:
            print "Double ERROR"
        print "Error" + imgUrl
        pass

#Replace the old links to new local links
for dictKey in imagesDict:
    urlContent = re.sub(imagesDict[dictKey], dictKey, urlContent)

#save HTML
f = open("imagesReplaced.html", 'w')
f.write(urlContent)
f.close()

rawDescription: Regex doesn't return all img tags - Python


code:
def run(self):
    if self.index == 0:
        time.sleep(0.1)
    while 1:
        time.sleep(0.2)
        item = self.queue.get()
        if item is None:
            break
        print "index:", self.index, "task", item, "finished"
        self.queue.task_done()

rawDescription: How does Queue work in python

description: How does Queue work in python


code:
import StringIO
import sys

# somewhere to store output
out = StringIO.StringIO()

# set stdout to our StringIO instance
sys.stdout = out

# print something (nothing will print)
print 'herp derp'

# restore stdout so we can really print (__stdout__ stores the original stdout)
sys.stdout = sys.__stdout__

# print the stored value from previous print
print out.getvalue()

rawDescription: Intercept python's `print` statement and display in GUI


rawDescription: Max number of columns using Table() for SQLAlchemy Core - Python


code:
import fileinput
for line in fileinput.input('example.txt', inplace = True):
    if line.startswith('rx_b_phase'):
        #if line starts with rx_b_phase then do something here
        print "rx_b_phase = foo"
    elif line.startswith('sample_gain_hi'):
        #if line starts with sample_gain_hi then do something here
        print "sample_gain_hi = bar"
    else:
        print line.strip()

rawDescription: Modifying parameter in existing text file with Python


code:
urls='''\
http://imdb.com/title/tt0285331/episodes?this=1&season=7&ref_=tt_eps_sn_7
http://imdb.com/title/tt0285331/'''

import re

print re.findall(r'^(?!.*\bseason\b)(.*)', urls, re.M)
# ['http://imdb.com/title/tt0285331/']

rawDescription: Do not match if word appears in regex

description: Do not match if word appears in regex


rawDescription: Count value in dictionary relative to another value


code:
import numpy as np
import cv2

cap = cv2.VideoCapture('video.avi')

current_state = False
annotation_list = []

while(True):
    # Read one frame.
    ret, frame = cap.read()
    if not ret:
        break

    # Show one frame.
    cv2.imshow('frame', frame)

    # Check, if the space bar is pressed to switch the mode.
    if cv2.waitKey(1) & 0xFF == ord(' '):
        current_state = not current_state

    annotation_list.append(current_state)

# Convert the list of boolean values to a list of int values.
annotation_list = map(int, annotation_list)
print annotation_list

cap.release()
cv2.destroyAllWindows()

rawDescription: Annotating video frames with a label based on state


code:
import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)
print data

rawDescription: Python urllib2: Receive JSON response from url


code:
from unidecode import unidecode
print unidecode(u"\u5317\u4EB0")

rawDescription: how to convert characters like these,"a³ a¡ a´a§" in unicode, using python?

description: Convert characters like these,"a³ a¡ a´a§" in unicode, using python


code:
import wx

class long_running(object):
    def __init__(self):
        bitmap = wx.EmptyBitmap(300, 150, 127)

        self.mainframe = wx.Frame(None, -1, 'mainframe')
        self.splash = wx.SplashScreen(bitmap, wx.SPLASH_TIMEOUT, 20000, self.mainframe)

    def start(self):
        import time

        # mimicking something taking very long time on startup
        for i in range(20):
            time.sleep(0.5)
            print i
        wx.CallAfter(self.continue_)

    def continue_(self):
        #Destroy the splash screen.
        if self.splash:
            self.splash.Hide()
#             self.splash.Destroy()

        self.mainframe.Show()

if __name__ == '__main__':
    import thread
    app = wx.App()

    long_rnn = long_running()

    # Begin loading the application.
    thread.start_new_thread(long_rnn.start, ())
    # Application loaded.

    app.MainLoop()

rawDescription: wxPython - Showing logo while importing

description: WxPython - Showing logo while importing


code:
from xml.etree import ElementTree as etree
corpus = '''<category1>
      <subcategory>
        entry1
        entry2
      </subcategory>
</category1>
'''
doc = etree.fromstring(corpus)
for subcategory in doc.getchildren():
    for entry in filter(bool,
                        map(str.strip,
                            subcategory.text.split('\n'))):
        print "entry output: (%s)" % entry
    print "subcategory output (%s)" % subcategory.tag

rawDescription: Automatically generating code from a text or xml file and then compiling?


code:
class Test():
    def __init__(self,q):
        self.Quantity = q
    def __repr__(self):
        return "<Class Test: Quantity=" + str(self.Quantity) + ">"
mydict = mydict = {"a":[ Test(3), Test(2), Test(4)], "b": [Test(8), Test(10), Test(6)], "c":[Test(14), Test(12), Test(20)]}
print "Before Sort"
for key in mydict:
    print (key,mydict[key])

dict_with_sorted_list = {}
for key in mydict:
    dict_with_sorted_list[key] = sorted(mydict[key], key=lambda k: k.Quantity, reverse=True)
print "After Sort"
for key in dict_with_sorted_list:
    print (key,dict_with_sorted_list[key])

rawDescription: Sorting a Dict whose values are objects Python


code:
import pandas as pd
import numpy as np
a = pd.DataFrame(np.random.randn(10))
print a
b = [{'color':'red','index':a.index},{'color':'blue','index':a.index}]

d = b[1]['index']
b[1]['index'] = d.delete(6)
print b[1]['index']

Int64Index([0, 1, 2, 3, 4, 5, 7, 8, 9], dtype='int64')

rawDescription: Remove an element from list of dictionaries with Pandas element


rawDescription: Python regex parsing

description: Python regex parsing


code:
class mod_user:

    def __init__(self):
        global MODE
        self._old_mode = MODE
        MODE = "user"

    def __enter__(self):
        pass

    def __exit__(self, *args, **kws):
        global MODE
        MODE = self._old_mode

MODE = "sudo"

with mod_user():
    print MODE  # print : user.

print MODE  # print: sudo.

mod_user()
print MODE   # print: user.

rawDescription: Is it possible to make a contextually-sensitive python context manager?


code:
import numpy.linalg
from igraph import *
import random
import numpy as np
import time

nbr_noeuds = 50
dens = .2

p=random.uniform(dens,dens)
G = Graph.Erdos_Renyi(nbr_noeuds, p, directed=False, loops=False)

t0 = time.time()
L = G.laplacian(normalized=True)
e = numpy.linalg.eigvals(L)
print time.time()-t0

rawDescription: Computing the Eigenvalue Spectrum of a Graph with Igraph


code:
#!/usr/bin/env python2

import curses
import time

# Create curses screen
scr = curses.initscr()
scr.keypad(True)
scr.refresh()
curses.noecho()

# Get screen width/height
height,width = scr.getmaxyx()

# Create a curses pad (pad size is height + 10)
mypad_height = height + 10
mypad = curses.newpad(mypad_height, width);
mypad.scrollok(True)
mypad_pos = 0
mypad_refresh = lambda: mypad.refresh(mypad_pos, 0, 0, 0, height-1, width)
mypad_refresh()

# Fill the window with text (note that 5 lines are lost forever)
for i in range(0, height + 15):
    mypad.addstr("{0} This is a sample string...\n".format(i))
    if i > height: mypad_pos = min(i - height, mypad_height - height)
    mypad_refresh()
    time.sleep(0.05)

# Wait for user to scroll or quit
running = True
while running:
    ch = scr.getch()
    if ch == curses.KEY_DOWN and mypad_pos < mypad_height - height:
        mypad_pos += 1
        mypad_refresh()
    elif ch == curses.KEY_UP and mypad_pos > 0:
        mypad_pos -= 1
        mypad_refresh()
    elif ch < 256 and chr(ch) == 'q':
        running = False

# Store the current contents of pad
mypad_contents = []
for i in range(0, mypad_height):
    mypad_contents.append(mypad.instr(i, 0))

# End curses
curses.endwin()

# Write the old contents of pad to console
print '\n'.join(mypad_contents)

rawDescription: Make curses program output persist in terminal scrollback history after program exits


code:
s = "Adam'sApple"
x = s.replace("'", "")
print x

rawDescription: Removing unwanted characters from a string in Python


code:
import pwd, grp
for p in pwd.getpwall():
    print p[0], grp.getgrgid(p[3])[0]

rawDescription: Python script to list users and groups

description: Python script to list users and groups


code:
import re
from math import *

def evaluate_expression(equation, **kwargs):
    for key in kwargs:
        exec key + " = " + str(kwargs[key])  # Creates x variable
    parser = re.compile(r'\$(\S+)')
    expressions = parser.findall(equation)
    for expression in expressions:
        print eval(expression)

evaluate_expression('line $sin(2*x) $x*cos(x) $x', x=1.0)

rawDescription: Evaluate mathematical expression inside string


code:
lis1 = ['A', 'B', 'C']
lis2 = ['X', 'Y', 'Z']
z1 = zip(lis1,lis1[1:])  #use itertools.izip in py2x for memory efficiency
z2 = zip(lis2,lis2[1:])
for x,y in zip(z1,z2):
    print x,y

rawDescription: How to create element pairs of two lists by iterating through them in parallel?

description: Create element pairs of two lists by iterating through them in parallel


code:
df_year.index.name = 'label'
df_year.columns = ['value']
print df_year.to_csv()

rawDescription: Adding headers to a DataFrame with Pandas while dropping the index


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

def home_callback():
    print "home called"
    ax.legend()

x=np.linspace(0,100,100)
y=np.linspace(100,200,100)
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x,y,label='test')
ax.legend()
plt.show()

fm = plt.get_current_fig_manager()

fm.toolbar.actions()[0].triggered.connect(home_callback)

rawDescription: How to update the legend from matplotlib toolbar

description: Update the legend from matplotlib toolbar


code:
import random

print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
print random.randint(1,10)
print ("times")
print random.randint(1,10)
answer = raw_input ("Make your choice: ")

if answer == ran1*ran2:
  print "That is correct"
  correct=correct +1
else:
  print "That is incorrect!"

rawDescription: Why won't my program work in python?

description: Why won't my program work in python


code:
print request.url_root  # prints "http://domain1.com/"
print request.headers['Host']  # prints "domain1.com"

rawDescription: Handling with multiple domains in Flask

description: Handling with multiple domains in Flask


code:
paths
for path in paths:
    print path.split('\\')[3]

rawDescription: Python Parse a List of Paths

description: Python Parse a List of Paths


code:
scrape = []
companies =[]
import lxml
import lxml.html
import lxml.etree

urlbase = 'http://reuters.com/finance/markets/index?symbol=us!spx&sortBy=&sortDir=&pn='
for i in range(1,18):
    url = urlbase+str(i)
    content = lxml.html.parse(url)
    item = content.xpath('//table[@class="dataTable sortable"]/form/tr/td[1]/a')
    ticker = [thing.text for thing in item]
    print ticker

rawDescription: python scraping reuters site...bad xpath?

description: Python scraping reuters site...bad xpath


code:
def setAttrs(object):
    for field_key,field_value in object.fields.items():
        print field_value.initial

rawDescription: Getting model default value from modelForm in django


code:
for i in xrange(1, N+1): # N is number of arrays
    arr = globals()['Level%i' % i] # this gets the Level<X> value for each i
    arr.dtype = [('AP%02i' % i,float), ('BP%02i' % i, float), ('AS%02i' % i, float), ('BS%02i' % i, float)]
# example
print Level1[0]['AP01']

rawDescription: How to auto generate numpy dtype?

description: Auto generate numpy dtype


rawDescription: Removing HTML until a certain point in a file


code:
from scrapy.contrib.spiders import CrawlSpider
from scrapy.http import Request

class JLSSpider(CrawlSpider):
    name = 'JLS'
    allowed_domains = ['johnlscott.com']

    def start_requests(self):
        yield Request("http://www.johnlscott.com/agent-search.aspx?p=agentResults.asp&OfficeID=8627", callback=self.parse_item)

    def parse_item(self, response):
        print response.body

rawDescription: Scrapy reverses order of arguments in url Python


code:
from Crypto.Cipher import AES
import base64
import os

# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32

# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length.  This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'

# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)

# generate a random secret key
secret = os.urandom(BLOCK_SIZE)

# create a cipher object using the random secret
cipher = AES.new(secret)

# encode a string
encoded = EncodeAES(cipher, 'password')
print 'Encrypted string:', encoded

# decode the encoded string
decoded = DecodeAES(cipher, encoded)

rawDescription: Encrypting Nodes within XML Document in Python


code:
res = common / np.sqrt(np.outer(*[df1.sum(1)] * 2))
import itertools
for col in res.columns:
    for _,g in res.groupby(col):
        pairs = zip(list(g.index[g.index < col]),itertools.repeat(col))
        if pairs: print pairs

rawDescription: Group values in Pandas DataFrame based on calculations


code:
def voting_plurality(votes):
    sums = dict(zip(INDEX_TO_NAME.values(), [0] * len(INDEX_TO_NAME)))
    for vote in votes:
        if vote in sums:
            sums[vote] += 1
        else:
            print "Bad vote: %s" % vote
    votes_by_index = sorted([(NAME_TO_INDEX[k], v) for k, v in sums.items()])
    votes_by_rank = sorted(votes_by_index, key=lambda x: x[1], reverse=True)
    votes_by_parts = [item[1] for item in votes_by_index]
    highest_votes = INDEX_TO_NAME[votes_by_rank[0][0]]
    return (highest_votes, votes_by_parts)

rawDescription: How to append the number of item frequencies in a list in Python 3.2?

description: Append the number of item frequencies in a list in Python 3.2


code: print sr1.__doc__

rawDescription: New to scapy. Trying to understand the sr()


code:
from sets import Set

A = [set([1,2]), set([3,4]), set([2,3]) ]

merges = any( a&b for a in A for b in A if a!=b)
while(merges):
    B = [A[0]]
    for a in A[1:] :
        merged = False
        for i,b in enumerate(B):
            if  a&b :
                B[i]=b | a
                merged =True
                break

        if not merged:
            B.append(a)
    A = B
    merges = any( a&b for a in A for b in A if a!=b)

print B

rawDescription: combining sets within a list

description: Combining sets within a list


code:
def functionx(x):
    while x > 0:
        x += 1
        yield x

for i in functionx(1):
    print i

rawDescription: Iterator python

description: Iterator python


code:
from collections import defaultdict

data = list()
groups = defaultdict(list)
i = 1
with open('input') as f:
    for line in f:
        row = line.strip().split() + [ i ]
        gname = " ".join(row[1:3])
        groups[gname] += [ row ]
        i += 1

output = defaultdict(list)
for gname, group in groups.items():
    gr = []
    last_key,last_col4, last_idx='',-1,-1
    for row in group:
        key, idx = " ".join(row[1:3]), int(row[-1])
        keys_same   = last_key == key and last_col4 + 1 == int(row[3])
        consequtive = last_idx + 1 == idx
        if not (gr and keys_same and consequtive):
            if gr: output[gr[0][1]] += [ float(row[0]) - float(gr[0][0]) ]
            gr = [ row ]
        else: gr += [ row ]
        last_key, last_col4, last_idx = key, int(row[3]), idx

for k,v in output.items():
    print k, ' --> ', v

rawDescription: Grouping of lines in a text file and further processing


code:
class Tree:
    def __init__(self, cities, n=0):
        self.branches = dict()
        if len(cities) == 1:
            nc = list(cities)  # create a working list
            # grab the nth element of the list, default to head
            # Stash that as the node value
            self.node = nc[n]
            print "Complete!"
        elif len(cities) == 0:
            print "Doubly Complete!"
        else:
            nc = list(cities)  # create a working list
            # grab the nth element of the list, default to head
            # Stash that as the node value
            self.node = nc[n]
            print self.node
            del nc[n]  # Pop off the nth value from the list
            print "deleted city! See?"
            print nc
            c = 0  # create a counter
            for a in nc:  # loop through the remaining cities
                self.branches[a] = Tree(nc, c)  # generate a new tree
                c += 1  # increase the counter

    def __repr__(self, tier=1):
        ret = ("\t" * tier)
        ret += self.node
        ret += "\n"
        for a in self.branches:
            ret += self.branches[a].__repr__(tier+1)
        return ret

    __str__ = __repr__

t = Tree(["SLC", "Ogden"], 1)
print t

rawDescription: Python Tree Recursion

description: Python Tree Recursion


code:
from tornado.ioloop import IOLoop
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from toro import Queue

q = Queue(maxsize=1)

@gen.coroutine
def consumer():
    item = yield q.get()
    while item:
        print item
        item = yield q.get()

@gen.coroutine
def producer():
    try:
        client = AsyncHTTPClient()
        for url in [
                'http://tornadoweb.org',
                'http://python.org',
                'http://readthedocs.org']:
            response = yield client.fetch(url)
            item = (url, len(response.body))
            yield q.put(item)

        # Done.
        q.put(None)
    except Exception:
        IOLoop.current().stop()
        raise

future = producer()
IOLoop.current().run_sync(consumer, timeout=20)

rawDescription: Write a tornado coroutine that also yields normal values


code:
import sys
A = []
sz = sys.getsizeof(A)
for i in range(100000):
    if sz != sys.getsizeof(A):
        sz = sys.getsizeof(A)
        print i, sz
    A.append(i)

rawDescription: Speed of using append in python repeatedly


code:
import os
import shutil
import logging

def push_updated_files(self):
    """
    Manually push auto-updated files from the application folder up to the appdata folder
    This enables shortcuts and other features on the computer to point to these files since the application
      directory name changes with each update.
    """
    logger = logging.getLogger(__name__)

    #Verify whether running script or frozen/deployed application
    if getattr(sys, 'frozen', False):
        logger.info("Verifying Application Integrity...")

        #Files which should by copied to appdata directory to be easily referenced by shortcuts, etc.
        data_files = ['main.ico',
                      'uninstall.ico',
                      'ReadMe.txt',
                      'changelog.txt',
                      'WhatsNew.txt',
                      'copyright.txt',
                      'Documentation.pdf']

        logger.debug("  App Path: {0}".format(self._app_path))

        #Get application top directory
        logger.debug("  AppData Directory: {0}".format(self._appdata_path))

        #Get application internal file path
        for f in data_files:
            a_file = f
            int_path = os.path.join(self._app_path, a_file)
            logger.debug("  Internal File Path: {0}".format(int_path))

            #Get file's creation time
            mtime_int = os.stat(int_path).st_mtime
            logger.debug("  Internal File Modified Time: {0}".format(time.ctime(mtime_int)))

            #Get external file path
            ext_path = os.path.join(self._appdata_path, a_file)
            if os.path.exists(ext_path):
                mtime_ext = os.stat(ext_path).st_mtime
                logger.debug("  External File Modified Time: {0}".format(time.ctime(mtime_ext)))

                if mtime_int > mtime_ext:
                    logger.debug("  Replacing external file with new file...")
                    try:
                        os.remove(ext_path)
                        shutil.copy(int_path, ext_path)
                    except Exception, e:
                        logger.error("  Failed to replace the external file...", exc_info=True)
                else:
                    logger.debug("  External file is newer than internal file - all is well.")
            else:
                logger.debug("  Copying file to appdata to be externally accessible")
                shutil.copy(int_path, ext_path)

rawDescription: Python Project Structure for Esky

description: Python Project Structure for Esky


code:
def api_response(request):
    try:
        data=json.loads(request.raw_post_data)
        label=data['label']
        url=data['url']
        print label, url
    except:
        print 'nope'
    return HttpResponse('')

rawDescription: Getting a JSON request in a view (using Django)


code:
from Tkinter import *

def image_clicked(event):
    print "an image on the canvas was clicked!"
    print "now opening xml file..."
    #todo: open xml file here

root = Tk()

canvas = Canvas(root, width=500, height=500)
canvas.pack()

canvas.create_rectangle([0,0,100,100], fill="blue", tag="opens_xml")
canvas.tag_bind("opens_xml", "<1>", image_clicked)

root.mainloop()

rawDescription: How can a make a photo respond to a mouse click?


rawDescription: Convert Data to float

description: Convert Data to float


code:
N = 20
nums = range(2, N)

for i in xrange(2, 8):
    print "NUMS:", nums
    new_nums = []
    for x in nums:
        print "CONDITION: x ({x}) == i ({i}) or x ({x}) % i({i}) == 0 ({x_mod_i})".format(x=x, i=i, x_mod_i=x % i)
        if x == i or x % i:
            print " => APPEND", x
            new_nums.append(x)
    nums = new_nums
    print "***********"

print nums    # [2, 3, 5, 7, 11, 13, 17, 19]

rawDescription: Clearing up a prime numbers algorithm

description: Clearing up a prime numbers algorithm


code:
import requests

URL = "http://www.study.cam.ac.uk/undergraduate/apply/statistics/data.php"
HEADERS = {'X-Requested-With': 'XMLHttpRequest'}

data = {
    'when': 'year',
    'year': 2014,
    'applications': 'on',
    'offers': 'on',
    'acceptances': 'on',
    'groupby': 'college',
    'for-5-years-what': 'university'
}

response = requests.post(URL, data=data, headers=HEADERS)
print response.json()

rawDescription: Screen scraping advice: Interactive graph


code:
from django.contrib.auth import authenticate

for username, password in get_usernames_and_passwords():
    if authenticate(username=username, password=password) is None:
        print "Failed to authenticate user {!r}".format(username)

rawDescription: Generating encrypted passwords in mysql, to populate a django database


code:
filename = '/var/log/nginx/access.log'
# Command to read file from the end
cmd = sys.platform == 'darwin' and ['tail', '-r', filename] or ['tac', filename]
# But if you want read it from beginning, use the following
#cmd = ['cat', filename]

proc = Popen(cmd, close_fds=True, stdout=PIPE, stderr=PIPE)
output = proc.stdout

FORMAT = [
    # 'foo',
    # 'bar',
]
def extract_log_data(line):
    '''Extact data in you log format, normalize it.
    '''
    return dict(zip(FORMAT, line))

csv.register_dialect('nginx', delimiter=' ', quoting=csv.QUOTE_MINIMAL)
lines = csv.reader(output, dialect='nginx')
started_at = dt.datetime.utcnow()
for line in lines:
    data = extract_log_data(line)
    print data
    if (dt.datetime.utcnow() - started_at) >= dt.timedelta(seconds=10):
        break

output.close()
proc.terminate()

rawDescription: Read a file for ten seconds

description: Read a file for ten seconds


code:
#!/usr/bin/env python

import os

def searchthis(location, searchterm):
   for dir_path, dirs, file_names in os.walk(location):
      for file_name in file_names:
         fullpath = os.path.join(dir_path, file_name)
         for line in file(fullpath):
            if searchterm in line:
                print line

searchthis(os.getcwd(), "mystring")

rawDescription: Searching for strings in files along with using os.walk


code:
import signal
import sys
def signal_handler(signal, frame):
    print 'Handling SIGHUP signal!'
    sys.exit(0)
signal.signal(signal.SIGHUHP, signal_handler)
print 'Waiting for SIGHUP'
signal.pause()

rawDescription: Python: Object destruction upon terminal close


code:
class A(object):
    def print_it(self):
            print 'A'

class B(A):
    def print_it(self):
            print 'B'

x = B()
x.print_it()                # calls derived class method as expected
super(B, x).print_it()      # calls base class method

rawDescription: Calling base class method in Python

description: Calling base class method in Python


code:
print timeit.Timer('''
d.sum(axis=0)
''', '''
import numpy as np
a = range(200)
b = range(199,-1,-1)
c = range(1,201)
d = np.array([a,b,c])''').timeit(number = 1000)

rawDescription: Is map(sum,zip(*list)) the fastest way to sum columns of list of arbitrary length?


code:
import re

pat = "^[A-Za-z][0-9]*_"
myStringA = 'c17898_some other characters and symbols'

output = re.sub(pat, "", myStringA)
print output

rawDescription: How to remove unwanted characters if their pattern known

description: Remove unwanted characters if their pattern known


code:
from collections import defaultdict

terms = ['Electronic rock', 'Alternative rock', 'Indie pop']
d = defaultdict(list)
for term in terms:
    for word in term.split():
        d[word].append(term)

for k,v in d.iteritems():
    if len(v) > 1:
        print k,v

rawDescription: Python: detect strings that share words

description: Python: detect strings that share words


code:
def ccid_year_1(seq):
  year, prefix, index, suffix = seq
  return year

def ccid_year_2(seq):
  return seq[0]

arg = {1:'a', 2:'b', 0:'c', 3:'d'}
print ccid_year_1(arg)
print ccid_year_2(arg)

rawDescription: Is Python allowed to optimize a function definition to eliminate unused code?


code:
def getPossibleDecompositions(s):
    if s == '':
        yield []
    else:
        for pattern in patterns:
            if s.startswith(pattern):
                for x in getPossibleDecompositions(s[len(pattern):]):
                    yield [pattern] + x

for x in getPossibleDecompositions('BBBBBBBB'):
    print x

rawDescription: decomposing a string into known patterns

description: Decomposing a string into known patterns


code:
class MyClass(object):
    def __init__(self, value):
        self.value = value
    def __radd__(self, other):
        print other, "radd", self.value
        return self.value + other

my = MyClass(1)

print 1 + my
# 1 radd 1
# 2

rawDescription: Override + operator in python for float + obj


code:
print "სკამი".decode('utf-8')[:-1]
print u"სკამი"[:-1]

rawDescription: removing the question mark in python output

description: Removing the question mark in python output


code:
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt

fname='index.png'
blur_radius = 1.0
threshold = 50

img = scipy.misc.imread(fname) # gray-scale image
print(img.shape)

# smooth the image (to remove small objects)
imgf = ndimage.gaussian_filter(img, blur_radius)
threshold = 50

# find connected components
labeled, nr_objects = ndimage.label(imgf > threshold)
print "Number of objects is %d " % nr_objects

plt.imsave('/tmp/out.png', labeled)
plt.imshow(labeled)

plt.show()

rawDescription: Extracting connected objects from an image in Python


code:
import re
import urllib2
from bs4 import BeautifulSoup as soup

url = "http://www.cms.gov/apps/ama/license.asp?file=/McrPartBDrugAvgSalesPrice/downloads/Apr-13-ASP-Pricing-file.zip"
web_soup = soup(urllib2.urlopen(url))

# get main-content div
main_div = web_soup.find(name="div", attrs={'class': 'main-content'})
print main_div

# get form action
form = web_soup.find(name="form", attrs={'action': re.compile('.*\.zip.*')})
print form['action']

rawDescription: Python - cannot access a specific div [Urllib, BeautifulSoup, maybe Mechanize?]


code:
def sandwich(bread, meat='turkey', cheese=None):
    if cheese:
        print bread,"bread sandwich with",meat,"and",cheese,"cheese"
    else:
        print bread,"bread sandwich with",meat

rawDescription: Python Keyword Argument extra word

description: Python Keyword Argument extra word


code:
for i in itertools.count():
    try:
        subname = EnumKey(akey, i)
    except WindowsError:
        break
    subkey = OpenKey(akey, subname, 0, KEY_READ)
    pathname, regtype = QueryValueEx(subkey, "InstallLocation")
    print subname, pathname
    CloseKey(subkey)

rawDescription: Python: Look into the registry to find install location of a program


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import inspect

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    x = Column(Integer)
    y = Column(Integer)

print inspect(A).c
print inspect(A).c.x
print inspect(A).column_attrs
print inspect(A).column_attrs.x
print inspect(A).column_attrs.x.expression

rawDescription: When the sqlalchemy ORM class attributes are different from database columns, how to get a list of the ORM class attributes?


code:
from lxml import etree

file = "file:///path/to/file.html" # can be a http URL too
doc = etree.parse(file)

print doc.xpath('//a/@href')[0]

rawDescription: Scraping data with Python LXML XPath

description: Scraping data with Python LXML XPath


code:
import random
import time

def strTimeProp(start, end, format, prop):
    """Get a time at a proportion of a range of two formatted times.

    start and end should be strings specifying times formated in the
    given format (strftime-style), giving an interval [start, end].
    prop specifies how a proportion of the interval to be taken after
    start.  The returned time will be in the specified format.
    """

    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))

    ptime = stime + prop * (etime - stime)

    return time.strftime(format, time.localtime(ptime))

def randomDate(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)

print randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random())

rawDescription: Generate a random date between two other dates


code:
LBMethods=[
  ("Round Robin", "LB_METHOD_ROUND_ROBIN"),
  ("Ratio (member)", "LB_METHOD_RATIO_MEMBER"),
  ("Least Connections (member)", "LB_METHOD_LEAST_CONNECTION_MEMBER"),
  ("Observed (member)", "LB_METHOD_OBSERVED_MEMBER"),
  ("Predictive (member)", "LB_METHOD_PREDICTIVE_MEMBER"),
  ("Ratio (node)", "LB_METHOD_RATIO_NODE_ADDRESS"),
  ("Least Connections (node)", "LB_METHOD_LEAST_CONNECTION_NODE_ADDRESS"),
  ("Fastest (node)", "LB_METHOD_FASTEST_NODE_ADDRESS"),
  ("Observed (node)", "LB_METHOD_OBSERVED_NODE_ADDRESS"),
  ("Predictive (node)", "LB_METHOD_PREDICTIVE_NODE_ADDRESS"),
  ("Dynamic Ratio (node)", "LB_METHOD_DYNAMIC_RATIO"),
  ("Fastest (application)", "LB_METHOD_FASTEST_APP_RESPONSE"),
  ("Least Sessions", "LB_METHOD_LEAST_SESSIONS"),
  ("Dynamic Ratio (member)", "LB_METHOD_DYNAMIC_RATIO_MEMBER"),
  ("Weighted Least Connections (member)", "LB_METHOD_WEIGHTED_LEAST_CONNECTION_MEMBER"),
  ("Weighted Least Connections (node)", "LB_METHOD_WEIGHTED_LEAST_CONNECTION_NODE_ADDRESS"),
  ("Ratio (session)", "LB_METHOD_RATIO_SESSION"),
  ("Ratio Least Connections (member)", "LB_METHOD_RATIO_LEAST_CONNECTION_MEMBER"),
  ("Ratio Least Connections (node)", "LB_METHOD_RATIO_LEAST_CONNECTION_NODE_ADDRESS"),
]

def show_methods(method_list):
     print "Load balance Methods"
     print "____________________"
     for index, method in enumerate(method_list):
       print "%d - %s"%(index+1, method[0])

if __name__=='__main__':
  show_methods(LBMethods)
  index = input('Please select Load Balance method by number from list above: ')
  print LBMethods[index-1][1]

rawDescription: Python - efficiently select from list based on user input


code:
def printtext():
    global e
    string = e.get()
    print string

from Tkinter import *
root = Tk()

root.title('Name')

e = Entry(root)
e.pack()
e.focus_set()

b = Button(root,text='okay',command=printtext)
b.pack(side='bottom')
root.mainloop()

rawDescription: Taking input from the user in Tkinter

description: Taking input from the user in Tkinter


code:
import json

#Fix the null, normalize the json since is not a valid json
null = None
data = json.dumps({"payment_methods": [{
    "payment_type": "CC",
    "cardSubType": "AX",
    "card_number": "377777684182882",
    "expiration_month": "01",
    "expiration_year": "2018",
    "security_code": "",
    "cvv2": "",
    "name": {
        "first_name": "John",
        "last_name": "Smith"
    },
    "billing_address": {
        "country": "United States",
        "address_line1": "666 SUNSET BLVD",
        "address_line2": null,
        "city": "Anaheim",
        "state": "California",
        "zip_code": "92808",
        "phone": "0123456789"
    },
    "payment_amount": "",
    "payment_percentage": ""
}]})

data = json.loads(data)

billing_address = data["payment_methods"][0]["billing_address"]

print billing_address

rawDescription: Getting a dict from a list Python

description: Getting a dict from a list Python


code:
data = ["A", 112, "apple", 74, 112]
index = {val: i for i, val in reversed(list(enumerate(data)))}
indexes = [index[x] for x in data]
indexed = [(x, index[x]) for x in data]

print index
print indexes
print indexed

rawDescription: Convert list to list of ids

description: Convert list to list of ids


code:
import re

server_name = 'blah'
webmaster_email = 'blah@blah.com'

SUBS = ( (r'^#ServerName www.example.com', 'ServerName %s' % server_name),
        (r'^ServerAdmin root@localhost', 'ServerAdmin %s' % webmaster_email),
        (r'KeepAlive On', 'KeepAlive Off')
       )

with open("httpd.conf", "r+") as file:
    tmp=[]
    for i in file:
        for s in SUBS:
            ret=re.subn(s[0], s[1], i)
            if ret[1]>0:
                tmp.append(ret[0])
                break
        else:
            tmp.append(i)
    for i in tmp:
        print i,

rawDescription: How to modify configuration file with Python

description: Modify configuration file with Python


rawDescription: binary numbers?

description: Binary numbers


code:
size = 10
maxlen = len(str(size * size))
m = size * 2 - 1
matrix = [[' ' * maxlen] * m for _ in range(m)]

for n in range(size * size):
    r = n // size
    c = n % size
    matrix[c + r][size - r - 1 + c] = '{0:{1}}'.format(n + 1, maxlen)

print '\n'.join(''.join(row) for row in matrix)

rawDescription: Printing numbers in a diamond shape

description: Printing numbers in a diamond shape


code:
from collections import Counter

values = ['a', 'b', 'a', 'c']

# Take an iterable and automatically produce key/value count
counts = Counter(values)
# Counter({'a': 2, 'c': 1, 'b': 1})
print counts['a'] # 2
print counts['d'] # 0
# Note that `counts` doesn't have `0` as an entry value like a `defaultdict` would
# a `dict` would cause a `KeyError` exception
# Counter({'a': 2, 'c': 1, 'b': 1})

# Manually update if finer control is required
counts = Counter()
for value in values:
    counts.update(value) # or use counts[value] += 1
# Counter({'a': 2, 'c': 1, 'b': 1})

rawDescription: how to add to a dictionary value or create if not exists

description: Add to a dictionary value or create if not exists


code:
p1 = subprocess.Popen(["/usr/bin/java", "MyClass"], stdout=subprocess.PIPE)
print p1.stdout.read()

rawDescription: Calling Java app with "subprocess" from Python and reading the Java app output


code:
import httplib2
from apiclient import discovery
from oauth2client import appengine

_SCOPE = 'https://www.googleapis.com/auth/bigquery'

# Change the following 3 values:
PROJECT_ID = 'your_project'
DATASET_ID = 'your_dataset'
TABLE_ID = 'TestTable'

body = {"rows":[
    {"json": {"Col1":7,}}
]}

credentials = appengine.AppAssertionCredentials(scope=_SCOPE)
http = credentials.authorize(httplib2.Http())

bigquery = discovery.build('bigquery', 'v2', http=http)
response = bigquery.tabledata().insertAll(
   projectId=PROJECT_ID,
   datasetId=DATASET_ID,
   tableId=TABLE_ID,
   body=body).execute()

print response

rawDescription: How to use Bigquery streaming insertall on app engine & python

description: Use Bigquery streaming insertall on app engine & python


code:
from itertools import takewhile

def get_items_upto_count(dct, n):
  data = dct.most_common()
  val = data[n-1][1] #get the value of n-1th item
  #Now collect all items whose value is greater than or equal to `val`.
  return list(takewhile(lambda x: x[1] >= val, data))

test = Counter(["A","A","A","B","B","C","C","D","D","E","F","G","H"])

print get_items_upto_count(test, 2)
#[('A', 3), ('C', 2), ('B', 2), ('D', 2)]

rawDescription: Python collections.Counter: most_common INCLUDING equal counts


code:
import win32com.client
import win32con
import win32gui
import time

print "Start"
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = 1   # Visible via automation
time.sleep(2)
hwnd = win32gui.FindWindow(None, "Microsoft Excel")  # Class or title
print "Hide"
win32gui.ShowWindow(hwnd, win32con.SW_HIDE) # Hide via Win32Api
time.sleep(2)
print "Show"
win32gui.ShowWindow(hwnd, win32con.SW_SHOW) # Show via Win32Api
time.sleep(2)

###

rawDescription: How to hide COM object Dispatched from Python

description: Hide COM object Dispatched from Python


code:
r = re.compile(r"(self\.uid\s*=\s*)'\w{12}'")
for line in fileinput.input(['file.py'], inplace=True):
    print r.sub(r"\1'%s'" %sys.argv[1],line),

rawDescription: Use Regular expression with fileinput

description: Use Regular expression with fileinput


code:
from pathos.multiprocessing import Pool
pool = Pool()
import itertools

def interstellar(i):
  return sum(i)**2

result = []
for i in pool.imap_unordered(interstellar, itertools.combinations(xrange(10),2)):
  result.append(i); print "{:3.2f}%".format(100.*len(result)/45)

result

rawDescription: Progress in a itertools.combinations pool() map , result passed in list


code:
Products = productBll.listProduct(params)
print [prd.__dict__ for prd in Products]

rawDescription: print all the values of a group of objects without iterating through it

description: Print all the values of a group of objects without iterating through it


code:
if response.rstrip() == '0D6020100':
   print 'beepity boop beep woohoo!'

rawDescription: Python, response and if statement

description: Python, response and if statement


code:
from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

rawDescription: How do I run some python code in another process?

description: Run some python code in another process


code:
import sys
from foo import *
print A, B        #prints 1, 2
A, B = 100, 200
mod = reload(sys.modules['foo'])#use imp.reload for Python 3
vars().update(mod.__dict__)     #update the global namespace
print A, B        #prints 1, 2

rawDescription: how to reload after "from <module> import *"?

description: Reload after "from <module> import *"


code:
from os.path import exists
print exists("C:\somefile.txt")

rawDescription: How to check if a file exists in python?

description: Check if a file exists in python


code:
for elem in things.iterfind('thing/nodes/node[@id="1"]'):
    # get parent of node - nodes
    print elem.getparent()
    # get grand parent of node - thing
    print elem.getparent().getparent()
    # now lets get the thing id
    print elem.getparent().getparent().attrib.get('id')

rawDescription: Finding parent from child in XML using python


code:
from sqlalchemy import create_engine
from sqlalchemy.engine import reflection
engine = create_engine('...')
insp = reflection.Inspector.from_engine(engine)
for name in insp.get_table_names():
    for index in insp.get_indexes(name):
        print index

rawDescription: Listing indices using sqlalchemy

description: Listing indices using sqlalchemy


rawDescription: Python code to use a regular expression to make sure a string is alphanumeric plus . - _


code:
import ast
f = open('data.txt', 'r')
lines = f.readlines()
for line in lines:
    list_representation_of_line = ast.literal_eval(line)
    for element in list_representation_of_line:
            if element.startswith('**') and element.endswith('**'):
                    print list_representation_of_line
                    # or print single fields, e.g. timeIndex = 0 or another index
                    # print list_representation_of_line[timeindex]
                    break

rawDescription: Python: extracting patterns from CSV

description: Python: extracting patterns from CSV


code:
def run(project_dir, main_class, specific_args):
    classpath = []

    for root, dirs, files in os.walk(project_dir):
        if os.path.basename(root) not in ('lib', 'properties'):
            continue

        has_properties = False
        for f in files:
            if f.endswith('.jar'):
                classpath.append(os.path.join(root, f))
            if f.endswith('.properties'):
                has_properties = True
        if has_properties:
            classpath.append(root)

    classpath_augment = ':'.join(classpath)

    print java_command, classpath_augment, main_class, specific_args

rawDescription: traverse only specific python directories

description: Traverse only specific python directories


code:
import itertools as it

cur.execute("SELECT * FROM expiration WHERE exp BETWEEN date('now','-1 days') AND date('now','+6 days') ORDER BY exp")
sql.commit()
row = cur.fetchall()
for i,g in it.groupby(row, key=lambda x: x[0]):
    msg += 'Expiring %s%s\n' % (i, '\n\t'.join(x[1] for x in g))
print msg

rawDescription: Python: Group single column by distinct value


code:
from bs4 import BeautifulSoup
import urllib

with open('twfile.txt','r') as inputf, open('tw2file.txt','w') as output:
    for line in inputf:
        try:
            list1 = line.split(' ')
            for i in range(len(list1)):
                if "http" in list1[i]:
                    response = urllib.urlopen(list1[i])
                    html = response.read()
                    soup = BeautifulSoup(html)
                    list1[i] = soup.html.head.title
                    list1[i] = ''.join(ch for ch in list1[i]).strip() # here
                else:
                    list1[i] = ''.join(ch for ch in list1[i]).strip() # here
            line = ' '.join(list1)
            print line
            output.write('{}\n'.format(line))  # here
        except:
            pass

rawDescription: Python: Replacing url with title

description: Python: Replacing url with title


code:
def G(mass1, mass2, radius, force):
    rightSide = (float(mass1)*mass2) / (radius**2) #I want this to be a float
    print rightSide
    if rightSide==0:
        print("The operation resulted in a zero, error!")
    else:
        answer=force/rightSide
        print(str(answer)+" is the gravitation constant (G)!")

rawDescription: How to define new variable as float?

description: Define new variable as float


code:
def pattern():
    integer = int(raw_input("Please enter a number"))
    for number in range(0, integer):
        print " " * number + "*" * (integer - number)

rawDescription: reverse upside down asterisk triangle in python

description: Reverse upside down asterisk triangle in python


code:
import re
import os
s = 'asodgnasAIDID12313%*(@&(!$ 1231'
result = re.sub('[^a-zA-Z\d\. ]|( ){2,}','',s )
if result =='' or os.path.splitext(result)[0].isspace():
    print "not a valid name"
else:
    print "valid name"

rawDescription: In Python how to whitelist certain characters in a filename?


code:
data=f.read(256)
data=data.splitlines(True)
if data[-1]!=data[-1].splitlines()[-1]:
    #must be newline at end of last line
    data="".join(data)
else:
    data="".join(data[:-1])

print data

rawDescription: python read file with block, but end with newline(\n)

description: Python read file with block, but end with newline(\n)


rawDescription: Python numpy exponential notation

description: Python numpy exponential notation


code:
import Tkinter
root = Tkinter.Tk()

def handle_click(text):
    print text

for r in range(3):
    for c in range(6):
        text = 'R%s/C%s'%(r,c)
        label = Tkinter.Label(root, text=text, borderwidth=1 )
        label.grid(row=r,column=c)
        label.bind("<Button-1>", lambda e, text=text:handle_click(text))

root.mainloop()

rawDescription: getting row and column from mouse click event

description: Getting row and column from mouse click event


rawDescription: Regex replace text between delimiters in python


code:
import re
import time
import serial

def doRead(ser,term):
    matcher = re.compile(term)    #gives you the ability to search for anything
    tic     = time.time()
    buff    = ser.read(128)
    # you can use if not ('\n' in buff) too if you don't like re
    while ((time.time() - tic) < tout) and (not matcher.search(buff)):
       buff += ser.read(128)

    return buff

if __name__ == "__main__":
    ser = serial.Serial(PORT, BAUD, timeout = TOUT)
    ser.write(CMD)
    print doRead(ser,term='\n')

rawDescription: Python PySerial read-line timeout

description: Python PySerial read-line timeout


code:
import os
from PIL import Image

for fname in os.listdir():
    try:
        img = Image.open(fname)
    except Exception, e:
        print('{}: could not read: {}'.format(fname, e))
    else:
        print('{}: {}x{}'.format(fname, f.size[0], f.size[1]))

rawDescription: How to print details of image files in the current directory in python

description: Print details of image files in the current directory in python


code:
property = 'foo'
value = 'bar'

class MC(type):
  def __init__(cls, name, bases, dict):
    setattr(cls, property, value)
    super(MC, cls).__init__(name, bases, dict)

class C(object):
  __metaclass__ = MC

print C.foo

rawDescription: Setting an class attribute with a given name in python while defining the class


code: print utc_dt.astimezone(eastern)

rawDescription: Expression of timezone offset - clarification appreciated


code:
import re

# Unique-ify list, preserving order
def uniquify(l):
    return reduce(lambda s, e: s + ([] if e in s else [e]), l, [])

# Replace all keys in replacements with corresponding values in str
def replace_all(str, replacements):
    for old, new in replacements.iteritems():
        str = str.replace(old, new)
    return str

class Expression:
    units = ["m", "s"]

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

    # Returns a list of symbols in the expression that are preceded
    # by the given unit, ordered by first appearance. Assumes the
    # symbol and unit are separated by a space. For example:
    # Expression("A m * B s / (A m + C m)").symbols_for_unit("m")
    # returns ['A', 'C']
    def symbols_for_unit(self, unit):
        sym_re = re.compile("(.) %s" % unit)
        symbols = sym_re.findall(self.exp)
        return uniquify(symbols)

    # Returns a string with all symbols that have units other than
    # unit "muted", that is replaced with the empty string. Example:
    # Expression("A m * B s / (A m + C m)").mute_symbols_for_other_units("m")
    # returns "A m *  s / (A m + C m)"
    def mute_symbols_for_other_units(self, unit):
        other_units = "".join(set(self.units) - set(unit))
        return re.sub("(.) ([%s])" % "".join(other_units), " \g<2>", self.exp)

    # Returns a string with all symbols that have the given unit
    # replaced with tokens of the form $0, $1, ..., by order of their
    # first appearance in the string, and all other symbols muted.
    # For example:
    # Expression("A m * B s / (A m + C m)").canonical_form("m")
    # returns "$0 m *  s / ($0 m + $1 m)"
    def canonical_form(self, unit):
        symbols = self.symbols_for_unit(unit)
        muted_self = self.mute_symbols_for_other_units(unit)
        for i, sym in enumerate(symbols):
            muted_self = muted_self.replace("%s %s" % (sym, unit), "$%s %s" % (i, unit))
        return muted_self

    # Define a permutation, represented as a dictionary, according to
    # the following rule: replace $i with the ith distinct symbol
    # occurring in the expression with the given unit. For example:
    # Expression("C m * B s / (C m + A m)").permutation("m")
    # returns {'$0':'C', '$1':'A'}
    def permutation(self, unit):
        enum = enumerate(self.symbols_for_unit(unit))
        return dict(("$%s" % i, sym) for i, sym in enum)

    # Return a string produced from the expression by first converting it
    # into canonical form, and then performing the replacements defined
    # by the given permutation. For example:
    # Expression("A m * B s / (A m + C m)").permute("m", {"$0":"C", "$1":"A"})
    # returns "C m *  s / (C m + A m)"
    def permute(self, unit, permutation):
        new_exp = self.canonical_form(unit)
        return replace_all(new_exp, permutation)

    # Test for equality under permutation and muting of all other symbols
    # than the unit provided.
    def eq_under_permutation(self, unit, other_exp):
        muted_self = self.mute_symbols_for_other_units(unit)
        other_permuted_str = other_exp.permute(unit, self.permutation(unit))
        return muted_self == other_permuted_str

    # Test for equality under permutation. This is done for each of
    # the possible units using eq_under_permutation
    def __eq__(self, other):
        return all([self.eq_under_permutation(unit, other) for unit in self.units])

e1 = Expression("A m * B s / (A m + C m)")
e2 = Expression("C m * B s / (C m + A m)")
e3 = Expression("A s * B s / (A m + C m)")

f1 = Expression("A s * (B s + D s) / (A m + C m)")
f2 = Expression("A s * (D s + B s) / (C m + A m)")
f3 = Expression("D s")

print "e1 == e2: ", e1 == e2 # True
print "e1 == e3: ", e1 == e3 # False
print "e2 == e3: ", e2 == e3 # False

print "f1 == f2: ", f1 == f2 # True
print "f1 == f3: ", f1 == f3 # False

rawDescription: Testing equivalence of mathematical expressions in Python


code:
for i in glob.glob("*.jpg"):
    text = textract.process(i)
    # Split text to multi lines
    for line in text.split('\n'):
        if line.startswith('5'):
                print line

rawDescription: How to clean up this python output

description: Clean up this python output


code:
import sys, logging

class SMSEmailFilter(logging.Filter):
    def filter(self, record):
        if not record.args:
            if record.levelno == logging.WARN:
                email(record.msg)
            elif record.levelno >= logging.ERROR:
                sms(record.msg)
        return True

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', stream=sys.stdout)
logger = logging.getLogger()
logger.addFilter(SMSEmailFilter())

def email(_msg):
    try:
        print "Sending email..."
    except:
        logger.error('from email', {'a': 1})

def sms(_msg):
    try:
        print "Sending sms..."
    except:
        logger.error('from sms', {'a': 1})

logger.warning('This is a warning')
logger.error('This is an error')

rawDescription: python intercept logging to email or sms

description: Python intercept logging to email or sms


rawDescription: How do I get the looping index when using Python zip-function?

description: Get the looping index when using Python zip-function


code:
from ctypes import *
class POINT(Structure):
    _fields_ = [("x", c_int),
                ("y", c_int)]
point = POINT(10, 20)
print point.x, point.y
point = POINT(y=5)
print point.x, point.y
POINT(1, 2, 3)

rawDescription: Python ctypes & libspeex.dll/libspeex.so; what are the equivilents to #define, typedef, and structs?


code:
import os, sys, tarfile

def extract(tar_url, extract_path='.'):
    print tar_url
    tar = tarfile.open(tar_url, 'r')
    for item in tar:
        tar.extract(item, extract_path)
        if item.name.find(".tgz") != -1 or item.name.find(".tar") != -1:
            extract(item.name, "./" + item.name[:item.name.rfind('/')])
try:

    extract(sys.argv[1] + '.tgz')
    print 'Done.'
except:
    name = os.path.basename(sys.argv[0])
    print name[:name.rfind('.')], '<filename>'

rawDescription: I want to extract a .tgz file and extract any subdirectories that have files that are .tgz and .tar


code:
import random
import time
import numpy as np
list1 = [random.choice((0,1)) for x in xrange(307200)]
list2 = [random.choice((0,1)) for x in xrange(307200)]
a1 = np.array(list1)
a2 = np.array(list2)

def foo1():
    start = time.clock()
    counter = 0
    for i in xrange(307200):
        if list1[i] != list2[i]:
            counter += 1
    print "%d, %f" % (counter, time.clock()-start)

def foo2():
    start = time.clock()
    ct = np.sum(a1!=a2)
    print "%d, %f" % (ct, time.clock()-start)

foo1() #153490, 0.096215
foo2() #153490, 0.010224

rawDescription: What's the fastest way to compare two large lists of 1's & 0's and return the difference count/percentage?


code:
def fix_machine(debris, product):
    n = 0
    while debris.find(product[n]) != -1:
        print product[n]
        n = n + 1

rawDescription: Why doesn't this loop?

description: Why doesn't this loop


code:
while True:
    ghuess=input("state a number between 1-100")
    if ghuess>number:
        print "too high try again!"
    elif ghuess<number:
        print "too low try again!"
    else:
        # Jackpot, exit the loop.
        break
print "well done! ghuess you have won.."
time.sleep(1)
print "3"
time.sleep(1)
print "2"
time.sleep(1)
print "1"
time.sleep(1)
print prize

rawDescription: How to repeat a section of program until the input is correct in python?

description: Repeat a section of program until the input is correct in python


code:
import math

def prime (n):
    for i in xrange(2, int(math.sqrt(n))+1):
        if n % i == 0:
            return False
    return True

s = 2 # Sum
for i in xrange(3,2000000, 2):
    if prime(i):
        s += i
print s

rawDescription: how to make this code on python run faster?

description: Make this code on python run faster


code:
class idClasses:
    class ID12345:pass
    class ID01234:pass
# could also be: import idClasses

class ProcessDirector:
    def __init__(self):
        self.allClasses = []

    def construct(self, builderName):
        targetClass = getattr(idClasses, builderName)
        instance = targetClass()
        self.allClasses.append(instance)

IDS = ["ID12345", "ID01234"]

director = ProcessDirector()
for id in IDS:
    director.construct(id)

print director.allClasses
# [<__main__.ID12345 instance at 0x7d850>, <__main__.ID01234 instance at 0x7d918>]

rawDescription: Can you use a string to instantiate a class in python?

description: Use a string to instantiate a class in python


code:
def remove_none(obj):
  if isinstance(obj, (list, tuple, set)):
    return type(obj)(remove_none(x) for x in obj if x is not None)
  elif isinstance(obj, dict):
    return type(obj)((remove_none(k), remove_none(v))
      for k, v in obj.items() if k is not None and v is not None)
  else:
    return obj

from collections import OrderedDict
data1 = ( 501, (None, 999), None, (None), 504 )
data2 = { 1:601, 2:None, None:603, 'four':'sixty' }
data3 = OrderedDict( [(None, 401), (12, 402), (13, None), (14, data2)] )
data = [ [None, 22, tuple([None]), (None,None), None], ( (None, 202), {None:301, 32:302, 33:data1}, data3 ) ]
print remove_none(data)

rawDescription: Python: How RECURSIVELY remove None values from a NESTED data structure (lists and dictionaries)?


code:
check_list = [11, 13, 14, 16, 17, 18, 19, 20]

def find_solution(step):
    for num in xrange(step, 999999999, step):
        if all(num % n == 0 for n in check_list):
            return num
    return None

if __name__ == '__main__':
    solution = find_solution(20)
    if solution is None:
        print "No answer found"
    else:
        print "found an answer:", solution

rawDescription: Project Euler 5 in Python - How can I optimize my solution?


rawDescription: How can I turn 000000000001 into 1?

description: Turn 000000000001 into 1


code:
bounds = [0, 100]
minimum, maximum = bounds

number = int(raw_input('Pick a number [{0}-{1}]: '.format(minimum, maximum)))

while guess != number:
  guess = int((maximum + minimum) / 2)
  raw_input('Guessing {0}'.format(guess))

  if guess > number:
    maximum = guess
  elif guess < number:
    maximum = bounds[1]
    minimum = guess

print 'I win!'

rawDescription: Help with a guess my number program in python


code:
#!/usr/bin/env python

''' Create a GTK Dialog containing a combobox that closes
    when a combobox item is selected

    See http://stackoverflow.com/q/35812198/4014959

    Written by PM 2Ring 2016.03.05
'''

import pygtk
pygtk.require('2.0')
import gtk

lista = ('zero', 'one', 'two', 'three')

class Demo:
    def __init__(self):
        self.win = win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        win.connect("destroy", lambda w: gtk.main_quit())

        button = gtk.Button("Open dialog")
        button.connect("clicked", self.dialog_button_cb)
        win.add(button)
        button.show()

        self.dialog = gtk.Dialog("Combo dialog", self.win,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))

        combobox = gtk.combo_box_new_text()
        for s in lista:
            combobox.append_text(s)
        combobox.connect("changed", self.combo_cb)
        self.dialog.action_area.pack_end(combobox)
        combobox.show()

        win.show()

    def dialog_button_cb(self, widget):
        response = self.dialog.run()
        print "dialog response:", response
        self.dialog.hide()
        return True

    def combo_cb(self, combobox):
        index = combobox.get_active()
        if index > -1:
            print "combo", index, lista[index]
            self.dialog.response(gtk.RESPONSE_ACCEPT)
        return True

def main():
    Demo()
    gtk.main()

if __name__ == "__main__":
    main()

rawDescription: How to Close GTK Dialogue on event change of combobox?


code:
filter_indices = [1,3,5]
print numpy.array([11,13,155,22,0xff,32,56,88])[filter_indices]

rawDescription: How to filter numpy array by list of indices?

description: Filter numpy array by list of indices


code:
import scipy.sparse

class SparseBlocks(object):
    def __init__(self, data, chunksize=5):
        self.data = data
        self.chunksize = chunksize
    def _convert_slices(self, slices):
        newslices = []
        for axslice in slices:
            if isinstance(axslice, slice):
                start, stop = axslice.start, axslice.stop
                if axslice.start is not None:
                    start *= self.chunksize
                if axslice.stop is not None:
                    stop *= self.chunksize
                axslice = slice(start, stop, None)
            elif axslice is not None:
                axslice = slice(axslice, axslice+self.chunksize)
            newslices.append(axslice)
        return tuple(newslices)

    def __getitem__(self, item):
        item = self._convert_slices(item)
        return self.data.__getitem__(item)
    def __setitem__(self, item, value):
        item = self._convert_slices(item)
        return self.data.__setitem__(item, value)

data = scipy.sparse.lil_matrix((20,20))
s = SparseBlocks(data)
s[0,0] = 1
print s.data

rawDescription: How to create view/python reference on scipy sparse matrix?

description: Create view/python reference on scipy sparse matrix


code:
import numpy

# some random arrays
ka = numpy.random.random_integers(0,1,37*31).reshape(31,37)
kb = numpy.random.random_integers(0,1,37*31).reshape(31,37)
kc = numpy.random.random_integers(0,1,37*31).reshape(31,37)
combined_rest = kb + kc

print "independance:", numpy.sum( (ka == 1) & (combined_rest < 2) )

rawDescription: Find an easier way to compare two 2-d array's independence


code:
for university in universities:
    span = [span.extract() for span in university('span')]
    univ = university.text.replace(' ','').replace('\r','').replace('\n','')
    print univ

rawDescription: Text before <span> flag

description: Text before <span> flag


code:
import re
import csv
import json
import urllib2

city = 'Helsinki';

csvFile = csv.writer(open( city + ".csv", "wb+"))
csvFile.writerow(["tempid","latitude", "longitude"])

pageID = 0

locPage = urllib2.urlopen("http://runkeeper.com/user/maxspowers79/route/2481336")
content = locPage.read()

start_at_s, end_at_s = 'var routePoints = ', 'mapController.initialize'

start_at_p = content.index(start_at_s) + len(start_at_s)
end_at_p = content.index(end_at_s)
raw_json = content[start_at_p:end_at_p].strip().strip(';')

jsonObj = json.loads(raw_json)

pageID += 1
print pageID

for x in jsonObj:
    print x
    csvFile.writerow([pageID,x["latitude"],x["longitude"]])

rawDescription: Beautifulsoup Parser Truncating larger json


code:
import csv, json
from collections import defaultdict

def tree():
    return defaultdict(tree)

d = tree()

with open('data.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=',')

    for name, code, count in list(reader)[1:]:
        path = code.split('.')
        iter_node = d
        for node in path:
            iter_node = iter_node[node]
        iter_node['values'][name] = count

print json.dumps(d, indent=2)

{
  "01": {
    "values": {
      "Chris": "4",
      "Bill": "32",
      "Adam": "48"
    },
    "01": {
      "values": {
        "Dave": "1",
        "Carl": "5",
        "David": "1"
      },
      "03": {
        "01": {
          "01": {
            "02": {
              "values": {
                "Oliver": "16"
              }
            },
            "03": {
              "values": {
                "Paul": "23"
              }
            },
            "01": {
              "values": {
                "Nick": "1"
              }
            },
            "values": {
              "Mike": "45"
            }
          },
          "values": {
            "Larry": "3"
          }
        }
      },
      "01": {
        "values": {
          "Eric": "26"
        },
        "02": {
          "values": {
            "Greg": "2"
          }
        },
        "03": {
          "values": {
            "Harold": "7",
            "Ian": "3",
            "Jack": "1"
          }
        },
        "01": {
          "values": {
            "Earl": "2",
            "Frank": "2"
          }
        },
        "04": {
          "values": {
            "John": "10",
            "Kyle": "2"
          }
        }
      }
    }
  }
}

rawDescription: Hierarchical JSON from csv python

description: Hierarchical JSON from csv python


code:
#!/usr/bin/env python
import os, sys, subprocess, time
while True:
    p=subprocess.Popen(["xsel"],stdout=subprocess.PIPE)
    print p.stdout.read()
    time.sleep(1)

rawDescription: Strip final 0 off a python string

description: Strip final 0 off a python string


code:
import twitter

# Remember to put these values
api = twitter.Api(consumer_key="",
                  consumer_secret="",
                  access_token_key="",
                  access_token_secret="")

# Get your timeline
print api.GetHomeTimeline()

rawDescription: Log-in to a website using Google, Facebook or Twitter accounts with Python


code:
seen = dict()
for row in data:
    n = seen.setdefault(row[0], 0)
    if n < 2:
        print row
    seen[row[0]] += 1

rawDescription: Get N lines from file

description: Get N lines from file


code:
import subprocess
import json

testing = "HelloWorld"

jsonStr = '{"script":"#!/bin/bash \\n STRING=\'%VP%\' \\n echo $STRING \\n"}'.replace('%VP%', testing)

j = json.loads(jsonStr)

print "start"
subprocess.call(j['script'], shell=True)
print "end"

rawDescription: How to execute shell script from Python after passing input parameters

description: Execute shell script from Python after passing input parameters


code:
fig, ax = plt.subplots()
ax.plot(range(10), 'ro-')

points = plt.ginput(n=4)
print points
np.savetxt('yourfilename', points)

plt.show()

rawDescription: Get data from Python plot with matplotlib then save to array


code:
# std lib modules. "Batteries included" FTW.
import threading
import time

thread_result = -1

def ThreadWork():
  global thread_result
  thread_result = 1 + 1
  time.sleep(5)  # phew, I'm tiered after all that addition!

my_thread = threading.Thread(target=ThreadWork)
my_thread.start()  # This will call ThreadWork in the background.
                   # In the mean time, you can do other stuff
y = 2 * 5  # Completely independent calculation.
my_thread.join()  # Wait for the thread to finish doing it's thing.
                  # This should take about 5 seconds,
                  # due to time.sleep being called
print "thread_result * y =", thread_result * y

rawDescription: How to make concurrent web service calls from a Django view?

description: Make concurrent web service calls from a Django view


code: print 'empty' if not any(seq) else 'not empty'

rawDescription: Easy way to check if nested list has any entries


code:
from sqlalchemy.event import listen
from sqlalchemy.pool import Pool

def my_on_connect(dbapi_con, connection_record):
    print "New DBAPI connection:", dbapi_con

listen(Pool, 'connect', my_on_connect)

rawDescription: Triggering connection pools with sqlalchemy in flask


code:
#! /usr/bin/env python

import sys
import os
from suds.client import Client

at_username = "foo@bar.com"
at_password = "foobar"

at_url = "https://webservices4.autotask.net/atservices/1.5/atws.wsdl"

def main():
    client = Client(at_url, username=at_username, password=at_password)           # Instatiate a suds.client.Client instance and connect to webservices URL

    q = """
    <queryxml>
        <entity>Ticket</entity>
        <query>
            <condition>
                <field>Id
                    <expression op="GreaterThan">0</expression>
                </field>
            </condition>
            <condition>
                <field>Status
                    <expression op="NotEqual">5</expression>
                </field>
            </condition>
            <condition>
                <field>EstimatedHours
                    <expression op="IsNull"></expression>
                </field>
            </condition>
        </query>
    </queryxml>"""

    # Status value '5' == Complete

    response = client.service.query(q)

    if response.ReturnCode != 1:
        print "Error code: %s" % response.ReturnCode
        print "Error response: %s" % response.Errors
        sys.exit(1)
    else:
        os.system("clear")
        print "Query successful..."
        print "============================="
        print response.EntityResults

main()

rawDescription: How to use QueryXML with SUDS and AutotaskAPI

description: Use QueryXML with SUDS and AutotaskAPI


code:
import stackless
ch1 = stackless.channel()
def a():
 ch2 = stackless.channel()
 ch1.send(ch2)
 ch2.send("Hello")
def b():
 ch3 = ch1.receive()
 print ch3.receive()
stackless.tasklet(a)()
stackless.tasklet(b)()
stackless.run()

rawDescription: In stackless Python, can you send a channel over a channel?


code:
import numpy as np
from scipy import optimize
from multiprocessing import Pool

def square(x, a=1):
    return [np.sum(x**2 + a), 2*x]

def minimize(args):
    f,x,a = args
    res = optimize.minimize(f, x, method = 'BFGS', jac = True, args = [a])
    return res.x

# your a values
a = np.arange(1,11)

# initial guess for all the x values
x = np.empty(len(a))
x[:] = 25

args = [(square,a[i],x[i]) for i in range(10)]
p = Pool(4)
print p.map(minimize,args)

rawDescription: Parallel optimizations in SciPy

description: Parallel optimizations in SciPy


code:
sent = nltk.corpus.treebank.tagged_sents()[22]
print nltk.ne_chunk(sent)

rawDescription: Parsing Meaning from Text

description: Parsing Meaning from Text


code:
import csv
with open('x.txt') as f:
    # use space as delimiter
    reader = csv.reader(f, delimiter=' ')
    # sort by the value in the second place of each line i.e. x[1]
    s = sorted(reader, key=lambda x: x[1], reverse=True)
    # filter only grater than 0.5 and take the first value only
    l = [x[0] for x in s if float(x[1])>0.5]
    print l[:3]
    print l[3:]

rawDescription: How to sort the text in a file in python?

description: Sort the text in a file in python


code:
import subprocess
cmd = ["ls", "-la"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in proc.stdout.readlines():
    print line

rawDescription: Read shell output from python line-by-line


code:
line = f.readline()
if not "@" in line:
    matches = re.findall(r'(\w+:\w+)@',line)
    for match in matches:
            print match

line = f.readline()
if not "@" in line:
    matches = re.findall(r'([\w.]+@[\w.]+:\w+)',f.read())
    for match in matches:
            print match

line = f.readline()
if not "@" in line:
    matches = re.findall(r'(\w+:\w+)\n',f.read())
    for match in matches:
        print match

rawDescription: Skip python from reading line if it has a certain character


code:
import numpy
import scipy.signal

a = numpy.zeros((6,6), dtype=numpy.int) # Example array
a[2:4, 2:4] = 1;a[2,4] = 1 # with example value structure

b = 1-a
c = scipy.signal.convolve2d(b, numpy.ones((3,3)), mode='same')

print numpy.sum(c * a)

rawDescription: Counting of adjacent cells in a numpy array


code:
def time(fileName) :
    with open(fileName, "r") as tFile :
            for line in tFile :
                li = line.split()
                if li :
                    start_time = (int(li[0]) / 10000000.)
                    end_time = (int(li[1]) / 10000000.)
                    duration = ((int(li[1]) -int(li[0]))/10000000.)
                    print start_time,' ',end_time,' ',duration

                    poly = poly_coeff(start_time, end_time, duration)
                    Newton(poly, 0.42, 1, 0)

def poly_coeff(stime, etime, dur) :
    """The equation is k6 * u^3 + k5 * u^2 + k4 * u + k0 = 0. Computing the        coefficients of this equation."""
    """Substituting the required values we get the coefficients."""
    w = 5  # weight for rational bezier curve equation

    t_u = dur
    t0 = stime
    t3 = etime
    t1 = t2 = (stime + etime) / 2
    w0 = w1 = w2 = w3 = w
    k0 = w0 * (t_u - t0)
    k1 = w1 * (t_u - t1)
    k2 = w2 * (t_u - t2)
    k3 = w3 * (t_u - t3)
    k4 = 3 * (k1 - k0)
    k5 = 3 * (k2 - 2 * k1 + k0)
    k6 = k3 - 3 * k2 + 3 * k1 -k0
    print k0, k1, k2, k3, k4, k5, k6

    return [[k6,3], [k5,2], [k4,1], [k0,0]]

if __name__ == "__main__" :
    if len(sys.argv) != 2 :
        Usage()
    else :
        transcriptionFile = sys.argv[1]

        time(transcriptionFile)

rawDescription: passing polynomial coefficients generated from one function to another

description: Passing polynomial coefficients generated from one function to another


code:
class node:
    name="temp"
    ID=-1
    abstract="a short description"
    text="the full description"
    sons=[]
    def sLen(self): # here
        print ("hello")
        return len(self.sons)

n = node()
n.sons = [1, 2, 3]
print n.sLen()

rawDescription: defining a method inside a class in python

description: Defining a method inside a class in python


code: print "".join(e[0] for e in x.split())

rawDescription: Creating acronyms in Python

description: Creating acronyms in Python


code:
for n in range(2, 10001):
    if sum(i for i in range(2, n/2 + 1) if n % i == 0) == n - 1:
        print n

rawDescription: did my program on perfect numbers in python and not sure if i should use (1,1000) or (2, n+1) in range

description: Did my program on perfect numbers in python and not sure if i should use (1,1000) or (2, n+1) in range


code:
from vtk import*
from parse import *
import os
import time, signal, threading

def ParseSIG(signum, stack):
        print signum
        return

class vtkGyroCallback():
        def __init__(self):
                pass
        def execute(self, obj, event):
                #Modified segment to accept input for leftCam position
                gyro = (raw_input())
                xyz = parse("{} {} {}", gyro)
                #print xyz

                # "Thread" the renders. Left is called on a right TimerEvent and right is called on a left TimerEvent.
                if obj.ID == 1 and event == 'TimerEvent':
                        self.leftCam.SetPosition(float(xyz[0]), float(xyz[1]), float(xyz[2]))
                        self.irenL.Render()
                        #print "Left"
                elif obj.ID == 2 and event == 'TimerEvent':
                        self.rightCam.SetPosition(float(xyz[0]), float(xyz[1]), float(xyz[2]))
                        self.irenR.Render()
                        #print "Right"
                return

def main():

        # create two cameras
        cameraR = vtkCamera()
        cameraR.SetPosition(0,0,200)
        cameraR.SetFocalPoint(0,0,0)

        cameraL = vtkCamera()
        cameraL.SetPosition(40,0,200)
        cameraL.SetFocalPoint(0,0,0)

        # create a rendering window and renderer
        renR = vtkRenderer()
        renR.SetActiveCamera(cameraR)

        renL = vtkRenderer()
        renL.SetActiveCamera(cameraL)

        # create source
        reader = vtkPolyDataReader()
        path = "/home/compilezone/Documents/3DSlicer/SlicerScenes/LegoModel-6_25/Model_5_blood.vtk"
        reader.SetFileName(path)
        reader.Update()

        # create render window

        renWinR = vtkRenderWindow()
        renWinR.AddRenderer(renR)
        renWinR.SetWindowName("Right")

        renWinL = vtkRenderWindow()
        renWinL.AddRenderer(renL)
        renWinL.SetWindowName("Left")

        # create a render window interactor
        irenR = vtkRenderWindowInteractor()
        irenR.SetRenderWindow(renWinR)

        irenL = vtkRenderWindowInteractor()
        irenL.SetRenderWindow(renWinL)

        # mapper
        mapper = vtkPolyDataMapper()
        mapper.SetInput(reader.GetOutput())

        # actor
        actor = vtkActor()
        actor.SetMapper(mapper)

        # assign actor to the renderer
        renR.AddActor(actor)
        renL.AddActor(actor)

        # enable user interface interactor
        renWinR.Render()
        renWinL.Render()
        irenR.Initialize()
        irenL.Initialize()

        #Create callback object for camera manipulation
        cb = vtkGyroCallback()
        cb.rightCam = renR.GetActiveCamera()#cameraR
        cb.leftCam = renL.GetActiveCamera()#cameraL
        cb.irenR = irenR
        cb.irenL = irenL

        irenR.ID = 1
        irenL.ID = 2
        irenR.AddObserver('TimerEvent', cb.execute)
        irenL.AddObserver('TimerEvent', cb.execute)
        timerIDR = irenR.CreateRepeatingTimer(100)
        timerIDL = irenL.CreateRepeatingTimer(100)

        irenL.Start()
        irenR.Start()

if __name__ == '__main__':

        main()

rawDescription: VTK update position of multiple render windows


code:
pagination_urls = ["http://google.com"]

def oss(url):
    data = url
    return data

for url in pagination_urls:
    data = oss(url)
    spider = data
    print spider

rawDescription: can't return a variable outside the function

description: Can't return a variable outside the function


code:
def f():
        global cat
        exec 'global cat; cat'+'="meow"'

f()
cat

rawDescription: Exec statement won't properly define names


code:
from unidecode import unidecode
print unidecode(u"\u5317\u4EB0")

rawDescription: Where is Python's "best ASCII for this Unicode" database?


code:
from xgoogle.search import GoogleSearch, SearchError
try:
  page = 1
  gs = GoogleSearch("foo bar")
  gs.results_per_page = 100
  results = []
  while page < 10:
      gs.page = page
      results += gs.get_results()
      page += 1
except SearchError, e:
  print "Search failed: %s" % e
for res in results:
    print res.url

rawDescription: problem with python xgoogle library. How to increase the limit of 10 results?

description: Problem with python xgoogle library. How to increase the limit of 10 results


code:
def shuffle(L, nswaps):
    n = 0

    for item in L:
        while n < nswaps:
            card_one = choose(L)
            card_two = choose(L)

            if card_two == card_one:
                card_two = choose(L)

            n += 1
            L[card_one], L[card_two] = L[card_two], L[card_one]

        print L

rawDescription: Printing issue in Python

description: Printing issue in Python


code:
import os
import sys

# Import System libraries
import glob
import random
import re

sys.coinit_flags = 0 # comtypes.COINIT_MULTITHREADED

# USE COMTYPES OR WIN32COM
#import comtypes
#from comtypes.client import CreateObject

# USE COMTYPES OR WIN32COM
import win32com
from win32com.client import Dispatch

scripts_dir = "C:\\scripts"
conv_scripts_dir = "C:\\converted_scripts"
strcode = \
'''
sub test()
   msgbox "Inside the macro"
end sub
'''

#com_instance = CreateObject("Excel.Application", dynamic = True) # USING COMTYPES
com_instance = Dispatch("Excel.Application") # USING WIN32COM
com_instance.Visible = True
com_instance.DisplayAlerts = False

for script_file in glob.glob(os.path.join(scripts_dir, "*.xls")):
    print "Processing: %s" % script_file
    (file_path, file_name) = os.path.split(script_file)
    objworkbook = com_instance.Workbooks.Open(script_file)
    xlmodule = objworkbook.VBProject.VBComponents.Add(1)
    xlmodule.CodeModule.AddFromString(strcode.strip())
    objworkbook.SaveAs(os.path.join(conv_scripts_dir, file_name))

com_instance.Quit()

rawDescription: Use Python to Inject Macros into Spreadsheets


code: print sum(map(len,dic.itervalues()))

rawDescription: Is there a pythonic way to grab the total amount of variables within lists inside a dict?


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(source_code)
for item in soup.find_all('a'):
    print item['name']

rawDescription: Getting 'name' attributes with Beautiful Soup


code:
import time
import inspect
import functools

def sleep(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        result = f(*args, **kwargs)
        time.sleep(0.1)
        return result
    return wrapper

def sleeper(cls):
    for name, method in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls, name, sleep(method))
    return cls

@sleeper
class Foo(object):
   def __init__(self, a, b):
       self.a = a
       self.b = b
   def printer(self, arg):
       print arg

f = Foo(1,2)
f.printer('hi')

rawDescription: Make a pause after each execution of a method


code:
last = ''
for line in f:
    x = line.split()[0]
    print last,x
    last = x

rawDescription: Accessing Multiple Lines

description: Accessing Multiple Lines


code:
import MySQLdb

db = MySQLdb.connect(user="username", db="dbname")
cursor = db.cursor()

batch_queries = '''
    SELECT * FROM posts WHERE id=1;
    SELECT * FROM posts WHERE id=2;
'''
cursor.execute(batch_queries)

print cursor.fetchone()
while cursor.nextset():  # iterate to next result set if there is any
    print cursor.fetchone()

cursor.close()

rawDescription: Multiqueries with python/mysql

description: Multiqueries with python/mysql


rawDescription: Search in a timespan

description: Search in a timespan


code:
import ctypes

import numpy as np
import pycuda.autoinit
import pycuda.gpuarray as gpuarray

CUSOLVER_STATUS_SUCCESS = 0

libcusolver = ctypes.cdll.LoadLibrary('libcusolver.so')

libcusolver.cusolverDnCreate.restype = int
libcusolver.cusolverDnCreate.argtypes = [ctypes.c_void_p]

def cusolverDnCreate():
    handle = ctypes.c_void_p()
    status = libcusolver.cusolverDnCreate(ctypes.byref(handle))
    if status != CUSOLVER_STATUS_SUCCESS:
        raise RuntimeError('error!')
    return handle.value

libcusolver.cusolverDnDestroy.restype = int
libcusolver.cusolverDnDestroy.argtypes = [ctypes.c_void_p]

def cusolverDnDestroy(handle):
    status = libcusolver.cusolverDnDestroy(handle)
    if status != CUSOLVER_STATUS_SUCCESS:
        raise RuntimeError('error!')

libcusolver.cusolverDnSgetrf_bufferSize.restype = int
libcusolver.cusolverDnSgetrf_bufferSize.argtypes = [ctypes.c_void_p,
                                                    ctypes.c_int,
                                                    ctypes.c_int,
                                                    ctypes.c_void_p,
                                                    ctypes.c_int,
                                                    ctypes.c_void_p]

def cusolverDnSgetrf_bufferSize(handle, m, n, A, lda, Lwork):
    status = libcusolver.cusolverDnSgetrf_bufferSize(handle, m, n,
                                                     int(A.gpudata),
                                                     n, ctypes.pointer(Lwork))
    if status != CUSOLVER_STATUS_SUCCESS:
        raise RuntimeError('error!')

libcusolver.cusolverDnSgetrf.restype = int
libcusolver.cusolverDnSgetrf.argtypes = [ctypes.c_void_p,
                                         ctypes.c_int,
                                         ctypes.c_int,
                                         ctypes.c_void_p,
                                         ctypes.c_int,
                                         ctypes.c_void_p,
                                         ctypes.c_void_p,
                                         ctypes.c_void_p]

def cusolverDnSgetrf(handle, m, n, A, lda, Workspace, devIpiv, devInfo):
    status = libcusolver.cusolverDnSgetrf(handle, m, n, int(A.gpudata),
                                          lda,
                                          int(Workspace.gpudata),
                                          int(devIpiv.gpudata),
                                          int(devInfo.gpudata))
    if status != CUSOLVER_STATUS_SUCCESS:
        raise RuntimeError('error!')

libcusolver.cusolverDnSgetrs.restype = int
libcusolver.cusolverDnSgetrs.argtypes = [ctypes.c_void_p,
                                         ctypes.c_int,
                                         ctypes.c_int,
                                         ctypes.c_int,
                                         ctypes.c_void_p,
                                         ctypes.c_int,
                                         ctypes.c_void_p,
                                         ctypes.c_void_p,
                                         ctypes.c_int,
                                         ctypes.c_void_p]

def cusolverDnSgetrs(handle, trans, n, nrhs, A, lda, devIpiv, B, ldb, devInfo):
    status = libcusolver.cusolverDnSgetrs(handle, trans, n, nrhs,
                                          int(A.gpudata), lda,
                                          int(devIpiv.gpudata), int(B.gpudata),
                                          ldb, int(devInfo.gpudata))
    if status != CUSOLVER_STATUS_SUCCESS:
        raise RuntimeError('error!')

if __name__ == '__main__':
    m = 3
    n = 3
    a = np.asarray(np.random.rand(m, n), np.float32)
    a_gpu = gpuarray.to_gpu(a.T.copy())
    lda = m
    b = np.asarray(np.random.rand(m, n), np.float32)
    b_gpu = gpuarray.to_gpu(b.T.copy())
    ldb = m

    handle = cusolverDnCreate()
    Lwork = ctypes.c_int()

    cusolverDnSgetrf_bufferSize(handle, m, n, a_gpu, lda, Lwork)
    Workspace = gpuarray.empty(Lwork.value, dtype=np.float32)
    devIpiv = gpuarray.zeros(min(m, n), dtype=np.int32)
    devInfo = gpuarray.zeros(1, dtype=np.int32)

    cusolverDnSgetrf(handle, m, n, a_gpu, lda, Workspace, devIpiv, devInfo)
    if devInfo.get()[0] != 0:
        raise RuntimeError('error!')
    CUBLAS_OP_N = 0
    nrhs = n
    devInfo = gpuarray.zeros(1, dtype=np.int32)
    cusolverDnSgetrs(handle, CUBLAS_OP_N, n, nrhs, a_gpu, lda, devIpiv, b_gpu, ldb, devInfo)

    x_cusolver = b_gpu.get().T
    cusolverDnDestroy(handle)

    x_numpy = np.linalg.solve(a, b)
    print np.allclose(x_numpy, x_cusolver)

rawDescription: getrs function of cuSolver over pycuda doesn't work properly

description: Getrs function of cuSolver over pycuda doesn't work properly


code:
from scrapy.exceptions import IgnoreRequest
import tldextract

class clearQueueDownloaderMiddleware(object):
    def process_request(self, request, spider):
        domain_obj = tldextract.extract(request.url)
        just_domain = domain_obj.registered_domain
        if(just_domain in spider.blocked):
            print "Blocked domain: %s (url: %s)" % (just_domain, request.url)
            raise IgnoreRequest("URL blocked: %s" % request.url)

rawDescription: Is it possible to remove requests from scrapys scheduler queue?


code: print u'\u2713'

rawDescription: Print the "approval" sign/check mark (✓) U+2713 in Python