code:
import netCDF4

src = netCDF4.Dataset("drycblles.1.nc")

for name, variable in src.variables.items():
    for attrname in variable.ncattrs():
        print("{} -- {}".format(attrname, getattr(variable, attrname)))
        # or :
        #print("{} -- {}".format(attrname, variable.getncattr(attrname)))

src = netCDF4.MFDataset("drycblles.*.nc")

for name, variable in src.variables.items():
    for attrname in variable.ncattrs():
        print("{} -- {}".format(attrname, getattr(variable, attrname)))

rawDescription: Getting variable attributes from NetCDF MFDataset in Python


code:
import matplotlib.pyplot as plt
from scipy import ndimage
from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox
import numpy as np

# Create and save an image with just a marker in it
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(0.5,0.5,'*',ms=200)
ax1.set_ylim(0,1)
ax1.set_xlim(0,1)
plt.axis('off')
fig1.savefig('marker.png')

# Read in the same marker image
marker = plt.imread('marker.png')

# New figure and data
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
x = 8*np.random.rand(10) + 1
y = 8*np.random.rand(10) + 1
sigma = np.arange(10,60,5)

# Blur the marker and image plot the blurred image at each data point.
for xi, yi, sigmai in zip(x,y,sigma):
    markerBlur = ndimage.gaussian_filter(marker,sigmai) # Blur the marker image

    # Create an BboxImage for the blurred marker and add it to the plot.
    bb = Bbox.from_bounds(xi,yi,1,1)
    bb2 = TransformedBbox(bb,ax2.transData)
    bbox_image = BboxImage(bb2,
                           norm = None,
                           origin=None,
                           clip_on=False)

    bbox_image.set_data(markerBlur)
    ax2.add_artist(bbox_image)

ax2.set_xlim(0,10)
ax2.set_ylim(0,10)
plt.show()

rawDescription: How to plot blurred points in Matplotlib

description: Plot blurred points in Matplotlib


code:
from traits.api import HasTraits, Button
from traitsui.api import View, Item
import numpy

##you may need to uncoment these 2 lines to prevent
##ImportErrors due to missing backends
#from traits.etsconfig.api import ETSConfig
#ETSConfig.toolkit = 'qt4' # or 'wx'

from pyface.api import FileDialog, OK

class ArrayToBeSaved(HasTraits):
    save_as = Button('save as')

    traits_view = View(Item('save_as'))

    def __init__(self):
        self.my_array = numpy.ones(3)

    def _save_as_changed(self):
        dlg = FileDialog(action='save as')
        if dlg.open() == OK:
            numpy.save(dlg.path, self.my_array)
            self.my_array = numpy.zeros(3)

atbs = ArrayToBeSaved()

atbs.configure_traits()

rawDescription: Python traitsui save file dialogue - overwriting


code:
bill_amt = True
while bill_amt:
    try:
        bill_amt = float(input('First, what was the price of your meal?(Please do not use signs such as "$"):'))
    except ValueError:
        print('Please enter just a number')
        continue
    if bill_amt <= 0: #or if bill_amt has letters or symbols
        print('Your meal wasn\'t $',bill_amt, '! Please try again.')
        bill_amt = True
    else:
        x = float(bill_amt)
        bill_amt = False

rawDescription: How to limit an input so only certain letters or numbers are used? (Python)

description: Limit an input so only certain letters or numbers are used? (Python)


code:
import matplotlib as mpl
mpl.rcParams['lines.markersize'] = 10

rawDescription: pyplot: Can I set a global marker size parameter?

description: Pyplot: Can I set a global marker size parameter


rawDescription: How to pass more data into scipy.integrate.odeint

description: Pass more data into scipy.integrate.odeint


code:
response = requests.get(url)
newUrl = response.url

rawDescription: Scraping Metacritic with urllib to follow redirect


code:
import itertools as it
import datetime
data = [['12:30:32', '12:33:12', 1],
        ['12:30:55', '12:33:43', 3],
        ['14:31:21', '12:34:34', 2],
        ['14:33:24', '12:35:34', -12]]

def continuous(series, time_format = '%H:%M:%S', criteria = 3600):
    '''Returns True if time series is continuous.

    series -- sequence of strings
    time_format -- str (default '%H:%M:%S')
    criteria -- int (default 3600)
    '''
    # make datetime objects
    t = [datetime.datetime.strptime(thing, time_format) for thing in series]
    # find the deltas
    t2 = (two - one for one, two in it.izip(t, t[1:]))
    # apply the criteria
    return all(item.seconds <= criteria for item in t2)

# extract the time series data
one, two, values = zip(*data)
if continuous(one):
    # make tuples - (t1, (t2, att))
    time_series_data = [(t1, (t2, att)) for t1, t2, att in it.izip(one, two, values)]
elif continuous(two):
    # make tuples - (t2, (t1, att))
    time_series_data = [(t2, (t1, att)) for t1, t2, att in it.izip(one, two, values)]
else:
    raise ValueError('No Continuous Data')

rawDescription: time series with alternative ways of index

description: Time series with alternative ways of index


code:
class le:
    def __init__(self, n):
        self.sn = (n, 0.6),
        #                 ^ make self.sn a tuple of tuples in all cases

class lf:
    def __init__(self, n, m, o):
        self.sn = (n, 0.7), (m, 0.8), (o, 0.9)

l1 = le("Ka")
l2 = le("La")
l3 = lf("Ma","Na","Oa")
theList = [l1, l2, l3]
result = dict([tup for thing in theList for tup in thing.sn])
# result == {'Na': 0.8, 'Ka': 0.6, 'Ma': 0.7, 'Oa': 0.9, 'La': 0.6}

rawDescription: Python convert a list of nested tuples into a dict


code:
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles
set1 = set(['A', 'B', 'C', 'D'])
set2 = set(['B', 'C', 'D', 'E'])
set3 = set(['C', 'D',' E', 'F', 'G'])

out = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))
for text in out.set_labels:
    text.set_fontsize(14)
for text in out.subset_labels:
    text.set_fontsize(16)

rawDescription: How to modify the font size in matplotlib-venn

description: Modify the font size in matplotlib-venn


rawDescription: How to remove the first and last item in a list?

description: Remove the first and last item in a list


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

driver = webdriver.Firefox()
driver.get("http://agmarknet.nic.in/")
time.sleep(4)

driver.switch_to_frame('main')
textinput = driver.find_element_by_name('cmm')
textinput.send_keys("banana")
time.sleep(1)

button = driver.find_element_by_name("Go3")
button.click()
driver.close()

rawDescription: Scrapy and submitting a javascript form

description: Scrapy and submitting a javascript form


code:
pixels, = np.where(bitflags & FLAG)
for i, pixel in zip(pixels, array[pixels]):
    do_something(i, pixel)

rawDescription: Efficient bit-testing conditional iteration over distinct array-elements


code:
raid_teams = Team.objects.filter(
    Q(tanks__id=profile.pk) |
    Q(healers__id=profile.pk) |
    Q(dps__id=profile.pk)
)

rawDescription: how to iterate over a m2m field with __contains

description: Iterate over a m2m field with __contains


code:
import csv
columns = []                        #save the columns in this list
with open('myfile.csv','r') as f:
 reader = csv.reader(f, delimiter='\t')
 ind = next(reader).index('Default')   #find the index of 'Default' in the header
 for row in reader:
     columns.append(row[ind])

rawDescription: Search a csv for a string and save that column


code:
def isBetween(a, b, c):
    crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
    if abs(crossproduct) > epsilon : return False   # (or != 0 if using integers)

    dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
    if dotproduct < 0 : return False

    squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
    if dotproduct > squaredlengthba: return False

    return True

rawDescription: How can you determine a point is between two other points on a line segment?

description: Determine a point is between two other points on a line segment


code: p.setopt(pycurl.WRITEFUNCTION, lambda x: None)

rawDescription: Pycurl keeps printing in terminal

description: Pycurl keeps printing in terminal


code: num = int(input("Enter a number between the two."))

rawDescription: Removing items in a set

description: Removing items in a set


code:
def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print (print_first_word(words))
    print (print_last_word(words))

def print_first_and_last_sorted(sentence):
    """Sorts the words and then prints the first and last one."""
    words = sort_sentence(sentence)
    print (print_first_word(words))
    print (print_last_word(words))

sentense = "All good things come to those who wait"
print_first_and_last(sentense)
print_first_and_last_sorted(sentense)

rawDescription: LPTHW - Ex:25 - values are not returned from a couple of function calls - why?


code:
import os

if os.name == 'nt':
    # We redefine timeout_decorator on windows
    class timeout_decorator:
        @staticmethod
        def timeout(*args, **kwargs):
            return lambda f: f # return a no-op decorator
else:
    import timeout_decorator

class BaseSeleniumTestCase(unittest.TestCase):
    ... # Keep your class intact

rawDescription: timeout_decorator - is it possible to disable or make it work on Windows?

description: Timeout_decorator - is it possible to disable or make it work on Windows


code:
high_score = 0

while True:
    try:
        score = int(raw_input('Enter score: '))
    except ValueError:
        continue

    high_score = max(high_score, score)

    print('Your score: {}'.format(score))
    print('High score: {}'.format(high_score))

rawDescription: Python accumlate

description: Python accumlate


code:
import numpy as np
from commpy.modulation import QAMModem
from commpy.filters import rrcosfilter
N = 1024  # output size
mod1 = QAMModem(16)  # QAM16
sB = randint(0, 2, mod1.num_bits_symbol*N*M/4)  # Random bit stream
sQ = mod1.modulate(sB)  # Modulated baud points
sPSF = rrcosfilter(N*4, 0.8, 1, 24)[1]
qW = np.convolve(sPSF, sQ) # Waveform with PSF

rawDescription: Easy way to implement a Root Raised Cosine (RRC) filter using Python & Numpy


code:
import sys
import time

for i in range(3):
    sys.stdout.write('\r' + ','.join([str(a) for a in range(i+1, 0, -1)]))
    sys.stdout.flush()
    time.sleep(1)

sys.stdout.write('\n')

rawDescription: Python: printing bottom up

description: Python: printing bottom up


rawDescription: How to dynamically access class properties in Python?

description: Dynamically access class properties in Python


code: curs.execute('''INSERT OR IGNORE INTO students (id,lastname,firstname,major,email,city,state,zip) VALUES (?,?,?,?,?,?,?,?)''', s)

rawDescription: inserting unique rows to sqlite3 with python

description: Inserting unique rows to sqlite3 with python


code:
import numpy as np
from scipy.optimize import fmin_l_bfgs_b

# do the math by hand, it's quite simple in this case
def target_fun(p, k, n):
    f = - k* np.log(p) - (n-k)*np.log(1-p)
    g =  - k/p + (n-k) / (1-p)
    return f, g

f = lambda p: target_fun(p, k=6, n=9)
epsilon = 1e-9
fmin_l_bfgs_b(f, 0.999, bounds=[(epsilon,1-epsilon)])

rawDescription: Why does scipy.optimize rely so heavily on start values?


code:
df.index.name
df.index.name = 'foo'
df.index.name
df

rawDescription: Pandas index column title or name

description: Pandas index column title or name


code:
values = [1,2,3]

# Turn list of values into list of Q objects
queries = [Q(pk=value) for value in values]

# Take one Q object from the list
query = queries.pop()

# Or the Q object with the ones remaining in the list
for item in queries:
    query |= item

# Query the model
Article.objects.filter(query)

rawDescription: How to dynamically compose an OR query filter in Django?

description: Dynamically compose an OR query filter in Django


code:
path = 'c:/DL/Others/%s%s' % (filename, file_ext)
uniq = 1
while os.path.exists(path):
  path = 'c:/DL/Others/%s_%d%s' % (filename, uniq, file_ext)
  uniq += 1

rawDescription: Avoid duplicate file names in a folder in Python


code:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

class ExampleForm(forms.Form):
    [...]
    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-exampleForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'

        self.helper.add_input(Submit('submit', 'Submit'))

rawDescription: 'FormHelper' object has no attribute 'append' while using crispy_forms in django


code: print("%.1f seconds" % (time.time() - start_time))

rawDescription: Python: Rounding output of the time module


code:
# to run: python betdaq_sample_api.py [username]

from xml.dom.minidom import Document, parseString

import http.client, urllib.parse

SOAPNamespaces=[("xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/"),
                ("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"),
                ("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")]

Namespace="http://www.GlobalBettingExchange.com/ExternalAPI/"

Endpoints={"read_only": "http://api.betdaq.com/v2.0/ReadOnlyService.asmx",
           "secure": "http://api.betdaq.com/v2.0/Secure/SecureService.asmx"}

UserAgent="python-2.5"

class ApiException(Exception):

    def __init__(self, message):
        Exception.__init__(self, message)

# xml helpers

def add_text_element(doc, parent, name, value):
    element=doc.createElement(name)
    element.appendChild(doc.createTextNode(str(value)))
    parent.appendChild(element)

class BetdaqApi:

    def create_request(self, action, username, annotator=None, password=None):
        doc=Document()
        soapenv=doc.createElement("soap:Envelope")
        for name, value in SOAPNamespaces:
            soapenv.setAttribute(name, value)
        # header
        soapheader=doc.createElement("soap:Header")
        header=doc.createElement("ExternalApiHeader")
        for name, value in [("version", "2"),
                            ("languageCode", "en"),
                            ("username", username),
                            ("xmlns", Namespace)]:
            header.setAttribute(name, value)
        if not password==None:
            header.setAttribute("password", password)
        soapheader.appendChild(header)
        soapenv.appendChild(soapheader)
        # body
        soapbody=doc.createElement("soap:Body")
        action_=doc.createElement(action)
        action_.setAttribute("xmlns", Namespace)
        request=doc.createElement("%sRequest" % (action[0].lower()+action[1:]))
        if not annotator==None:
            annotator(doc, request)
        action_.appendChild(request)
        soapbody.appendChild(action_)
        soapenv.appendChild(soapbody)
        doc.appendChild(soapenv)
        return doc

    def http_post(self, url, action, request):
        urlsegs=urllib.parse.urlparse(url)
        host, port, path = urlsegs[1], 443, urlsegs[2]
        httpp=http.client.HTTPSConnection(host, port)
        payload=request.toxml(encoding="utf-8")
        headers={"SOAPAction": "%s%s" % (Namespace, action),
                 "Content-Type": "text/xml",
                 "User-Agent": UserAgent}
        httpp.request("POST", path, payload, headers)
        resp=httpp.getresponse()
        if not resp.status==200:
            raise ApiException("Betdaq returned HTTP %i" % resp.status)
        doc=parseString(resp.read())
        result=doc.getElementsByTagName("%sResult" % action)[0]
        returnstatus=result.getElementsByTagName("ReturnStatus")[0]
        returncode=int(returnstatus.getAttribute("Code"))
        returndesc=returnstatus.getAttribute("Description")
        if not (returncode==0 and returndesc=="Success"):
            raise ApiException("Betdaq returned ReturnStatus code/description %i/'%s'" % (returncode, returndesc))
        return result

    # api methods

    def get_root_events(self, username):
        endpoint, action = Endpoints["read_only"], "ListTopLevelEvents"
        request=self.create_request(action, username)
        result=self.http_post(endpoint, action, request)
        def parse_element(el):
            name=el.getAttribute("Name")
            id=int(el.getAttribute("Id"))
            return (name, id)
        return [parse_element(el) for el in result.getElementsByTagName("EventClassifiers")]

    def get_events(self, id, username):
        endpoint, action = Endpoints["read_only"], "GetEventSubTreeNoSelections"
        def annotator(doc, request):
            request.setAttribute("WantDirectDescendentsOnly", "true")
            add_text_element(doc, request, "EventClassifierIds", id)
        request=self.create_request(action, username, annotator)
        result=self.http_post(endpoint, action, request)
        def parse_element(el):
            name=el.getAttribute("Name")
            id=int(el.getAttribute("Id"))
            return (name, id)
        events=[parse_element(el) for el in result.getElementsByTagName("EventClassifiers")]
        markets=[parse_element(el) for el in result.getElementsByTagName("Markets")]
        return (events[1:], markets) # ignore root event

# test

if __name__=="__main__":
    try:
        import sys
        if len(sys.argv) < 2:
            raise ApiException("Please enter username")
        api, username = BetdaqApi(), sys.argv[1]
        rootevents=api.get_root_events(username)
        print(rootevents)
        rootevents=dict(rootevents)
        if "Soccer" not in rootevents:
            raise ApiException("Couldn't find Soccer id")
        events, markets = api.get_events(rootevents["Soccer"], username)
        print((events, markets))
    except ApiException as error:
        print(str(error))

rawDescription: API code for betdaq for Python 3.3

description: API code for betdaq for Python 3.3


code:
df = pd.DataFrame({'a':pd.date_range('2014-1-1', periods=300)})
df.to_hdf('store.h5', 'df', format='table', data_columns=True)
pd.read_hdf('store.h5', 'df', where='a > 20141015')
pd.read_hdf('store.h5', 'df', where='a > Timestamp("10/15/2014")')

rawDescription: In pandas, how to use "where" argument to query on a datetime indexed column?


code:
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
  z, addr = sock.recvfrom(1024) #buffer size is 1024 bytes
  decode = base64.b64decode(z)
  print("Received message:", z, decode)
  if not z:break

rawDescription: Base64 decoding python help in socket programming


code:
def subfind(needle, haystack):
    """Returns index if found, None otherwise."""
    length = len(needle)
    index = 0
    for item in haystack:
        if isinstance(item, list):
            for ee in xrange(0, len(item) - length + 1):
                if item[ee:ee+length] == needle:
                   return index
            index += 1

rawDescription: Finding where a pair of numbers are located in a list of lists in Python?


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

rawDescription: Access to the cookies of the default browser


code:
fns = []
for p in dir(hi):
    a = getattr(hi, p)
    if hasattr(a, '__code__'):
        fns.append((a.__code__.co_firstlineno, p))

print([x[1] for x in sorted(fns)])  # ['__init__', 'question', 'answer']

rawDescription: List methods of a class but not sorted alphabetically


code:
from flask.wrappers import Request
Request
help(Request)

rawDescription: Need explanation on flask.request

description: Need explanation on flask.request


code:
# Game button click event
def game_button_click(self, index):
    lock = Lock()
    with lock:
        self.show_image(index)

    t = Thread(target=self.check_for_match, args=(index,))
    t.start()

# function to check for matches
def check_for_match(self, index):
    self.clicks += 1
    if self.clicks % 2 == 0 and self.uncovered % 2 == 0:
        self.moves += 1
        moves = self.MOVE_TEXT if self.moves == 1 else self.MOVES_TEXT
        self.lbl_moves.config(text=str(self.moves) + moves)
        if self.scrambled_names[self.prev_index] == self.scrambled_names[index]:
            self.uncovered += 2
        else:
            self.do_pause()
            self.buttons[self.prev_index].config(image=self.default_img,
                command=lambda myIndex=self.prev_index: self.game_button_click(myIndex))
            self.buttons[index].config(image=self.default_img,
                command=lambda myIndex=index: self.game_button_click(myIndex))
    self.prev_index = index

rawDescription: python thread.join() hangs

description: Python thread.join() hangs


code: first_char_list = [x[0] for x in com_list if len(x)]

rawDescription: Create a list of first letters from a list of words


code:
from pptx.util import Inches
from pptx import Presentation

def open_PowerPoint_Presentation(oldFileName, newFileName, img, left, top):
    prs = Presentation(oldFileName)
    slide = prs.slides[3]
    pic = slide.shapes.add_picture(img, left, top)
    prs.save(newFileName)

open_PowerPoint_Presentation('Template.pptx', 'NewTemplate.pptx',
                             'mypic.png', Inches(1), Inches(1))

rawDescription: Python Insert Image into the middle of an existing PowerPoint


code:
a = models.ManyToManyField('A')
# ...
b = models.ManyToManyField('B')

rawDescription: Forward class declaration in Python

description: Forward class declaration in Python


code:
from distutils.core import setup

setup(name='Distutils',
      version='1.0',
      description='Python Distribution Utilities',
      author='Greg Ward',
      author_email='gward@python.net',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['distutils', 'distutils.command'],
     )

rawDescription: How to add my module to travis-ci pythonpath

description: Add my module to travis-ci pythonpath


code:
from numpy import exp
from scipy.integrate import quad

def f(x):
    return exp(x)

result, error = quad(f, 0, 2)

rawDescription: Python odeint usage

description: Python odeint usage


code:
path =r'C:\DRO\DCL_rawdata_files' # use your path
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
    df = pd.read_csv(file_,index_col=None, header=0)
    list_.append(df)
frame = pd.concat(list_)

rawDescription: Import multiple csv files into pandas and concatenate into one DataFrame


code:
start = datetime.date.today()
end = start + datetime.timedelta(days=1)
Model.objects.filter(datetime__range=(start, end))

rawDescription: how to compare only date from a model's datetimefield with current date?

description: Compare only date from a model's datetimefield with current date


code:
def DelUser():

    # read the current files, and get one line per user/password
    with open('LogIn.txt',"r+") as fd:
        lines = fd.readlines()

    # ask the user which one he want to delete
    delete = raw_input("Input username to delete: ")

    # filter the lines without the line starting by the "user:"
    lines = [x for x in lines if not x.startswith('%s:' % delete)]

    # write the final file
    with open('LogIn.txt', 'w') as fd:
        fd.writelines(lines)

rawDescription: Deleting usernames and not via password in a text file


code:
A = np.empty(2, dtype=object)
A[0] = array([0, 0, 0])
A[1] = array([1, 2, 3])
A
np.vstack(A)

rawDescription: Unnesting Numpy Arrays

description: Unnesting Numpy Arrays


code:
from django.db.models import Q
Objects.objects.filter(Q(name=search_field_value) | Q(term=search_field_value))

rawDescription: Build search with filter to search over at least two fields


rawDescription: How to do a data frame join with pandas?

description: Do a data frame join with pandas


rawDescription: Can someone explain this statement? lpadded = win // 2 * [-1] + l + win // 2 * [-1]


code:
d = {x.firstname: x for x in mylist}
mylist = list(d.values())

rawDescription: Removing duplicates using custom comparisons


code: dict(set.intersection(*(set(d.iteritems()) for d in dicts)))

rawDescription: python: find only common key-value pairs of several dicts: dict intersection

description: Python: find only common key-value pairs of several dicts: dict intersection


code:
for x in list:
    if x not in board.values():
        computermove = x
        break

rawDescription: how to traverse through a for loop

description: Traverse through a for loop


code:
def tokenize(source):
    search = re.compile(r'^(.+?)(?:;(.+?))*?(?:#.+)?$', re.MULTILINE)
    return (token.strip() for line in source.split('\n') if search.match(line)
                  for token in line.split('#', 1)[0].split(';') if token)

for token in tokenize('''\
a = 1 + 2; b = a - 3 # create zero in b
c = b * 4; d = 5 / c # trigger div error

e = (6 + 7) * 8
# try a boolean operation
f = 0 and 1 or 2
a; b; c; e; f'''):
    print(repr(token))

rawDescription: How to rewrite a simple tokenizer to use regular expressions?

description: Rewrite a simple tokenizer to use regular expressions


code:
def save(self, *args, **kwargs):
    if not self.uid:
        self.uid = str(shortuuid.uuid(name=self.user))
    return super(website, self).save(*args, **kwargs)

rawDescription: Automate some entries in Django models passing the entry value from same model


rawDescription: converting string to dictionary using json.loads

description: Converting string to dictionary using json.loads


code:
add_next = False # Do not add lines
# Until you encounter the first "start_here", which sets it to True
with open("file1.html", "r") as in_file:
    with open("file2.html", "w") as out_file:
        for line in in_file:
            if "end_here" in line: # or line.startswith("end_here") for example
                add_next = False
            if add_next:
                out_file.write(line)
            if "begin_here" in line:
                add_next = True

rawDescription: keep contents between one pattern to another pattern

description: Keep contents between one pattern to another pattern


code:
plt.table(cellText=table_vals,
                  colWidths = [0.1]*3,
                  rowLabels=row_labels,
                  colLabels=col_labels,
                  loc='center left',
                  bbox=[0.25, -0.5, 0.5, 0.3])

rawDescription: Matplotlib table falls outside plot area


code:
import subprocess
args = ['/usr/local/bin/casperjs', '--ignore-ssl-errors=true', '/path/to/script.js']
subprocess.call(args)

rawDescription: Running phantomjs/casperjs native option in script that is launched with Python


code:
import sys
sys.path.append("/path/to/eclipse indigo/plugins/org.python.pydev_2.7.0.2013032300/pysrc/")
import pydevd

def application(env, start_response):
    #break here
    pydevd.settrace()

rawDescription: Debug uWsgi application in eclipse

description: Debug uWsgi application in eclipse


code:
from math import sin, cos, pi

class Ellipse(object):
    @classmethod
    def fromBox(cls, p1=(-1.,-1.), p2=(1.,1.), period=1., offs=0., clockwise=False):
        """
        Construct an Ellipse from an axis-aligned bounding box
        p1, p2      diagonally-opposed corners of the bounding box
        period      time for a complete orbit
        offs        offset into initial rotation
        clockwise   direction of rotation
        """
        x1,y1 = p1
        x2,y2 = p2
        # find center point
        cx, cy = (x1 + x2)*0.5, (y1 + y2)*0.5
        # find major and minor semi-axes and corresponding theta
        a,b = abs(x2 - x1)*0.5, abs(y2 - y1)*0.5
        if a >= b:
            theta = 0.0
        else:
            a,b = b,a
            theta = pi/2
        # return an Ellipse object
        return cls(cx, cy, a, b, theta, period, offs, clockwise)

    def __init__(self, x=0., y=0., a=1., b=1., theta=0., period=1., offs=0., clockwise=False):
        """
        Create  an ellipse
        x,y         center point
        a           semi-major axis
        b           semi-minor axis
        theta       major axis inclination (in radians)
        period      time for a complete orbit
        offs        offset into initial rotation
        clockwise   direction of rotation
        """
        self.x = x
        self.y = y
        self.period = -period if clockwise else period
        self._freq = self.period / (2. * pi)
        self.offs = offs

        s_th = sin(theta)
        c_th = cos(theta)
        self._ast = a * s_th
        self._act = a * c_th
        self._bst = b * s_th
        self._bct = b * c_th

    def at(self, t):
        """
        Evaluate the ellipse at time t
        """
        _t = (t - self.offs) * self._freq
        st = sin(_t)
        ct = cos(_t)
        return self.x + self._act*ct - self._bst*st, self.y + self._act*st + self._bst*ct

def main():
    a = Ellipse.fromBox((-0.67436675, -0.376502), (1.32563325, 0.623498))
    b = Ellipse(0.32563325, 0.123498, 0.9, 0.6, pi/6)
    c = Ellipse(0.32563325, 0.123498, 1.1, 0.5, pi/4)
    d = Ellipse(0.32563325, 0.123498, 1.0, 0.5, pi/2)

    t_step = 0.03
    for t in xrange(200):
        drawCircle(a.at(t*t_step), "red")
        drawCircle(b.at(t*t_step), "blue")
        drawCircle(c.at(t*t_step), "green")
        drawCircle(d.at(t*t_step), "yellow")

if __name__=="__main__":
    main()

rawDescription: Orbiting four objects around centroid in an elliptic shape, Python


code:
import itertools
import collections
foo = [[('a',),('a','b'),('a','b','c'),('b','c'),('c',)],[('a',),('a','b')]]
for x, cnt in collections.Counter(itertools.chain.from_iterable(foo)).most_common():
    print(x, cnt)

rawDescription: Get counts of exact matches for tuple in a nested list of tuples


code:
import gtk
import webkit
win = gtk.Window()
win.set_default_size(600, 400)
web = webkit.WebView()
web.open('https://google-developers.appspot.com/maps/documentation/javascript/examples/map-simple')
map=gtk.Frame('Maps')
scroll = gtk.ScrolledWindow()
scroll.add(web)
map.add(scroll)
win.add(map)
win.show_all()
gtk.main()

rawDescription: best way to visualize google map in python

description: Visualize google map in python


code:
ms = (time.time() - start)*1000
bid_response = realtime_bidding_pb2.BidResponse()
bid_response.processing_time_ms = int(ms)
ad = bid_response.ad.add()
ad.html_snippet = """<img src='http://cdn.test.com/test.gif' />"""
ad.click_through_url = """test.com"""

adslot = ad.adslot.add()
adslot.id = adslots_id[0]
adslot.max_cpm_micros=150000000

rawDescription: Python, protocol buffers, and getting nested messages and repeated fields to work


code:
class Image(ctypes.Structure):
  _fields_ = (
      ('image_info', ImageInfo),
      ('type', ctypes.c_int),
      ('format', ctypes.POINTER(Format) ),
  )
  @classmethod
  def open(cls,filename):
    img = my_image_open( filename )
    if img: return img[0]
    return None

rawDescription: Turning ctypes.POINTER(instance) into an actual instance?


code:
import pygame, sys, random
from pygame.locals import *

arr=[]
RED=(255,10,10)
BLU=(10,255,10)
GRN=(10,10,255)
arr.append(RED)
arr.append(BLU)
arr.append(GRN)
SCREEN_X=100
SCREEN_Y=100

screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y))
square=pygame.Surface((1, 1))

for j in range (SCREEN_Y):
    for i in range (SCREEN_X):
        num=random.randint(0,2)
        square.fill(arr[num])
        draw_me=pygame.Rect((j+1), (i+1), 1, 1)
        screen.blit(square,draw_me)
pygame.display.flip()

rawDescription: How can i put a whole array of pixels on screen with pygame?

description: Put a whole array of pixels on screen with pygame


code:
import RPi.GPIO as GPIO
import signal
import subprocess
import os
from time import sleep

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)

rec_proc = None
try:
    while True:
        if GPIO.input(4):
            GPIO.output(25, 1)
            if rec_proc is None:
                rec_proc = subprocess.Popen("/script/start.sh",
                           shell=True, preexec_fn=os.setsid)
        else:
            GPIO.output(25, 0)
            if rec_proc is not None:
                os.killpg(rec_proc.pid, signal.SIGTERM)
                rec_proc = None
        sleep(0.2)

finally:
    GPIO.cleanup()

rawDescription: Start and stop application within python using the RPi GPIO?


code:
import statsmodels.formula.api as sm
import pandas as pd
import numpy as np
import patsy
url = "http://vincentarelbundock.github.com/Rdatasets/csv/HistData/Guerry.csv"
df = pd.read_csv(url)
w = np.ones(df.shape[0])
f = 'Lottery ~ Wealth : C(Region)'
y,X = patsy.dmatrices(f, df, return_type='dataframe')
X.head()
X = X.ix[:,[2,3,4]]
X.head()
mod = sm.WLS(y, X, 1./w).fit()
mod.params

rawDescription: Statsmodels formula API (patsy): How to exclude a subset of interaction components?


code:
for k in dic.keys():
  if k.startswith('s_'):
    dic.pop(k)

rawDescription: Python dictionary: Remove all the keys that begins with s


code:
# Setup problem
import pandas as pd
import numpy as np

num_samples = 100
s = pd.Series(np.random.randint(0, 500, num_samples), index=pd.date_range('03/06/2015', periods=num_samples, freq='10min'))
mask = np.random.rand(num_samples) < .7
s[mask] = np.nan

# Loop through index
# Note the perc_nan variable can be changed depending on what percentage of the interval must be nan for the mean value to also be nan
perc_nan = 0.5
data, indices = [], []
for dt in s.index:
    if dt.minute == 0:
        d = s[('00:00:00' <= dt - s.index) & (dt - s.index < '01:00:00')]
        data.append(d.mean() if d.isnull().sum() <= len(d)*perc_nan else np.nan)
        indices.append(dt)

# Solution
pd.Series(data, index=indices)

rawDescription: Python pandas - averaging 10 min measurements to 15min mean and 60min mean depending on the length of the data gap


code:
Task1: parameter1=140
Task2: parameter1=142
Task3: parameter1=144
Task4: parameter1=146
Task5: parameter1=148

rawDescription: Logic for grouping similar parameters

description: Logic for grouping similar parameters


code:
while 1:
    messages = q.get_messages()
    # do something with messages
    time.sleep(N)

rawDescription: Processing SQS queues with boto

description: Processing SQS queues with boto


code:
transactions = ['BUY', 'SELL']
companies = ['Acer', 'Cemex']
values = [[0.5344, 2.23423], [5.43534, 4.3342543]]
for trans, company, (val1, val2) in zip(transactions, companies, values):
    if trans == 'BUY':
        print("Bought {}: {}, {}".format(company, val1, val2))
    elif trans == 'SELL':
        print("Sold {}: {}, {}".format(company, val1, val2))

rawDescription: Loops with multiple conditions in python


code:
label = soup.find("input", {"aria-label": "Select Report format XLS"})
link = label.find_next_sibling("a", href=True)["href"]

rawDescription: Parsing table for a link

description: Parsing table for a link


code:
def replaceVars(matchObj):
    return "{{{%s}}}" % matchObj.groups()[0]

c = r"\$(\w+)\s*"

s = "$who likes $what"

converted = re.sub(c, replaceVars, s)

rawDescription: extract variables from python string template

description: Extract variables from python string template


code:
def ig_f(dir, files):
    return [f for f in files if os.path.isfile(os.path.join(dir, f))]

shutil.copytree(SRC, DES, ignore=ig_f)

rawDescription: shutil.copytree without files

description: Shutil.copytree without files


code:
repo = MagicMock()
repo.heads.__getitem__.side_effect = IndexError
with self.assertRaises(IndexError):
    _ = repo.heads['nonexistant']

rawDescription: What is the proper way to mock a subscriptable property that raises an exception when accessed in Python 2.7?


rawDescription: check if numpy array is multidimensional or not

description: Check if numpy array is multidimensional or not


code:
import urllib.request
import urllib.error

first = int(input('First:'))
last = int(input('Last:'))

while first <= last:
    response = urllib.request.urlopen("http://www.netapp.com/us/media/tr-" + str(first) +".pdf")
    file = open(str(first) + ".pdf", 'wb')
    file.write(response.read())
    file.close()
    response.close()
    first = first + 1
print("Completed")

rawDescription: Download pdf loop

description: Download pdf loop


code:
class MyModelForm(forms.ModelForm):
    class Meta:
         model = MyModel
         widgets = {
             'field1': Textarea(attrs={'rows':1, 'cols':40}),
         }

...
class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

rawDescription: Is it possible to override a single textfield in Django admin?


code:
def __init__(self, coro, *, loop=None):
    assert iscoroutine(coro), repr(coro)  # Not a coroutine function!
    super().__init__(loop=loop)
    self._coro = iter(coro)  # Use the iterator just in case.
    self._fut_waiter = None
    self._must_cancel = False
    self._loop.call_soon(self._step)  # This schedules the coroutine to be run
    self.__class__._all_tasks.add(self)

rawDescription: Python 3 asyncio - yield from vs asyncio.async stack usage


code: foo_list = [ (ele - k) / j for ele in foo_list]

rawDescription: subtracting and dividing all the elements of the list in python

description: Subtracting and dividing all the elements of the list in python


code:
from itertools import combinations

l = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'e', 'f'), ('h', 'b', 'c')]
print([(a[0], b[0]) for a, b in combinations(l, 2) if a[1:] == b[1:]])

rawDescription: How to create a new list of tuples based on a values from original list of tuples?

description: Create a new list of tuples based on a values from original list of tuples


code:
class MyDict(dict):
    def __repr__(self):
        s = "{"
        for key in self:
            s += "{0}:{1}, ".format(key, self[key])
        if len(s) > 1:
            s = s[0: -2]
        s += "}"
        return s

MyDict({'a': 1, 'b': 2})
{a:1, b:2}

rawDescription: Removing quotes from keys of dicts when rendering to template


code:
#!/usr/bin/env python3
import multiprocessing as muproc

def ParallelCheck(me):
    print(" Testing {}...".format(me))
    global abort
    abort.clear()
    ParChild = ParallelChild(me)
    jobs = []
    N = 4
    for i in range(N):
        jobs.append(muproc.Process(target = ParChild.run, args=(range(i * 2500, (i+1) * 2500),)))
    for p in jobs:
        p.start()
    for p in jobs:
        p.join()
    if abort.is_set():
        print("MATCH FOUND")
        return 1
    else:
        print(" no match...")
        return 0

def Computation(me, neighbour):
    return me == neighbour

class ParallelChild(object):
    def __init__(self, me):
        self.me = me

    def run(self, neighbours):
        global abort
        for neighbour in neighbours:
            print("{} vs {} by {}".format(self.me, neighbour, self.CurProc()))
            if abort.is_set():
                print("Aborting {}".format(self.CurProc()))
                return 0
            else:
                if Computation(self.me, neighbour):
                    abort.set()
                    print("GOTCHA {}".format(self.CurProc()))
                    return 1

    def CurProc(self):
        return muproc.current_process()._identity[0]

if __name__ == "__main__":
    abort = muproc.Event()
    values = [12000, 130, 7]
    for v in values:
        print("value={} match={}".format(v, ParallelCheck(v)))

rawDescription: python multiprocessing pool abort if value

description: Python multiprocessing pool abort if value


code: newtype = np.result_type(x, y, np.byte)

rawDescription: How to subtract two unsigned numpy arrays to give a signed result?

description: Subtract two unsigned numpy arrays to give a signed result


code:
from suds.transport import Request

transport = client.options.transport
request = Request('http://www.example.org/document.html')
document = transport.open(request).read()

rawDescription: How do I make a normal HTTP request with a suds transport?

description: Make a normal HTTP request with a suds transport


code:
from apps.ingest.platform_export import BaseExporter

class Vudu(BaseExporter):

    def __init__(self):
        BaseExporter.__init__(self)
        self.platform = ' Vudu'

rawDescription: How to extend init method with inheritance

description: Extend init method with inheritance


code:
class index:
    form = web.form.Form(form.Dropdown(name='option',args=[]))

    def GET(self):
            dbresult = db.select('test')
            options = db.select('test',what='name',group='name')
            form = self.form()
            form.option.args = [(o.name, o.name) for o in options]
            return render.index(dbresult,form)

rawDescription: Web Py | How to set form.Dropdown args using db.select query


code:
d = {'abc':'abc','def':{'ghi':'ghi','jkl':'jkl'}}
for ele in d.values():
    if isinstance(ele,dict):
       for k, v in ele.items():
           print(k,' ',v)

rawDescription: How to check if a variable is a dictionary in python

description: Check if a variable is a dictionary in python


code:
class Test:
    items = []
    @classmethod
    def method_test(cls):
        cls.items.append('test')

class Best(Test):
    items = []
    @classmethod
    def method_best(cls):
        cls.items.append('best')

Test.method_test()

assert Test.items == ['test']
assert Best.items == []

Test.items = []
Best.method_test()
Best.method_best()

assert Test.items == []
assert Best.items == ['test', 'best']

rawDescription: Python class inheritance - Base is modified by a subclass


code:
class foo(object):
    ...

rawDescription: Python - do I need to learn about old style classes?


code:
root = etree.Element('{http://www.example.org/eHorizon}sample1',nsmap={'p1':'http://www.example.org/eHorizon'})
for elem in new_list:
    root.append(elem)

etree.ElementTree(root).write("c.xml") # write data to another file and check results

rawDescription: writing edited xml content to another file issue - python

description: Writing edited xml content to another file issue - python


rawDescription: modifying values in numpy array

description: Modifying values in numpy array


code:
import Tkinter as tk
import ttk
import platform
import time

class Window(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.init_progbar()
        self.prog_data()
        self.top.destroy()

    #initializing progress bar, may be used with self.top.
    def init_progbar(self):
        #The frame here was unnecessary.
        self.top = tk.Toplevel(self)
        self.top.progbar = ttk.Progressbar(self.top, \
            orient='horizontal', mode = 'determinate', length = '500')
        self.top.progbar.grid()
        Window.center(self.top)

    #static method to center a toplevel window
    @staticmethod
    def center(toplevel, size=None):
        toplevel.update_idletasks()
        w = toplevel.winfo_screenwidth()
        h = toplevel.winfo_screenheight()
        if not size:
            size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
        x = w/2 - size[0]/2
        y = h/2 - size[1]/2
        toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))
        #This processes every pending geometry change and redraws the widget.
        self.update()

    #dummy method - somethings done, then the value of the progress bar
    #is raised by 10
    def prog_data(self):
        for i in range(10):
            time.sleep(1)
            self.top.frame.progbar.step(10)
            #Updates the whole GUI every time some data gets processed.
            self.update()

def main():
    window = Window()
    window.mainloop()

if __name__=='__main__':
    main()

rawDescription: Tkinter progressbar not working under Windows


code:
url = 'https://www.googleapis.com/appsmarket/v2/upgradableApp/oldlisting/newlisting/mybeacon.biz'

consumer_key = 'key'
consumer_secret = 'secret'

consumer = oauth.Consumer(consumer_key, consumer_secret)

client = oauth.Client(consumer)

# Step 1: Get a request token. This is a temporary token that is used for
# having the user authorize an access token and to sign the request to obtain
# said access token.

resp, content = client.request(url, "PUT")

rawDescription: Calling Google Apps Marketplace UpgradeableApp API with Python Appengine App


code:
with open("filename", "a") as f:
     f.write("Next line\n")

rawDescription: How would I tell Python to write to a new line if the previous line is occupied with other text?


code: print("Your total is: ${:,.2f}".format(dollars_total))

rawDescription: Hey need assistance on defining dollar and then being allowed to make that a float in python


code:
def match_text(raw_data_file, concentration):
    look_for = ' WITH A CONCENTRATION IN ' + concentration
    with open(raw_data_file) as fin, open('lines.txt', 'w') as fout:
        fout.writelines(line for line in fin if look_for in line)

rawDescription: How to find a specific line of text in a text file with python?

description: Find a specific line of text in a text file with python


code: plt.hist(l, bins=range(1,7), align='left', rwidth=1, normed=True)

rawDescription: Hist in matplotlib: Bins are not centered and proportions not correct on the axis


code:
sql_fmt = 'INSERT INTO %s (consensus, identityb32, pubdate, dirport, ip, orport, identityhash, nick, version, flags, identity, digest, pubtime) VALUES (' + ', '.join(['%s']*14) + ')'

...

cursor.execute(sql_fmt, (onion_Add, consensus.consensus_name,
                         identityb32[c], pubdate[c], dirport[c],
                         ip[c], orport[c], identityhash[c], nick[c],
                         version[c], ','.join(flags), identity[c],
                         digest[c], pubtime[c])
              )

rawDescription: Adding a list into a single MySQL table field


code: TIME_ZONE =  'Asia/Kolkata'

rawDescription: How to add Indian Standard Time (IST) in Django?

description: Add Indian Standard Time (IST) in Django


code:
rlabsC = ['100','110','101','111']
xs = [1,2,3,4]
ys = [0,.5,.25,.25]

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.bar(xs,ys)
ax.set_xticks([a+.5 for a in xs])

plt.tick_params('x', labelbottom='off')

text_kwargs = dict(rotation='vertical', fontsize=16, va='top', ha='center')
offset = -0.02

for x, label in zip(ax.xaxis.get_ticklocs(), rlabsC):
    first, rest = label[0], label[1:]

    # plot the second and third numbers
    text = ax.text(x, offset, rest, **text_kwargs)

    # determine how far below the axis to place the first number
    text.draw(ax.figure.canvas.get_renderer())
    ex = text.get_window_extent()
    tr = transforms.offset_copy(text._transform, y=-ex.height, units='dots')

    # plot the first number
    ax.text(x, offset, first, transform=tr, color='red', **text_kwargs)

rawDescription: Changing color of single characters in matplotlib plot labels


code: s = ','.join([ r[0] for r in cur.fetchall() ])

rawDescription: Build comma-separated list of rows from SQL results


code:
def process(total):
    total.sort()
    return total[1:-1] #take all numbers except the first and the last

rawDescription: how do I display the elements in the slice all on one line separated by a single space and sorted in highest to lowest order

description: Display the elements in the slice all on one line separated by a single space and sorted in highest to lowest order


code:
from numpy import int32
skimage.color.rgb2xyz((rgb / 255 * (2**31 - 1)).astype(int32))
skimage.color.rgb2xyz(rgb.astype(uint8))
skimage.color.rgb2xyz(rgb.astype(float) / 255)

rawDescription: RGB to XYZ in Scikit-Image

description: RGB to XYZ in Scikit-Image


code:
input("something:")
print( '\x1b[1A\x1b[2K\x1b[1A')
input("something else:")

rawDescription: Python program to take user input and refresh console without "scrolling"


code:
for cat in cats:
    if cat and cat[0] in row[5]:
        row[2] = cat[1]
        row[3] = cat[2]

rawDescription: Iterating through csv file in python to change values if string matches items in nested list


code:
from tasks import add
add.delay(2, 2)
from celery import current_app
conn = current_app.broker_connection()
consumer = current_app.amqp.get_task_consumer(conn)
messages = []
def callback(body, message):
    messages.append(message)
consumer.register_callback(callback)
consumer.consume()
conn.drain_events(timeout=1)
messages[0].properties
messages[0].properties

rawDescription: Why is RabbitMQ not persisting messages on a durable queue?


code:
class Class1Test(TestCase):

    @mock.patch('mymodule.external_function')
    def test_method1(self, mock_external_function):
        pass

rawDescription: How can I mock an external function within a method in a class

description: Mock an external function within a method in a class


code:
import re
regex = re.compile(r"(?<!honey(?=suckle))suck")
regex.search("honeysuckle")
regex.search("honeysucker")
regex.search("suckle")
regex.search("suck")

rawDescription: Regex match if not before and after

description: Regex match if not before and after


code:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
p_surf=ax.plot_surface(x,y,z,rstride=1,cstride=1,linewidth=0,antialiased=True,facecolors=cm.jet(np.sqrt(x*x + y*y + z*z)))
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array(x*x + y*y + z*z)
plt.colorbar(m)
plt.show()

rawDescription: Map colors in colorbar in Python

description: Map colors in colorbar in Python


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

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

mu, sigma=100, 15
x=mu + sigma*np.random.randn(1000000)
n, bins, patches=ax.hist(x, 50, facecolor='green', alpha=0.75)

ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, pos: ('%.2f')%(y*1e-3)))
ax.set_ylabel('Frequency (000s)')

plt.show()

rawDescription: Matplotlib histogram, frequency as thousands


code:
variable = ''
while True:
    variable = input("Age: ")
    if variable.isdigit():
        break
    else:
        print("That's not an age!")
variable = int(variable)

rawDescription: Easier way to find if string is a number in Python 3


code:
for i in range(0, size):
    for j in range(0, size):
        pixArray[p1+i][p2+j] = mousecolor
        pixArray[p1-i][p2+j] = mousecolor
        pixArray[p1+i][p2-j] = mousecolor
        pixArray[p1-i][p2-j] = mousecolor

rawDescription: Using Pygame's pixArray to draw a square


code:
if file_name2 is None:
    file_name2 = os.devnull

rawDescription: Passing None to open()

description: Passing None to open()


code:
import pandas as pd
df = pd.DataFrame([[1,2],[3,4]], columns=list('ab'))
df
df['c'] = df['b']**2
df

rawDescription: Square of each element of a column in pandas


code:
from itertools import count
lis = [ [(6, 8, 9), 111], [(15, ), 22], [(11, 20), 80] ]
c = count(0)
[tuple(next(c) for _ in x[0]) for x in lis]

rawDescription: extract tuple and overwrite with int iteration

description: Extract tuple and overwrite with int iteration


code:
radii = np.linspace(0.5,1,10)
thetas = np.linspace(0,2*np.pi,20)
theta, r = np.meshgrid(thetas, radii)

dr = 1
dt = 1

f = plt.figure()
ax = f.add_subplot(111, polar=True)
ax.quiver(theta, r, dr * cos(theta) - dt * sin (theta), dr * sin(theta) + dt * cos(theta))

rawDescription: How to make a quiver plot in polar coordinates

description: Make a quiver plot in polar coordinates


code:
import random
zagadka = [1,2,3]
random.shuffle(zagadka)
print ("Please enter number between 1 and 3")

zagadkaa = zagadka.pop()
vvod = int(raw_input("Enter number here"))   # make sure we have a number, not a string, and don't eval it.
if vvod == zagadkaa:
    print ("ok")
else:
    print ("wrong %d"%zagadkaa)
print ("Goodbye")

rawDescription: Why doesn't input integer match integer literal in code?


code:
v = float(input('start vlocity m/s: '))
a = float(input('start angle : '))
p = v*math.sin(math.radians(a))
g = 9.81
equ = p*p/(2*g)
print(str(equ) + ' M')

rawDescription: Python How To Square Sin For The Height Equation


code:
def paginated_class_method(default_page_size=25):
    def wrap(func):
        @functools.wraps(func)
        def inner(self_or_cls, page=1, page_size=default_page_size, *args, **kwargs):
            objects = func(self_or_cls, *args, **kwargs)
            return _paginate(objects, page, page_size)
        return inner
    return wrap

rawDescription: Python -- Decorator that works on both classmethods and instance methods


code: [sum([x.count(1) for x in L[:i]]) for i in range(1, len(L) + 1)]

rawDescription: Count elements in nested list

description: Count elements in nested list


code:
#make sure factor is float
factor = float(factor)
#get keys as sets
c1keys, c2keys = set(c1.keys()), set(c2.keys())
#keys only in c1
c1only = c1keys.difference(c2keys)
#keys only in c2
c2only = c1keys.difference(c1keys)
#keys guaranteed in both
both = c1keys.intersection(c2keys)

#generate dicts for keys which are unique to c1 or c2
c1onlydict = dict((w,c1[w]) for w in c1only)
c2onlydict = dict((w,c2[w]*factor) for w in c2only)
#merge
loners = dict(c1onlydict, **c2onlydict)

#now create the directory with keys which exist in both
bothdict = dict((key, c1[key] + c2[key]*factor) for key in both)

#merge everything
return dict(loners, **bothdict)

rawDescription: Fastest way to accumulate weighted counts from multiple collections.Counter Objects?


code:
query = "insert into cms_object_metadata (cms_object_id, cms_object_metadata_data, cms_object_metadata_type_id, \
         cms_object_metadata_status_id) values ((select id from cms_objects where cms_object_ident = %(objIdent)s), \
         %(objMetaString)s, (select id from cms_object_metadata_types where cms_object_metadata_type_name = 'PDAT'), \
         (select id from cms_object_metadata_status where cms_object_metadata_status_name = 'active'))"

dataDict = {'objIdent':objIdent, 'objMetaString':objMetaString}

dbCursor.execute(query, dataDict)

rawDescription: Inserting large text data into postgres with python


code:
D = D.objects.all()
for element in D:
    if hasattr(element.user, "A"):
        results.append(element.user.A)
    elif hasattr(element.user, "B"):
        results.append(element.user.B)
    elif hasattr(element.user, "C"):
        results.append(element.user.C)

rawDescription: Get related model with Django query

description: Get related model with Django query


code:
_entities = []
class entity(object):
    @staticmethod
    def get_entity_registry():
         return _entities

rawDescription: python global object cache

description: Python global object cache


code:
for file in glob.glob('*.xml'):
    if file=="xyz.xml":
        continue
    data = open(file).read()
    print(file)

rawDescription: python read all files in a folder except a file named "xyz"

description: Python read all files in a folder except a file named "xyz"


code:
import pandas as pd

df = pd.DataFrame({'data':[10*i for i in range(0,10)]})

def sum_(x):
    return sum(x)

df['example'] = pd.expanding_apply(df['data'], sum_)

print(df)

#   data  example
#0     0        0
#1    10       10
#2    20       30
#3    30       60
#4    40      100
#5    50      150
#6    60      210
#7    70      280
#8    80      360
#9    90      450

rawDescription: Apply function on cumulative values of pandas series


code:
num = [1,2,3,4]
names = ['shiva','naga','sharath','krishna','pavan','adi','mulagala']
import itertools
for i, name in zip(itertools.cycle(num), names):
    print('{} for {}'.format(i, name))

rawDescription: How to work with two lists as round robin python

description: Work with two lists as round robin python


code:
import numpy as np

def transf1d(f, x, y, out):
    """Transform `f(x)` to `g(y)`.

    This function is actually a C-function that is far more complicated
    and should not be modified. It only takes 1D arrays as parameters.

    """
    out[...] = (f[None,:]*np.exp(-1j*x[None,:]*y[:,None])).sum(-1)

def transf_all(F, x, y, axis=-1, out=None):
    """General N-D transform.

    Perform `transf1d` along the given `axis`.

    Given the following:
      F.shape == (2, 3, 100, 4, 5)
      x.shape == (100,)
      y.shape == (50,)
      axis == 2

    Then the output shape would be:
      out.shape == (2, 3, 50, 4, 5)

    This function should wrap `transf1d` such that it works on arbitrarily
    shaped (compatible) arrays `F`, and `out`.

    """

    def wrapper(f):
        """
        wrap transf1d for apply_along_axis compatibility
        that is, having a signature of F.shape[axis] -> out.shape[axis]
        """
        out = np.empty_like(y)
        transf1d(f, x, y, out)
        return out
    return np.apply_along_axis(wrapper, axis, F)

rawDescription: Apply 1D function on one axis of nd-array


code: issubclass(A, B)

rawDescription: isinstance - Python Class

description: Isinstance - Python Class


code:
import glob, os, shutil
dirs = glob.glob("tmp*/")
for dir in dirs:
    shutil.rmtree(dir)

rawDescription: Remove all folders by name

description: Remove all folders by name


code:
from PyQt4 import QtDBus
from PyQt4.QtCore import (QCoreApplication, QObject, Q_CLASSINFO, pyqtSlot,
                          pyqtProperty)
from PyQt4.QtDBus import QDBusConnection, QDBusAbstractAdaptor

class MyServer(QObject):

    def __init__(self):
        QObject.__init__(self)
        self.__dbusAdaptor = ServerAdaptor(self)
        self.__name = 'myname'

    def echo(self, value):
        return'Received: {0}'.format(value)

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        self.__name = value

class ServerAdaptor(QDBusAbstractAdaptor):
    """ This provides the DBus adaptor to the outside world"""

    Q_CLASSINFO("D-Bus Interface", "com.home.dbus")
    Q_CLASSINFO("D-Bus Introspection",
    '  <interface name="com.home.dbus">\n'
    '    <property name="name" type="s" access="readwrite"/>\n'
    '    <method name="echo">\n'
    '      <arg direction="in" type="s" name="phrase"/>\n'
    '      <arg direction="out" type="s" name="echoed"/>\n'
    '    </method>\n'
    '  </interface>\n')

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

    @pyqtSlot(str, result=str)
    def echo(self, phrase):
        return self.parent().echo(phrase)

    @pyqtProperty(str)
    def name(self):
        return self.parent().name

    @name.setter
    def name(self, value):
        self.parent().name = value

def start():
    app = QCoreApplication([])
    bus = QDBusConnection.sessionBus()
    server = MyServer()
    bus.registerObject('/mydbus', server)
    bus.registerService('com.home.dbus')
    app.exec()

if __name__ == '__main__':
    start()

rawDescription: How does one expose methods and properties on DBus using a QDBusAbstractAdaptor with PyQt4?

description: Expose methods and properties on DBus using a QDBusAbstractAdaptor with PyQt4


code:
import numpy as np

def find_closest(A, target):
    order = A.argsort()
    A = A[order]

    idx = A.searchsorted(target)
    idx = np.clip(idx, 1, len(A)-1)
    left = A[idx-1]
    right = A[idx]
    idx -= target - left < right - target
    return order[idx]

array1d = np.array([7.2, 2.5, 3.9])
array2d = np.array([[7.2, 2.5],
                    [3.9, 7.2]])

indices = find_closest(array1d, array2d)
print(indices)
# [[0 1]
#  [2 0]]

rawDescription: Creating index array in numpy - eliminating double for loop


rawDescription: How do I select from multiple tables in one query with Django?

description: Select from multiple tables in one query with Django


rawDescription: python script to convert " into a html tag

description: Python script to convert " into a html tag


code:
class AllMyFields:
    def __init__(self, dictionary):
        for k, v in dictionary.items():
            setattr(self, k, v)

o = AllMyFields({'a': 1, 'b': 2})
o.a

rawDescription: Creating class instance properties from a dictionary in Python


code:
# module.py:
"""About the module.

module.data: contains the word "spam"

"""

data = "spam"

rawDescription: Docstrings for data?

description: Docstrings for data


code:
def stripInnermostHTMLtags(text):
    '''Strip all but outermost HTML start and end tags.
    '''
    # Regex to match outermost HTML element and its contents.
    p_outer = re.compile(r"""
        ^                 # Anchor to start of string.
        (.*?<html[^>]*>)  # $1: Outer HTML start tag.
        (.*)              # $2: Outer HTML element contents.
        (</html\s*>.*)    # $3: Outer HTML end tag.
        $                 # Anchor to end of string.
        """, re.DOTALL | re.VERBOSE | re.IGNORECASE)
    # Split text into outermost HTML tags and its contents.
    m = p_outer.match(text)
    if m:
        # Regex to match HTML element start or end tag.
        p_inner = re.compile("</?html[^>]*>", re.IGNORECASE)
        # Strip contents of any/all HTML start and end tags.
        contents = p_inner.sub("", m.group(2))
        # Put string back together stripped of inner HTML tags.
        text = m.group(1) + contents + m.group(3)
    return text

rawDescription: Python: Remove all occurrences in a string except first occurrence (case insensitive)


code:
node = aliased(Category)
parent = aliased(Category)
sub_parent = aliased(Category)

sub_tree = DBSession.query(node.name,
    (func.count(parent.name) - 1).label('depth')).\
    join(parent, node.lft.between(parent.lft, parent.rgt)).\
    filter(node.name == category_name).\
    group_by(node.name).\
    order_by(node.lft).subquery()

depth = (func.count(parent.name) - (sub_tree.c.depth + 1)).label('depth')
children = DBSession.query(node.name, depth).\
    join(parent, node.lft.between(parent.lft, parent.rgt)).\
    join(sub_parent, node.lft.between(sub_parent.lft, sub_parent.rgt)).\
    join(sub_tree, sub_parent.name == sub_tree.c.name).\
    group_by(node.name, sub_tree.c.depth).\
    having(depth <= 1).\
    order_by(node.lft).all()

rawDescription: Using Labels in HAVING() Clause in SQLAlchemy


rawDescription: How can I Have Cherry Py redirect a browser to a website?


code:
import shlex
import subprocess

def url_screengrab(url, **kwargs):
    cmd = '''xvfb-run --server-args "-screen 0, 1100x800x24"
             /usr/bin/cutycapt --url={u} --out=temp.png '''.format(u = url)
    proc = subprocess.Popen(shlex.split(cmd))
    proc.communicate()

url = 'http://www.google.com'
url_screengrab(url)

rawDescription: Running Xvfb and CutyCapt as Python subprocess


code:
def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))

rawDescription: How to create full compressed tar file using Python?

description: Create full compressed tar file using Python


code:
mask = np.zeros(X.shape, dtype='bool')
mask[ix] = True

rawDescription: How to invert numpy.where (np.where) function

description: Invert numpy.where (np.where) function


code:
s = b'I would like the following characters to display correctly after reading this file into Python:\r\n\r\n\xc3\x84\xc3\x96\xc3\x9c\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\r\n'
print(s)
print(s.decode("utf-8"))

rawDescription: Python 3: Read UTF-8 file containing German umlaut


code:
names = 'Benjamin Franklin, Thomas Jefferson, Carl Sagan'
names.split(',')

rawDescription: There are some method or function in Python 2.x that can form a list recognizing the comma which separate string elements?


code:
from traits.api import HasTraits, Int, Instance, on_trait_change
from traitsui.api import View, Item, Group
from mayavi.core.ui.api import SceneEditor, MlabSceneModel, MayaviScene

class Data_plot(HasTraits):
  a = my_array
  t = Int(0)
  scene = Instance(MlabSceneModel, ())
  plot = Instance(PipelineBase)

  @on_trait_change('scene.activated')
  def show_plot(self):
    self.plot = something(self.a[self.t]) #something can be surf or mesh or other

  @on_trait_change('t')
  def update_plot(self):
    self.plot.parent.parent.scalar_data = self.a[self.t] #Change the data

  view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene),
                show_label=False),
                Group('_', 't'),
                resizable=True,
                )

my_plot = Data_plot(a=my_array)
my_plot.configure_traits()

rawDescription: Time dependent data in Mayavi

description: Time dependent data in Mayavi


code:
# You might need to do this to get X as an ndarray (for example if X is a list)
X = numpy.asarray(X)

# Then you can simply do
X[s, [0, 1, 2]]

# Or more generally
X_argmax = X[s, numpy.arange(X.shape[1])]

rawDescription: Extracting numpy array slice from numpy.argmax results


code:
for i, (entry, exit, met) in enumerate(t.stats):
    t.stats[i] = (entry, exit, 1)

rawDescription: Iterating over zipped lists in python

description: Iterating over zipped lists in python


code:
def countify2(ar):
    ar2 = np.ravel(ar)
    ar3 = np.empty(ar2.shape, dtype=np.int32)
    uniques = np.unique(ar2)
    myarange = np.arange(ar2.shape[0])
    for u in uniques:
        ar3[ar2 == u] = myarange
    return ar3

rawDescription: How to get running counts for numpy array values?

description: Get running counts for numpy array values


code:
X = np.array(xvals)
Y = np.array(yvals)
Z = np.array(zvals)
Y_bot = np.array(bottomvals)

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

jet = plt.get_cmap('jet')

log_norm = colors.LogNorm()

for x,y,z,bot in zip(X,Y,Z,Y_bot):
    log_z = np.log10(z)/np.log10(max(Z))
    colour = jet(log_price)
    ax.bar(x,y,bottom=bot, width=1, edgecolor='none',color=c_col)

a = np.vstack((Z,Z))
im = plt.imshow(a, aspect='auto', cmap=jet, origin='lower', norm=log_norm)
im.set_visible(False)
plt.colorbar(format='%.1f')
plt.axis([values])
plt.show()

rawDescription: Plotting discrete, lumpy 2D matplotlib plots with logarithmic colouring


code:
from urlparse import parse_qs, urlparse

parse_qs(urlparse(url).query, keep_blank_values=True)
# {'param2': ['2'], 'param1': ['']}

rawDescription: Parse query part from url

description: Parse query part from url


code:
class ItemCapability:
    pass

class Consumable(ItemCapability):
    def __init__(self, amount):
        super().__init__()
        self.amount = amount

class Usable(ItemCapability):
    pass

class Item:
    def __init__(self, name):
        self.name = name
        self.capabilities = {}

    def make(self, capability):
        assert isinstance(capability, ItemCapability)
        assert capability.__class__ not in self.capabilities

        self.capabilities[capability.__class__] = capability

    def has(self, capability_cls):
        try:
            return self.capabilities[capability_cls]
        except KeyError:
            return False

potion = Item('potion')
potion.make(Usable())
potion.make(Consumable(amount=10))

print(potion.has(Usable))
print(potion.has(Consumable))

rawDescription: Chaining class decorators to extend game item's abilities


code:
#!/usr/bin/env python3

print("Welcome to the Global Grocery, where world leaders do their shopping!","\n")

print("To view sales information for each customer type \'customers\'.")
print("To view sales information for each product type \'products\'.")
print("To quit type \'q\'.")

while True:  # Keep going forever until a 'break' statement is met
    data = input("")
    if data == "q":
        print("Good bye!")
        break  # end the 'while' loop
    elif data == "customers":
        print("Ok, customer stuff")
    elif data == "products":
        print("Ok, product stuff")
    else:  # A non-valid option must have been selected
        print("Please choose \'customers\', \'products'', or \'q\' to quit.")

rawDescription: How to loop until one specific value or request again through an input

description: Loop until one specific value or request again through an input


code:
class HandlerBase(webapp.RequestHandler):

    def get_context(self):
        return {}

    def get(self):
        tUser = users.get_current_user()
        tContext = {
            'user':      tUser,
            'login':     users.create_login_url(self.request.uri),
            'logout':    users.create_logout_url(self.request.uri),
        }
        # tContext holds the defaults for your context

        #User is logged in
        if (tUser):
            # if the dict returned by self.get_context() contains a key
            # that's already in tContext, tContext[key] will be overridden
            # with self.get_context()[key]
            tContext.update(self.get_context())
        else:
            self.redirect("/")

        tmpl = os.path.join(os.path.dirname(__file__), 'logged-in.html')
        self.response.out.write(render(tmpl, tContext))

class MainHandler(HandlerBase):

    def get_context(self):
        # the contents of the following dict will be added to
        # the context in HandlerBase
        return {'greeting': 'Hi!'}

rawDescription: Make a Class Method "Template" in GAE Python


code:
idx = pd.MultiIndex.from_product([["A", "B"], [1, 2, 3]])
col = pd.MultiIndex.from_product([["X", "Y"], ["aa", "bb"]])
df = pd.DataFrame(np.random.randint(0, 100, size=(6, 4)), index=idx, columns=col)
df.index.names = "name1", "name2"
df.columns.names = "NAME1", "NAME2"

df.to_csv("tmp.csv")
df2 = pd.read_csv("tmp.csv", header=[0, 1], index_col=[0, 1])

rawDescription: Read and write Pandas DataFrame with multi-row and multi-column index


code:
from lxml import html

x = html.parse("http://www.racingpost.com/horses/result_home.sd?race_id=651402&r_date=2016-06-07&popup=yes#results_top_tabs=re_&results_bottom_tabs=ANALYSIS")

tbodys= x.xpath('//table[@class="grid resultRaceGrid"]/tbody')
# iterate over the list of tbody tags
for tbody in tbodys:
    # get all the rows from the tbody
    for row in tbody.xpath("./tr"):
        # extract the tds and do whatever you want.
        tds = row.xpath("./td")
        print(tds)

rawDescription: Python xml - how to loop through <tbody> to get data


code:
class Thing(object):
    x = 1
something = Thing()
something.y = something.x

rawDescription: How to prevent a function from being overridden in python

description: Prevent a function from being overridden in python


code: ax.plot_surface(X,Y,z, facecolors=plt.cm.jet(np.clip(fc,0,vmax)*np.max(z)/vmax), cstride=1, rstride=1, vmax=vmax)

rawDescription: Scaled colormap of facecolors with mplot3d


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

fig = plt.figure()
ax = Axes3D(fig)

x = [6,3,6,9,12,24]
y = [3,5,78,12,23,56]
# put 0s on the y-axis, and put the y axis on the z-axis
ax.plot(xs=x, ys=[0]*len(x), zs=y, zdir='z', label='ys=0, zdir=z')
plt.show()

rawDescription: Python : How to plot 3d graphs using Python?


code:
airodump = subprocess.Popen(['airodump-ng', '-w', 'outputfilename', 'mon0'],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(secs)
airodump.terminate()
return_code = airodump.wait()

rawDescription: Popen confusion - redirecting output, methods not working


code:
import os
from pydub.utils import get_player_name

PLAYER = get_player_name()

def play_with_ffplay(seg):
    with NamedTemporaryFile("w+b", suffix=".wav") as f:
        seg.export(f.name, "wav")
        subprocess.call(
            [PLAYER, "-nodisp", "-autoexit", f.name],
            stdout=open(os.devnull, 'w'),
            stderr=os.stdout
        )

rawDescription: Pydub and Aplay: suppress verbose output?


code:
Agent.objects.filter(
    name='ashraf',
    __raw__={"skills": {
        "$elemMatch": {
            "level": {"$gt": 5},
            "name": "Computer Skills"
        }
    }}
)

rawDescription: can't query over ListField(EmbeddedDocumentField)

description: Can't query over ListField(EmbeddedDocumentField)


code:
class MyConstraint (Clutter.Constraint):
    def __init__(self, source, width_fraction=1.0, height_fraction=1.0):
        Clutter.Constraint.__init__(self)
        self._source = source
        self._widthf = width_fraction
        self._heightf = height_fraction
    def do_update_allocation(self, actor, allocation):
        source_alloc = self._source.get_allocation()
        width = source_alloc.get_width() * self._widthf
        height = source_alloc.get_height() * self._heightf
        allocation.x2 = allocation.x1 + width
        allocation.y2 = allocation.y1 + height

rawDescription: Using BindConstraint in Clutter to constrain the size of an actor


code:
def memoize(func):
    S = {}
    def wrappingfunction(*args):
        if args not in S:
            S[args] = func(*args)
        return S[args]
    return wrappingfunction

# This function is now memoized
@memoize
def cube(x):
    return x**3

rawDescription: How to "cache" time-consuming results?

description: "cache" time-consuming results


code:
if request.method == 'POST':
    form = ProgrammeForm(user=request.user, data=request.POST)
    if form.is_valid():
        form.save()
else: ##this is the changge
    form = ProgrammeForm(request.user)
return render_to_response('form.html', {'form': form })

rawDescription: django forms MultipleChoiceField reverts to original value on save

description: Django forms MultipleChoiceField reverts to original value on save


code:
import os
cmd = """
osascript -e 'tell application "System Events" to keystroke "m" using {command down}'
"""
# minimize active window
os.system(cmd)

rawDescription: Is there a sendKey for Mac in Python?

description: Is there a sendKey for Mac in Python


code:
import pygame, pygame.gfxdraw
import time

screen = pygame.display.set_mode((800, 600), pygame.FULLSCREEN)
screen.fill((0, 0, 0))
pygame.gfxdraw.circle(screen, 400, 300, 200, (255, 255, 255))
pygame.display.flip()

time.sleep() # otherwise the display will immediately close

rawDescription: How to paint something directly into screen?

description: Paint something directly into screen


code:
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

rawDescription: Python 3 script to upload a file to a REST URL (multipart request)


code:
import ast
s = "['[0,0,0]','[0,0,0]']"
s = ast.literal_eval(s)
s
s = [ast.literal_eval(sub) for sub in s]
s

rawDescription: Convert Array formatted as a string - Python


rawDescription: Join dictionary item, keys

description: Join dictionary item, keys


code:
def predict(self, x):
    """
    Predict values for a single data point or an RDD of points
    using the model trained.
    """
    if isinstance(x, RDD):
        return x.map(lambda v: self.predict(v))

    x = _convert_to_vector(x)
    if self.numClasses == 2:
        margin = self.weights.dot(x) + self._intercept
        if margin > 0:
            prob = 1 / (1 + exp(-margin))
        else:
            exp_margin = exp(margin)
            prob = exp_margin / (1 + exp_margin)
        if self._threshold is None:
            return prob
        else:
            return 1 if prob > self._threshold else 0
    else:
        best_class = 0
        max_margin = 0.0
        if x.size + 1 == self._dataWithBiasSize:
            for i in range(0, self._numClasses - 1):
                margin = x.dot(self._weightsMatrix[i][0:x.size]) + \
                    self._weightsMatrix[i][x.size]
                if margin > max_margin:
                    max_margin = margin
                    best_class = i + 1
        else:
            for i in range(0, self._numClasses - 1):
                margin = x.dot(self._weightsMatrix[i])
                if margin > max_margin:
                    max_margin = margin
                    best_class = i + 1
        return best_class

rawDescription: pyspark, logistic regression, how to get coefficient of respective features

description: Pyspark, logistic regression, how to get coefficient of respective features


rawDescription: Following links with Mechanize

description: Following links with Mechanize


code:
@property
def total_weight(self):
    return queryset_with_sum_annotation.values('sum_value').sum_value

rawDescription: How to make a dynamic model's field value?

description: Make a dynamic model's field value


code:
with open('StackOverflow.desktop', 'w+') as f:
    f.write("""[Desktop Entry]
Encoding=UTF-8
Name=Link to                     Stack Overflow
Type=Link
URL=http://stackoverflow.com/
Icon=text-html
Name[en_US]=StackOverflow
""")

rawDescription: Is it possible to create a url link shortcut using Python, under Ubuntu?


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

from matplotlib.finance import candlestick
from matplotlib.dates import num2date

# data in a text file, 5 columns: time, opening, close, high, low
# note that I'm using the time you formated into an ordinal float
data = np.loadtxt('finance-data.txt', delimiter=',')

# determine number of days and create a list of those days
ndays = np.unique(np.trunc(data[:,0]), return_index=True)
xdays =  []
for n in np.arange(len(ndays[0])):
    xdays.append(datetime.date.isoformat(num2date(data[ndays[1],0][n])))

# creation of new data by replacing the time array with equally spaced values.
# this will allow to remove the gap between the days, when plotting the data
data2 = np.hstack([np.arange(data[:,0].size)[:, np.newaxis], data[:,1:]])

# plot the data
fig = plt.figure(figsize=(10, 5))
ax = fig.add_axes([0.1, 0.2, 0.85, 0.7])
    # customization of the axis
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.tick_params(axis='both', direction='out', width=2, length=8,
               labelsize=12, pad=8)
ax.spines['left'].set_linewidth(2)
ax.spines['bottom'].set_linewidth(2)
    # set the ticks of the x axis only when starting a new day
ax.set_xticks(data2[ndays[1],0])
ax.set_xticklabels(xdays, rotation=45, horizontalalignment='right')

ax.set_ylabel('Quote ($)', size=20)
ax.set_ylim([177, 196])

candlestick(ax, data2, width=0.5, colorup='g', colordown='r')

plt.show()

rawDescription: Intraday candlestick charts using MatPlotLib


code:
results = Salespersons.objects.extra(tables=["Store"],
                          where=["""Salespersons.xsin = Store.xsin"""])

rawDescription: How can I do INNER JOIN in Django in legacy database?

description: Do INNER JOIN in Django in legacy database


code:
#!/usr/bin/env python

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

class Foo(QWidget):
    def __init__(self, parent=None):
        super(Foo, self).__init__(parent)

        self.count  = 0
        self.params = range(4)
        self.url    = 'http://forums.fedoraforum.org/showthread.php?t={0}'

        self.gridLayout = QGridLayout(self)
        self.tabWidget = QTabWidget(self)
        self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)

        self.mapper = QSignalMapper(self)
        self.mapper.mapped.connect(self.on_mapper_mapped)

        for i in range(2):
            grabber = QWebView()
            grabber.loadFinished.connect(self.mapper.map)

            self.mapper.setMapping(grabber, i)
            self.tabWidget.addTab(grabber, "opener {0}".format(str(i)))

            grabber.loadFinished.emit(True)

    @pyqtSlot(int)
    def on_mapper_mapped(self, gNumber):
        self.count += 1
        if self.count < len(self.params):
            gParam = self.params[self.count]

            opener = self.mapper.mapping(gNumber)
            opener.load(QUrl(self.url.format(gParam)))

if __name__ == "__main__":
    import  sys

    app = QApplication(sys.argv)
    main = Foo()
    main.show()
    app.exec_()

rawDescription: Open multiple webpages with different parametrs. PyQt4


code:
from twisted.python.failure import Failure

from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory

from twisted.conch.recvline import HistoricRecvLine
from twisted.conch.stdio import runWithProtocol

class ConsolePrompter(HistoricRecvLine, object):
    ps = ["Message: "]

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

    def lineReceived(self, line):
        try:
            if not line:
                reactor.stop()
            self.drawInputLine()
            self.multiEcho.tellAllClients(line)
        except:
            f = Failure()
            data = f.getTraceback()
            self.terminal.write(data)

    def clientSaid(self, data):
        self.terminal.write("\r")
        self.terminal.eraseLine()
        self.terminal.write("Client Said:" + repr(data))
        self.terminal.write("\n")
        self.drawInputLine()

class MultiEcho(Protocol):
    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.echoers.append(self)

    def dataReceived(self, data):
        self.factory.prompter.clientSaid(data)

    def connectionLost(self, reason):
        self.factory.echoers.remove(self)

class MultiEchoFactory(Factory):
    def __init__(self):
        self.echoers = []
        self.prompter = ConsolePrompter(self)

    def buildProtocol(self, addr):
        return MultiEcho(self)

    def tellAllClients(self, message):
        for echoer in self.echoers:
            echoer.transport.write(message + "\r\n")

mef = MultiEchoFactory()

reactor.listenTCP(8000, mef)

runWithProtocol(lambda: mef.prompter)

rawDescription: Twisted transport.write in seperate thread


code:
from subprocess import Popen, PIPE

p0 = Popen(['wget', '-O', '-', 'http://www.google.com'], stdout=PIPE)
p1 = Popen(['sed', '2,8d'], stdin=p0.stdout, stdout=PIPE)
with open('c1', 'w') as c1:
    p2 = Popen(['sed', '2,7d'], stdin=p1.stdout, stdout=c1)
    p2.wait()

rawDescription: Sub-processing pipe write to file malfunction


code:
import re
f = lambda x: [int(x) for x in re.findall(r'\d+', x)]
sorted(strings, key=f)

rawDescription: Ordering a string by its substring numerical value in python


code: newlist = [word for word in words if len(word) == 9]

rawDescription: Python: Create a new list from a list when a certain condition is met


code:
indices = np.argmax(x, axis=0)
y[indices, np.arange(x.shape[1])]

rawDescription: numpy matrix minimum applied to second array

description: Numpy matrix minimum applied to second array


code:
loader = QUiLoader()
file = QFile(":/forms/myform.ui")
file.open(QFile.ReadOnly)
myWidget = loader.load(file, self)
file.close()

rawDescription: Loading QtDesigner's .ui files in PySide


code:
import platform

def is_linux(distro, architecture):
    if not platform.system() == 'Linux':
        return False

    if platform.linux_distribution()[0].lower() != distro:
        return False

    return platform.processor() == architecture

def is_64bit_ubuntu():
    return is_linux('ubuntu', 'x86_64')

if not is_64bit_ubuntu():
    print(err_msg)

rawDescription: Is there a pythonic way to check whether OS is a 64bit Ubuntu?


code:
mylst = ['bla,bli', 'blula', 'blabla,bloblu,blibla', 'bla']
mylst = [item.split(',') for item in mylst]
mylst

rawDescription: Nested list from list in Python

description: Nested list from list in Python


code:
from collections import Counter
my_dict= {10:[23,24,23,23,24],11:[17,23,23,17,24]}
{k: Counter(v) for k, v in my_dict.items()}

rawDescription: Counting values in a dictionary

description: Counting values in a dictionary


code:
from ghost import Ghost
ghost = Ghost()
ghost.open('https://google.lt')
width, resources = ghost.evaluate("document.getElementById('gbqfq').offsetWidth;")
width

rawDescription: How to programmatically measure the elements' sizes in HTML source code using python?

description: Programmatically measure the elements' sizes in HTML source code using python


code:
columns = ['ID', 'Colour', 'Type', 'Size', 'Date', 'Cost']
newResult = {rec[0]: dict(zip(columns, rec)) for rec in result}

rawDescription: Python converting query output

description: Python converting query output


code:
tp = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tp.ndim
tp.shape
fp = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
fp.ndim
fp.shape
combined = np.vstack((tp, fp)).T
combined
combined.ndim
combined.shape

rawDescription: Create 2 dimensional array with 2 one dimensional array


code:
from decimal import Decimal

# second derivative of a function
def diff2(f, x, h=1E-6):
    x, h = Decimal(x), Decimal(h)
    r = (f(x - h) - 2 * f(x) + f(x + h)) / Decimal(h * h)
    return r

rawDescription: python: arbitrary precision

description: Python: arbitrary precision


code:
import csv
from operator import itemgetter

histogram = dict()

with open('yourfile.csv', 'r') as f:
    csv_read = csv.reader(f, delimiter=',')
    sort_src = sorted(csv_read, key=itemgetter(0))
    print("The Number of records:", len(sort_src))
    #
    for row in sort_src:
        if row[0].isdigit(): #Because you don't want to count headers
            if row[0] in histogram:
                histogram[row[0]] += 1
            else:
                histogram[row[0]] = 1

    #
for item in sorted(histogram.items()):
    print('ID {0} is repeated {1} times'.format(item[0], item[1]))

if __name__ == '__main__':
    pass

rawDescription: Duplicate Count on key column CSV file python 3


code:
class AnuncioSolucaoIndex(RealTimeSearchIndex):
    text = CharField(document=True,use_template=True)
    def read_queryset(self):
        super(AnuncioSolucaoIndex,self).read_queryset()
        return AnuncioSolucao.objects.filter(is_active=True)

rawDescription: Django haystack filter in search index

description: Django haystack filter in search index


code:
app = App(0)
funcs = [app.value1, app.value2, app.value3]
for i, (key, items) in enumerate(d.iteritems()):
    app.x = i
    app.key(key)
    for func, item in zip(funcs, items):
        func(item)

rawDescription: Iterating over a dictionary in Python

description: Iterating over a dictionary in Python


code:
import Tkinter, time, tkMessageBox

top = Tkinter.Tk()
top.withdraw() #to make the main window invisible

def notify(title='Default title', notification='Default notification'):
   tkMessageBox.showinfo(title, notification)

notify()
notify('Yo','Did you know this is a notification!')

rawDescription: Python native notifications

description: Python native notifications


code:
class Meta:
    authentication = BasicAuthentication(realm="your-website.com")

rawDescription: How can you change what the password prompt says in Django-Tastypie?

description: Change what the password prompt says in Django-Tastypie


code:
cursor = connections['prod'].cursor()
cursor.execute('''Your SQL''')
row = cursor.fetchone()

# do what you need to do with the first result set

cursor.nextset() #sets cursor to the next result set

# fetchone or fetchall and do whatever you want with the next result set

rawDescription: Django Multiple Result Sets

description: Django Multiple Result Sets


code:
from random import shuffle
listOfLists = []
for i in range(0,len(importantStuff)/3):
    listOfLists.append([importantStuff[i*3+0],importantStuff[i*3+1],importantStuff[i*3+2]])
shuffle(listOfLists)

singleList = listOfLists[0]
singleItem = listOfLists[0][2]

rawDescription: python randomize preserving every 3 items (list of lists?)

description: Python randomize preserving every 3 items (list of lists?)


code:
def get_position_in_direction(position, direction):
    DIRECTIONS = {'n': (-1, 0), 's': (1, 0), 'e': (0, 1), 'w': (0, -1)}
    offset = DIRECTIONS[direction]
    return (position[0] + offset[0], position[1] + offset[1])

rawDescription: How to add and subtract values of an argument using a dictionary

description: Add and subtract values of an argument using a dictionary


code:
def isPrime(n):
    d = n - 1
    s = 0
    while not d & 1:
        s += 1
        d >>= 1
    for a in (2, 13, 23, 1662803):
        if pow(a, d, n) != 1 and all(pow(a, (1 << r) * d, n) != n - 1 for r in range(0, s)):
            return False
    return True

print(sum(x for x in range(1000000000001, 1000000100000, 2) if isPrime(x)))

rawDescription: finding prime numbers greater than 10^12

description: Finding prime numbers greater than 10^12


code:
test = re.compile(r'[T]\d[A-Z] *\d[A-Z]\d')
addr = '12345-67 Ave, Edmonton, AB T1A 2B3, Canada'
test.search(addr).group()

rawDescription: Extract Alberta (Canada) postal code through regular expressions in python


code: [m.get("gparents", {}).get("parent", {}).get("child") for m in M]

rawDescription: Chained, nested dict() get calls in python


code:
import time

def menu():

        play_game = print("1. Play the game")
        instruc = print("2. Instructions")
        question = input("Enter choice")

        if question == "2":
                print("You will given a list of coded words, you have to replace the symbols to letters to get the word")
                print("\n")
                menu()
        else:
                play()

#How many turns user would like

def play():

        global words_loaded

        x = int(input("How many guesses would you like?\n(You'll need atleast 23, only input numbers) \n"))
        for i in range(x):

#symbol replacing

                sym = input("Which symbol do you want to replace? ")
                cha = input("Which character do you want to replace with it? ")

#shows the symbol changes

                words_loaded = words_loaded.replace(sym, cha)
                print("Your Puzzle now looks like... \n")
                print(words_loaded)

#Messages for user if they win or lose

                if words_loaded == solved:
                    print("PUZZLE SOLVED")
                    break

        if i ==(x-1):
               print("Better luck next time")
#        ask = input("would you like to play again?")

#Asks if user would like to play again
        Tryagain = input("would you like to play?")

        if Tryagain == "yes":
                play()

        elif Tryagain == "no":
               print("Thanks for playing")

        else:
               menu()

print("If A is represented by the symbol #, M by * and N by %, then the word\nMANNA would be represented by the symbols *#%%#")

#Loads files

with open("words.txt", 'rt') as in_file:
        words_loaded = in_file.read()
        print(words_loaded)

print("Here are your clues!")
time.sleep(0.5)

with open("clues.txt", 'rt') as in_file:
            clues_loaded = in_file.read()
            print(clues_loaded)

with open("solved.txt", 'rt') as in_file:
            solved = in_file.read()

#Menu

menu()

rawDescription: Python - not printing win message

description: Python - not printing win message


rawDescription: How to get char from string by index?

description: Get char from string by index


code:
# helper functions
def getRGB(pix):
    return getRed(pix), getGreen(pix), getBlue(pix)

def setRGB(pix, r, g, b):
    setRed(pix,r)
    setGreen(pix,g)
    setBlue(pix,b)

def markYellow(pic):
    for pix in getPixels(pic):
        r, g, b = getRGB(pix)
        if r > 200 and b < 90 and g > 150:
            setRGB(pix, 255, 255, 255)
        else:
            setRGB(pix, 0, 0, 0)

def pctMarked(pic):
    # is there a more direct way to get the totalPixels?
    # totalPixels = len(pic) # perhaps?
    totalPixels = sum(1 for pix in getPixels(pic))
    whitePixels = sum(getRGB(pix) == (255, 255, 255) for pix in getPixels(pic))
    return whitePixels / float(totalPixels)

rawDescription: Python Condensing Code

description: Python Condensing Code


rawDescription: Is it possible to initialize an empty default value on leftOuterJoin?


code:
import os
indir = '/Users/dhunter/GRID01/'  # input directory
for i in os.listdir(indir):  # for each "i" (iteration) within the indir variable directory...
    if i.lower().endswith('.gps'):  # if the filename of an iteration ends with .GPS, then...
        if not i.lower().endswith('.gpsnew.gps'):  # if the filename does not end with .gpsnew.gps, then...
            print(i + ' loaded')  # print the filename to CLI.
            with open (indir + i, 'r') as my_file:
                for line in my_file:
                    if not line.startswith('$GNGSA'):
                        if not line.startswith('$GNVTG'):
                            with open(indir + i + 'new.gps', 'a') as outputfile:
                                outputfile.write(line)
                                outputfile.write('\r\n')

rawDescription: Delete a line in multiple text files with the same line beginning but varying line ending using Python v3.5


code:
import re

re_user_amount = r'\s+(\w+)\s+(\d*\.\d{2})'
re_date = r'\w{3}\s+\w{3}\s+\d+\s+\d\d:\d\d:\d\d \w+ \d{4}'

with open('/var/log/monthly.out', 'r') as f:
    content = f.read()
    sections = content.split('-- End of monthly output --')

    for section in sections:
        date = re.findall(re_date, section)
        matches = re.findall(re_user_amount, section)

        print(date, matches)

rawDescription: Regex to use monthly.out for user accounting


code:
from django.db.models.loading import get_models, get_app
app = get_app('myappname')
models = get_models(app)

rawDescription: How do I list all classes of a given type in a python file?

description: List all classes of a given type in a python file


code:
params= {
'id': acodec.getCodecId('mp3'),
'bitrate': r.bitrate,
'sample_rate': r.sample_rate,
'ext': 'mp3',
'channels': r.channels }
enc= acodec.Encoder( params )

rawDescription: Python library for converting files to MP3 and setting their quality


code:
import wx

class CPFSFrame(wx.Frame):
    def __init__(self, parent, title):
        super(CPFSFrame, self).__init__(parent, title=title,
                                    style = wx.BORDER | wx.CAPTION | wx.SYSTEM_MENU | wx.CLOSE_BOX,
                                    size=(350, 200))
        panel = wx.Panel(self, -1)

        pNumberLabel = wx.StaticText(panel, -1, 'Project number: ')
        pNumberText = wx.TextCtrl(panel, -1, '', size=(175, -1))
        pNumberText.SetInsertionPoint(0)

        pNameLabel = wx.StaticText(panel, -1, 'Project name: ')
        pNameText = wx.TextCtrl(panel, -1, '', size=(175, -1))
        pNameText.SetInsertionPoint(0)

        pButton = wx.Button(panel, label='Create')
        pButton.Bind(wx.EVT_BUTTON, self.OnClose)

        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
        sizer.AddMany([pNumberLabel, pNumberText, pNameLabel, pNameText, pButton])
        panel.SetSizer(sizer)

        statusBar = self.CreateStatusBar()
        self.Show()

    def OnClose(self, evt):
        self.Close(True)

if __name__ == '__main__':
    app = wx.App()
    CPFSFrame(None, title='Create New Project Folder Structure')
    app.MainLoop()

rawDescription: wxPython: How to bind the button?

description: WxPython: How to bind the button


code: df.groupby("Job").filter(lambda x : x["Dept"].isin(["TC"]).any())

rawDescription: Filter groups based on occurrence of a value


code:
def dot(K, L):
   if len(K) != len(L):
      return 0

   return sum(i[0] * i[1] for i in zip(K, L))

rawDescription: Dot product of two lists in Python

description: Dot product of two lists in Python


code:
def _generate_report_test(self, rows, cid, tid, n, t, o, e):
    # e.g. 'pt1.1', 'ft1.1', etc
    has_output = bool(o or e)
    tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)
    # name = t.id().split('.')[-1]
    name = t.id().split('test_')[-1]
    doc = t.shortDescription() or ""
    desc = doc and ('%s: %s' % (name, doc)) or name
    tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL

rawDescription: Python HTMLTestRunner test report contains only partial test case names


code:
@tools.decode(encoding='ISO-88510-1')
def decodingFunction(self, data):
    return "%s" % (data, )

rawDescription: How to decode Get/Post Request headers into tuples using Cherry Py?

description: Decode Get/Post Request headers into tuples using Cherry Py


code:
with open('/Users/d-sdf/test_erick/test/essays.csv') as csvfile:
    for i, line in enumerate(csvfile):
        with open("essay{}.txt".format(str(i+1)), "w") as txtfile:
            txtfile.write(line)

rawDescription: Saving each line I read from a file as a different file


code:
highest_order = s.query(Order.customer_id, func.max(Order.position).label('position')).\
                    filter(Order.oh_reqdate == date_q).\
                    filter(Order.vehicle_id == vehicle.id).\
                    group_by(Order.customer_id).\
                    subquery()

s.query(Order).\
    join(Customer).\
    join(highest_order, highest_order.c.customer_id == Customer.id).\
    filter(Order.oh_reqdate == date_q).\
    filter(Order.vehicle_id == vehicle.id).\
    filter(Order.position == highest_order.c.position)

rawDescription: SQLalchemy distinct, order_by different column


code:
throw_card(7,2)
throw_card(19,4)
throw_card(10,5)
throw_card(6,3)
throw_card(4000,7)

rawDescription: ThrowCards in python

description: ThrowCards in python


code:
d = defaultdict(int)
d[1] += 1
d[1]
d[5]

rawDescription: Incrementing values of potentially empty keys of a python dictionary


rawDescription: Python , nested list row and column

description: Python , nested list row and column


code:
a = np.random.rand (100)
t = np.linspace (0, 2*np.pi, len(a))
x = np.cos (t)
y = np.sin (t)

plt.scatter (x, y, c = a)
plt.show ()

rawDescription: Visualize datapoints along a circle in Matplotlib


code:
import requests

def download_file_from_url(url, file_save_path):
    r = requests.get(url)
    if r.ok: # checks if the download succeeded
        with file(file_save_path, 'w') as f:
           f.write(r.content)
        return True
    else:
        return r.status_code

download_file_from_url('http://imgs.xkcd.com/comics/tech_support_cheat_sheet.png', 'new_image.png')
# will download image and save to current directory as 'new_image.png'

rawDescription: can python be useful to open multiple tabs in a browser in one shot?

description: Can python be useful to open multiple tabs in a browser in one shot


code: values = [l[3] for l in data[:100]]

rawDescription: Accessing a list of lists

description: Accessing a list of lists


rawDescription: Find min, max and average of an ID in Python Pandas


code:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'youremail@gmail.com'
EMAIL_HOST_PASSWORD = 'yourpassword'
EMAIL_PORT = 587

rawDescription: How to use python -m smtpd to actually send emails?

description: Use python -m smtpd to actually send emails


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

x = np.arange(0,5,0.001)
y = np.sin(2*np.pi*x)

def update_line(num, data, line):
    line.set_data(data[..., :num])
    return line,

fig = plt.figure()

data = np.vstack((x,y))
l, = plt.plot([], [], 'r-')
plt.xlim(0, 5)
plt.ylim(-1, 1)
line_ani = animation.FuncAnimation(fig, update_line, frames=1000,
                           fargs=(data, l), interval=20, blit=False)
plt.show()

rawDescription: Plot a graph point to point python

description: Plot a graph point to point python


code:
import pdb
def main():
  list = [1,2,3]
  pdb.set_trace()
  list = [2,3,4]

if __name__ == '__main__':
    main()

rawDescription: vim and python scripts debugging

description: Vim and python scripts debugging