code:
import numpy as np
import cv2

def inside(r, q):
    rx, ry, rw, rh = r
    qx, qy, qw, qh = q
    return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh

def draw_detections(img, rects, thickness = 1):
    for x, y, w, h in rects:
        # the HOG detector returns slightly larger rectangles than the real objects.
        # so we slightly shrink the rectangles to get a nicer output.
        pad_w, pad_h = int(0.15*w), int(0.05*h)
        cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)

if __name__ == '__main__':

    hog = cv2.HOGDescriptor()
    hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )
    cap=cv2.VideoCapture('vid.avi')
    while True:
        _,frame=cap.read()
        found,w=hog.detectMultiScale(frame, winStride=(8,8), padding=(32,32), scale=1.05)
        draw_detections(frame,found)
        cv2.imshow('feed',frame)
        ch = 0xFF & cv2.waitKey(1)
        if ch == 27:
            break
    cv2.destroyAllWindows()

rawDescription: Full body detection and tracking using OpenCV+Python-2.7


code:
if 'last_date' not in context.dicts[0] or context.dicts[0]['last_date'] != date:
    context.dicts[0]['last_date'] = date

rawDescription: maintain state between custom tag calls?

description: Maintain state between custom tag calls


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

x = np.arange(0, 2, 0.01)
y = np.random.random_sample(len(x))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xlabel('Power Point')
ax.set_ylabel('Voltage (V)')
plt.savefig('example.png')

rawDescription: A method to plot power consumption graph with matplotlib?


code:
"""store the variable in a dictionary whose key is the
   row and column number
"""
import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

from functools import partial

root=tk.Tk()

def callback(key):
    if variables_dict[key].get() == "_":
        variables_dict[key].set("Pushed")
    else:
        variables_dict[key].set("Error")

variables_dict={}
for j in range(3):
    for k in range(5):
        v = tk.StringVar()

        ## send same key to the callback function and use as
        ## dictionary's key
        key="%02d-%02d" % (j, k)
        ## no need to keep a reference to the Button's class
        ## instance & all of not used modules within it
        tk.Button(root, textvariable=v,
                  command=partial(callback, key)).grid(row=j,
                  column=k, sticky="nsew")
        variables_dict[key]=v
        v.set('_')

root.mainloop()

rawDescription: Initialise a board filled with StringVar() and update variables using Tkinter, Python


code:
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
    items = match.groups()
    # items is ("foo", "21")

rawDescription: How to split strings into text and number?

description: Split strings into text and number


code: "SELECT {} FROM a_table".format(','.join(parameter_list))

rawDescription: How to use a parameter to select one or more columns in a SELECT statement

description: Use a parameter to select one or more columns in a SELECT statement


code:
def logOnsetTime():
    """Function which allows launching this code right after a window.flip()"""
    logfile.write('OnsetTime, %s' % clock.getTime())

window.callOnFlip(logOnsetTime)  # runs on first flip
while timer.getTime() >0: # while time isn't up (turns neg when time's up)
    for key in event.getKeys():
        if key in ['escape']:
            core.quit() # quit if they press escape

        timeText.draw(window)
        timeline.draw(window)
        cursorImage.draw(window)

        ## flip so it actually appears.
        window.flip()

rawDescription: Write out only first result in while loop in psychopy


code:
List1 = ['jacob','batman','mozarella']
[i[:4] for i in List1]

rawDescription: Use list comprehension to print out a list with words of length 4


rawDescription: Sorting a list of lists in python

description: Sorting a list of lists in python


code:
class BlogAdmin(admin.ModelAdmin):

    ...
    actions = ['approve']
    ...

    def approve(self, request, queryset):
        rejects = queryset.filter(state = rejected)
        if len(rejects) != 0:
            # You might want to raise an exception here, or notify yourself somehow
            self.message_user(request,
                              "%s of the blogs you selected were already rejected." % len(rejects))
            return

        rows_updated = queryset.update(state = approved)
        self.message_user(request, "%s blogs approved." % rows_updated)
    approve.short_description = "Mark selected blogs as approved"

rawDescription: How to notify user when django's custom action doesn't behave as expected?

description: Notify user when django's custom action doesn't behave as expected


code:
import sys,codecs
reload(sys)
sys.setdefaultencoding("utf-8")

rawDescription: Python saving unicode to XML

description: Python saving unicode to XML


code: button.clicked.connect(lambda state, x=idx: self.button_pushed(x))

rawDescription: Using lambda expression to connect slots in pyqt


code:
import os, csv

path1 = os.path.abspath("../data/file1.txt")
path2 = os.path.abspath("../data/file2.txt")
merged_path = os.path.abspath('../data/output.txt')

#file1
fg = csv.DictReader(open(path1, 'rb'), delimiter = '\t')

fieldnames = fg.fieldnames
fieldnames.append('source')
# merge the two files for further processing
merged_file = csv.DictWriter(open(merged_path, 'ab'), delimiter = '\t', fieldnames=fieldnames)
merged_file.writeheader()

for row in fg:
    row['source'] = os.path.basename(path1)
    merged_file.writerow(row)

#file2
bg = csv.DictReader(open(path2, 'rb'), delimiter = '\t')

for row in bg:
    row['source'] = os.path.basename(path1)
    merged_file.writerow(row)

rawDescription: How to merge two files in python

description: Merge two files in python


code: re.findall(r'NAME (.+) VER (.+) DATE (.+)', 'NAME Test VER 2.00 DATE 1/2/12')

rawDescription: How to read a file between two points in Python

description: Read a file between two points in Python


code:
def openfile1(self):
    file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
    self.oLabel.configure(text=file1.name)
    rfile1 = file1.read()
    tkMessageBox.showinfo("oy", rfile1, parent=root)

rawDescription: python 2.7 Tk change label to carry file name from opened file

description: Python 2.7 Tk change label to carry file name from opened file


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

def main():
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)

        self.la = QLabel("Press tab in this box:")
        self.le = MyLineEdit()

        layout = QVBoxLayout()
        layout.addWidget(self.la)
        layout.addWidget(self.le)
        self.setLayout(layout)

        self.le.keyPressed.connect(self.update)

    def update(self, text):
        self.le.setText(text)

MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)

class MyLineEdit(QLineEdit):
    keyPressed = pyqtSignal(str)

    def keyPressEvent(self, event):
        keyname = ''
        key = event.key()
        modifiers = int(event.modifiers())
        if (modifiers and modifiers & MOD_MASK == modifiers and
            key > 0 and key != Qt.Key_Shift and key != Qt.Key_Alt and
            key != Qt.Key_Control and key != Qt.Key_Meta):

            keyname = QKeySequence(modifiers + key).toString()

            print('event.text(): %r' % event.text())
            print('event.key(): %d, %#x, %s' % (key, key, keyname))

        self.keyPressed.emit(keyname)

if __name__ == "__main__":
    main()

rawDescription: in pyqt how to print "Ctrl+key" in QLineEdit when pressed Ctrl + anyKey

description: In pyqt how to print "Ctrl+key" in QLineEdit when pressed Ctrl + anyKey


code:
from numpy import *
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection # New import

#x,y = genfromtxt("data.dat",unpack=True)
# Generated some random data
w = 3
x,y = np.arange(100), np.random.randint(0,100+w,100)
y = np.array([y[i-w:i+w].mean() for i in range(3,100+w)])
z = np.zeros(x.shape)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#ax.add_collection3d(plt.fill_between(x,y,-0.1, color='orange', alpha=0.3,label="filled plot"),1, zdir='y')
verts = [(x[i],z[i],y[i]) for i in range(len(x))] + [(x.max(),0,0),(x.min(),0,0)]
ax.add_collection3d(Poly3DCollection([verts],color='orange')) # Add a polygon instead of fill_between

ax.plot(x,z,y,label="line plot")
ax.legend()
ax.set_ylim(-1,1)
plt.show()

rawDescription: mplot3D fill_between extends over axis limits

description: Mplot3D fill_between extends over axis limits


code:
dict2 = {}
for k,v in dict1.items():
  for x in v:
    dict2[x] = k

rawDescription: Dictionary changing many values to many keys


code:
df = pd.DataFrame()
f = open('workfile', 'r')
for line in f:
    df = pd.concat([df, pd.read_json(line, orient='columns')])

rawDescription: Turning a huge TextEdit file of JSON into a Pandas dataframe


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

plt.figure()
inner_offset = 0.05
r = np.arange(inner_offset,1. + inner_offset,1./720.)
theta = np.arange(0.,2.,1./360.)*np.pi

c1 = plt.polar(theta/2.,r, color='b')[0]
x1 = c1.get_xdata()
y1 = c1.get_ydata()
c2 = plt.polar((theta/2.)+(np.pi/3.),r, color='y')[0]
x2 = c2.get_xdata()
y2 = c2.get_ydata()

plt.fill_betweenx(y1, x1, x2, color='g')
plt.show()

rawDescription: fill between two lines in polar coordinates

description: Fill between two lines in polar coordinates


code:
import copy
new_matrix = copy.deepcopy(myMatrix)

rawDescription: How to assign the same value to multiple variables in Python

description: Assign the same value to multiple variables in Python


code:
p = {k:[x[y] for x in A for y in v] for k, v in patterrnDict.iteritems()}
p[1]
p[5]

rawDescription: Iterating over an array and dictionary and storing the values in another array


rawDescription: Volumetric slice plot of a parallelepiped volume data


rawDescription: Selecting rows from a Dataframe based on values in multiple columns in pandas


code:
def get_nested(d, keys):
    return reduce(dict.get, [d] + keys)

def set_nested(d, keys, value):
    get_nested(d, keys[:-1])[keys[-1]] = value

dict1 = {
  'server' : {
    'index' : 0,
    'info' : {
      'ip' : '127.0.0.1',
      'user' : {
        'number' : 1001,
        'tel' : '123456'
      }
    }
  }
}

keys = 'server-info-user-number'.split('-')
get_nested(dict1, keys)
set_nested(dict1, keys, 2555)
dict1

rawDescription: how to update a python dictionary by using the keys of arbitrary length?

description: Update a python dictionary by using the keys of arbitrary length


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

import argparse

def parseArguments():
    # Create argument parser
    parser = argparse.ArgumentParser()

    # Positional mandatory arguments
    parser.add_argument("creditMom", help="Credit mom.", type=float)
    parser.add_argument("creditDad", help="Credit dad.", type=float)
    parser.add_argument("debtMom", help="Debt mom.", type=float)

    # Optional arguments
    parser.add_argument("-dD", "--debtDad", help="Debt dad.", type=float, default=1000.)
    parser.add_argument("-s", "--salary", help="Debt dad.", type=float, default=2000.)
    parser.add_argument("-b", "--bonus", help="Debt dad.", type=float, default=0.)

    # Print version
    parser.add_argument("--version", action="version", version='%(prog)s - Version 1.0')

    # Parse arguments
    args = parser.parse_args()

    return args

def example(credit_mom, credit_dad, debt_mom, debt_dad = 1000, salary = 2000, bonus = 0):
    total_gain = salary + credit_dad + credit_mom + bonus
    total_loss = debt_dad + debt_mom

    return total_gain - total_loss

if __name__ == '__main__':
    # Parse the arguments
    args = parseArguments()

    # Raw print arguments
    print("You are running the script with arguments: ")
    for a in args.__dict__:
        print(str(a) + ": " + str(args.__dict__[a]))

    # Run function
    print(example(args.creditMom, args.creditDad, args.debtMom, args.debtDad, args.salary, args.bonus))

rawDescription: Run python script with some of the argument that are optional


code:
import json

def gen():
    yield 20
    yield 30
    yield 40

class StreamArray(list):
    def __iter__(self):
        return gen()

    # according to the comment below
    def __len__(self):
        return 1

a = [1,2,3]
b = StreamArray()

print(json.dumps([1,a,b]))

rawDescription: Python: make a list generator JSON serializable


code:
from xml.etree import cElementTree as ET
xmlstr = """
<root>
<page>
  <title>Chapter 1</title>
  <content>Welcome to Chapter 1</content>
</page>
<page>
 <title>Chapter 2</title>
 <content>Welcome to Chapter 2</content>
</page>
</root>
"""
root = ET.fromstring(xmlstr)
for page in list(root):
    title = page.find('title').text
    content = page.find('content').text
    print('title: %s; content: %s' % (title, content))

rawDescription: Extracting text from XML using python

description: Extracting text from XML using python


code:
driver = gdal.GetDriverByName('MEM')
outds = driver.Create('', pixelxsize, pixelysize, 1, GDT_Byte)
outds.SetProjection(target_proj)
outds.SetGeoTransform(target_gt)

gdal.RasterizeLayer(outds, [1], vectorlayer, burn_values=[1])

rawDescription: How to do zonal statistics on raster file based on polyon in Python?

description: Do zonal statistics on raster file based on polyon in Python


code:
from twisted.internet import protocol, reactor

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

reactor.listenTCP(1234, EchoFactory())
reactor.run()

rawDescription: multiple users doing form submission with python CGI

description: Multiple users doing form submission with python CGI


rawDescription: How can you print cipher text as a hex string?

description: Print cipher text as a hex string


code:
MyModel.objects.extra(
    select={
        'tags_occurance': "(tags LIKE '%tag1%') + (tags LIKE '%tag2%')"
    },
).order_by('-tags_occurance')

rawDescription: Django Queryset most accurate search result


code:
import sys
log_file = open("newc.txt","a")
this_no, prev_no = 0, 0

with open("newfileinput.txt",'r') as f:
    for line in f:
        row = line.split()
        this_no = int(row[1])
        log_file.write(line.replace(str(this_no), str(this_no - prev_no)))
        prev_no = this_no

log_file.close()

rawDescription: To find the difference b/w two numbers in a column of file?


code:
langs = {
  "en-US" : "chapter",
  "fr-FR" : "chapitre"
}

test = langs['en-US']

rawDescription: Map a set of values in python

description: Map a set of values in python


code:
import shapefile as sf
import os

filename2 = 'test/point16'

lis = [(33.21, -122.15, 'france'), (35.31, -122.15, 'germany'), (35.41, -123.15, 'Hawaii'), (30.51, -122.15, 'Philippines'),(32.30, -122.15, 'Texas')]

w = sf.Writer(sf.POINT)
w.field('location')

for l in lis:
    w.point(l[0], l[1])
    w.record(l[2], 'Point')
w.save(filename2)

# create the PRJ file
prj = open("%s.prj" % filename2, "w")
epsg = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]'
prj.write(epsg)
prj.close()

rawDescription: where do I append point values with pyshp

description: Where do I append point values with pyshp


code:
class Base(object):
    def __init__(self, base_arg1, base_arg2):
        self.base_arg1 = base_arg1
        self.base_arg2 = base_arg2
        ...

class Derived(Base):
    def __init__(self, base_arg1, base_arg2, derived_arg1, derived_arg2):
        super().__init__(base_arg1, base_arg2)
        ...

    @classmethod
    def from_base(cls, b, da1, da2):
        return cls(b.base_arg1, b.base_arg2, da1, da2)

rawDescription: Sharing base object with inheritance

description: Sharing base object with inheritance


code: sent_with_not_null = sent2 and sent1

rawDescription: Simplifying convoluted if-else conditions to check if len(list) =0 - Python


code:
from django.db.models import F
Good.objects.all().update(cost_to_display=F('cost_in_currenty') * F('currency__value'))

rawDescription: Bulk update in django with calculations

description: Bulk update in django with calculations


code:
def save(self, force_insert=False, force_update=False, using=None):
    """
    Saves the current instance. Override this in a subclass if you want to
    control the saving process.

    The 'force_insert' and 'force_update' parameters can be used to insist
    that the "save" must be an SQL insert or update (or equivalent for
    non-SQL backends), respectively. Normally, they should not be set.
    """
    if force_insert and force_update:
        raise ValueError("Cannot force both insert and updating in model saving.")
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)

rawDescription: Django : difference between calling self.model.save() and self.model.save(*args,**kwargs)


code: ' '.join([word.capitalize() for word in your_string.split(' ')])

rawDescription: Python: Is there a one line script to title case strings except for strings that start with a digit?


code:
operator.lt
operator.le

rawDescription: operator python parameter

description: Operator python parameter


code:
if df.empty:
    print('DataFrame is empty!')

rawDescription: How to check whether a pandas DataFrame is empty?

description: Check whether a pandas DataFrame is empty


code:
f = open('lorem ipsum.txt', 'r')
o = open('output.txt', 'w')
contents = f.read()
new = contents.split('.\n')
o.write('\n'.join([content.replace('\n', '') for content in new]))

rawDescription: Python reading file, error recognizing dot character


code:
import struct

file = open( "/dev/input/mice", "rb" );

def getMouseEvent():
  buf = file.read(3);
  button = ord( buf[0] );
  bLeft = button & 0x1;
  bMiddle = ( button & 0x4 ) > 0;
  bRight = ( button & 0x2 ) > 0;
  x,y = struct.unpack( "bb", buf[1:] );
  print ("L:%d, M: %d, R: %d, x: %d, y: %d\n" % (bLeft,bMiddle,bRight, x, y) );
  # return stuffs

while( 1 ):
  getMouseEvent();
file.close();

rawDescription: Get mouse deltas using Python! (in Linux)


code:
import subprocess
nmap = subprocess.Popen(('nmap'), stdout-subprocess.PIPE)
ipout = nmap.communicate()[0]

rawDescription: Get all connected device name on the network - Python


code:
from decimal import *
from sys import maxint
getcontext()
d=Decimal(maxint)
d
e=Decimal(maxint)
f=d**e

rawDescription: Python: Is there a way to keep an automatic conversion from int to long int from happening?


code:
a = 'abcdefg'
j=2;h=4
my_slice = slice(j,h) # you can pass this object around if you wish

a[my_slice] # -> cd

rawDescription: How do I slice a python string programmatically?

description: Slice a python string programmatically


code:
from numpy import log2
import matplotlib.pyplot as plt

from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms

class CustomScale(mscale.ScaleBase):
    name = 'custom'

    def __init__(self, axis, **kwargs):
        mscale.ScaleBase.__init__(self)
        self.thresh = None #thresh

    def get_transform(self):
        return self.CustomTransform(self.thresh)

    def set_default_locators_and_formatters(self, axis):
        pass

    class CustomTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, thresh):
            mtransforms.Transform.__init__(self)
            self.thresh = thresh

        def transform(self, a):
            return 10**(a/10)

        def inverted(self):
            return CustomScale.InvertedCustomTransform(self.thresh)

    class InvertedCustomTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, thresh):
            mtransforms.Transform.__init__(self)
            self.thresh = thresh

        def transform(self, a):
            return log2(a)*(10/log2(10))

        def inverted(self):
            return CustomScale.CustomTransform(self.thresh)

mscale.register_scale(CustomScale)

xdata = [log2(x)*(10/log2(10)) for x in range(1,11)]
ydata = range(10)
plt.plot(xdata, ydata)

plt.gca().set_xscale('custom')
plt.show()

rawDescription: How to produce an exponentially scaled axis?

description: Produce an exponentially scaled axis


code:
import sys
for line in iter(sys.stdin.readline,""):
    print(line)

rawDescription: Immediately output user input to console


code:
url(r'^about/$', views.about, name='about')
url(r'^login/$', views.login, name='login')
# etc
# and last:
url(r'^(?P<pagename>[a-zA-Z0-9_.-]*)/$',
     views.all_pagenames, name='all_pagenames')

rawDescription: How to exclude certain parameters in dynamic urls?

description: Exclude certain parameters in dynamic urls


rawDescription: python class with many attributes

description: Python class with many attributes


code:
from celery import Celery
from kombu import Exchange

results_exchange = Exchange('myres', type='fanout')

app = Celery()

@app.task(ignore_result=True)
def something():
    res = do_something()
    with app.producer_or_acquire(block=True) as producer:
        producer.send(
            {'result': res},
            exchange=results_exchange,
            serializer='json',
            declare=[results_exchange],
        )

rawDescription: Have Celery broadcast return results from all workers


code:
hdul = fits.HDUList()
hdul.append(fits.PrimaryHDU())

for img in export_array:
    hdul.append(fits.ImageHDU(data=img))

hdul.writeto('output.fits')

rawDescription: Write 3d Numpy array to FITS file with Astropy


code:
import seaborn as sns
data = np.random.rand(2,2)
sns.heatmap(data, annot=True,  linewidths=.5)

rawDescription: Python heatmap plot colorbar

description: Python heatmap plot colorbar


code:
def send_mail(recipient, subject, message):

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText

    username = "sender@outlook.com"
    password = "sender's password"

    msg = MIMEMultipart()
    msg['From'] = username
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.attach(MIMEText(message))

    try:
        print('sending mail to ' + recipient + ' on ' + subject)

        mailServer = smtplib.SMTP('smtp-mail.outlook.com', 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(username, password)
        mailServer.sendmail(username, recipient, msg.as_string())
        mailServer.close()

    except error as e:
        print(str(e))

send_mail('recipient@example.com', 'Sent using Python', 'May the force be with you.')

rawDescription: Having trouble with sending an email through SMTP Python


code:
return self.transmit('GET', 'compression?mediatypeid={0}'.format(media_type)
                             if media_type is not None else 'compression')

rawDescription: How to Use Ternary Operator in Python

description: Use Ternary Operator in Python


code:
# "flup_fcgi_client.py" is the modified flup.client.fcgi_app module
# located in the same directory
import flup_fcgi_client as fcgi_client
fcgi = fcgi_client.FCGIApp(connect='/path/to/socket')
script = '/status'
query = 'json'
env = {
    'SCRIPT_NAME': script,
    'SCRIPT_FILENAME': script,
    'QUERY_STRING': query,
    'REQUEST_METHOD': 'GET'}

code, headers, out, err = fcgi(env)

# Handle return values here...

rawDescription: Python: emulate the functionality of "cgi-fcgi" program


code:
#!/usr/bin/python
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders

def send_mail(send_from,send_to,subject,text,files,server,port,username='',password='',isTls=True):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime = True)
    msg['Subject'] = subject
    msg.attach(MIMEText(text))

    part = MIMEBase('application', "octet-stream")
    part.set_payload(open("WorkBook3.xlsx", "rb").read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="WorkBook3.xlsx"')
    msg.attach(part)

    #context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
    #SSL connection only working on Python 3+
    smtp = smtplib.SMTP(server, port)
    if isTls:
        smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

rawDescription: add excel file attachment when sending python email

description: Add excel file attachment when sending python email


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)-5
Ys = np.array([x**i for i in range(5)])
plt.figure(figsize=(12, 2))
for i, y in enumerate(Ys):
    plt.subplot(1, len(Ys), i+1)
    plt.plot(x, y)
    plt.title('x^%d' % i)
plt.tight_layout()

rawDescription: Plot 3D figure in python

description: Plot 3D figure in python


code:
puzzle = ['#+/084&"', '#3w#%#+', '8%203*','']
clues = {'A': '#', 'N': '%', 'M': '*'}
answer = []
for p in puzzle:
    for dest,src in clues.items():
        p = p.replace(src,dest)
    answer.append(d)

rawDescription: Using a dictionary to replace characters in a list of strings


code:
#Returns a set of matches from the given list. Its a tuple, containing
#the match location of both the Sequence followed by the size
matches = SequenceMatcher(None, a , b).get_matching_blocks()[:-1]
#Now its straight forward, just extract the info and represent in the manner
#that suits you
[a[e.a: e.a + e.size] for e in matches]
[[1, 2], [5, 6]]

rawDescription: Intersection of ordered collection in python


code:
row_data = ['Col 1', row.col2, XML(body_col.replace(".", ".

")), row.col4]

rawDescription: Web2Py add newlines in a column's text while rendering HTML table


code:
from scipy.optimize import fmin_cobyla
import matplotlib.pyplot as plt

def by_minimize(A, B, eps=1e-6):
    A = np.nan_to_num(A)
    B = np.nan_to_num(B)
    def objective(x, A=A, B=B):
        return np.sum((np.dot(A, x) - B)**2)
    x0 = np.zeros(A.shape[1])
    x = fmin_cobyla(objective, x0, lambda x: x-eps)
    return x / np.sum(x), objective(x)

results = []
obj = []
e = []
for eps in np.logspace(-1, -6, 100):
    x, o = by_minimize(A=A1, B=B1, eps=eps)
    e.append(eps)
    results.append(x[1])
    obj.append(o)

h1 = plt.semilogx(e, results, 'b')
plt.ylabel('x[1]', color='b')
plt.xlabel('eps')
plt.twinx()
h2 = plt.semilogx(e, obj, 'r')
plt.ylabel('objective', color='r')
plt.yticks([])

rawDescription: Method for finding strictly greater-than-zero solution for Python's Scipy Linear Programing


rawDescription: Split a list into half by even and odd elements?


code:
res = [
    e +  # filter list itself
    [
        sum( # sum all
            l[4]  # get fourth item if contains all
            for l in data  # take each element of data
            if all(i in l for i in e)  # check if contains all filter list
        )
    ]  # concat sum to list itself
    for e in ls  # take each element of filter list
]

rawDescription: Sum intersection of two lists in Python

description: Sum intersection of two lists in Python


code:
import re
item_list = ['item1', 'item2']
regex = re.compile("^("+"|".join(item_list)+")\.")
search_list = ['item1.exe', 'item2.pdf']
matches = []
for file in search_list:
    match = regex.match(file)
    if match:
        matches.append((match.group(1), file))

rawDescription: How to use re to search for items in one list inside another list in Python

description: Use re to search for items in one list inside another list in Python


code:
import tornado.ioloop
import tornado.web

class UserHandler(tornado.web.RequestHandler):
    def get(self, user_id):
        self.set_status(401)
        self.set_header('WWW-Authenticate', 'Basic realm=Users')

application = tornado.web.Application([
    (r"/users/(\w+)", UserHandler),
],debug=True)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: BasicAuth Prompt won't show with Status 401


code:
upper('hi')
'hi'.upper() # method from the str type
from string import upper
upper('hi') # function from the string module

rawDescription: Inconsistency in python help('string') versus help(list)?


code:
from matplotlib import colors

cmap1 = colors.ListedColormap(['b', 'g', 'r', 'c','m','y','w', 'b','g'])
bounds=[0,11,18,26,31,61,91,501,701,901]
norm = colors.BoundaryNorm(bounds, cmap1.N)
plt.table(cellText=np.int16(table_vals),
                  rowLabels=rows,
                  cellLoc='center',
                  cellColours= cmap1(norm(table_vals)),
                  loc='bottom')

rawDescription: matplotlib table columns with different colormap

description: Matplotlib table columns with different colormap


code:
from datetime import datetime

while True:
    try:
        inp = input("Please enter date in format yyyy/mon/dd. ie 2015/feb/05")
        dte = datetime.strptime(inp,"%Y/%b/%d")
        break
    except ValueError as e:
        print("Invalid format")
print(dte)

rawDescription: date format check for inputted date python

description: Date format check for inputted date python


code:
from functools import lru_cache, wraps
import inspect

def canonicalize_args(f):
    """Wrapper for functools.lru_cache() to canonicalize default
    and keyword arguments so cache hits are maximized."""

    @wraps(f)
    def wrapper(*args, **kwargs):
        sig = inspect.getargspec(f.__wrapped__)

        # build newargs by filling in defaults, args, kwargs
        newargs = [None] * len(sig.args)
        newargs[-len(sig.defaults):] = sig.defaults
        newargs[:len(args)] = args
        for name, value in kwargs.items():
            newargs[sig.args.index(name)] = value

        return f(*newargs)

    return wrapper

@canonicalize_args
@lru_cache()
def add(a, b, negative=False):
    print("Computing")
    return (a + b) * (1 if negative is False else -1)

rawDescription: Memoization/Caching with default optional arguments


code:
from cStringIO import StringIO
import shutil

data = StringIO()
data.write('[ALL]\n')
with open(self._infilename, 'r') as f:
    shutil.copyfileobj(f, data)
data.seek(0)
config.readfp(data)

rawDescription: python reading ini files

description: Python reading ini files


code:
s = "string"
match = True

if "z" in s:
   variable = "something something"
elif "y" in s:
   variable = "something else"
elif "x" in s:
   variable = "something"
else:
   match=False

rawDescription: Set variable to True if one of any conditions are met


code:
class strAs:

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

    def __call__(self, cls):
        prop = self.prop
        def __str__(s):
            return getattr(s, prop)
        cls.__str__ = __str__
        return cls

rawDescription: How to Override a Python class's __str__ method on construction with argument?


code:
d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
','.join(d.keys())
','.join(d.values())

rawDescription: python data dictionary output

description: Python data dictionary output


code:
def preparer_donnees(data):
    from collections import defaultdict

    ret = defaultdict(list)

    for v in data:
        ret[v[0]].append(v[1:])

    return ret

rawDescription: Python: transform list of tuples in dictionary


code:
import numpy.lib.recfunctions as rfn

merged_array = rfn.merge_arrays((array1,array2), usemask = False)

rawDescription: Merge two 2D Numpy array's while persevering row order


code:
from collections import defaultdict
extracted_data = defaultdict(lambda: [set(), set(), set()])
# Splitting of data depends upon your input format
for entry in input:
    # Assume split() returns a 4-length iterable containing name,
    # phone, email, and url where the value is falsy if not present
    for index, value in enumerate(split(entry)):
        if index == 0:
            data_set = extracted_data[name]
        elif value:
            data_set[index - 1].add(value)

rawDescription: Removing duplicate rows?

description: Removing duplicate rows


rawDescription: Python JSON String (containing hex) to HEX


code: set([a, b, c, a])

rawDescription: Fastest way to uniqify a list in Python

description: Fastest way to uniqify a list in Python


rawDescription: How to encode Python 3 string using \u escape code?

description: Encode Python 3 string using \u escape code


code:
from django import forms
from django.contrib import admin

class UserChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.last_name

# Now you have to hook this field up to lab admin.

class LabAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'responsible':
            kwargs['form_class'] = UserChoiceField
        return super(LabAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: Display field for User ForeignKey in Django admin


code:
import csv
import json

csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

rawDescription: Python CSV to JSON

description: Python CSV to JSON


code:
import sys
if sys.stdout.isatty():
    print("Interactive")
else:
    print("Non-interactive")

rawDescription: python: find out if running in shell or not (e.g. sun grid engine queue)

description: Python: find out if running in shell or not (e.g. sun grid engine queue)


code:
string1 = "Likes %s."
string2 = "Likes %s and %s."
string3 = "Likes %s, %s, and %s."

def findveg(row):
    veggies = []
    if DF['cucumber_lover'][row] == 1:
        veggies.append('cucumber')
    if DF['carrot_lover'][row] == 1:
        veggies.append('carrot')
    if DF['spinach_lover'][row] == 1:
        veggies.append('spinach')
    return tuple(veggies)

flist['msg'] = ''
for row in DF.index:
        veggies = findfac(row)
        if len(veggies) == 1:
            findveg['msg'][row] = string1 % veggies
        if len(veggies) == 2:
            findveg['msg'][row] = string2 % veggies
        if len(veggies) == 3:
            findveg['msg'][row] = string3 % veggies

rawDescription: pandas alternative to string creation loop

description: Pandas alternative to string creation loop


rawDescription: Index into list in multiple places in Python?


code:
from PyQt4.QtGui import *
from functools import partial
import sys

def appendAnything(self, app):
    app.textedit.append("test")

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

        vbox = QVBoxLayout(self)

        self.textedit = QTextEdit('')
        self.button = QPushButton("Do anything")

        #Layouts
        vbox.addWidget(self.textedit)
        vbox.addWidget(self.button)

        #Connections
        self.button.clicked.connect(partial(appendAnything, app=self))

    def aFunction(self):
        self.textedit.append("A string")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = Aplicacion()
    test.show()
    app.exec_()

rawDescription: PYQT 4: How can i call a GUI Function in another class?


code:
import os
parent_folder_path = '.'
canned_insert = [
    '.DEF' + os.linesep,
    '..DRIFTSMERKING T26' + os.linesep,
    '..SPENNING T16' + os.linesep]
canned_insert_buf = ''.join(canned_insert)
for eachFile in os.listdir(parent_folder_path):
    if eachFile.endswith('.sos'):
        newfilePath = os.path.join(parent_folder_path, eachFile)
        lines = open(newfilePath, 'r').readlines()
        with open(newfilePath, 'w') as f:
            for i, line in enumerate(lines):
                if line.strip() == '...KOORDSYS -1':
                    f.write('...KOORDSYS 22' + os.linesep)
                else:
                    f.write(line)
                    if line.startswith('..DATO') and lines[i+1:i+4] != canned_insert:
                        f.write(canned_insert_buf)

rawDescription: how to insert a string in a specific position in multiple sequential ascii files?

description: Insert a string in a specific position in multiple sequential ascii files


code:
proc = subprocess.Popen(["myprog.exe"], stdin=subprocess.PIPE)
stdout, stderr = proc.communicate('my input')

rawDescription: In Python how to pipe a string into an executables stdin?


code:
import csv
import operator
def sort_records(csv_filename, new_filename):
    with open(csv_filename, 'r') as i, open(new_filename, 'w') as o:
        reader = csv.reader(i, delimiter = ',')
        writer = csv.writer(o, delimiter=',')
        writer.writerow(next(reader)) # header row
        writer.writerows(sorted(reader, key=operator.itemgetter(0)))
sort_records('a.csv', 'b.csv')

rawDescription: Sorting a csv file by column

description: Sorting a csv file by column


code:
import ftplib

def callback(p):
    print("This is the callback function")

s = ftplib.FTP('myserver.com','login','password') # Connect

f = open('test.txt','rb')                # file to send
s.storbinary('STOR test.txt', f, 1024, callback)         # Send the file

f.close()                                # Close file and FTP
s.quit()

rawDescription: Python FTP uploading bar

description: Python FTP uploading bar


code:
for k in tab.keys():
    tab[k] += 5

rawDescription: Python: Using addition to modify dictionary values


code:
x = np.random.rand(10)
y = np.random.rand(10)
numbers = np.arange(len(x))
for i in range(len(x)):
    plt.text(x[i], y[i], numbers[i])

rawDescription: Markers as "list" in python scatter plot


code:
# No class!
def do_stuff():
    ...
    do_other_stuff()
    ...

def do_other_stuff():
    ...

rawDescription: Reference class from @staticmethod

description: Reference class from @staticmethod


code:
import pandas as pd
from numpy.random import random_integers
from numpy import reshape
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, FixedFormatter
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lalph = list(alph.lower())
alph = list(alph)

df = pd.DataFrame(random_integers(0,100,(26,26)),columns=alph,
                  index=lalph)

# Two lines just to make a plaid image in imshow
differ = reshape([sum(df[col2]-df[col]) for col2 in df for col in df], (26,26))
differ = pd.DataFrame(differ, columns=alph,index=alph)

# pick the labels you want
ticks = [2, 14, 18, 19, 22] # C=2 because A=0 because Python is 0-indexed
ticklabels = [alph[x] for x in ticks]

fig = plt.figure(figsize=(3,5))
ax = fig.add_subplot(111)
ax.imshow(differ)
ax.autoscale(False)

# display only the chosen ticks and ticklabels
ax.xaxis.set_major_locator(FixedLocator(ticks))
ax.xaxis.set_major_formatter(FixedFormatter(ticklabels))

rawDescription: Label groups in a heat map

description: Label groups in a heat map


code: from _module import *

rawDescription: conditionally import a .py or a .pyd module?

description: Conditionally import a .py or a .pyd module


code:
inc = [['A', 'B'], ['C', 'D'], ['E', 'F'], ['G', 'H']]
te = ['A', 'C', 'B']

def flatten(target):
    return_list = list()
    for element in target:
        if isinstance(element,list):
            return_list.extend(flatten(element))
        else:
            return_list.append(element)
    return return_list

set_inc = set(flatten(inc))
set_te = set(te)

print(set_te.issubset(set_inc)) # True

rawDescription: Comparing two lists in python in no specific order


code:
x = numpy.arange(0, 7, 0.01)

subplot(2, 1, 1)
plot(x, sin(x))

subplot(2, 2, 3)
plot(x, cos(x))

subplot(2, 2, 4)
plot(x, sin(x)*cos(x))

rawDescription: How to make an axes occupy multiple subplots with pyplot (Python)

description: Make an axes occupy multiple subplots with pyplot (Python)


code:
import seaborn as sns
iris = sns.load_dataset("iris")
g = sns.pairplot(iris)
g.set(xticklabels=[])

rawDescription: Control tick labels in Python seaborn package


code:
path_list = [
        (50, 10, 30),
        (5, 90, 20),
        (40, 2, 25),
        (10, 8, 0),
]

A = 0
B = 1
Switch = 2

def cheapest_path(path_list, path=None, history=None):
    if history is not None:
        # Terminate when path_list is empty
        if not path_list:
            return history

        # Determine cost to stay this path, vs. cost to switch
        step = path_list[0]
        path_list = path_list[1:]

        stay_on_path = cheapest_path(path_list, path, history + [step[path]])
        switch_path = cheapest_path(path_list, B if path == A else A, history + [step[path], step[Switch]])

        return switch_path if sum(switch_path) < sum(stay_on_path) else stay_on_path
    else:

        pathA = cheapest_path(path_list, A, [])
        pathB = cheapest_path(path_list, B, [])
        return pathA if sum(pathA) < sum(pathB) else pathB

print(", ".join(map(str, cheapest_path(path_list))))

rawDescription: Functional solution for short path algorithm in Python


code:
#!/usr/bin/env python

from __future__ import print_function, division
import scipy.io.wavfile as wavf
import numpy as np
from sys import argv

def pad_audio(data, fs, T):
    # Calculate target number of samples
    N_tar = int(fs * T)
    # Calculate number of zero samples to append
    shape = data.shape
    # Create the target shape
    N_pad = N_tar - shape[0]
    print("Padding with %s seconds of silence" % str(N_pad/fs) )
    shape = (N_pad,) + shape[1:]
    # Stack only if there is something to append
    if shape[0] > 0:
        if len(shape) > 1:
            return np.vstack((np.zeros(shape),
                              data))
        else:
            return np.hstack((np.zeros(shape),
                              data))
    else:
        return data

if __name__ == "__main__":
    if len(argv) != 4:
        print("Wrong arguments.")
        print("Use: %s in.wav out.wav target_time_s" % argv[0])
    else:
        in_wav = argv[1]
        out_wav = argv[2]
        T = float(argv[3])
        # Read the wav file
        fs, in_data = wavf.read(in_wav)
        # Prepend with zeros
        out_data = pad_audio(in_data, fs, T)
        # Save the output file
        wavf.write(out_wav, fs, out_data)

rawDescription: How to add silence in front of a wav file

description: Add silence in front of a wav file


code:
import os

if __name__ == "__main__":
   startingDir = os.getcwd() # save our current directory
   testDir = "\\test" # note that \ is windows specific, and we have to escape it
   os.chdir(testDir) # change to our test directory
   os.system("java -jar run_this.jar required_paramter.ext")
   os.chdir(startingDir) # change back to where we started

rawDescription: How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?

description: Get my python (version 2.5) script to run a jar file inside a folder instead of from command line


code:
import re
import os

f = open('names.txt')
lines = f.readlines()
last_names = first_names = result = []
for line in lines:
    if line.startswith('last:'):
       last_names.append(line[6:])
    elif line.startswith('first:'):
        first_names.append(line[7:])
result = [name for name in last_names if name in first_names]
#do whatever you want to with result

rawDescription: Compare and Extract lines then send to new file


code:
# I just picked 50 and 500 to demonstrate
# You can tweak it to your needs
msg = Text(app, height=50, width=500)

rawDescription: Python Tkinter text size

description: Python Tkinter text size


code: number_of_rows = len(table.findAll(lambda tag: tag.name == 'tr' and tag.findParent('table') == table))

rawDescription: Get table with maximum number of rows in a page using BeautifulSoup


code:
import threading
import time

# define a thread which takes input
class InputThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.user_input = None

    def run(self):
        self.user_input = input('input something: ')

    def get_user_input(self):
        return self.user_input

# main
it = InputThread()
it.start()
while True:
    print('\nsleeping 1s and waiting for input... ')
    time.sleep(1)
    ui = it.get_user_input()
    if ui != None:
        print('The user input was', ui)
        it = InputThread()
        it.start()

rawDescription: Key press and wait for a fixed amount of time


code:
class GUIApp(tk.Tk):
   ...

app = GUIApp()
app.mainloop()

rawDescription: Python method strangely on pause until tkinter root is closed


code:
#!/usr/bin/env python
import subprocess
frommp3 = subprocess.Popen(['mpg123', '-w', '-', '/tmp/test.mp3'], stdout=subprocess.PIPE)
toogg = subprocess.Popen(['oggenc', '-'], stdin=frommp3.stdout, stdout=subprocess.PIPE)
with open('/tmp/test.ogg', 'wb') as outfile:
    while True:
        data = toogg.stdout.read(1024 * 100)
        if not data:
            break
        outfile.write(data)

rawDescription: Simple way to transcode mp3 to ogg in python (live)?


code:
the_string = '1-2-3-4'

[int(x) for x in the_string.split('-') if x != '']

description: Python: "1-2-3-4" to [1, 2, 3, 4]


code:
with open('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
lines = [line.split() for line in data]

rawDescription: Creating lists with loops in Python

description: Creating lists with loops in Python


code:
import bs4, re
html="""

"""
soup = bs4.BeautifulSoup(html)
predicates = [
    {'id' : re.compile('.*thumb.*')},
    {'class' : re.compile('.*thumb.*')},
]
for p in predicates:
    soup.find_all(**p)
#will print [], [

]

rawDescription: Find a particular word in ID or CLASS name using beautifulsoup


code:
import tldextract

def get_domain(url):
    result = tldextract.extract(url)

    return result.domain + '.' + result.tld

rawDescription: Python Regex: Matching from end of string (reverse)


code:
articles = list(Article.objects.order_by('release_date'))

for index, art in enumerate(articles):
    if art.slug == slug:
        article = art
        newer_article = articles[index+1]
        older_article = articles[index-1]
        break

rawDescription: How can i optimize my database queryset in a django view

description: Optimize my database queryset in a django view


code:
x = date1.year
y = date2.year

if x == y:
    do_my_stuff()

rawDescription: Is there a way to handle only year in a datetime object?


rawDescription: Python Visual Basic's CDate equivalent

description: Python Visual Basic's CDate equivalent


code:
import OSC
c = OSC.OSCClient()
c.connect(('127.0.0.1', 57120))   # connect to SuperCollider
oscmsg = OSC.OSCMessage()
oscmsg.setAddress("/startup")
oscmsg.append('HELLO')
c.send(oscmsg)

rawDescription: A plethora of Python OSC modules - which one to use?


rawDescription: Parse date string and change format

description: Parse date string and change format


code:
sep = r'\s+'
ref ='/home/user/Dir/Reference'
ref = pd.read_csv(ref, sep=sep, header=0)

for filename in file_DE:
    name = os.path.basename(os.path.normpath(filename))
    df   = pd.read_csv(filename, sep=sep, header=0)
    pd.merge(df, ref, on='Gene').to_csv('merged_' + name, index=False)

rawDescription: Pandas merge on multiple file and saving it on the same file


code:
multiplier = 2 / (relevant + 1) # floats are rounded! => * with 0 => same result
multiplier = float(2) / float(relevant + 1) # unique values! :)

rawDescription: Python 2.7.2 Win32 # Loop Through List, Buffer Part Of List, Call Function Multiple Times, SAME Return


code:
@app.route("/upload-complete", methods=["POST"])
def handle_upload_response():
    """This will be called after every upload, but we can ignore it"""
    return "Success"

@app.route("/upload", methods=["POST"])
def upload():
    fp = request.files["name_of_file"]
    url = create_upload_url(url_for('handle_upload_response'))
    response = requests.post(url, {'file':
                                   (fp.filename, fp.stream,
                                    fp.content_type, fp.headers)})
    if response == "Success":
        return "File uploaded successfully"
    else:
        return "Something didn't work out"

rawDescription: Using Flask as pass through proxy for file upload?


code:
alist = [6,8,3,4,5]
[x for x in alist if x != 8]
alist = [6,8,8,3,4,5]
[x for x in alist if x != 8]

rawDescription: Python: Using del in for loops

description: Python: Using del in for loops


code:
p = re.compile( '(blue|white|red)')
p.sub( 'colour', 'blue socks and red shoes')
p.sub( 'colour', 'blue socks and red shoes', count=1)

rawDescription: AutoKey Python - How do I do Regular Expression Replacement


rawDescription: How to place progress bar in specific field of status bar in wxpython?

description: Place progress bar in specific field of status bar in wxpython


code:
with open(filename1) as file1, open(filename2) as file2:
    for line1, line2 in zip(file1, file2):
        do_something(line1, line2)

rawDescription: Make python program read 2 files line by line in sync and conduct program on each line


code:
import datetime

# year, month, day
a_date = datetime.date(2014, 11, 1)
b_date = datetime.date.today()

print(b_date)          # 2016-01-13
print(a_date < b_date) # true

rawDescription: building and comparing times

description: Building and comparing times


code:
import project.helpers

project.helpers.somefunction()

rawDescription: Strange Python import behaviour

description: Strange Python import behaviour


code:
regexpattern = r'pattern'
m=re.search(regexpattern,string)

rawDescription: About python re raw pattern search

description: About python re raw pattern search


code:
a = raw_input("Enter a word: ")
sentence = ""
while a != ("stop"):
    sentence = sentence + " " + a
    a = raw_input("Enter a word: ")
print (sentence)

rawDescription: Python while loop to prompt until stop is entered


code:
import re
mylist = ['Julio Cesar por inhumana (?)', '1/4/2015', '1/4/2015', '1/4/2015']
dates = [x for x in mylist if re.match(r'\b(\d+/\d+/\d{4})\b', x)]
dates

rawDescription: Get a specific string from a list - Python


code:
import multiprocessing

def runmycode(result_queue, iterations):
   print("Requested...")
   while 1==1: # This is an infinite loop, so I assume you want something else here
       with iterations.get_lock(): # Need a lock because incrementing isn't atomic
           iterations.value += 1
   if "result found (for example)":
       result_queue.put("result!")

   print("Done")

if __name__ == "__main__":
    processs = []
    result_queue = multiprocessing.Queue()

    iterations = multiprocessing.Value('i', 0)
    for n in range(4): # start 4 processes
        process = multiprocessing.Process(target=runmycode, args=(result_queue, iterations))
        process.start()
        processs.append(process)

    print("Waiting for result...")

    result = result_queue.get() # wait

    for process in processs: # then kill them all off
        process.terminate()

    print("Got result: {}".format(result))
    print("Total iterations {}".format(iterations.value))

rawDescription: Keep unified count during multiprocessing?


code:
class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
         super(MyForm, self).__init__(*args, **kwargs)
         for item in Item.objects.all():
              self.fields[item.name] = forms.BooleanField()

rawDescription: Dynamic class based on database query in Python (Django)


code:
class Organization(models.Model):
    name = models.CharField(max_length=64)

class OrgUser(User):
    organization = models.ForeignKey(Organization, related_name='users')
    role = models.CharField(max_length=1, choices=USER_TYPE_CHOICES)

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = OrgUser
        depth = 1
        fields = ('email', 'role', 'organization',)

class OrganizationUserSerializer(serializers.HyperlinkedModelSerializer): # New Serializer
    class Meta:
        model = OrgUser
        depth = 1
        fields = ('email', 'role',)

class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
    users = OrganizationUserSerializer(many=True) # Change to new serializer
    class Meta:
        model = Organization
        depth = 1
        fields = ('name', 'users',)

rawDescription: Django Rest Framework depth based on direction


code:
#!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-

import sys
from PySide import QtGui

class Sample(QtGui.QWidget):

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

        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 800, 600)
        self.setWindowTitle('Sample')

        btn1 = QtGui.QPushButton("Button 1")

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(btn1)

        self.setLayout(hbox)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Sample()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: How to Resize and Position Buttons in PySide?

description: Resize and Position Buttons in PySide


code:
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)

rawDescription: Python output to terminal during ssh login


rawDescription: propagating values over non-unique (duplicate) cells in pandas

description: Propagating values over non-unique (duplicate) cells in pandas


code:
from itertools import izip

l = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]]
# flatten the list and sort it
f = sorted(inner for outer in l for inner in outer)
# group it into 3s again using izip
new_list = [list(l) for l in izip(*[iter(f)]*3)]

rawDescription: What would be the most efficient/clean way to deeply sort a multidimensional list in Python?


code:
import numpy as np

def read_path(interface):
    inputfile = "/{0}/PATH_ACC.dat".format(interface)
    with open(inputfile, "r") as fileh:
        for lines in fileh:
            linesplit = lines.split()
            yield linesplit[0:3]

interface = input('Enter your interface: ')
acc = [idx for idx in read_path(interface)]

rawDescription: Change directory address from terminal by python


code:
import matploltib.pyplot as plt
import seaborn

import mylib

a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = plt.subplots(figsize=a4_dims)
seaborn.voilinplot(ax=ax, data=df, **violin_options)

rawDescription: How do I change the figure size for a seaborn.violin_plot?

description: Change the figure size for a seaborn.violin_plot


code: exec(compile(open("somefile.py").read(), "somefile.py", 'exec'), local_vars, global_vars)

rawDescription: Python3 - runpy.run_path not working on Ubuntu 10.10


code:
from itertools import groupby
import os

def conc_by_name(names):
    for tail, group in groupby(names, key=os.path.split):
        with open(tail, 'w') as out:
           for name in group:
              with open(name) as f:
                  out.writelines(f)

rawDescription: Concatenating fasta files from different folders


code:
from flask import Flask, Blueprint

app = Flask(__name__)
bp = Blueprint('main', __name__)

@bp.route('/')
def hello(lang):
    return 'Hello ' + lang + '!'

app.register_blueprint(bp, url_defaults={'lang': 'en'})
app.register_blueprint(bp, url_prefix='/<lang>')

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

rawDescription: Optional URL variables

description: Optional URL variables


code:
import os
sys.path.append('relative/path/to/settings/file')
from django.conf import settings
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"

rawDescription: Access Django DB from Task

description: Access Django DB from Task


code:
import re
exp = '\$\d+(,|\.)?\d+'
s = '$1,000|hi,you|$45.43'
'|'.join(i.translate(None, '$,') if re.match(exp, i) else i for i in s.split('|'))

rawDescription: In Python how to strip dollar signs and commas from dollar related fields only


rawDescription: How to change radial ticks in julia PyPlot polar plot?

description: Change radial ticks in julia PyPlot polar plot


code:
def __contains__(self, obj):
    for item in self:
        if item == obj:
            return True

    return False

rawDescription: How do you investigate python's implementation of built-in methods?

description: Investigate python's implementation of built-in methods


code:
import MySQLdb.cursors
connection=MySQLdb.connect(
    host="thehost",user="theuser",
    passwd="thepassword",db="thedb",
    cursorclass = MySQLdb.cursors.SSCursor)
cursor=connection.cursor()
cursor.execute(query)
for row in cursor:
    print(row)

rawDescription: How to efficiently use MySQLDB SScursor?

description: Efficiently use MySQLDB SScursor


rawDescription: How can django sql queries use case insensitive and contains at the same time?


code:
from fabric.contrib.files import uncomment
uncomment("~/.bashrc", "^#force_color_prompt=yes", char='#')

rawDescription: How to write a Fabric script that uncomments a particular line of a user's .bashrc file?

description: Write a Fabric script that uncomments a particular line of a user's .bashrc file


code:
class GameScreen(Screen):

    # overwrite on_pre_enter method
    def on_pre_enter(self):
        self.add_widget(DiceMazeGame())

    # overwrite on_leave method - optional
    def on_leave(self):
        self.clear_widgets()

rawDescription: How to add a widget each time i enter game screen?

description: Add a widget each time i enter game screen


code:
from nltk import tokenize
p = "Good morning Dr. Adams. The patient is waiting for you in room number 3."
tokenize.sent_tokenize(p)

rawDescription: How to break up a paragraph by sentences in Python

description: Break up a paragraph by sentences in Python


code:
# -*- coding: utf-8 -*-

from __future__ import print_function
from functools import cmp_to_key
import collections
import urllib2
import json

def sort_it(obj=None, sort_order=None):
    """Sort a composite python object.

    :param obj: Python object
    :param sort_order: optional custom sort order
    :rtype: OrderedDict
    :returns: Sorted composite object.
    """

    # TODO: Refactor to use key rather than cmp (cmp is not supported in python3)
    # using cmp_to_key as transitional solution
    text_types = (basestring, int, float, complex)
    iterable_types = (list, tuple, set, frozenset)

    def cmp_func(a, b):
        """Function passed as `cmp` arg to sorted method

        Basic Algorithm
        - text_types take precedence over non text_types
        - Mapping types take precedence over iterable container types
        - Values of the same (or similar) type:
           - if sort_order is defined
              - if both keys are in sort order, the key index position determines precedence
              - if only one of the keys are in sort order then it takes precedence
              - if neither keys are in sort_order their lexicographic order is the determinant
           - otherwise, fall back to lexicographic ordering

        :param a: first arg passed to sorted's cmp arg
        :param b: second arg passed to sorted's cmp arg
        :rtype: int
        :return: int to determine which object (a/b) should take precedence
        """

        # ensure a and b are k/v pairs
        if not any([len(a) == 2, len(b) == 2]):
            return 0

        # text_types take precedence over non-text types
        elif isinstance(a[1], text_types) and not isinstance(b[1], text_types):
            return -1
        elif not isinstance(a[1], text_types) and isinstance(b[1], text_types):
            return 1

        # Mappings take precedence over iterable types
        elif isinstance(a[1], collections.Mapping) and isinstance(b[1], iterable_types):
            return -1
        elif isinstance(b[1], collections.Mapping) and isinstance(a[1], iterable_types):
            return 1

        # if type of values are of the same/similar type
        elif any([isinstance(a[1], text_types) and isinstance(b[1], text_types),
                  isinstance(a[1], iterable_types) and isinstance(b[1], iterable_types),
                  isinstance(a[1], collections.Mapping) and isinstance(b[1], collections.Mapping),
                  isinstance(a[1], type(b[1])),
                  ]):
            if sort_order:
                if any([a[0] in sort_order, b[0] in sort_order]):
                    if a[0] in sort_order and b[0] not in sort_order:
                        return -1
                    if b[0] in sort_order and a[0] not in sort_order:
                        return 1
                    if a[0] in sort_order and b[0] in sort_order:
                        if sort_order.index(a[0]) > sort_order.index(b[0]):
                            return 1
                        else:
                            return -1
            # no sort_order ( or keys not in sort_order) -- sort lexicographically
            if sorted([a[0].lower(), b[0].lower()]).index(a[0].lower()) == 0:
                return -1
            elif sorted([a[0].lower(), b[0].lower()]).index(a[0].lower()) == 1:
                return 1
        else:
            raise ValueError('Unhandled condition for values %s, %s' % (a, b))

    if isinstance(obj, collections.Mapping):
        return collections.OrderedDict(
            (key, sort_it(value, sort_order=sort_order)) for key, value in
            sorted(obj.items(), key=cmp_to_key(cmp_func)))
    elif isinstance(obj, iterable_types):
        return type(obj)([sort_it(value, sort_order=sort_order) for value in obj])
    else:
        return obj

sort_order = [
    'id',
    'rn',
    'dn',
    'vendor',
    'model',
    'serial',
    'name',
    'description',
    'tray'
    'presence'
]

sample_data_uri = 'https://bit.ly/1jOpQF2'

### EXAMPLE - Sans sort order

print(json.dumps(sort_it(json.loads(urllib2.urlopen(sample_data_uri).read())), indent=4))

### EXAMPLE - with sort_order

print(json.dumps(sort_it(json.loads(urllib2.urlopen(sample_data_uri).read()), sort_order=sort_order), indent=4))

rawDescription: python - complex sorting of nested data

description: Python - complex sorting of nested data


code:
import xlsxwriter
import random
wb = xlsxwriter.Workbook('page_breaks.xlsx')
ws = wb.add_worksheet('Sample page')

headers = ['header1', 'header2']
# set headers
for col, header in enumerate(headers):
    ws.write(0+1, col+1, 'header'+str(col))

# let it be 300 rows of data
for row in xrange(2,302):
    ws.write(row, 1, row)

# fill table with some random data
for _ in xrange(3000):
    row = random.randrange(2, 302)
    col = random.randrange(2, 16)
    ws.write(row, col, 'X')

# print_area(), set_paper() and fit_to_pages() do the trick
ws.print_area(1, 1, 301, 15)
ws.set_paper(9)  # set A4 as page format
pages_horz = 1
pages_vert = 4
ws.fit_to_pages(pages_horz, pages_vert)

wb.close()

rawDescription: Changing default page breaks in xls-file via Python module xlwt


code:
def main():
    inFile=open('3weightcalc.in','r')
    i=0
    for line in inFile.readlines():
        items=line.split()

        listEleVP=items[1]
        listEleVS=items[3]
        valP=float(listEleVP)
        valS=float(listEleVS)
        FinVal=float(valP*valS)
        txtA=items [0]
        txtB=items [2]
        print("On ",txtB,txtA,"would weigh ",FinVal,"pounds.")
    inFile.close()
main()

rawDescription: ValueError: could not convert string to float: 'r'


code:
from bs4 import BeautifulSoup

s=requests.Session()
headers = {'User-Agent': 'Mozilla/5.0'}

URL = 'http://test.dev/api/login'
s.get(URL)

soup = BeautifulSoup(s.get(URL).text)
csrf = soup.find(name="csrf")

rawDescription: Passing csrftoken with python Requests use input type hidden


code:
import networkx as nx
G = nx.Graph()
G.add_node(1,profit=17)
G.add_node(2,profit=42)
a = nx.get_node_attributes(G,'profit')
a.items()

rawDescription: How to get values from specific node attributes in NetworkX with Python

description: Get values from specific node attributes in NetworkX with Python


code:
import matplotlib.pyplot as plt

x = [0 ,1, 2]
y = [10 ,20, 30]

fig, axs = plt.subplots(2,1)

plt.axes(axs[0])
plt.plot(x,y)
plt.axes(axs[1])
plt.plot(y,x)
plt.show()

rawDescription: Setting active subplot using axes object in matplotlib?


rawDescription: Drawing lines between pairs in Python

description: Drawing lines between pairs in Python


code:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.example.com')
browser.find_element_by_name('username').send_keys('myusername')
browser.find_element_by_name('password').send_keys('mypassword')
browser.find_element_by_class_name('welcomeLoginButton').click()
cookies = browser.get_cookies()

rawDescription: Log in to a website with Python

description: Log in to a website with Python


code: lowest = min(alist, key=lambda o: len(o.attr_name))

rawDescription: find longest shortest attribute in a list of objects

description: Find longest shortest attribute in a list of objects


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

driver = webdriver.Firefox()
# Load some webpage
wait = WebDriverWait(driver, 10, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException])
element = wait.until(EC.element_to_be_clickable((By.XPATH, "//div")))

rawDescription: Java's FluentWait in Python

description: Java's FluentWait in Python


code: next(d for d in lst if d['name'] == 'jerry')

rawDescription: how to get the dictionary with a given value in a list of dictionary in python?

description: Get the dictionary with a given value in a list of dictionary in python


code:
class label_datetime(QtGui.QLabel):
    def __init__(self, parent=None):
        super(label_datetime,self).__init__(parent)
        qf = QtGui.QFont("Arial", 20)
        self.setFont(qf)
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.adjustSize()
        self.setStyleSheet('color: #d3d3d3; border:1px solid rgb(0, 255, 0)')
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.displaytime)
        timer.start(1000)
        self.show()

    def displaytime(self):
        tijd = QtCore.QDateTime.currentDateTime().toString()
        self.setText(QtCore.QDateTime.currentDateTime().toString())
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.adjustSize()

rawDescription: PyQT4 Datetime widget

description: PyQT4 Datetime widget


rawDescription: What are the coefficients of the end value for the Runge-Kutta 3 (RK3) method in python


code:
a = [{'key': 'value'} for _ in range(3)]
a
a[0]['key'] = 'poop'
a

rawDescription: Make List of Unique Objects in Python

description: Make List of Unique Objects in Python


code:
class PostUpdate(UpdateView):
    model = Post
    fields = ['title','body','page','category']
    template_name = 'post_update.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(PostUpdate, self).dispatch(*args, **kwargs)

    def get_object(self, *args, **kwargs):
        obj = super(PostUpdate, self).get_object(*args, **kwargs)
        if not obj.owner_user == self.request.user:
            raise Http404
        return obj

    def form_valid(self, form):
        form.instance.owner_user = self.request.user
        return super(PostUpdate, self).form_valid(form)

rawDescription: Django generic UpdateView. How to check credential


code:
import copy
tmp_keys = copy.copy(global_files)

rawDescription: Python dictionary value assignment from variable


code:
i = 0
while i < len(ml):
  if ml[i] == 2:
    ml.pop(i)
    continue
  i+=1

rawDescription: Can for-loop index depend on the varying length of a list?


code:
from OpenGL.GL import *
type(GL_COLOR_BUFFER_BIT)
int(GL_COLOR_BUFFER_BIT)
bin(GL_COLOR_BUFFER_BIT)
int(GL_DEPTH_BUFFER_BIT)
bin(GL_DEPTH_BUFFER_BIT)
int(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
bin(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

rawDescription: Python/PyOpenGL: Pipes

description: Python/PyOpenGL: Pipes


code:
class MainApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent = None):
        super(MainApp, self).__init__(parent)
        self.setupUi(self)

rawDescription: Pyside and Qt4 returning an empty window


code:
from tinymce.models import HTMLField

class MyModel(models.Model):
    text = HTMLField()

rawDescription: Using Rich Text Editor in Django admin with tinymice


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item, Field

class Product(Item):
    name = Field()

class siteSpider(CrawlSpider):
    name = "domain-name.com"
    allowed_domains = ['www.domain-name.com']
    start_urls = ["https://www.domain-name.com/en/"]
    rules = (
        Rule(SgmlLinkExtractor(allow=('\/en\/item\-[a-z0-9\-]+\-scrap\.html')), process_links='process_links', callback='parse_item', follow=True),
        Rule(SgmlLinkExtractor(allow=('')), process_links='process_links', follow=True),
    )

    def parse_item(self, response):
        x = HtmlXPathSelector(response)
        product = Product()
        product['name'] = ''
        name = x.select('//title/text()').extract()
        if type(name) is list:
            for s in name:
                if s != ' ' and s != '':
                    product['name'] = s
                    break
        return product

    def process_links(self,links):
        for i, w in enumerate(links):
            w.url = w.url.replace("../", "")
            links[i] = w
        return links

rawDescription: Avoid bad requests due to relative urls

description: Avoid bad requests due to relative urls


code:
import re

# compile regex
regex = re.compile('[0-9]+')

# open the files
with open('Corpus.txt','r') as inputFile:
    with open('OutputLineNumbers', 'w') as outputLineNumbers:
        # loop through each line in corpus
        for line_i, line in enumerate(inputFile, 1):
            # check if we have a regex match
            if regex.search( line ):
                # if so, write it the output file
                outputLineNumbers.write( "%d\n" % line_i )

rawDescription: How to extract lines numbers that match a regular expression in a text file

description: Extract lines numbers that match a regular expression in a text file


code:
# Save the existing list of warning filters before we modify it using simplefilter().
# Note: the '[:]' causes a copy of the list to be created. Without it, original_filter
# would alias the one and only 'real' list and then we'd have nothing to restore.
original_filters = warnings.filters[:]

# Ignore warnings.
warnings.simplefilter("ignore")

try:
    # Execute the code that presumably causes the warnings.
    fxn()

finally:
    # Restore the list of warning filters.
    warnings.filters = original_filters

rawDescription: Catching warnings pre-python 2.6

description: Catching warnings pre-python 2.6


code:
AVAILABLE_CHOICES = [('1','1'),('2','2')]
DEFAULT_CHOICES = []

class MyForm(Form):
    assigned = SelectMultipleField('Assigned', choices=DEFAULT_CHOICES)
    available = SelectMultipleField('Available', choices=AVAILABLE_CHOICES)

@app.view("/myview", methods=['GET','POST'])
def myview():
    form = MyForm(request.form)
    if request.method == 'POST':
        form.assigned.choices = AVAILABLE_CHOICES
        if form.validate():
            return render_template("success.html")
        else:
            form.assigned.choices = DEFAULT_CHOICES

    return render_template("index.html", form=form)

rawDescription: Flask + WTForms + SelectMultipleField and Dynamic Choices


code:
a = np.zeros((3,3,3)) # a 3x3x3 array of zeros
g = np.ones(3) # a row of 3 ones
a[:] = g
a

rawDescription: Numpy: copying an array to more dimensions


code:
from matplotlib import pyplot as pl
import numpy as np

x = np.linspace(0, 5, 10)
y = np.sin(x)
pl.plot(x, y, 'o')
pl.plot(x[:5], y[:5], 'g-')
pl.plot(x[5:], y[5:], 'g-')
pl.show()

rawDescription: Break the line in a line plot

description: Break the line in a line plot


code:
# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://cs.simpson.edu/?q=python_pygame_examples

import pygame

black = (0,0,0)
white = (255,255,255)
blue = (0,0,255)

# This class represents the bar at the bottom that the player controls
class Wall(pygame.sprite.Sprite):
    # Constructor function
    def __init__(self,x,y,width,height):
        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)

        # Make a blue wall, of the size specified in the parameters
        self.image = pygame.Surface([width, height])
        self.image.fill(blue)

        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.top = y
        self.rect.left = x

# This class represents the bar at the bottom that the player controls
class Player(pygame.sprite.Sprite):

    # Set speed vector
    change_x=0
    change_y=0

    # Constructor function
    def __init__(self,x,y):
        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)

        # Set height, width
        self.image = pygame.Surface([15, 15])
        self.image.fill(white)

        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.top = y
        self.rect.left = x

    # Change the speed of the player
    def changespeed(self,x,y):
        self.change_x+=x
        self.change_y+=y

    # Find a new position for the player
    def update(self,walls):
        # Get the old position, in case we need to go back to it
        old_x=self.rect.left
        new_x=old_x+self.change_x
        self.rect.left = new_x

        # Did this update cause us to hit a wall?
        collide = pygame.sprite.spritecollide(self, walls, False)
        if collide:
            # Whoops, hit a wall. Go back to the old position
            self.rect.left=old_x

        old_y=self.rect.top
        new_y=old_y+self.change_y
        self.rect.top = new_y

        # Did this update cause us to hit a wall?
        collide = pygame.sprite.spritecollide(self, walls, False)
        if collide:
            # Whoops, hit a wall. Go back to the old position
            self.rect.top=old_y

score = 0
# Call this function so the Pygame library can initialize itself
pygame.init()

# Create an 800x600 sized screen
screen = pygame.display.set_mode([800, 600])

# Set the title of the window
pygame.display.set_caption('Test')

# Create a surface we can draw on
background = pygame.Surface(screen.get_size())

# Used for converting color maps and such
background = background.convert()

# Fill the screen with a black background
background.fill(black)

# Create the player paddle object
player = Player( 50,50 )
movingsprites = pygame.sprite.RenderPlain()
movingsprites.add(player)

# Make the walls. (x_pos, y_pos, width, height)
wall_list=pygame.sprite.RenderPlain()
wall=Wall(0,0,10,600)
wall_list.add(wall)
wall=Wall(10,0,790,10)
wall_list.add(wall)
wall=Wall(10,200,100,10)
wall_list.add(wall)

clock = pygame.time.Clock()

done = False

while done == False:

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.changespeed(-3,0)
            if event.key == pygame.K_RIGHT:
                player.changespeed(3,0)
            if event.key == pygame.K_UP:
                player.changespeed(0,-3)
            if event.key == pygame.K_DOWN:
                player.changespeed(0,3)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.changespeed(3,0)
            if event.key == pygame.K_RIGHT:
                player.changespeed(-3,0)
            if event.key == pygame.K_UP:
                player.changespeed(0,3)
            if event.key == pygame.K_DOWN:
                player.changespeed(0,-3)

    player.update(wall_list)

    screen.fill(black)

    movingsprites.draw(screen)
    wall_list.draw(screen)
    pygame.display.flip()

    clock.tick(40)

pygame.quit()

rawDescription: PyGame get sprite group

description: PyGame get sprite group


code:
from flask import Response

@app.route('/image')
def generate_large_image():
    def generate():
        while True:
            if not processing_finished():
                yield ""
            else:
                yield get_image()
    return Response(generate(), mimetype='image/jpeg')

rawDescription: is there a way to partially return results from Python web service....?

description: Is there a way to partially return results from Python web service....


code:
class Bar(Foo):
    def __init__(self, *args, **kwargs):
        try:
            hello = kwargs.pop('hello')
        except KeyError:
            hello = False
        Foo.__init__(self, *args, **kwargs)

rawDescription: Named-only arguments when subclassing in Python


code:
mycal = icalendar.ics()
mycal.local_load("work.ics")
dates = mycal.get_event_instances(start,end)
#dates will contain the json with all explicit dates of the events spec'ed by the iCalendar file

rawDescription: Parse events from an .ics file in Python


code:
import seaborn as sns
sns.set_style("whitegrid")

sns.factorplot("month", "rainfall", row="temp", data=rain_record,
               size=2, aspect=5, kind="box", palette="PuBuGn_d")
sns.despine(left=True)

rawDescription: Box Plot Trellis

description: Box Plot Trellis


code:
import re
t1 = 'Hilary Clinton'
t2 = 'Clinton, Hilary'
re.search(r'(?:\s?Hilary()|\s?Clinton(),?){2}', t1)
re.search(r'(?:\s?Hilary()|\s?Clinton(),?){2}', t2)

rawDescription: Lucene or Python: Select both "Hilary Clinton" and "Clinton, Hilary" name entries


code: df.pivot_table(index=['place', 'X_UTM', 'Y_UTM'], aggfunc=lambda x: ','.join(x))

rawDescription: PANDAS merge content of multiple cells wrt to an index


code: pd.DataFrame({k: [tuple(v)] for k, v in employer.iteritems()})

rawDescription: Pandas DataFrame column from a tuple

description: Pandas DataFrame column from a tuple


code:
version.revision.revert()
sales = version.object.sales_set.all()
version.revision.revert()

rawDescription: django reversion - revert related field to the same version

description: Django reversion - revert related field to the same version


code: tag['onmouseover']

rawDescription: Python BeautifulSoup - get onmouseover attibutes


code:
# -*- coding: utf-8 -*-
# (or w/ever other coding you use for unicode literals;-)
import qt, sys
a=qt.QApplication(sys.argv)
w=qt.QPushButton(u"Olá Mundo", None)
w.show()
a.exec_loop()

rawDescription: Displaying other language characters in PyQt


code:
app = QtGui.QApplication(sys.argv)
QtGui.QFontDatabase.addApplicationFont('path/to/font')
# or load the font data directly
# QtGui.QFontDatabase.addApplicationFontFromData(fontdata)
stylesheet = open('mystylesheet.qss').read()
app.setStyleSheet(stylesheet)

rawDescription: How to use Non-Standard Custom Font with Stylesheets?

description: Use Non-Standard Custom Font with Stylesheets


code:
def reduced(word):
    ''' returns a list of reduced words or an empty list if no reduced words '''

    if word == 'a' or word == 'i':
        return list(word)

    words = list()

    for letter in range(len(word)):
        reduced_word = word[:letter] + word[letter + 1:]
        if reduced_word in word_list:
            words = reduced(reduced_word)
            if words:
                return [word] + words
    return words

rawDescription: exercise 12.4 from "think python", the script doesnt get to the end

description: Exercise 12.4 from "think python", the script doesnt get to the end


code:
from collections import OrderedDict
d = OrderedDict([('first', 1), ('second', 2),
                 ('third', 3)])
d.items()

rawDescription: Storing Python dictionary entries in the order they are pushed


rawDescription: Dictionary comprehension with lambda expression fails to produce desired result


code:
response = render(request, template, context)
response.set_cookie('my_cookie', 'my_cookie_value')
return response

rawDescription: Django: How to set a (permanent) cookie, in addition to temp session, in Class based views?


code:
from http.cookies import SimpleCookie

rawdata = 'Cookie: devicePixelRatio=1; ident=exists; __utma=13103r6942.2918; __utmc=13103656942; __utmz=13105942.1.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); mp_3cb27825a6612988r46d00tinct_id%22%3A%201752338%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fwww.pion_created_at%22%3A%20%222015-08-03%22%2C%22platform%22%3A%20%22web%22%2C%%22%3A%20%%22%7D; t_session=BAh7DUkiD3Nlc3NpbWVfZV9uYW1lBjsARkkiH1BhY2lmaWMgVGltZSAoVVMgJiBDYW5hZGEpBjsAVEkiFXNpZ25pbl9wZXJzb25faWQGOwBGaQMSvRpJIhRsYXN0X2xvZ2luX2RhdGUGOwBGVTogQWN0aXZlU3VwcG9ydDo6VGltZVdpdGhab25lWwhJdToJVGltZQ2T3RzAAABA7QY6CXpvbmVJIghVVEMGOwBUSSIfUGFjaWZpZWRfZGFzaGJvYXJkX21lc3NhZ2UGOwBGVA%3D%3D--6ce6ef4bd6bc1a469164b6740e7571c754b31cca'
cookie = SimpleCookie()
cookie.load(rawdata)

# Even though SimpleCookie is dictionary-like, it internally uses a Morsel object
# which is incompatible with requests. Manually construct a dictionary instead.
cookies = {}
for key, morsel in cookie.items():
    cookies[key] = morsel.value

rawDescription: Converting cookie string into Python dict


code:
class Torrent(ScrapedItem):
    pass

class MininovaSpider(CrawlSpider):
    domain_name = 'mininova.org'
    start_urls = ['http://www.mininova.org/today']
    rules = [Rule(RegexLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')]

    def parse_torrent(self, response):
        x = HtmlXPathSelector(response)
        torrent = Torrent()

        torrent.url = response.url
        torrent.name = x.x("//h1/text()").extract()
        torrent.description = x.x("//div[@id='description']").extract()
        torrent.size = x.x("//div[@id='info-left']/p[2]/text()[2]").extract()
        return [torrent]

rawDescription: What are the best prebuilt libraries for doing Web Crawling in Python


code:
main_list = []
for i in range(n):
  temp_list = []
  for j in range(n):
    temp_list.append(raw_input("Element {0}:{1}: ".format(i,j)))
  main_list.append(temp_list)

rawDescription: how to read user defined input for 2d array in python

description: Read user defined input for 2d array in python


code:
Topiccenter.objects.annotate(
    sum_books=Sum('tc_book_entries'),
    sum_journals=Sum('tc_journal_entries')
).extra({
    'select': {
        'sum_entries': 'sum_books + sum_journals'
    }
}).order_by('-sum_entries')

rawDescription: Django Count() multiple fields and sort by their sum


code:
if q.find("http://www.dlib.org") != -1:
    tree = etree.HTML(page.text)
    element = tree.xpath('./body/form/table[3]/tr/td/table[5]')
else:
    p = etree.XMLParser(remove_blank_text=True, resolve_entities=False)
    tree = etree.fromstring(page.content, p)
    element = tree.xpath('.//*[@id="content"]')
    cookies_alert = element[0].xpath('.//*[@id="cookiesAlert"]')
    for ca in cookies_alert:
        ca.getparent().remove(ca)

rawDescription: Python/HTML How to scrape webpage content without cookie advisor?


code:
def parse(self, response):
    keys = response.xpath('//div[2]/p/strong')
    for key in keys:
        yield {
            key.extract(): key.xpath('following-sibling::node()').extract()
        }

rawDescription: Scrapy: scrape key/value pairs from weird HTML markup


code:
container = context.unrestrictedTraverse('/media/news/2010')
item_ids = list(container.objectIds())
for image_id in ('image.jpg', 'image.gif', 'image.png'):
    if image_id in item_ids:
        return container._getOb(image_id).absolute_url()
raise ValueError('No image found')

rawDescription: Check in Zope if a Object / image is available / uploaded


code:
import os, sys
import Tkinter
from PIL import ImageTk, Image

main = Tkinter.Tk()

catalog1 = 'imgs'
catalog2 = 'newImgs'
file1 = 'n.png'
ima1 = os.path.join(catalog1, file1)
img_path = "%s/%s"%(catalog1,file1);
image_ob = ImageTk.PhotoImage(Image.open(img_path).rotate(270))
Tkinter.Label(main,text="",image=image_ob).pack()

main.mainloop()

rawDescription: how to display an inverted image on the screen?

description: Display an inverted image on the screen


code:
text_file = 'Hello.txt'
search_key = 'Hello'
out_file = 'charlie_%d.txt'
current_file = None
occurrence = 0

with open(text_file, 'r') as input_file:
    try:
        for src_line in input_file:
            if search_key in src_line:
                # searched text is found, writing to file
                occurrence += 1
                if current_file:
                    current_file.close()
                current_file = open(out_file % occurrence, 'w')
                current_file.write("============================================ \n")
                current_file.write(src_line)
            elif current_file:
                # no searched text, write line to already open file
                current_file.write(src_line)
    finally:
        if current_file:
            current_file.close()

rawDescription: Assigning incremental file names

description: Assigning incremental file names


code:
L = [1, 2, 3, 4]
M = [5, 6, 7, 8, 9]
L.append(M)    # Takes the list M as a whole object
               # and puts it at the end of L
L
L = [1, 2, 3, 4]
L.extend(M)    # Takes each element of M and adds
               # them one by one to the end of L
L

rawDescription: Appending to a Python list without making list of lists


code:
from rpy2 import *
import rpy2.robjects as RO

RO.r('library(forecast)')

# use example WWWusage data
RO.r('fit <- auto.arima(WWWusage)')

rawDescription: How the function auto.arima() in R determines d?


code:
df
df.T

rawDescription: Invert index and columns in a pandas DataFrame


code:
class ItemAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(ItemAdmin, self).get_queryset(request)
        return qs.filter(status='pending')

rawDescription: Django admin, show only needed models

description: Django admin, show only needed models


code:
import os
tmp = os.popen("tasklist").read()  # it would return a str type
"python.exe" in tmp

rawDescription: How to know whether a process in windows is running or not in python

description: Know whether a process in windows is running or not in python


rawDescription: Convert STDOUT hex output to string in Python


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

rawDescription: How do I upload a large file without blocking my webserver? Using python and Amazon Beanstalk/EC2

description: Upload a large file without blocking my webserver? Using python and Amazon Beanstalk/EC2


code:
import re, requests, logging, os, time, json
from bs4 import BeautifulSoup as bs

class Crawler(object):
    logger = logging.getLogger("crawler_logger")
    logger.setLevel(logging.DEBUG)
    file_handler = logging.FileHandler(os.getcwd()+"/logs/{}.log".format( str(int(round(time.time()*1000))) ))
    file_handler.setLevel(logging.DEBUG)
    terminal_handler = logging.StreamHandler()
    terminal_handler.setLevel(logging.INFO)
    log_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    file_handler.setFormatter(log_format)
    terminal_handler.setFormatter(log_format)
    logger.addHandler(terminal_handler)
    logger.addHandler(file_handler)

    def __init__(self, *args):
        self.logger.info("Initializing Crawler object on '{}' domain with {} urls.".format(args[0], str(args)))
        self.domain = args[0]
        self.urls = list(args)
        self.crawled = []
        self.limit = [0, 0]
        self.dump_file = "urls.json"

    def crawl(self):
        # while urls in self.urls
        while self.urls:
            if self.limit[0] != 0:
                if self.limit[0] == self.limit[1]:
                    self.logger.info("Limit reached, writing to file and returns.")
                    with open(self.dump_file, "w") as dump_file:
                        dump_file.write(json.dumps(self.urls))
                    return

            try:
                self.logger.info("Connecting to {}...".format(self.urls[0]))
                response = requests.get(self.urls[0])
                response.encoding = "utf-8"
                self.logger.info("Analyzing to structures...")
                soup = bs(response.text, "html.parser")
                links = soup.find_all("a", {"href" : re.compile("^/")})
                hrefs = [x.attrs["href"] for x in links]
                self.logger.info("Links are checked if they are crawled...")
                for href in hrefs:
                    if self.domain[0:-1]+href in self.crawled:
                        self.logger.warn("{} already crawled.".format(str(href)))
                        pass
                    else: self.urls.append(self.domain[0:-1]+href)
                self.crawled.append(self.urls[0])
                # Remove first url from reversed self.urls list
                self.urls[::-1].pop()
                self.limit[1]+=1
                self.logger.info("Reached count {}/{}".format(str(self.limit[1]), str(self.limit[0])))
            except Exception as e:
                self.logger.error("Crawling function raised an error, passing: {}".format(str(e)))

        if len(self.urls) == 0:
            self.logger.info("No url left to crawl, returns.")
            with open(self.dump_file, "w+") as dump_file:
                dump_file.write(json.dumps(self.urls))
            return

if __name__ == "__main__":
    mycrawler = Crawler("http://metasozluk.com/")
    mycrawler.limit[0] = 5
    mycrawler.crawl()

rawDescription: My Own Crawler Does Not Work If I Change The Attribute


code:
variables = {}
for i in xrange(0, 7):
    variables['result%s' % i] = [1000 + i]
variables
variables['result2']
variables['result6']

rawDescription: Dynamic array name

description: Dynamic array name


code:
def parse(row):
   bytestring = row[0]
   json_data = convert_bytes_and_parse_json(bytestring)
   return [ json_data["mycolumn1"], json_data["mycolumn2"] ]

parsedRDD = dataframe.rdd.map(parse)
parsedDf = sql_context.createDataframe(parsedRDD, ["mycolumn1", "mycolumn2"])

# now you can access columns by name
parsedDf.select(parsedDf["mycolumn1"])

rawDescription: Memsql::Streamliner Python Transform

description: Memsql::Streamliner Python Transform


code:
class Athlete:
    def __init__(self, strength, skill, weight):
        self.strength = strength
        self.skill = skill
        self.weight = weight
    def anAthleteMethod(self):
        pass

class Runner(Athlete):
    def __init__(self, strenght, skill, weight, specialty):
        super(Athlete, self, strenght, skill, weight)
        self.specialty = specialty
    def run(self):
        pass

rawDescription: Does a class have to be an object, can it be an action?


code: return '%s/%s/%s' % ('//example.blob.core.windows.net', 'mypictures', name)

rawDescription: Accessing user uri scheme in models.py in Django web app


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

with open('text_file.txt') as input_file:
    csv_data = []

    for row in csv.reader(input_file, delimiter=','):
        csv_data += [[row[0], int(row[1].strip()) + 10]]

    convert_to_csv = True

    if convert_to_csv:
        with open('input.csv', 'w') as output_file:
            csv_file = csv.writer(output_file, delimiter=',')
            csv_file.writerow(['Text', 'Count'])

            for row in csv_data:
                csv_file.writerow(row)

rawDescription: CSV calculation with Python. Get data from list


code:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)      # pandas series works too
y = np.random.rand(N)
colors = np.random.rand(N)
circle = 100* np.ones(50)
plt.scatter(x, y, c=colors, s=circle, alpha=0.6)
plt.show()

rawDescription: Change color of scatter point w.r.t a feature


code:
db.checks_reports_data_df8.aggregate([
        {
                '$match' :
                    {
                        "report_id": str(report["_id"])
                    }
        },
        {
            '$group' :
                {
                    '_id': '$report_id',
                    count_success :{'$sum': '$success'},
                    count_is_listed:{'$sum':'$is_listed'}
                }
        }
])

rawDescription: Count multiple fields in MongoDB using python


code:
import itertools
from collections import defaultdict

words = defaultdict(list)
with open('/usr/share/dict/words') as qfile:
    for word in qfile:
        word = word.rstrip('\n').lower()
        words[''.join(sorted(word))].append(word)

def longest_anagram(term, words):
    search_length = len(term)
    term = sorted(term) # combinations maintains sort order
    while search_length > 0:
        for combo in itertools.combinations(term, search_length):
            search = ''.join(combo) # sort above means we dont need it here
            if search in words:
                return words[search]
        search_length -= 1
    return None

found = longest_anagram('qugteroda', words)
for w in found:
    print(w)

rawDescription: How can I find the longest word in a text file?

description: Find the longest word in a text file


code:
import time
start = time.time()
# do something you want to time
elapsed = time.time() - start

rawDescription: Is it possible to measure packet rate with libpcap?


rawDescription: python select specific elements from a list

description: Python select specific elements from a list


code: new_list = [(x, my_function(y)) for x, y in my_list]

rawDescription: Altering tuples within a list - is this the best way?


code:
import pylab as pl
import numpy as np

x, y = np.mgrid[-10:10:100j, -10:50:100j]
z1 = - 12.8 * x - 0.108 * y + x * y + 1.3824
z2 = - 40 * x - 5 * y + x * y + 200
z3 = - 40 * x - 0.108 * y + x * y + 4.32
z4 = - 12.8 * x - 5 * y + x * y + 64

fig, axes = pl.subplots(2, 2, figsize=(12, 8))
axes = axes.ravel()
axes[0].contourf(x, y, z1, levels=[0, 1e10], alpha=0.2, colors=["blue"])
axes[1].contourf(x, y, z2, levels=[0, 1e10], alpha=0.2, colors=["green"])
axes[2].contourf(x, y, z3, levels=[-1e10, 0], alpha=0.2, colors=["red"])
axes[3].contourf(x, y, z4, levels=[-1e10, 0], alpha=0.2, colors=["yellow"])

rawDescription: Plot graph with 4 equations consist of f(x,y, xy)


code:
name, args = re.match(r'(\w+)\((.*)\)', 'function_name(foo=<str>, bar=<array>, baz=<int>)').groups()
args = [re.match(r'(\w+)=<(\w+)>', arg).groups() for arg in args.split(', ')]
name, args

rawDescription: Regex question about parsing method signature


code:
class Sale(models.Model):
    car = models.ForeignKey(settings.MODELO_AUTO)
    amount = models.FloatField()
    ...

    def save(self, *args, **kwargs):
        self.amount = self.car.price
        super(Sale, self).save(*args, **kwargs)

rawDescription: How can I access the value of ForeignKey inside the model definions ? Django 1.8

description: Access the value of ForeignKey inside the model definions ? Django 1.8


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

np.random.seed(123)
x, y = np.random.uniform(size=(100, 2)).T
z = np.exp(-x**2 - y**2)
levels = np.linspace(0, 1, 100)

cnt = plt.tricontourf(x, y, z, levels=levels, cmap="ocean")

# This is the fix for the white lines between contour levels
for c in cnt.collections:
    c.set_edgecolor("face")

plt.savefig("test.pdf")

rawDescription: Hide contour linestroke on pyplot.contourf to get only fills


rawDescription: python 3 convert list slice into string

description: Python 3 convert list slice into string


code:
import decimal
D = decimal.Decimal
cent = D('0.01')

x = D('39.142')
print(x.quantize(cent,rounding=decimal.ROUND_UP))
# 39.15

rawDescription: rounding float up $.01 in python

description: Rounding float up $.01 in python


code:
my_gui = GUI()
my_gui.Dataset()
my_gui.LoadImages()

rawDescription: Getting user input in one function of the class and using it in another in Python


code:
from geopy.distance import vincenty
this_country = (latitude, longitude)
radius = 10  # 10 miles

while radius >= 0:
    other_country_within_circle_found = False
    # other_countries is a list of tuples which are lat & long
    # positions of other country eg. (-12.3456, 78.91011)
    for other_country in other_countries:
        # note: other_country = (latitude, longitude)
        if other_country == this_country:
            continue  # skip if other country is the same as this country.
        distance = vincenty(this_country, other_country).miles
        if distance <= radius:
            other_country_within_circle_found = True
            break
    if not other_country_within_circle_found:
        # the circle of this radius, have no other countries inside it.
        break
    radius -= 1  # reduce the circle radius by 1 mile.

rawDescription: Going through latitude and longitude of a country


code:
def is_latin_9(c):
    try:
        c.encode('iso-8859-15')
        return True
    except UnicodeEncodeError:
        return False

def replace_non_latin_9(s):
    return ''.join(c if is_latin_9(c) else u'\ufffd' for c in s)

rawDescription: Replace characters outside a given charset with U+FFFD?


rawDescription: Modifying x tick label for date in Python


code:
unique_indices = np.setdiff1d(np.unioin1d(old_close.index.to_list(), new_close.index.to_list()),
                              np.intersect1d(old_close.index.to_list(), new_close.index.to_list()))
merged_close = pd.concat([old_close, new_close]).ix[unique_indices]

rawDescription: Concatenating pandas dataframes along time series index without duplicating columns