code:
import web

urls = ('/', 'Upload')

class Upload:
    def GET(self):
        web.header("Content-Type","text/html; charset=utf-8")
        return """
               <form method="POST" enctype="multipart/form-data" action="">
               <input type="file" name="myfile" />
               <br/>
               <input type="submit" />
               """

    def POST(self):
        x = web.input(myfile={})
        filedir = '/uploads' # change this to the directory you want to store the file in.
        if 'myfile' in x: # to check if the file-object is created
            filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
            fout = open(filedir +'/'+ filename,'wb') # creates the file where the uploaded file should be stored
            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete.
        raise web.seeother('/')

if __name__ == "__main__":
   app = web.application(urls, globals())
   app.run()

rawDescription: Uploading CSV to Flask for background processing


code:
def countLongestSequence(nums):
        countMax=0
        count=0
        for i in range(0, len(nums)+1):
                if i == len(nums) or nums[i] <= 0:
                        if count > countMax:
                                countMax=count
                        count=0
                else:
                        count+=1
        return countMax

rawDescription: Python function that will return a count (int) representing the longest consecutive sequence of positive numbers in array


code:
members = {}
for m in elem.text.split(' '):
    key, value = m.split(':')
    members[key.replace("'", '')] = map(int, value.split(','))
    return members

rawDescription: Not-quite-JSON string deserialization in Python


code:
#!/usr/bin/python

import subprocess

def asExec(ascript):

    osa = subprocess.Popen(['osascript', '-'],
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE)
    return osa.communicate(ascript)[0]

def asConv(astr):

    astr = astr.replace('"', '" & quote & "')
    return '"{}"'.format(astr)

def aScript(aspath):

    ascript = '''
    set posixPath to POSIX path of {0}
    '''.format(asConv(aspath))
    return ascript

aliasPath = "Main HD:Users:sasha:Documents:SomeText.txt"
print(asExec(aScript(aliasPath)))

rawDescription: Convert mac path to posix in python

description: Convert mac path to posix in python


code:
raw = []
# Kind of make a very ugly typecast by using a lot of Memomory
tmp = np.fromstring(f0.tostring(), dtype=np.int32)
raw.append(tmp[::2])
raw.append(tmp[1::2])

... # do the same of f1

raw.append(i0)

# Finaly write it down
np.array(raw).transpose().tofile(file_id)

rawDescription: save binary binary columns with numpy

description: Save binary binary columns with numpy


rawDescription: Quick way to access first element in Numpy array with arbitrary number of dimensions?


code:
import web

class MyApplication(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))

urls = (
   '/(.*)', 'hello'
)

class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app = MyApplication(urls, globals())
    app.run(port=8888)

rawDescription: How to deploy a simple python webserver in a right way?

description: Deploy a simple python webserver in a right way


code:
df
cond = df.ORG2 == 'ESBL'
df.ORG1[cond] = df.ORG2[cond]
df

rawDescription: Change a pandas DataFrame column value based on another column value


code:
from reportlab.lib.units import mm

t = Table(makeReportData(paranote), colWidths=(None, None, None, None, 100*mm))

rawDescription: Python & ReportLab: wrong column width and alignment in PDF table


code:
from sklearn.datasets import load_boston
boston = load_boston()
boston.data.std(0)

rawDescription: Normalization in sci-kit learn linear_models


code:
from xml.etree.cElementTree import iterparse

# get an iterable and turn it into an iterator
context = iter(iterparse("path/to/big.xml", events=("start", "end")))

# get the root element
event, root = next(context)
assert event == "start"

for event, elem in context:
    if event == "end" and elem.tag == "book":
       # ... process book elements ...
       root.clear()

rawDescription: How to split an XML file the simple way in Python?

description: Split an XML file the simple way in Python


code:
import re
text = '''
Started by upstream project "fcm-dummy-web" build number 99
originally caused by:
 Started by user Kaul, Kuber
'''
m = re.search(r'Started by upstream project "([^"]+)" build number (\d+)', text)
print("project = %s, build number %d" % (m.group(1), int(m.group(2))))

rawDescription: use regex to find value in quotes in the string with an integer value

description: Use regex to find value in quotes in the string with an integer value


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

a = np.array(((1, 2, 3), (4, 5, 6)))
plt.imshow(a)
plt.show()

rawDescription: Represent a 2D list as a map of colored squares in Pylab


code:
from selenium.webdriver import Remote # Remote imported only for code completion

def get_current_browser():
    """
    :rtype: Remote
    """
    browser = BuiltIn().get_library_instance('Selenium2Library')._current_browser()
    return browser

rawDescription: Selenium2Library code completion in PyCharm


code:
i = len(lines)
i = -1 if i > 1 else i
for fullName in lines[:i]:
    dostuff()

rawDescription: Process at least one line in Python

description: Process at least one line in Python


rawDescription: Is it possible to set multiple list elements using slice notation without inserting new elements?


code:
def scrollwheel(event):
    return 'break'

text.bind('<MouseWheel>', scrollwheel)

rawDescription: Python Tkinter: Text widget unbind mouse wheel


code:
libc = ctypes.cdll.LoadLibrary("libc.so")
mask = '\x00' * 17 # 16 byte empty mask + null terminator
libc.sigprocmask(3, mask, None) # '3' on FreeBSD is the value for SIG_SETMASK

rawDescription: Python processes stops responding to SIGTERM / SIGINT after being restarted


code: all(l[i] <= l[i+1] for i in xrange(len(l)-1))

rawDescription: Pythonic way to check if a list is sorted or not


code:
import re
import os
import xmlutils # download it from: https://gist.github.com/huseyinyilmaz/1448723

my_dir = '<absolute path to my dir>'

doc_dict = dict()

for root, dirs, files in os.walk(my_dir):
    for filename in files:
        if filename.endswith('.py'):
            with open(os.path.join(root, filename), 'r') as py_file:
                basename = os.path.basename(filename)
                doc_dict[basename] = [m.group('doc') for m in re.finditer(
                    re.compile(r'("|\'){3}(?P<doc>.*?)\1{3}', re.DOTALL),
                    py_file.read()
                )]

dict2xml(dict(root=doc_dict))

rawDescription: python doc for docstring

description: Python doc for docstring


code:
import json
import urlparse
s = urlparse.unquote("%7B%22postid%22%3A1234%2C%22commentid%22%3A8999%7D")
s
v = json.loads(s)
v['commentid']

rawDescription: Decode Django session cookie value

description: Decode Django session cookie value


code:
def bouquets(n_price, t_price, r_price, total_price):
    """
    Count how many n, t, r (integers >= 0) exist
    such that
      n * n_price + t * t_price + r * r_price <= total_price
    and
      n + t + r is odd
    """
    count = 0

    max_n = total_price // n_price
    for n in xrange(max_n + 1):
        rem_n = total_price - n * n_price
        max_t = rem_n // t_price
        for t in xrange(max_t + 1):
            rem_t = rem_n - t * t_price
            max_r = rem_t // r_price
            min_r = (n + t + 1) % 2
            count += (max_r - min_r) // 2 + 1
    return count

rawDescription: How can I improve my algorithm runtime? cpmoptimithe not to propose

description: Improve my algorithm runtime? cpmoptimithe not to propose


code:
with open("output.txt", "w") as f:
    for item in vocab:
        f.write(item + "\n")

rawDescription: Creating Vocabulary in python

description: Creating Vocabulary in python


rawDescription: How can I retrieve last x elements in Django

description: Retrieve last x elements in Django


code:
@app.route('/<version>/users')
def users(version):
    # do something
    return jsonify(response)

rawDescription: What is the best way to run REST API versions with Python Flask


code:
label_positions = np.arange(start, end, step, endpoint=True)
plt.xticks(label_positions)

rawDescription: Graph Customization in python

description: Graph Customization in python


code:
frm = 'acdefhnoprstuw'
to = 'אקדיפהנופרסתאו'
trans_table = str.maketrans(frm, to)
hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table)
hebrew_phrase

rawDescription: Python 3.x: Using string.maketrans() in order to create a unicode-character transformation


code:
br.select_form(nr=0)
for control in br.form.controls:
    if control.type == "submit":
        control.disabled = True
resp=br.submit()

rawDescription: Mechanize - Submit form without click on submit button


code:
pixmap = QtGui.QPixmap.grabWidget(scroll)
pixmap.save('path/to/file.png', None, 100)

rawDescription: Generate an image of all widgets within a scrollarea


code:
import wx

class myFrame(wx.Frame):
    def __init__(self, size, *arg, **kwarg):
        wx.Frame.__init__(self, *arg, **kwarg)
        self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE, size=size)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.text, proportion=1, flag=wx.EXPAND)
        self.SetSizerAndFit(self.sizer)

        self.Show()

myApp = wx.App(False)

size = []
for a in ["X", "Y"]:
    d = wx.NumberEntryDialog(None, "Text size", "%s: " % a, "Window size entry", 100, 50, 200)
    if d.ShowModal() == wx.ID_OK:
        size.append(d.GetValue())

frameNow = myFrame(size, None)
myApp.MainLoop()

rawDescription: Issue with wxPython mulltiline text box being too large for wx.Frame - can I auto "shrink" to the correct size of the text box?


code:
for character in text2:
    if character in text1:
        count += 1

rawDescription: Processing Strings Using a For Loop

description: Processing Strings Using a For Loop


code:
from sys import getsizeof
a = 42
getsizeof(a)
a = 2**1000
getsizeof(a)

rawDescription: Variable's memory size in Python

description: Variable's memory size in Python


code: cmd = "sudo ./deepbelief  {}  > try5.txt".format(newest)

rawDescription: search for latest image inside a folder, and save it as a png file with python

description: Search for latest image inside a folder, and save it as a png file with python


code:
result = []
for L in range(1, 5):
    for subset in itertools.permutations(letters, L):
        result.append(''.join(subset))

rawDescription: How do I get possible combinations of a list within a specific range in Python?

description: Get possible combinations of a list within a specific range in Python


rawDescription: How to send multiple input field values with same name?

description: Send multiple input field values with same name


code:
from collections import OrderedDict
d=OrderedDict()
d["key1"]="foo"
d["key2"]="bar"
d

rawDescription: Dictionary keys are not coming in serial


code:
#Script2

import script1

script1.function_1()
myvar2 = script1.myvar + 1

rawDescription: Calling a global variable in a function in one program from another


code:
def process_item(self, item, spider):
    if spider.name not in ['spider1', 'spider2']:
        return item

    # process item

rawDescription: Is there any method to using seperate scrapy pipeline for each spider?


code:
list_total  = list.GetItemCount()
list_top    = list.GetTopItem()
list_pp     = list.GetCountPerPage()
list_bottom = min(list_top + list_pp, list_total - 1)
list.EnsureVisible((list_bottom - 1))

rawDescription: Python wx.listctrl scroll position

description: Python wx.listctrl scroll position


code:
lst = foo.split("|")
lst[0]
lst[1]
...

rawDescription: Python: Assign split value to mulitple variables


code:
def get_md5_as_bytes(data):
    m = hashlib.md5()
    m.update(data)
    return m.hexdigest()[:8]

rawDescription: Extract the first 8 bytes of an MD5 Hash


code:
#inside urls.py
router = ExtendedSimpleRouter()
(
    router.register(r'users', UserViewSet)
          .register(r'things', ThingViewSet, parents_query_lookups=['thing_usages__user'])
)

#inside views.py
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()

class ThingViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
    queryset = Thing.objects.all()

rawDescription: Django REST Framework: Two models nested via a third one (with 2 FKs )


code:
def codeOnly(file):
    '''Opens a file and prints the content excluding anything with a hash in it'''
    with open(file, 'r') as f_input:
        for line in f_input:
            if '#' not in line:
                print(line, end='')

codeOnly('boring.txt')

rawDescription: How to remove lines from a file that is being printed with certain conditions?

description: Remove lines from a file that is being printed with certain conditions


code:
def login(request):
    m = Member.objects.get(username=request.POST['username'])
    if m.password == request.POST['password']:
        request.session['member_id'] = m.id
        return HttpResponse("You're logged in.")
    else:
        return HttpResponse("Your username and password didn't match.")

rawDescription: set user session in django

description: Set user session in django


code:
rddob = df.rdd.map(lambda line: (line.A + line.B, 1))
counts_by_key = rddob.reduceByKey(lambda a,b: a+b)

rawDescription: count the lines in rdd depended on the lines context, pyspark

description: Count the lines in rdd depended on the lines context, pyspark


code:
import csv
with open('activations.csv','rb') as act_data:
    rdr= csv.DictReader( act_data)
    activations = dict( (row['user'],row) for row in rdr )
with open('users.csv','rb') as user_data:
    rdr= csv.DictReader( user_data )
    with open( 'users_2.csv','wb') as updated_data:
        wtr= csv.DictWriter( updated_data, ['some','list','of','columns'])
        for user in rdr:
             user['some_field']= activations[user['user_id_column']]['some_field']
             wtr.writerow( user )

rawDescription: Merging two datasets in Python efficiently


code:
import hashlib
from base64 import b64decode

def build_id(pub_key_pem):
    pub_key_der = b64decode(pub_key_pem)
    sha = hashlib.sha256(pub_key_der).hexdigest()
    prefix = sha[:32]

    reencoded = ""
    ord_a = ord('a')
    for old_char in prefix:
        code = int(old_char, 16)
        new_char = chr(ord_a + code)

        reencoded += new_char

    return reencoded

def main():
    pub_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjvF5pjuK8gRaw/2LoRYi37QqRd48B/FeO9yFtT6ueY84z/u0NrJ/xbPFc9OCGBi8RKIblVvcbY0ySGqdmp0QsUr/oXN0b06GL4iB8rMhlO082HhMzrClV8OKRJ+eJNhNBl8viwmtJs3MN0x9ljA4HQLaAPBA9a14IUKLjP0pWuwIDAQAB'

    id_ = build_id(pub_key)
    print(id_)

if __name__ == '__main__':
    main()

rawDescription: How to programmatically calculate Chrome extension ID?

description: Programmatically calculate Chrome extension ID


code:
if self.norm:
        X = normalize(X, norm=self.norm, copy=False)

rawDescription: Python scikit learn's TfidfVectorizer - max of 1.0?


code:
from pyramid.httpexceptions import HTTPFound

def form_received_here(request):
    # do stuff here
    return HTTPFound('http://example.com')

rawDescription: Pyramid Direct User to DIfferent Domain

description: Pyramid Direct User to DIfferent Domain


rawDescription: Regex in python to catch a string like MMS-2839


code:
s = 'hello abcde hello xyz hello goodbye'
words = s.split('hello')
'hello'.join(words[:2]) + 'bye' + 'hello'.join(words[2:])

rawDescription: Replacing specific occurrences of strings in Python


code:
import urllib2
req = urllib2.urlopen("http://en.wikipedia.org/w/api.php?action=parse&page=China&format=json&prop=text")
content = req.read()
# content in json - use json or simplejson to get relevant sections.

rawDescription: How to parse a wikipedia page in Python?

description: Parse a wikipedia page in Python


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

data = [1,1,1,1,1,1,1,1,1,1]
arr = np.zeros((4,4))
indices = np.tril_indices(4)
arr[indices] = data
print(arr)

# array([[ 1.,  0.,  0.,  0.],
#        [ 1.,  1.,  0.,  0.],
#        [ 1.,  1.,  1.,  0.],
#        [ 1.,  1.,  1.,  1.]])

plt.imshow(arr, interpolation='nearest', cmap=plt.get_cmap('RdYlGn'))
plt.show()

rawDescription: Python: Populate lower triangle matrix from a list


code: print

rawDescription: What does printing an empty line do?

description: What does printing an empty line do


code:
from decimal import Decimal
x = Decimal("0.00000061")
format(x, 'f')

rawDescription: Python format Decimal near zero

description: Python format Decimal near zero


rawDescription: Python-matplotlib: Can't display text on figure using a function linked to an event


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

# Random data
bottom10 = pd.DataFrame({'amount':-np.sort(np.random.rand(10))})
top10 = pd.DataFrame({'amount':np.sort(np.random.rand(10))[::-1]})

# Create figure and axes for top10
fig,axt = plt.subplots(1)

# Plot top10 on axt
top10.plot.barh(color='red',edgecolor='k',align='edge',ax=axt,legend=False)

# Create twin axes
axb = axt.twiny()

# Plot bottom10 on axb
bottom10.plot.barh(color='green',edgecolor='k',align='edge',ax=axb,legend=False)

# Set some sensible axes limits
axt.set_xlim(0,1.5)
axb.set_xlim(-1.5,0)

# Add some axes labels
axt.set_ylabel('Best items')
axb.set_ylabel('Worst items')

# Need to manually move axb label to right hand side
axb.yaxis.set_label_position('right')

plt.show()

rawDescription: how to plot two barh in one axis?

description: Plot two barh in one axis


code:
import httplib2
from google.appengine.api import memcache
from oauth2client.appengine import AppAssertionCredentials
from apiclient import discovery
...
credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/devstorage.read_write')
http = credentials.authorize(httplib2.Http(memcache))
storage = discovery.build(serviceName='storage', version='v1beta2', http=http, developerKey=your_api_key)

rawDescription: How do I get an access token of my own account to be stored/used in my server?

description: Get an access token of my own account to be stored/used in my server


code:
testList = [1, 1, 1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 8, 9]
from itertools import groupby
[k for k, g in groupby(testList)]

rawDescription: Loopless program to remove duplicate elements in a sorted array


code:
for line in input_file:
    if line.endswith(" \n"):
       line = line.replace(' \n', '\n')

rawDescription: Remove single white space from end of lines for .TXT file


code:
df = pd.read_csv(StringIO(s), sep="\s+")
df
df.iloc[np.random.permutation(len(df))]

rawDescription: Shuffle DataFrame rows

description: Shuffle DataFrame rows


code:
import os
f = open(os.devnull,"w")
twill.set_output(f)

rawDescription: Elegantly suppress Twill output in Python


code:
#!/usr/bin/env python
"""
https://stem.torproject.org/tutorials/to_russia_with_love.html

Usage:
  russian-tor-exit-node [<tor>] [--color] [--geoipfile=</path/to/file>]
  russian-tor-exit-node -h | --help
  russion-tor-exit-node --version

Dependencies:

- tor (packaged and standalone executables work)
- pip install stem
- pip install PySocks
- pip install docopt
  : parse options
- pip install colorama
  : cross-platform support for ANSI colors
- [optional] sudo apt-get tor-geoipdb
  : if tor is bundled without geoip files; --geoipfile=/usr/share/tor/geoip
"""
import sys
from contextlib import closing

import colorama  # $ pip install colorama
import docopt  # $ pip install docopt
import socks  # $ pip install PySocks
import stem.process  # $ pip install stem
from sockshandler import SocksiPyHandler  # see pysocks repository
from stem.util import term

try:
    import urllib2
except ImportError: # Python 3
    import urllib.request as urllib2

args = docopt.docopt(__doc__, version='0.2')
colorama.init(strip=not (sys.stdout.isatty() or args['--color']))

tor_cmd = args['<tor>'] or 'tor'
socks_port = 7000
config = dict(SocksPort=str(socks_port), ExitNodes='{ru}')
if args['--geoipfile']:
    config.update(GeoIPFile=args['--geoipfile'], GeoIPv6File=args['--geoipfile']+'6')

def query(url, opener=urllib2.build_opener(
        SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, "localhost", socks_port))):
  try:
      with closing(opener.open(url)) as r:
          return r.read().decode('ascii')
  except EnvironmentError as e:
    return "Unable to reach %s: %s" % (url, e)

# Start an instance of Tor configured to only exit through Russia. This prints
# Tor's bootstrap information as it starts. Note that this likely will not
# work if you have another Tor instance running.
def print_bootstrap_lines(line):
  if "Bootstrapped " in line:
    print(term.format(line, term.Color.BLUE))
  else:
    print(line)

print(term.format("Starting Tor:\n", term.Attr.BOLD))
tor_process = stem.process.launch_tor_with_config(
    tor_cmd=tor_cmd,
    config=config,
    init_msg_handler=print_bootstrap_lines,
)
try:
    print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD))
    print(term.format(query("https://icanhazip.com"), term.Color.BLUE))
finally:
    if tor_process.poll() is None: # still running
        tor_process.terminate()  # stops tor
        tor_process.wait()

rawDescription: Tor Stem - To Russia With Love Connection Issues


code:
from concurrent.futures import ThreadPoolExecutor
from requests import Session
from requests.adapters import DEFAULT_POOLSIZE, HTTPAdapter

class FuturesSession(Session):

    def __init__(self, executor=None, max_workers=2, *args, **kwargs):
        super(FuturesSession, self).__init__(*args, **kwargs)
        if executor is None:
            executor = ThreadPoolExecutor(max_workers=max_workers)
            # set connection pool size equal to max_workers if needed
            if max_workers > DEFAULT_POOLSIZE:
                adapter_kwargs = dict(pool_connections=max_workers,
                                      pool_maxsize=max_workers)
                self.mount('https://', HTTPAdapter(**adapter_kwargs))
                self.mount('http://', HTTPAdapter(**adapter_kwargs))

        self.executor = executor

    def request(self, *args, **kwargs):
        func = sup = super(FuturesSession, self).request

        background_callback = kwargs.pop('background_callback', None)
        if background_callback:
            def wrap(*args_, **kwargs_):
                resp = sup(*args_, **kwargs_)
                background_callback(self, resp)
                return resp

            func = wrap

        return self.executor.submit(func, *args, **kwargs) # This returns a concurrent.futures.Future

rawDescription: What's the difference between concurrent.futures' async and requests-futures' async in python?


code: [numpy.mean([x for x in sublist if isinstance(x, numbers.Number)]) for sublist in mainlist]

rawDescription: compute average over a list in python, excluding literals

description: Compute average over a list in python, excluding literals


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
driver.find_element_by_id("IDOFLOGIN").sendKeys("YOUR LOGIN")
driver.find_element_by_id("PASSOFLOGIN").sendKeys("YOUR PASSWORD")
driver.find_element_by_id("login button").click()
# Continue

rawDescription: Authentication with selenium (Python)

description: Authentication with selenium (Python)


code: line = linecache.getline(thefilename, 33)

rawDescription: Go to a specific line in Python?

description: Go to a specific line in Python


code:
import glob
files = glob.glob('*.txt')
for file in files:
    # this will remove the .txt extension and keep the "aN"
    first_part = file[:-4]
    # find the matching directory
    dir = glob.glob('%s_*/' % first_part)[0]
    os.rename(file, os.path.join(dir, file))

rawDescription: match filenames to foldernames then move files

description: Match filenames to foldernames then move files


code:
import sys
from tkinter import *
from PIL import Image, ImageTk

def clear():
    txtDisplay.delete(0,END);
    return;

#Parent Window.
root = Tk();
root.title('Calculator ++ [1.7.2]');
root.geometry('350x450');

#Main entry.
num1 = StringVar();
txtDisplay = Entry(root, textvariable = num1, relief=RIDGE, bd = 10, width=33,    insertwidth = 1, font = 40);
txtDisplay.place(x=15, y=10);
txtDisplay.focus();

def update_entry(v):
    current_value = num1.get()
    num1.set(current_value + v)

#Buttons:
zeroButton = Button(root, text='0', width=20, height=3, bg='LightBlue', fg='red', command = lambda: update_entry('0')).place(x=17,y=382);
oneButton = Button(root, text='1', width=8, height=3, bg='LightBlue', fg='red', command = lambda: update_entry('1')).place(x=17, y=302);
twoButton = Button(root, text='2', width=8, height=3, bg='LightBlue', fg='red').place(x=100, y=302);
threeButton = Button(root, text='3', width=8, height=3, bg='LightBlue', fg='red').place(x=182, y=302);
fourButton = Button(root, text='4', width=8, height=3, bg='LightBlue', fg='red').place(x=17, y=222);
fiveButton = Button(root, text='5', width=8, height=3, bg='LightBlue', fg='red').place(x=100, y=222);
sixButton = Button(root, text='6', width=8, height=3, bg='LightBlue', fg='red').place(x=182, y=222);
sevenButton = Button(root, text='7', width=8, height=3, bg='LightBlue', fg='red').place(x=17, y=142);
eightButton = Button(root, text='8', width=8, height=3, bg='LightBlue', fg='red').place(x=100, y=142);
ninthButton = Button(root, text='9', width=8, height=3, bg='LightBlue', fg='red').place(x=182, y=142);

decimalButton = Button(root, text='.', width=8, height=3, bg='powder blue').place(x=182, y=382);
equalButton = Button(root, text='=', width=8, height=8, bg='Lightgreen').place(x=264, y=307);
plusButton = Button(root, text='+', width=8, height=3, bg='gray', command = lambda: update_entry('+')).place(x=264, y=222);
minusButton = Button(root, text='-', width=8, height=3, bg='gray').place(x=264, y=142);
multiplyButton = Button(root, text='x', width=8, height=3, bg='gray').place(x=264, y=66);
divideButton = Button(root, text='÷', width=8, height=3, bg='gray').place(x=182, y=66);
clearButton = Button(root, text='Clear (CE)', width=20, height=3, command =      clear, bg='Orange').place(x=17, y=66);

#Locks the parent windows size.
root.maxsize(350,450);
root.minsize(350,450);

#Parent window's background color:
root.configure(background = 'black');
root.mainloop();

rawDescription: Tkinter Calculator Python 3.4.2

description: Tkinter Calculator Python 3.4.2


code:
class A: pass

import weakref
d1 = {}
d2 = {'sub': weakref.WeakValueDictionary()}
d1['a'] = A()
d2['sub']['a'] = d1['a']
del d1['a']
d2['sub']['a']

rawDescription: Weakref-ing an item from one dict in a subdict of another in python


code:
names = ['my _id', 'some a', 'some b']
sanitized_names = "({})".format(", ".join(x.replace(' ','') for x in names))

# => (my_id, somea, someb)

rawDescription: dynamic csv to sqlite importing

description: Dynamic csv to sqlite importing


code:
captcha_key = get_config('RECAPTCHA_PUB_KEY',None)
recaptcha_challenge_field = request.POST.get('recaptcha_challenge_field', None)
recaptcha_response_field = request.POST.get('recaptcha_response_field', None)
check_captcha = captcha.submit(recaptcha_challenge_field, recaptcha_response_field, settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
if check_captcha.is_valid is False:
    log.info('captcha_error : %s' % check_captcha.error_code)
    return {'TEMPLATE':template_name,'captcha_error': True,'register_form': f,'captcha_key':captcha_key ,'next':redirect_to}

rawDescription: Recaptcha in Django without forms?

description: Recaptcha in Django without forms


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'sql_mode': 'traditional',
        }
    }
}

rawDescription: Force strict sql mode in django

description: Force strict sql mode in django


code:
import random
import wx

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None)
        self.SetTitle('Title')
        panel = wx.Panel(self)
        style = wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE
        self.text = wx.StaticText(panel, style=style)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.AddStretchSpacer(1)
        sizer.Add(self.text, 0, wx.EXPAND)
        sizer.AddStretchSpacer(1)
        panel.SetSizer(sizer)
        self.on_timer()
    def on_timer(self):
        self.text.SetLabel(str(random.randint(0, 100)))
        wx.CallLater(1000, self.on_timer)

if __name__ == '__main__':
    app = wx.App()
    frame = Frame()
    frame.Show()
    app.MainLoop()

rawDescription: wxPython update StaticText every x seconds/minutes using timer

description: WxPython update StaticText every x seconds/minutes using timer


code:
def F(totalTime, timeLeft, rideNum, loopOnCurrRide):
    # time of line+operation of ride
    totalTimePerRide = {1: 0, 2: 40, 3: 15, 4: 20, 5: 23, 6: 11}
    # time of operation of rides
    operationTimePerRide = {1: 0, 2: 4, 3: 5, 4: 8, 5: 3, 6: 6}
    if timeLeft + loopOnCurrRide * operationTimePerRide[rideNum] > totalTime:
        return -10, []

    if loopOnCurrRide > 3:
        return -10, []

    if timeLeft == 0:
        return 0, []

    staying, staying_path = F(totalTime, timeLeft - operationTimePerRide[rideNum], rideNum, loopOnCurrRide + 1)
    staying += funPerRide(rideNum, loopOnCurrRide + 1) - funPerRide(rideNum, loopOnCurrRide)
    staying_path = [-1] + staying_path

    switching = -1
    switching_path = []
    for i in range(1, 7):
        if i > rideNum:
            switchOption, switchOption_path = F(totalTime, timeLeft - 4.5 - totalTimePerRide[i], i, 1)
            switchOption += funPerRide(i, loopOnCurrRide)
            if switchOption > switching:
                switching = switchOption
                switching_path = [i] + switchOption_path

    return max((staying, staying_path), (switching, switching_path))

answer, path = F(120, 120, 1, 0)

rawDescription: Finding a path of a solved recursive function


rawDescription: Change default iPython in homebrew to use Python 2.x.x instead of Python 3.x.x


code:
class Company(models.Model):
    ...
    def save(self, *args, **kw):
       if self.employees is None:
            self.employees = self.DEFAULT_EMPLOYEES
       super(Company, self).save(*args, **kw)

rawDescription: Override Class Attribute, with a generic way to refer to class


code:
# Note, your path probably differs
subprocess.call(r"C:\Program Files\Microsoft Office\Office12\EXCEL.exe")

# The script will wait until Excel is closed and then continue

rawDescription: How do I open Excel Application using xlrd or xlwt?

description: Open Excel Application using xlrd or xlwt


code:
from selenium import webdriver

driver = webdriver.Firefox()
link = "http://yourlink.com"
driver.get(link)

#this waits for the new page to load
while(link == driver.current_url):
  time.sleep(1)

redirected_url = driver.current_url

rawDescription: Getting the final destination of a javascript redirect on a website


code:
def convert(t):
    result = t[-1]
    for x in t[-2::-1]:
        result = x + (result,)
    return result

rawDescription: Convert from tuple of tuples to nested tuples in Python


code:
row_idxs = N[4]
r,c = np.where(N[row_idxs] == 6)
N[row_idxs[r],c] = 0

rawDescription: Strange asignment in numpy arrays

description: Strange asignment in numpy arrays


rawDescription: Python bytes literal has extra characters that aren't hex, but alter the value of the string


code:
import datetime

@receiver(post_save, sender=None, dispatch_uid='update_last_modified')
def update_last_modified(sender, instance, raw, using, update_fields):
    if raw: # database might not be in a consistent state yet
        return
    if sender in (B, C, D): # all models which A has a fk/m2m to
        qs = instance.a_set.using(using)
    elif sender in (E,): # all models which have a fk/o2o to A
        qs = A.objects.filter(pk=instance.a.pk).using(using)
    elif sender is A:
        qs = A.objects.filter(pk=instance.pk).using(using)
    try:
        qs.update(last_update=datetime.datetime.now())
    except NameError:
        pass

rawDescription: Better approach on Django signal managemanet


rawDescription: How to easy_install egg plugin and load it without restarting application?

description: Easy_install egg plugin and load it without restarting application


code:
class Post(models.Model):
    title = models.CharField(max_length=100)
    pub_date = models.DateTimeField()
    cover_photo = models.ImageField(upload_to='coverphotos/')
    text = models.TextField()
    summary = models.CharField(max_length=200)
    slug = models.SlugField(max_length=40, unique=True)

    def save(self, *args, **kwargs):
        if self.text:
            self.summary = self.text[:100]
        super(Post, self).save(*args, **kwargs)

rawDescription: Automatically create a summary of TextField


code:
import time
from socket import socket, AF_INET, SOCK_STREAM
from multiprocessing import Process
from settings import host, port, number_of_connections

def logging(message):
        print(message)
        with open('log.txt', 'a') as f:
            f.write('%s\n' % message)

clients = []

sock = socket(AF_INET, SOCK_STREAM)

sock.bind((host, port))

sock.listen(number_of_connections)

while True:
    conn, addr = sock.accept()
    data = conn.recv(1024)
    if not data:
        break
    udata = data.decode("utf-8")
    logging("Server recieve Data: %s" % udata)
    conn.send(b"Hello! From server!\n")
    conn.send(b"Your data: " + udata.encode("utf-8"))

rawDescription: Cant connect to python server

description: Cant connect to python server


code: cmd = CMD % (option1, option2)

rawDescription: Python string formatting

description: Python string formatting


rawDescription: Efficient memory usage in python

description: Efficient memory usage in python


code:
class MyBool:
    def __init__(self, is_true):
        self.is_true = bool(is_true)

    def __eq__(self, other):
        return self.is_true == bool(other)

    def __bool__(self):
        return self.is_true

rawDescription: Why is comparison to True/False using the "is" operator bad?


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

#---------
# IMPORT
#---------
from PyQt4 import QtGui, QtCore

#---------
# MAIN
#---------
class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        numberRows    = 1
        numberColumns = 2

        self.tableWidget = QtGui.QTableWidget(self)
        self.tableWidget.setRowCount(numberRows)
        self.tableWidget.setColumnCount(numberColumns)

        for rowNumber in range(numberRows):
            for columnNumber in range(numberColumns):
                item = QtGui.QTableWidgetItem("item {0} {1}".format(rowNumber, columnNumber))
                item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
                item.setCheckState(QtCore.Qt.Unchecked)

                self.tableWidget.setItem(rowNumber, columnNumber, item)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.tableWidget)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(333, 111)
    main.show()

    sys.exit(app.exec_())

rawDescription: Add several Checkboxes to QListWidgetItem with setflags()


rawDescription: How can I interact with irregular elements using Python/Selenium?

description: Interact with irregular elements using Python/Selenium


code: vals = [random.choice(integers) for _ in range(num_ints)]

rawDescription: How to generate list of random integers, but only using specified integers? (Python)

description: Generate list of random integers, but only using specified integers? (Python)


code:
for root, directories, files in os.walk(directory):
    directories[:] = [d for d in directories if d not in ['thumbs']]
    for filename in files:
        if filename.endswith(extensions):
            filepath = os.path.join(root, filename)
            file_list.append(filepath)

rawDescription: Ignore certain subdirectories using os.walk() [Python]


code: from .. import myFile2

rawDescription: importing modules' files into submodules

description: Importing modules' files into submodules


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

n=20
x=np.linspace(0,np.pi,n)
y=np.sin(x)
plt.plot(x,y)
fname='/tmp/test.pdf'
plt.savefig(fname)
proc=subprocess.Popen(shlex.split('lpr {f}'.format(f=fname)))

rawDescription: How can I print a plot in matplotlib either from the plot window or with a command?

description: Print a plot in matplotlib either from the plot window or with a command


rawDescription: Python: Comparing Lists

description: Python: Comparing Lists


rawDescription: Python How to get set bit

description: Python How to get set bit


code:
import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        label = QtGui.QLabel("Test")
        label.setAlignment(QtCore.Qt.AlignCenter)
        label.setFrameStyle(QtGui.QFrame.WinPanel | QtGui.QFrame.Sunken)

        edit = QtGui.QTextEdit()
        edit.setFrameStyle(QtGui.QFrame.WinPanel | QtGui.QFrame.Sunken)
        edit.setText("Some text")
        edit.moveCursor(QtGui.QTextCursor.MoveOperation.End)

        vbox = QtGui.QVBoxLayout()
        vbox.setContentsMargins(1, 1, 1, 1)
        vbox.setSpacing(1)
        vbox.addWidget(label)
        vbox.addWidget(edit)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Window Title')
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: pyqt Window similar to Win32 style

description: Pyqt Window similar to Win32 style


code:
list_of_names = ['a', 'b', 'c', 'd']
for name in list_of_names:
    globals()[name] = your_object()

rawDescription: Creating instances in a loop with different variables


rawDescription: Python List Comprehensions Splitting loop variable


code:
conn = psycopg2.connect(database='cpn')
cur = conn.cursor()

location_filter = "SELECT id FROM developers WHERE location = %s"
out_file.write(cur.mogrify(location_filter, (location,)))

rawDescription: How to get sanitized postgres SQL string in python for later use?

description: Get sanitized postgres SQL string in python for later use


rawDescription: How can I check if a string has a numeric value in it in Python?

description: Check if a string has a numeric value in it in Python


code:
from django.db.models import Min
besties = {}
for team in teams:
    besties[team] = Placing.objects \
    .filter(event_date__gte=start_date, best_time__gt=0).order_by(-event_date) \
    .filter(team_name=team)[:3].aggregate(Min('best_time'))['best_time__min']

rawDescription: Django get the latest 3 results in a filter set


code:
# this is your model form for extended OneOnOne with user
class ExtendedForm(forms.ModelForm):
    model = ExtendedModel
    # temporary exclude user field to pass the validation
    exclude = ('user')

def create_user(request):
    user_form = UserForm(request.POST or None)
    extra_form = ExtendedForm(request.POST or None)

    if user_form.is_valid() and extra_form.is_valid():
        # create a new user first
        new_user = user_form.save()
        # create an object in memory but not save it
        new_extended_obj = extra_form.save(commit=False)
        # assign the user to the extended obj
        new_extended_obj.user = new_user
        # write to database
        new_extended_obj.save()

rawDescription: Add extra fields to my UserCreationForm from my extended User model


code:
wb=openpyxl.load_workbook('simpleCoordinate.xlsx')
sheet=wb.get_sheet_by_name('Sheet1')

from collections import defaultdict

coordinate_list = list()
for i in range (1,201,1):
    coordinate_list += [(sheet.cell(row=i,column=1).value, sheet.cell(row=i,     column=2).value)]

coord_dict = defaultdict(list)
for oid, xy in coordinate_list:
    coord_dict[oid] = xy

print(list(coord_dict.items()))

rawDescription: Using defaultdict to append a list from an .xlsx file


code:
from twisted.internet.protocol import Protocol, Factory, DatagramProtocol
from twisted.internet import reactor

class TCPServer(Protocol):
    def connectionMade(self):
        self.port = reactor.listenUDP(8000, UDPServer(self))

    def connectionLost(self, reason):
        self.port.stopListening()

class UDPServer(DatagramProtocol):
    def __init__(self, stream):
        self.stream = stream

    def datagramReceived(self, datagram, address):
        self.stream.transport.write(datagram)

def main():
    f = Factory()
    f.protocol = TCPServer
    reactor.listenTCP(8000, f)
    reactor.run()

if __name__ == '__main__':
    main()

rawDescription: Twisted UDP to TCP Bridge

description: Twisted UDP to TCP Bridge


code:
s = socket.create_connection(('X.X.X.X', 2068))
data = s.recv(1024)
...

rawDescription: Python telnetlib and console connection cisco node


code:
s = """\
First Line
Second Line
Third Line
"""
ba = QtCore.QByteArray(s.encode('utf-8'))
ts = QtCore.QTextStream(ba)
ts.setCodec('utf-8')
ts.readLine()

rawDescription: Use QTextStream to read the first line in a string


code:
# threshold the image using a threshold value 0
ret, bw = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)
# find contours of the binarized image
contours, heirarchy = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# curves
curves = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)

for i in range(len(contours)):
    # for each contour, draw the filled contour
    draw = np.zeros((img.shape[0], img.shape[1]), np.uint8)
    cv2.drawContours(draw, contours, i, (255,255,255), -1)
    # for each column, calculate the centroid
    for col in range(draw.shape[1]):
        M = cv2.moments(draw[:, col])
        if M['m00'] != 0:
            x = col
            y = int(M['m01']/M['m00'])
            curves[y, x, :] = (0, 0, 255)

rawDescription: laser curved line detection using opencv and python

description: Laser curved line detection using opencv and python


code:
import numpy as np
import pylab as pl
import matplotlib.collections as mc

x = np.logspace(1, 2, 20)
polys = []
values = []
for xs, xe in zip(x[:-1], x[1:]):
    y = np.logspace(1.0, 2+np.random.rand()+2*np.log10(xs), 30)
    c = -np.log(xs*y)
    yp = np.c_[y[:-1], y[:-1], y[1:], y[1:]]
    xp = np.repeat([[xs, xe, xe, xs]], len(yp), axis=0)
    points = np.dstack((xp, yp))
    polys.append(points)
    values.append(c[:-1])

polys = np.concatenate(polys, 0)
values = np.concatenate(values, 0)

pc = mc.PolyCollection(polys)
pc.set_array(values)
fig, ax = pl.subplots()
ax.add_collection(pc)
ax.set_yscale("log")
ax.set_xscale("log")
ax.autoscale()
pl.colorbar(mappable=pc)

rawDescription: Plot 2D Histogram as heat map in matplotlib


code:
import clr

clr.AddReference("RevitServices")
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument

clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *

par_name = IN[0]
exec("par_type = ParameterType.%s" % IN[1])
exec("par_grp = BuiltInParameterGroup.%s" % IN[2])
inst_or_typ = IN[3]
families = UnwrapElement(IN[4])

# class for overwriting loaded families in the project
class FamOpt1(IFamilyLoadOptions):
    def __init__(self): pass
    def OnFamilyFound(self,familyInUse, overwriteParameterValues): return True
    def OnSharedFamilyFound(self,familyInUse, source, overwriteParameterValues): return True

trans1 = TransactionManager.Instance
trans1.ForceCloseTransaction() #just to make sure everything is closed down
# Dynamo's transaction handling is pretty poor for
# multiple documents, so we'll need to force close
# every single transaction we open
result = []

for f1 in families:
    famdoc = doc.EditFamily(f1)
    try: # this might fail if the parameter exists or for some other reason
        trans1.EnsureInTransaction(famdoc)
        famdoc.FamilyManager.AddParameter(par_name, par_grp, par_type, inst_or_typ)
        trans1.ForceCloseTransaction()
        famdoc.LoadFamily(doc, FamOpt1())
        result.append(True)
    except: #you might want to import traceback for a more detailed error report
        result.append(False)
        trans1.ForceCloseTransaction()
    famdoc.Close(False)

OUT = result

rawDescription: Revit API & Dynamo, Creating a Family Parameter from Project Document


code:
def f():
  while True: 42

import dis
dis.dis(f)

rawDescription: What does the following infinite loop do?


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

rawDescription: Python Get on a website and running $(document).ready(function()


code:
func_map = {0: f1, 1: f2, 2: f3}

def parent(a):
    for i in range(3):
        pid = os.fork()
        if pid == 0:
            func_map[i](a)
            return

rawDescription: How to call different functions with os.fork() in loop?

description: Call different functions with os.fork() in loop


code:
l = [1, 2, 2]
max(set(l), key=l.count)

rawDescription: Most common value in flat list

description: Most common value in flat list


code:
import sqlite3
conn = sqlite3.connect(":memory:")
c = conn.cursor()
for x in range(0, 100):
    c.execute('''CREATE TABLE table%s (id real, name text,price real)'''%x)

rawDescription: How can I create table (sql) in python with for loop?

description: Create table (sql) in python with for loop


code:
dev.new() # opens a new window, and can control the size
dev.off() # closes the window

rawDescription: Python and rpy2: How do I adjust/clear a graphic during runtime?


code:
import thread, time

def timer():
    while True:
        time.sleep(1)
        # do something here

thread.start_new_thread(timer, ())

rawDescription: Is there an alternative to gobject.timeout_add() in Python?


code:
from collections import Counter
def find_duplicates(master):
    cn = Counter(feature for organism in master for feature in set(organism))
    with open("duplicates_list.txt", "wt") as t:
      for k,v in cn.items():
         if v >= 10:
             t.write("{}\n".format(k))

rawDescription: Finding elements that appear in n number of lists in a list of lists


code:
def transform_dictionary(dictionary, callback, qualification_callback=None):
        return {k: callback(v) if (qualification_callback and qualification_callback(v)) or not qualification_callback else v for k, v in dictionary.items()}

rawDescription: Conditionals in dict comprehensions

description: Conditionals in dict comprehensions


code:
import re
d = r.headers['content-disposition']
fname = re.findall("filename=(.+)", d)

rawDescription: How to get pdf filename with Python requests?

description: Get pdf filename with Python requests


code:
import textwrap

row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'

print(textwrap.fill(row,width=55))
# saint george 1739 1799 violin concerti g 029 039 050
# symphonie concertante for two violins g 024 bertrand
# cervera in 024 039 christophe guiot in 024 029 and
# thibault vieux violin soloists orchestre les archets de
# paris

rawDescription: python: breaking a string into substrings using a for loop

description: Python: breaking a string into substrings using a for loop


code:
class ConstantVwModelForm(forms.ModelForm):
    #couple attributes
    def __init__(self, hasData, *args, **kwargs):
        if hasData:
            del self.fields['hh']
        else:
            del self.fields['xx']
            del self.fields['yy']

    class Meta:
        model = ConstantVwModel

rawDescription: Django Meta Class Access Outer Attribute


code:
lims = gca().get_xlim()
i = np.where( (x > lims[0]) &  (x < lims[1]) )[0]
gca().set_ylim( y[i].min(), y[i].max() )
show()

rawDescription: How to automatically set ylim from data shown on the screen after setting xlim

description: Automatically set ylim from data shown on the screen after setting xlim


code:
file_data = open('x:\\path\\to\\file','r').read()
my_list = re.findall(pattern, file_data, re.MULTILINE)
my_dict = {c:b for a,b,c in my_list}

rawDescription: Build a dictionary from successful regex matches in python


code:
to_insert = zip(item['link'], item['title'])
for link, title in to_insert:
    xxx.excute(sql % (link, title))

rawDescription: How to loop over two iterables at once, insert into mysql by python like this?

description: Loop over two iterables at once, insert into mysql by python like this


rawDescription: pyvot: can I run Excel VBA macros from python script?

description: Pyvot: can I run Excel VBA macros from python script


code:
df['lunch'] = (df['hour']<=11) & (df['hour']<=1)
df['lunch']
df['lunch'].astype(int)

rawDescription: Setting 1 or 0 to new Pandas column conditionally


code:
import csv
clean_vars = []
with open('foo.txt', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar=",")
    for row in reader:
        # clean up your file here and append it to the list
        clean_vars.append([char for char in row if char])

# do your processing with numpy with your clean vars

rawDescription: NumPy genfromtxt for different column sizes


rawDescription: Python lookup hostname from IP with 1 second timeout


code:
import json
def save_check(app, nat1, nat2, rt):
    check_dict = {
        app: {
            "nat1": nat1,
            "nat2": nat2,
            "rt": rt
        }
    }
    with open("/home/ubuntu/check.json", "w") as fh:
        json.dump(check_dict, fh, indent=4)

rawDescription: python populate file passing variables to jinja

description: Python populate file passing variables to jinja


code: newString = oldString[6:-6]

rawDescription: Get specific chars from a string in python


code:
class A(object):
    def __init__(self, a):
        self._a = np.asarray(a)
    @property
    def arr(self):
        return self._a
a = A([1,2,3])
a.arr
a.arr = [4,5,6] # There is no setter...
a.arr[1] = 7 # ...but the array is mutable
a.arr

rawDescription: How to make the elements of a NumPy array property settable?

description: Make the elements of a NumPy array property settable


code:
d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

rawDescription: Python - file to dictionary?

description: Python - file to dictionary


code:
class A:
    pass

A.mydict = {A: 3, B: 2}

rawDescription: Can you reference a class inside of itself in Python?

description: Reference a class inside of itself in Python


code:
class Dummy(object):
    aliases = {
        'xValue': 'x',
        'another': 'x',
        }

    def __init__(self):
        self.x = 17

    def __setattr__(self, name, value):
        name = self.aliases.get(name, name)
        object.__setattr__(self, name, value)

    def __getattr__(self, name):
        if name == "aliases":
            raise AttributeError  # http://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html
        name = self.aliases.get(name, name)
        #return getattr(self, name) #Causes infinite recursion on non-existent attribute
        return object.__getattribute__(self, name)

d = Dummy()
assert d.x == 17
assert d.xValue == 17
d.x = 23
assert d.xValue == 23
d.xValue = 1492
assert d.x == 1492

rawDescription: How can I make an alias to a non-function member attribute in a Python class?

description: Make an alias to a non-function member attribute in a Python class


code:
from PyQt4 import QtGui as qt
from PyQt4 import QtCore as qc

class MainWin(qt.QMainWindow):
    def setKeepAbove(self, above):
        if above:
            self.setWindowFlags(self.windowFlags() | qc.Qt.WindowStaysOnTopHint)
        else:
            self.setWindowFlags(self.windowFlags() & ~qc.Qt.WindowStaysOnTopHint)

rawDescription: What is the PyQt4 equivalent of GTK set_keep_above(True) method?


code:
for event in pygame.event.get(): # User did something
    # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION
    if event.type == pygame.JOYBUTTONDOWN:
        print("Joystick button pressed.")
    if event.type == pygame.JOYBUTTONUP:
        print("Joystick button released.")

rawDescription: Is it possible to combine VPython and Pygame?


code:
import nltk

tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
text = "Machine learning is the science of getting computers to act without being explicitly programmed. Machine learning is so pervasive today that you probably use it dozens of times a day without knowing it. Many researchers also think it is the best way to make progress towards human-level AI."
word_list = ['computer', 'researcher']
output_list = []

for sentence in tokenizer.tokenize(text):
    for word in word_list:
        if word in sentence:
            output_list.append(sentence)
            break # useful when word_list is large

rawDescription: How to get sentences from a paragraph with custom list of words in Python

description: Get sentences from a paragraph with custom list of words in Python


code:
subprocess.call(['bash', '-c',
    'comm -23 <(sort "$1") <(sort "$2") >"$3"', '_',
    infile1_name, infile2_name, outfile_name])

rawDescription: How can i execute comm Linux command in Python

description: Execute comm Linux command in Python


code:
everything=[]
for tr in tree.xpath("//tr[td[@class='section_detail']]"):
    row={}
    row['endorsement']=tr.xpath("td[@bgcolor='#8AFF8A']")
    row['auth']=tr.xpath("td[@bgcolor='#FFFFCC']")
    everything.append(row)

rawDescription: xpath following-sibling and grouping like elements in a table

description: Xpath following-sibling and grouping like elements in a table


code:
l = list('hello world')
l
sorted(l)
l
l.sort()
l

rawDescription: Python naming conventions for functions that do modify the object or return a modified copy


code:
sections_to_cut = [
        ['HE670029', '4095', '4096'],
        ['HE670029', '4098', '4099'],
        ['HE670029', '4102', '4102']
    ]

ropes = {}
for rope in sections_to_cut:
    if rope[0] not in ropes: # could use default dict instead
        ropes[rope[0]] = []
    ropes[rope[0]].append((int(rope[1]), int(rope[2])))

cut_ropes = []

for rope_name, exclude_values in ropes.items():
    sorted_ex = sorted(exclude_values, key=lambda x: x[0])
    a = 0
    for i in sorted_ex:
        cut_ropes.append([rope_name, str(a), str(i[0]-1)])
        a = i[1] + 1
    cut_ropes.append([rope_name, str(a), str(5000)])

print(cut_ropes)
# [['HE670029', '0', '4094'], ['HE670029', '4097', '4097'], ['HE670029', '4100', '4101'], ['HE670029', '4103', '5000']]

rawDescription: Excluding positions to create new intervals in python


code: name = forms.RegexField(regex=r'(?u)\w+$', label=u'Name', required=True)

rawDescription: How to validate unicode "word characters" in Python regex?

description: Validate unicode "word characters" in Python regex


code:
orders = got_something_from_db()
for order in orders: #make got something return empty iterable on failure
    if order["event_id"] in event_id_dict:
        product_id = order["product_id"]
        try:
            sku_id = product_sku_dict[product_id]
            #Change sku_ids to a collections.Counter (assuming order is unimportant)
            sku_ids[sku_id] += order["qty"]
        except KeyError:
            pass

rawDescription: pythonic way to write this code

description: Pythonic way to write this code


code:
#!/usr/env/bin python2.7

import unittest
from fib import fib

class FibTests(unittest.TestCase):
    pass

def test_gen(expected, actual):
    def test_method(self):
        return self.assertEqual(expected, actual)
    return test_method

if __name__ == '__main__':
    cases = ((fib(1), 1), (fib(2), 1), (fib(5), 5))
    for index, case in enumerate(cases):
        test_name = 'test_{0}'.format(index)
        test = test_gen(case[1], case[0])
        setattr(FibTests, test_name, test)
    suite = unittest.TestLoader().loadTestsFromTestCase(FibTests)
    result = unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: Python Unittests continue after failure

description: Python Unittests continue after failure


code:
from itertools import groupby
MyList=['Apple1','Pear1','Apple3','Pear2']
[tuple(v) for k, v in groupby(sorted(MyList, key=lambda x: x[:-1]), lambda x: x[:-1])]

rawDescription: Pair strings in list based on containing text in Python


code:
import __builtin__
my_str = getattr(__builtin__, "str")

rawDescription: Get built-in function from the function name


code: sumindex = [sum(elts) for elts in zip(*lisolis)]

rawDescription: Sum elements of same index from different lists


code:
from datetime import datetime

timestamp1 = "Feb 12 08:02:32 2015"
timestamp2 = "Jan 27 11:52:02 2014"

t1 = datetime.strptime(timestamp1, "%b %d %H:%M:%S %Y")
t2 = datetime.strptime(timestamp2, "%b %d %H:%M:%S %Y")

difference = t1 - t2

print(difference.days) # 380, in this case

latest = max((t1, t2)) # t1, in this case

rawDescription: Compare two timestamps in Python

description: Compare two timestamps in Python


code:
def linecleanup():

    with open("Server.txt1", 'r') as file_in:
        lines = file_in.read()

    lines = re.sub("\s\s\s\s\<revision>", "Revision: ", lines)
    # Where a simple find&replace (non-regex) is required, you could just use this instead:
    # lines = lines.replace("</version>"," ")
    lines = re.sub("</version>", " ", lines)
    lines = re.sub("</revision>", " " + '\n', lines)

    with open("Server.txt3", "w") as outp:
        outp.write(lines)

linecleanup()

rawDescription: Run multiple different re.subs against single file in python


code: window.getShell().setText( 'Custom shell text' )

rawDescription: Changing eclipse window's name

description: Changing eclipse window's name


code:
def computeIndicators(group):
    # group is year-group
    return pd.DataFrame(sub['category'].unique(), columns={'category'})

def computeInitialIndicators(group):
    # group is group-category
    return group['year'].min()

results = patents.groupby(level=[0,1]).apply(computeIndicators)
results = results.reset_index().drop('level_2', 1).sort(['group', 'year'])
results2 = results.groupby(['group', 'category']).apply(computeInitialIndicators)

rawDescription: First time that X has happened

description: First time that X has happened


code:
my_ids = {}

def widget_factory(widget_class,parent,id,*args,**kwargs):
     w = widget_class(parent,id,*args,**kwargs)
     my_ids[id] = w

def get_widget_by_id(widget_id):
     return my_ids[widget_id]

rawDescription: wxpython Accessing an object from an ID

description: Wxpython Accessing an object from an ID


code:
import numpy as np
from itertools import product

A = np.zeros([20,20])

col_coord = [0,1,3]
row_coord = [1,2]

coords = np.array(list(product(row_coord, col_coord)))

B = 1

A[coords[:,0], coords[:,1]] = B

rawDescription: Substitute elements of a matrix at specific coordinates in python


code:
pl.plot([1], [1])
pl.ylabel('Total resistance\n$\\regular_{{m}^{4} kg^{-1}s^{-1}}$', fontsize=20)

rawDescription: Matplotlib multiline axis text with different font size


code:
import csv

def compute_average(clsnam, fulnam):
    """ Determine average score in class for named person.
    """
    scores = []
    with open(clsnam + ".csv", 'r') as file:
        for name, score in csv.reader(file):
            if name.strip() == fulnam:
                scores.append(int(score))

    return None if not scores else float(sum(scores)) / len(scores)

rawDescription: How can I work out average of One person in same class when calling from Csv

description: Work out average of One person in same class when calling from Csv


code:
def nrofleadingchars(stringtotest, testchar='\t'):
    count = 0
    for c in stringtotest:
        if c != testchar:
            break
        count += 1
    return count

rawDescription: looking for more pythonic apporach

description: Looking for more pythonic apporach


code:
s = raw_input("Please input something: ")
# now I input "f John Cleese", so that is now the value of 's'
# printing the value of 's' will let you see what it is exactly.

command = s.split(' ', 1)
# the above code will split the string 's' on a ' ' space,
# and only do it once, and then create a list with the pieces
# so the value of 'command' will be ['f', 'John Cleese'] for your example.

# to access items in the command list use brackets []
command[0] # 'f'
command[1] # 'John Cleese'

rawDescription: raw_input that able to do detect multiple input

description: Raw_input that able to do detect multiple input


code:
from google.appengine.ext.appstats import recording
recording.recorder.record_custom_event('hello', 'data')

rawDescription: Extending Google Appstats

description: Extending Google Appstats


code:
S = """\
<a> <b> <c>.
<d> db:connect <e>.
db:start <f> <g>.
<h> <i> "hello".
"""

import re

expand_tags = re.sub(r"<(.*?)>", r"<http://www.mycompany.com/\1>", S)
expand_db = re.sub(r"db:(.*?)\s", r"<http://www.mydbcompany.com/\1>", expand_tags)

print(expand_db)
#>>> <http://www.mycompany.com/a> <http://www.mycompany.com/b> <http://www.mycompany.com/c>.
#>>> <http://www.mycompany.com/d> <http://www.mydbcompany.com/connect><http://www.mycompany.com/e>.
#>>> <http://www.mydbcompany.com/start><http://www.mycompany.com/f> <http://www.mycompany.com/g>.
#>>> <http://www.mycompany.com/h> <http://www.mycompany.com/i> "hello".

rawDescription: Convert string to desired format using python


code: {{ form.fields|length }}

rawDescription: How to get the number of form fields in a django template?

description: Get the number of form fields in a django template


rawDescription: Python encoding (get rid of unnecessary symbols)


code:
import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
   dd = dd.replace(year=dd.year-100)

rawDescription: How to parse string dates with 2-digit year?

description: Parse string dates with 2-digit year


code:
grunt.initConfig({
    shell: {
        pythonServer: {
            options: {
                stdout: true
            },
            command: 'python manage.py runserver 0.0.0.0:8000 --insecure'
        }
    }
});

grunt.loadNpmTasks('grunt-shell');
grunt.registerTask('default', ['shell:pythonServer']);

rawDescription: Run Python localhost through Grunt

description: Run Python localhost through Grunt


code:
def get_queryset(self, request):
    return self.model.objects.filter(is_special=True,)

def render_change_form(self, request, context, *args, **kwargs):
     context['adminform'].form.fields['assigned_teacher'].queryset = Teacher.objects.filter(has_certification=True)
     return super(ManageSpecialStudent, self).render_change_form(request, context, *args, **kwargs)

rawDescription: Django admin proxy model edit form, prefilter on the form level only


code:
for word in words:
  inner_dic = {}
  for pair in text:
    if pair[0] == word:
      num = text.count(pair)
      inner_dic[pair[1]] = num
  dic[word] = inner_dic

rawDescription: finding frequencies of pair items in a list of pairs

description: Finding frequencies of pair items in a list of pairs


code:
from itertools import product, repeat
given = [1, 2]
with_nones = zip(given, repeat(None))
print(list(product(*with_nones)))

rawDescription: Most efficient way to generate "ordered subsets" of a sequence


code:
#download file
download = "http://status.calibre-ebook.com/dist/portable/" + result
request = urllib2.urlopen( download )

#save
output = open("install.zip", "w")
output.write(request.read())
output.close()

rawDescription: Saving a downloaded ZIP file w/Python

description: Saving a downloaded ZIP file w/Python


code:
from distutils import sysconfig
from distutils.core import setup
import platform

if platform.system() != 'Windows':  # When compilinig con visual no -g is added to params
    cflags = sysconfig.get_config_var('CFLAGS')
    opt = sysconfig.get_config_var('OPT')
    sysconfig._config_vars['CFLAGS'] = cflags.replace(' -g ', ' ')
    sysconfig._config_vars['OPT'] = opt.replace(' -g ', ' ')

if platform.system() == 'Linux':  # In macos there seems not to be -g in LDSHARED
    ldshared = sysconfig.get_config_var('LDSHARED')
    sysconfig._config_vars['LDSHARED'] = ldshared.replace(' -g ', ' ')

setup(...)

rawDescription: Distutils - How to disable including debug symbols when building an extension


code:
import os

s = '''this is a test of the... What? What is going on now?
You guys are cu-rayzy!
Morons!'''

new_lines = []
lines=s.strip().split("\n")
for line in lines:
    new_words = []
    for word in line.strip().split(" "):
        new_words.append(word[1:])
    new_lines.append(' '.join(new_words))
new_statement = "\n".join(new_lines)

print (s)

print (new_statement)

rawDescription: Python: Remove First Character of each Word in String


code: dtfix=[dt.datetime.strptime(x, "%m/%d/%y %H:%M:%S") for x in dtcode]

rawDescription: How do I get date and time from two columns of a numpy array into a datetime format that can be used by matplotlib?

description: Get date and time from two columns of a numpy array into a datetime format that can be used by matplotlib


code:
from collections import defaultdict

def make_letter_dict(word):
  letters = defaultdict(int)
  for c in word:
    letters[c] += 1

letters = make_letter_dict(raw_input("Letters: "))
words = (w for w in wordlist if make_letter_dict(w) == letters)

rawDescription: Python: Making a wordbook to search within


code:
from iComplex import SplitComplex as c_split
...
ctype = c_split
constructor = np.vectorize(ctype, otypes=[np.object])
field = constructor(np.zeros((field_size, field_size)))

rawDescription: implementing exotic complex numbers to use with numpy

description: Implementing exotic complex numbers to use with numpy


code:
posts = GqlQuery("SELECT * from BLOGPOSTS")
posts_and_comments = []
for post in posts:
    two_comments = GqlQuery("SELECT * from COMMENTS WHERE blogpost_id = :1 ORDER BY age LIMIT 2", post.blogpost_id)
    current_post = {post: two_comments}
    posts_and_comments.append(current_post)

rawDescription: Displaying Comments Jinja2-Python

description: Displaying Comments Jinja2-Python


code:
tbl.write('test.txt', format='ascii.ipac')
with open('test.txt', 'r') as fh:
    output = []
    for ii, line in enumerate(fh):
        if ii not in (1,3):
            output.append(line)

with open('test.txt', 'w') as fh:
    fh.writelines(output)

rawDescription: How do I save the header and units of an astropy Table into an ascii file

description: Save the header and units of an astropy Table into an ascii file


code:
from random import SystemRandom
r = SystemRandom()
choice = r.choice

for _ in range(1000000):
    ''.join(choice('abcdef') for _ in range(5))

rawDescription: Is it good Python practice to reuse SystemRandom?


code: s = dict([ (k,r) for k,r in mydict.iteritems() if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ])

rawDescription: Python list comprehension for dictionaries in dictionaries?


code:
message = EmailMessage(subject, body, from_email, bcc=recipient_list)
message.attach(FILENAME, mymodel.myfilefield.read())

rawDescription: Sending email from a Django app hosted on Heroku with attachment stored in AWS S3


code:
def start_requests(self):
    yield Request(url1, callback=self.my_callback)
    yield Request(url2, callback=self.my_callback)

rawDescription: How can use a pipeline in Scrapy when using a spider through the parse command


code:
import numpy as np

def asscalar(v):
    """
    Try converting a numpy array of size 1 to a scalar equivalent, or return
    the value as is.

    Returns:
        A scalar value, if a numpy array of size 1 was given, the value itself
        otherwise. Note that a python list of size 1 will be returned as is.

    Raises:
        A ValueError, if v is a numpy array of size larger than 1.
    """
    try:
        return np.asscalar(v)

    except AttributeError:
        # Not something numpy understands
        return v

rawDescription: Convert numpy scalar to python simple native (with one twist)


code:
df['file'] = 'abc.xlsx'
df['group'] = 'first'

rawDescription: Add File Name to Created Pandas Dataframe From Excel File


code:
from __future__ import print_function, unicode_literals

import json
import numpy
import tifffile  # http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html

data = numpy.arange(256).reshape((16, 16)).astype('u1')
metadata = dict(microscope='george', shape=data.shape, dtype=data.dtype.str)
print(data.shape, data.dtype, metadata['microscope'])

metadata = json.dumps(metadata)
tifffile.imsave('microscope.tif', data, description=metadata)

with tifffile.TiffFile('microscope.tif') as tif:
    data = tif.asarray()
    metadata = tif[0].image_description
metadata = json.loads(metadata.decode('utf-8'))
print(data.shape, data.dtype, metadata['microscope'])

rawDescription: What is the best way to save image metadata alongside a tif with Python?


code:
import csv

bottle_list = []

# Read all data from the csv file.
with open('a.csv', 'rb') as b:
    bottles = csv.reader(b)
    bottle_list.extend(bottles)

# data to override in the format {line_num_to_override:data_to_write}.
line_to_override = {1:['e', 'c', 'd'] }

# Write data to the csv file and replace the lines in the line_to_override dict.
with open('a.csv', 'wb') as b:
    writer = csv.writer(b)
    for line, row in enumerate(bottle_list):
         data = line_to_override.get(line, row)
         writer.writerow(data)

rawDescription: Overwriting a specific row in a csv file using Python's CSV module


code:
def func(*args): # The trick here is the use of the star
    if len(args) < 3: # In case needed, also protects against IndexError
        raise TypeError("func takes at least 3 arguments")
    return [args[0], args[-1]]

rawDescription: Getting first and last function parameter in Python


code:
from sqlalchemy.orm import aliased

off_Team = aliased(Team)
obs_Team = aliased(Team)

results = db.session.query(obs_Team.email, Game.id)\
    .select_from(GameObserver)\
    .join(Game)\
    .join(obs_Team, GameObserver.observer)\
    .join(off_Team, Game.offense)\
    .filter(off_Team.email == 'foo@email123.com')\
    .all()

rawDescription: SQLAlchemy - How to query 3 tables (with association table)


rawDescription: django.db aggregation across multiple fields

description: Django.db aggregation across multiple fields


code:
def test():
    a = A()
    a.doSomethingThatResultsInChangingStatus()
    assert a._status == 'changed correctly'

rawDescription: Python: Unit test of a function not returning anything, but changing state of the object


rawDescription: Python string slice indices - slice to end of string


code:
import StringIO
import ConfigParser

# Create a deep copy of the configuration object
config_string = StringIO.StringIO()
base_config.write(config_string)

# We must reset the buffer to make it ready for reading.
config_string.seek(0)
new_config = ConfigParser.ConfigParser()
new_config.readfp(config_string)

rawDescription: Manually building a deep copy of a ConfigParser in Python 2.7


code:
df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
df
df.iloc[0]
type(_)

rawDescription: Convert pandas data frame to series

description: Convert pandas data frame to series


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

k=np.array([12,11,12,12,20,10,12,0,12,10,11])
x2=np.arange(1,12,1)

# find out which parameters are more than 1.5*std away from mean
warning = np.abs(k-np.mean(k)) > 1.5*np.std(k)

# enable drawing of multiple graphs on one plot
plt.hold(True)

# draw some lines behind the scatter plots (using zorder)
plt.plot(x2, k, c='black', zorder=-1)

# scatter valid (not warning) points in blue (c='b')
plt.scatter(x2[~warning], k[~warning], label='signal', c='b')

# scatter warning points in red (c='r')
plt.scatter(x2[warning], k[warning], label='warning', c='r')

# draw the legend
plt.legend()

# show the figure
plt.show()

rawDescription: how to color data points based on some rules in matplotlib

description: Color data points based on some rules in matplotlib


code:
import pandas as pd

data = []
for line in open('temp.text'):
    if line.startswith('/media/'):
        path = line[:-1]
    else:
        rights = line.split()[1]
        owner = re.match('.*.CN=([^.]+).*', line).groups()[0]
        row = {'path': path, 'right': rights, 'owner': owner}
        data.append(row)
df = pd.DataFrame(data)
df[df.owner=='Dog']

rawDescription: Pandas DF and RE - Find a match Y. Then find the last occurence of X


code: incomplete_df['reason'] = "Reason is " + incomplete_df.T.idxmin()

rawDescription: Pandas: getting the name of the minimum column


code:
import csv
import random

a = [1,2]

with open('DD{}filename.csv'.format(fileName), 'w') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(['trial','numbers']) # Note this is a two element
                                         # list, not a string

    for i in range(4):
        random.shuffle(a)
        if a == [1,2]:
           num = 'top'
        else:
           num = 'bottom'

        writer.writerow([i, num])

rawDescription: exporting data into a column of an excel file in python

description: Exporting data into a column of an excel file in python


code:
z1 = np.dstack([np.in1d(img[...,0],B),np.in1d(img[...,1],G),np.in1d(img[...,2],R)]).reshape(img.shape)
q = np.all(z1,axis=2)
out = np.uint8(q)*255

rawDescription: OpenCV multicolor thresholding

description: OpenCV multicolor thresholding


code:
sen = "en aquest sentit, la llei preveu que quan l'administració s'hagi abstingut d'actuar per sancionar una determinada conducta, com a conseqüència d'un procés penal, i aquest procediment acabi en sentència absolutòria, podrà iniciar o continuar el corresponent procediment administratiu."
tokens = sen.split()
tokens
def get_index(tokens, substr):
   for i, tk in enumerate(tokens):
      if substr in tk: return i

get_index(tokens, "actuar")

rawDescription: Fuzzy matching to find the index of a word in a sentence Python


code:
def deactivate_prompts(ctx, param, value):
    if not value:
        click.echo("entering batch mode, deactivating all prompts ...")
        for p in ctx.command.params:
            if isinstance(p, click.Option) and p.prompt is not None:
                p.prompt = None
    return value

@click.option('--i/--b', default=True, is_eager=True, expose_value=False, callback=deactivate_prompts)
@click.option('--x', default=42, prompt=True)
@click.command
def cli_c(x):
  print(x)

rawDescription: python-click: Adding an option that modifies the behavior of other parameters

description: Python-click: Adding an option that modifies the behavior of other parameters


code:
from robot.libraries.BuiltIn import BuiltIn
class SeleniumTestLibrary(object):
  def element_should_be_really_visible(self):
    s2l = BuiltIn().get_library_instance('Selenium2Library')
    element = s2l._element_find(locator, True, False)

rawDescription: How to call methods of the instance of a library already in scope of the current running test case

description: Call methods of the instance of a library already in scope of the current running test case


code:
import urllib2
url = urllib2.Request("http://...", headers={'HTTP_REFERER': "http://..."})
doc = pyQuery(url=url)

rawDescription: Pyquery： I'm using pyquery ,the HTTP_REFFER is required in this page,How can i do with it?


code:
import locale
locale.getdefaultlocale()

rawDescription: Proper way to grab environments locale in python


code:
from functools import partial

def zero(number):
    return number == "zero"

def one():
    return "one"

def numbers_to_functions_to_strings(argument):
    switcher = {
        0: partial(zero, argument),
        1: one,
        2: lambda: "two",
    }

    func = switcher.get(argument, lambda: "nothing")
    return func()

rawDescription: Python switch case allowing optional arguments


code:
y = compile("m*x+b","","eval")
m = 100
x = 5
b = 1
eval(y)

rawDescription: Partial evaluation with pyparsing

description: Partial evaluation with pyparsing


code:
s = "23423 NewYork"
[sub for sub in s.split() if all(c.isalpha() for c in sub)]
s = "NewYork 23423"
[sub for sub in s.split() if all(c.isalpha() for c in sub)]

rawDescription: I want to extract string from a string that also contains numbers - python


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
def setcolor(x, color):
     for m in x:
         for t in x[m][1]:
             t.set_color(color)
m = Basemap(lon_0=0)
m.drawcoastlines()
par = m.drawparallels(np.arange(-90,90,30),labels=[1,0,0,1])
setcolor(par,'r')
merid = m.drawmeridians(np.arange(0,360,60),labels=[1,0,0,1])
setcolor(merid,'r')
plt.show()

rawDescription: Basemap drawparallels tick label color

description: Basemap drawparallels tick label color


code:
s = df[df['gender'] == 'm'].groupby('id').size()
s.name = 'size'
df2 = df.join(s, on='id')
df2[df2['size'] == 2]

rawDescription: Select first or last n groups after applying "group by"


code: setattr(foo, mystring, False)   # this is just here to let me submit

rawDescription: Python: Add atribute to object named after an existing string


code:
class Config(db.Model):
    """
    Application Config
    """

    name  = db.StringProperty(required=True)
    value = db.StringProperty(required=True)

    @staticmethod
    def create_config(name,
                      value):
        pass

rawDescription: What is the best way to store config settings in Google App Engine?


code:
import urllib
import time

while True:
   urllib.urlopen(url, post_data)
   time.sleep(60)

rawDescription: How to periodically create an HTTP POST request from windows

description: Periodically create an HTTP POST request from windows


code:
s = re.search(r".*\/(app.*)", "/home/python/app/index.html")
s.groups()[0]

rawDescription: Python regular expression that replaces test before a particular pattern


code:
def export_to_png(self, filename, *args):
        '''Saves an image of the widget and its children in png format at the
        specified filename. Works by removing the widget canvas from its
        parent, rendering to an :class:`~kivy.graphics.fbo.Fbo`, and calling
        :meth:`~kivy.graphics.texture.Texture.save`.

        .. note::

            The image includes only this widget and its children. If you want
            to include widgets elsewhere in the tree, you must call
            :meth:`~Widget.export_to_png` from their common parent, or use
            :meth:`~kivy.core.window.WindowBase.screenshot` to capture the whole
            window.

        .. note::

            The image will be saved in png format, you should include the
            extension in your filename.

        .. versionadded:: 1.9.0
        '''

        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            self.parent.canvas.remove(self.canvas)

        fbo = Fbo(size=self.size, with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 1)
            ClearBuffers()
            Scale(1, -1, 1)
            Translate(-self.x, -self.y - self.height, 0)

rawDescription: Kivy take screenshot with clear background


code:
from my_lib import *

# well, maybe not `not at_goal()` since it only check it after
# the below code finish running, it would be better to use `while True`
# and find a better way to implement the at_goal()

while not at_goal():
    while front_is_clear():
        move()

    if not front_is_clear():
        jump_over_hurdle()

done()

rawDescription: How to return to the beginning of the code after it turns false?

description: Return to the beginning of the code after it turns false


code:
def display_user_content(self, details):
    self.user_sizer.Clear(True)
    self.single_user_sizer = wx.GridSizer(cols=2, hgap=5, vgap=5)
    for each in details:
        #Get username
        self.username_sizer = wx.BoxSizer(wx.HORIZONTAL)
        username = each[0]
        #Get location of image file
        location = each[-1]
        #Create static text to contain username
        stat = wx.StaticText(self, -1, 'username')
        #Load image from location and convert to bitmap.
        png = wx.Image(location, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        #Create bitmap
        avatar = wx.StaticBitmap(self, -1, png)
        #Add to sizer
        self.single_user_sizer.Add(avatar, 0)
        self.username_sizer.Add(stat, 0)
        self.single_user_sizer.Add(self.username_sizer, 0)
    #Add each users sizer to main user sizer
    self.user_sizer.Add(self.single_user_sizer, 0)
    #Add main user sizer to widget sizer
    #self.widget_sizer.Add(self.user_sizer, 0)
    self.Fit()

rawDescription: WxPython dynamically added sizers mis-behaving


code: print ('%3d'*len(nums)) % tuple(nums)

rawDescription: python string format for variable tuple lengths

description: Python string format for variable tuple lengths


code:
#!/usr/bin/python

import glib
import socket
import ssl

def cb(fd, cond):
    print('data: %s' % repr(s.read(1)))
    while(s.pending()):
        print('more data: %s' % repr(s.read(1)))
    return True

s = ssl.wrap_socket (socket.create_connection(('localhost', 1234)))
glib.io_add_watch(s.fileno(), glib.IO_IN, cb)
glib.MainLoop().run()

rawDescription: How to use select with Python ssl socket buffering?

description: Use select with Python ssl socket buffering


code:
def rwh_primes1(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

def rwh_primes_tjv(n):
    # recurrence formula for length by amount1 and amount2 tjv
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)
    amount1 = n-10
    amount2 = 6

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
             ## can you make recurrence formula for whole reciprocal?
            sieve[i*i//2::i] = [False] * (amount1//amount2+1)
        amount1-=4*i+4
        amount2+=4

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]

def rwh_primes_len(n):
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * len(sieve[i*i//2::i])

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]

def rwh_primes_any(n):
    """ Returns  a list of primes < n """
    halfn=n//2
    sieve = [True] * (halfn)

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            any(sieve.__setitem__(item,False) for item in range(i*i//2,halfn,i))

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]

if __name__ == "__main__":
    n = 1000000

    print("rwh sieve1")
    t=clock()
    r=rwh_primes1(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with recurrence formula")
    t=clock()
    r=rwh_primes_tjv(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with len function")
    t=clock()
    r=rwh_primes_len(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with any with side effects")
    t=clock()
    r=rwh_primes_any(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))
    raw_input('Ready')

""" Output:
rwh sieve1
Length 78498,  213.199442946 ms
rwh sieve with recurrence formula
Length 78498,  218.34143725 ms
rwh sieve with len function
Length 78498,  257.80008353 ms
rwh sieve with any with side effects
Length 78498,  829.977273648 ms
Ready
"""

rawDescription: Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation?


code:
def setUp(self):
        self.warehouse = Warehouse.objects.create(
            location_name = 'Mumbai',
            address = 'D1/D2 tex center Chandivali',
        )
        self.supplier = Supplier.objects.create(
            name = "John Doe",
            website = "johndoe@johndoe.com",
            address = "USA, San francisco , CA"
        )
        self.procurement_detail = ProcurementDetail.objects.create(
            invoice_name = "Indore Mill",
            invoice_number = "14235",
            details = "Cloth from Central India",
            total_cost_price = "0.00",
            payment_method = "CASH",
            supplier_id = self.supplier.id,
            is_paid = "True"
        )
        self.inventory_category = InventoryCategory.objects.create(
            name = "party time"
        )
        self.color = Color.objects.create(
            name = "Green",
            hex_val = "#007089"
        )
        self.occasion = Occasion.objects.create(
            name = "BDay"
        )
        self.photo_shoot = PhotoShoot.objects.create(
            name = 'front 1',
            details = 'This is the front facing image',
            model_size = {'name':'abcd'}
        )
        self.brand = Brand.objects.create(
            name = "ZARA1"
        )
        self.parent_item_description = ParentItemDescription.objects.create(
            features = 'Indian clothing at its best',
            style_tip = 'This is style tip',
            fitting_notes = 'This is fitting notes',
            long_description = 'This is the Long description'
        )
        self.parent_item = ParentItem.objects.create(
            parent_id = "1003",
            mrp = "0.00",
            photo_shoot_id = self.photo_shoot.id,
            description_id = self.parent_item_description.id,
            cost_price = "0.00",
            rental_price = "0.00",
            discount_price = "0.00",
            discount_percent = "0.00",
            security_deposit = "0.00",
            material_percentage = '"cotton"=>"20"',
            mode = "Express",
            brand_id = self.brand.id,
            features = "THe best feature the best it is ",
            size = ['S','M','L'],
            online_link_url = "http://chitrank-dixit.github.io/",
            visibility_order_index = 1,
            category = 'Express clothing',
            inventory_category_id = self.inventory_category.id,
            popularity_index = 90,
            item_domain = "CLT",
            gender = "FML"
        )
        self.inventory_item = InventoryItem.objects.create(
            warehouse_id = self.warehouse.id,
            parent_item_id = self.parent_item.id,
            size = ['S','M','L'],
            procurement_detail_id = self.procurement_detail.id,
            size_range_id = 2,
            product_tag = {'name':'abcd'},
            short_description = 'abcd',
            is_virtual = False,
            warehouse_stack_id = "12345",
            reason_for_out_stock = "NA",
            status = "ILV"
        )
        self.inventory_item.color.add(self.color)
        self.inventory_item.occasion.add(self.occasion)
        self.resource_url = '/api/v2/inventory/inventory_item_detail/'+str(self.inventory_item.parent_item.parent_id)+'/'

rawDescription: Test case for GET api for APIView not working in djangorestframework


code:
from setuptools import setup
setup(
    name='name',
    version='1.0.0',
    scripts=['myscript_filename'],
    install_requires=['other_module'],
)

rawDescription: Python Modules in Unix Command Line Programs


code:
import os
for i in "abc":
    os.system ("mkdir "+i)
    for j in range (5):
            os.system ("touch "+str(i)+"/"+str(j)+".txt")

rawDescription: creating file and folder loop

description: Creating file and folder loop


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

class MyFrame(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.le = QLineEdit(self)
        self.le.setGeometry(200,200,75,35)

        i = 0
        self.le.setText(str(i))

        self.connect(self.le, SIGNAL("textEdited(QString)"),self.updatedvalue)

    def updatedvalue(self):
        for i in range(1,5):
            self.le.setText(str(i))
            QApplication.instance().processEvents()
            print(i)
            time.sleep(1)

app=QApplication(sys.argv)
f=MyFrame()
f.show()
app.exec_()

rawDescription: Python Pyqt: could not display data in lineedit and print command in terminal window


code: [(b, e) for a, b in zip(mynestedlist, otherlist) for e in a]

rawDescription: Combine two Python lists with partly empty sublists


code:
from operator import itemgetter

names = set(d['name'] for d in result)
uniq = []
for name in names:
    scores = [res for res in result if res['name'] == name]
    uniq.append(max(scores, key=itemgetter('score')))

rawDescription: How to uniqufy the tuple element?

description: Uniqufy the tuple element


code:
people = [('bob', 28), ('alice', 21), ('jeff', 78)]
sorted(people, key=lambda tup: tup[1], reverse=True)

rawDescription: sort object based on attribute

description: Sort object based on attribute


code:
import numpy
A = numpy.array(((1,2),(3,4)))
idx = (0,0)
A[idx]

rawDescription: Unpacking tuples/arrays/lists as indices for Numpy Arrays


code:
location = (element.location['x'] + element.size['width'] / 2, element.location['y'] + element.size['height'] / 2)

#Switching to the n-1 th frame, frames is an array of frames' name
frames = page.frame

browser.switch_to_default_content()
for frameName in frames[:len(frames) - 1]:
    browser.switch_to_frame(frameName)

#Handle to the n th frame
frame = browser.find_element_by_tag_name(name="iframe")
action = ActionChains(context.browser)
action.move_to_element_with_offset(frame, location[0], location[1]).double_click()
action.perform()

rawDescription: Double Click On A WebElement in an iframe nested in an other iframe


code: converted_image = image.convert_alpha()

rawDescription: The pygame set_at function doesn't seem to work correctly. Can somebody explain it's behavior and help me work around it?


code:
from sklearn.cluster import AgglomerativeClustering
from sklearn.grid_search import GridSearchCV

ac = AgglomerativeClustering(memory='mycachedir',
                             compute_full_tree=True)
classifier = GridSearchCV(ac,
                          {n_clusters: range(2,6)},
                          scoring = 'adjusted_rand_score',
                          n_jobs=-1, verbose=2)
classifier.fit(X,y)

rawDescription: sklearn agglomerative clustering: dynamically updating the number of clusters

description: Sklearn agglomerative clustering: dynamically updating the number of clusters


code:
# If there is an argument passed to your file
if len(sys.argv) > 1:
    # argv[1] has your filename
    filename = sys.argv[1]
    print (filename)

# Output...
# new-host:~ yanwchan$ python3.2 test.py text.txt
# text.txt

rawDescription: Is it possible to pass arguments to a python made exe at runtime?


code:
def nonprefix_combinations(iterable, maxlen):
    iterable = list(iterable)
    if not (iterable and maxlen):
        return
    for comb in combinations(iterable, maxlen):
        yield comb
    for length in xrange(maxlen-2, -1, -1):
        for comb in combinations(iterable[:-1], length):
            yield comb + (iterable[-1],)

rawDescription: Efficient enumeration of ordered subsets in Python


code:
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
for r, row in enumerate(data):
    for c, col in enumerate(row):
        ws.write(r, 2 + c, label=col)

rawDescription: write array starting from specific column to new workbook using xlwt

description: Write array starting from specific column to new workbook using xlwt


code:
def half_list(l):
    return l[:len(l)/2]

rawDescription: Python index like MATLAB's end/2

description: Python index like MATLAB's end/2


code:
import os.path
from whoosh.index import create_in

if not os.path.exists("index"):
    os.mkdir("index")
ix = create_in("index", schema)

rawDescription: Where does Whoosh (Python) physically store the indexed content?


code:
from Tkinter import Tk, Menu, Frame

class MyTkWindow(Tk):

    def __init__(self):

        Tk.__init__(self)

        # replace these three lines to create your own menu
        self.menubar = Menu(self)
        self.menubar.add_command(label='Hello')
        self.config(menu=self.menubar)

        # replace these two lines to embed your own widgets in the window
        self.frame = Frame(self, width=500)
        self.frame.grid(sticky='news')

        # this block makes the window not resizable in width,
        # only in height (and within a certain range only)
        self.update_idletasks()
        self.max_w = self.winfo_width()
        self.state('zoomed')
        self.update_idletasks()
        self.max_h = self.winfo_height()
        self.wm_minsize(width=self.max_w, height=self.max_h-100)
        self.wm_maxsize(width=self.max_w, height=self.max_h)

t = MyTkWindow()
t.mainloop()

rawDescription: Tkinter resizable attribute ignored on windows Vista when a menu is added to the window


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

rawDescription: Is it possible to turn on directory indexes when serving static files in development in Django?


code:
class Event(models.Model):
    publicID = models.CharField(max_length=128)

    @property
    def time_data(self):
        origins= self.origin.all()

        return ' '.join([ str(x.time.value) for x in origins])

class EventsTable(tables.Table):
    time = tables.Column(accessor='time_data')

    class Meta:
        model = Event
        fields = ('time')

rawDescription: Django Tables 2 Field Accessor backward relationship


code: soup.find("div", text="Email").next_sibling.strip()  # prints "info@blah.com"

rawDescription: Find elements which have a specific child with BeautifulSoup


code:
y_data = [4, 1, 2, 3, np.nan, np.nan, np.nan, 4, 4, 5]
x_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
p1 = figure(plot_width=600, plot_height=400)
p1.line(x_data, y_data, size=12, color="blue")

rawDescription: Bokeh - Plotting Data with Gaps

description: Bokeh - Plotting Data with Gaps


code:
from pywinauto import clipboard
print(clipboard.GetData())

rawDescription: How can I get a url from Chrome by Python?

description: Get a url from Chrome by Python


code:
import bpy
material_list = ['oak','redwood','plastic']
camera_positions = [[2.0,1.0,1.0],[1.0,2.0,1.0],[2.0,2.0,1.0]]

for mat in material_list:
    bpy.data.objects['Chair'].material_slots[0].material = bpy.data.materials[mat]
    for campos in camera_positions:
        bpy.data.objects['Camera'].location = campos
        bpy.ops.render.render()

rawDescription: Simple python script with blender

description: Simple python script with blender


code:
# Equals user ID if active; otherwise null.
is_active = models.IntegerField(null = True, unique = True)

rawDescription: Is there any more elegant way to add a value sensitive unique together constraint in Django Model?


code:
interventionPreventivesVisits = InterventionPreventiveVisit.objects.filter(
    date__range=(self.weekDays[0], self.weekDays[len(self.weekDays)-1])
).select_related("housing"
).prefetch_related("housing__tenants")

rawDescription: Prefetch related django

description: Prefetch related django


code:
import re
s = "Ex1.  This is a random sentence.1,7,9 This is a sentence followed by it."
print(re.sub(r'\.(\S)', r'.\n\1', s))

rawDescription: What is the regular expression?

description: What is the regular expression


code:
from collections import Counter
d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}
# create a list of only the values you want to count,
# and pass to Counter()
c = Counter([values[1] for values in d.itervalues()])
c

rawDescription: Python count of items in a dictionary of lists


code:
from cStringIO import StringIO
# or, in Py3/Py2.6+:
#from io import BytesIO, StringIO

s = StringIO(large_string)
while True:
    chunk = s.read(200)
    if len(chunk) > 0:
        process(chunk)
    if len(chunk) < 200:
        break

rawDescription: Equivalent for pop on strings

description: Equivalent for pop on strings


code:
from operator import itemgetter
from itertools import groupby
data=[["apple",2],["cake",5],["cake",8],["chocolate",3],["chocolate",9],["chocolate",10],["grapes",6]]
[list(g) for _,g in groupby(sorted(data,key=itemgetter(0)),itemgetter(0))]

rawDescription: PYTHON: Create sublists of same values from nested list into one list


code:
from datetime import timedelta
import logging
import time

class ElapsedFormatter():

    def __init__(self):
        self.start_time = time.time()

    def format(self, record):
        elapsed_seconds = record.created - self.start_time
        #using timedelta here for convenient default formatting
        elapsed = timedelta(seconds = elapsed_seconds)
        return "{} {}".format(elapsed, record.getMessage())

#add custom formatter to root logger for simple demonstration
handler = logging.StreamHandler()
handler.setFormatter(ElapsedFormatter())
logging.getLogger().addHandler(handler)

log = logging.getLogger('test')
log.error("Message 1")

time.sleep(5)

log.error("Message 2")

rawDescription: Python logging time since start of program