code:
import os

dir = "myDirectory"
extList = ['ext1', 'ext2', 'ext3']
allfiles = os.listdir(dir) # all files in that directory

myfiles = [] # will be appended to to only contain files with extensiosn matching extlist
for file in allfiles:
    parts = file.split('.') # split the filename based on .
    if parts[-1] in extensionlist:
        myfiles.append(file)

if len(myfiles) == len(allfiles):
    for file in myfiles:
        path = "%s/%s" % (dir, file)
        os.remove(path)
        os.remove(file)

rawDescription: Delete files of given types IFF there are no other file types in folder


code: os.system('pdv -t %s > 123.txt' % epoch_name)

rawDescription: writing terminal output to file

description: Writing terminal output to file


code:
x = np.linspace(0,5,100)
y = np.sin(2*np.pi*x)

## fourier transform
f = np.fft.fft(y)
## sample frequencies
freq = np.fft.fftfreq(len(y), d=x[1]-x[0])
plt.plot(freq, abs(f)**2) ## will show a peak at a frequency of 1 as it should.

rawDescription: Fourier Transform in Python

description: Fourier Transform in Python


rawDescription: Pandas read_html() converts numbers in table to string


code: vars = list(set(permutations(vars)))

rawDescription: Why is this function not giving consistent output?


code:
rs = sql.with_query_result("""
    select distinct on (_timestamp::date)
        _timestamp::date, id
    from
        record
        inner  join
        unnest(:current_date::timestamp[]) d(_timestamp) on
            utc_dates @> _timestamp
            or
            extract(isodow from _timestamp) = any(day_ids)
            or
            "type" = 'default'
    order by 1, priority desc
    """,
    {
        'current_date':
        rrule.rrule(rrule.DAILY, dtstart=start_date, until=end_date)
    }
)

ids = {}

for (current_date, id) in rs:
    ids[current_date] = id

rawDescription: PostgreSQL: Construct a Query That Takes a Date Range


code:
class BlogIndexView(BlogBaseView, ListView):
    queryset = Post.objects.all().order_by('-date_create')
    template_name = 'index_blog.html'
    context_object_name  = 'posts'

    def get_context_data(self, **kwargs):
        # use the (super) force Luke
        context = super(BlogIndexView, self).get_context_data(**kwargs)
        if self.request.GET.get('tag'):
            context['posts'] = Post.objects.filter(tags__name__in=[self.request.GET.get('tag')])
        return context

rawDescription: How can I return regular response in override get method, Django

description: Return regular response in override get method, Django


rawDescription: How to query filter in django without multiple occurrences

description: Query filter in django without multiple occurrences


code: ps,rs,fs,ss = precision_recall_fscore_support(dataGT.T, dataOUT.T)

rawDescription: How do I use sklearn.metrics to compute micro/macro measures for multilabel classification task?

description: Use sklearn.metrics to compute micro/macro measures for multilabel classification task


code:
soup = BeautifulSoup(html)
projects =[]
table = soup.find('table', class_='objects_items_list')
for row in table.find_all('tr'):
    internal_id = row.get('id')
    if internal_id is not None:
        print( internal_id )

rawDescription: How to replace or delete None at parser(python)

description: Replace or delete None at parser(python)


code:
class GenericThread(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.stopFlag = False

    def stop(self):
        self.stopFlag = True

    def __del__(self):
        self.quit()
        self.wait()

    def run(self):
        #Some very long stuff
            if self.stopFlag:
                self.stopFlag = False #Resetting the flag (in my case I have to do this!)
                break #Breaks main loop to finish 'run()'
            else:
                self.emit( QtCore.SIGNAL('itemSelectionChanged()'))

class MainUI(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_Win()
        self.ui.setupUi(self)

        self.genericThread = GenericThread(self, listIndex=2)
        self.connect(self.genericThread, QtCore.SIGNAL("fillListWithItems(QString, int)"), self.fillListWithItems )
        self.ui.List1.list1SelectedItem.connect(self.fill_List2)
        ...

    def fill_List2(self):
        if self.genericThread.isRunning():
            self.genericThread.stop()
        self.ui.List2.clear()
        list1SelectedItem = str(self.ui.List1.currentItem().text())
        self.genericThread.start()

rawDescription: Cannot terminate PyQT QThread

description: Cannot terminate PyQT QThread


code:
def repeat(string, length):
  L = len(string)
  return string * (length // L) + string[:length % L]

rawDescription: Optimization: Python String Repetition

description: Optimization: Python String Repetition


code:
import matplotlib.dates as mdates
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import datetime as dt
import sys

def main( datafile ):
    np_rec_array = mlab.csv2rec( datafile, delimiter='\t' )
    np_rec_array.sort() # in-place sort
    # a `figure` is a starting point for MPL visualizations
    fig = plt.figure( figsize=(8,6) )
    # add a set of `axes` to above `figure`
    ax = fig.add_subplot(111)
    x = np_rec_array.visit_time
    y = np_rec_array.total_visits
    # `plot_date` is like `plot` but allows for easier x-axis formatting
    ax.plot_date(x, y, 'o-', color='g')
    # show time every 30 minutes
    ax.xaxis.set_major_locator( mdates.MinuteLocator(interval=30) )
    # specify time format
    ax.xaxis.set_major_formatter( mdates.DateFormatter("%H:%M") )
    # set x-axis label rotation (otherwise they can overlap)
    for l in ax.get_xticklabels():
        l.set_rotation(60)
    plt.title( 'Website Visits' )
    plt.show()

if __name__ == '__main__':
    if len( sys.argv ) == 1:
        sys.stderr.write( 'need a filename, exiting...' )
        sys.exit(-1)
    main( sys.argv[1] )

rawDescription: How can one plot time-related information with python in a natural human-readable way?


rawDescription: Python "safe" eval (string to bool/int/float/None/string)


code:
all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd', 'a'], 2))
all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd'], 2))

rawDescription: Python: determining whether any item in sequence is equal to any other


code: self.assertTrue(998 <= my_integer <= 1000)

rawDescription: Assert an integer is within range

description: Assert an integer is within range


rawDescription: Convert a string list to a true list in python


code:
from flask import Flask, g, abort, jsonify, request
from v1.entries import access as entry_access

app = Flask(__name__)

# load the endpoints
PRE = "/v1.0/<lang_code>"
app.register_blueprint(entry_access.entries, url_prefix=PRE+"/entries")

@app.before_request
def verify_language():
    # check if there are any parameters in the url and get lang_code
    url_params = request.view_args
    lang = (url_params and url_params.pop('lang_code', None)) or None
    # if lang_code is given, make sure it is valid
    if lang:
        LANG = ["eng-code", "swe-code"]
        if lang in LANG or lang == "global":
            # set globally to provide access for all views
            g.lang = lang
        else:
            return jsonify({"error": "Invalid Parameters (lang_code)"})

rawDescription: API with Flask: hand parameter to blueprint based on URL (enforce url parameter for EVERY view)


rawDescription: Summing first 2 elements in a Python list when the length of the list is unknown


code:
import base64
import numpy as np

t = np.arange(25, dtype=np.float64)
s = base64.b64encode(t)
r = base64.decodestring(s)
q = np.frombuffer(r, dtype=np.float64)

print(np.allclose(q, t))
# True

rawDescription: Numpy Array to base64 and back to Numpy Array - Python


code:
df = DataFrame(np.random.randn(10,5))
df.to_hdf('test.h5','df',mode='w',format='table')
store = pd.HDFStore('test.h5')
store
nrows = store.get_storer('df').nrows
nrows
store.select('df',start=nrows-1,stop=nrows)
store.close()

rawDescription: Pandas HDFStore - Get Last Record from Multiple Tables


code:
element = pylab.plot(range(100))
pylab.legend([element],[ "first line \n second line"])

rawDescription: PyLab title/legend labels with multiple line of text


code:
a = np.array([[1, 2, 10],[1, 2, 99]])
scipy.stats.rankdata(a,'dense').reshape(a.shape)-1

rawDescription: change numpy array to start from zero

description: Change numpy array to start from zero


code:
words = response.xpath("//table[@id='pagecolumns_0_columncontent_0__rptLetter_ctl00__dlTerms']//td")

for word in words:
    item = PetroleoItem()

    if word.xpath("./a/em").extract():
        item['title'] = word.xpath("./a/em/text()").extract()[0]
        item['title'] += word.xpath("./a/sub/text()").extract()[0]

    if word.xpath("./a/i").extract():
        item['title'] = {'en': word.xpath("./a/i/text()").extract()}
        item['title']['en'][0] += word.xpath("./a/i/sub/text()").extract()[0]

    if word.xpath("./a/text()").extract():
        item['title'] = {'en': word.xpath("./a/text()").extract()}

    yield item

rawDescription: Why all my items on scrapy are the same?

description: Why all my items on scrapy are the same


code: df3 = pd.concat([df1, df2], join='inner')

rawDescription: Python Pandas drop columns not found in both dataframes


code:
import pandas as pd
def collect_to_set(grp):                               # 3
    return set.union(*[set(row.split()) for row in grp['Address']])

data = pd.read_table('data', sep='\s{2,}')             # 1
result = data.groupby(['Area']).apply(collect_to_set)  # 2
print(result)                                          # 4
# Area
# mahadevapura         set([ballet, outer, road, ring, d1001, akme])
# vasanth nagar            set([cant, station, railway, cantonment])
# whitefield       set([hotel,room, sap, fortune, villa, no, oppo...
# dtype: object

print(result.to_dict())                                # 5
# {'vasanth nagar': set(['cant', 'station', 'railway', 'cantonment']),
# 'mahadevapura': set(['ballet', 'outer', 'road', 'ring', 'd1001', 'akme']),
# 'whitefield': set(['hotel,room', 'sap', 'fortune', 'villa', 'no', 'opposite',
# 'palm', 'labs,', '4112', 'medose', '106/107'])}

rawDescription: Grouping different addresses according to Areas ,Python


rawDescription: Getting original list from string of list python


code: pandas.DataFrame({"A": 'City', "B": d['City']})

rawDescription: Pandas Dataframe from Dict key and list of values to have same key for multiple rows


code:
from heapq import nlargest
items = [100, 300, 200, 400]
indexes = [0, 1, 2, 3]
nlargest(2, indexes, key=lambda i: items[i])

rawDescription: Index of nth biggest item in Python list


code:
import logging

class MyFormatter(logging.Formatter):
    width = 24
    datefmt='%Y-%m-%d %H:%M:%S'

    def format(self, record):
       record.message = record.getMessage()
       s = "%s :: %-10s :: %s" % (self.formatTime(record, self.datefmt), "[" + record.levelname + "]", record.getMessage())
       if record.exc_info:
         # Cache the traceback text to avoid converting it multiple times
         # (it's constant anyway)
         if not record.exc_text:
            record.exc_text = self.formatException(record.exc_info)
       if record.exc_text:
         if s[-1:] != "\n":
            s = s + "\n"
         s = s + record.exc_text
       return s

logger = logging.getLogger('simple_example')
#logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = MyFormatter()
ch.setFormatter(formatter)
logger.addHandler(ch)

logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

rawDescription: How to add alignment to python standart logger if I use [LOGLEVEL]?

description: Add alignment to python standart logger if I use [LOGLEVEL]


code: possible = range(1, 101)

rawDescription: Auto Increment While Building list in Python


code:
import os
filename, extn = os.path.splitext(kid.image_url)
thumb_filename = filename + ".thumb" + extn

rawDescription: Modify image extension to use later

description: Modify image extension to use later


code:
import subprocess

def callback(self, widget, date=None):
    cmd = "Your command here"
    other_process = subprocess.Popen(cmd, shell=True)

rawDescription: How to run a standalone application from the current one?

description: Run a standalone application from the current one


code:
u = {'flavor': {'version': u'X', 'name': 'MacOS'}, 'dist': {'version': u'AppleCoreMedia/1.0.0.8C148', 'name': 'iPad'}}
terminal = u['dist']['name']
terminal

rawDescription: how to select an item in multiple dictionaries, python

description: Select an item in multiple dictionaries, python


code:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from pandas.tools.plotting import bootstrap_plot
from pandas.tools.plotting import scatter_matrix
from pandas import *

range_days = 10
ydate = "2014-09-09"
wdate = "2014-08-31"

c_data = [1,3,3,2,3,2,1,6,7,9]
p_data = [0,5,6,11,3,2,1,1,3,4]
d_data = [1,7,3,8,3,2,1,3,2,3]

d = {"C":Series(c_data, index=date_range(wdate, periods=range_days)),"P": Series(p_data, index=date_range(wdate, periods=range_days)),"D":Series(d_data, index=date_range(wdate, periods=range_days))}
d2 = {"C":d["C"], "P":d["P"]}

ts2 = DataFrame(d2, index=date_range(wdate, periods=range_days))
ts = DataFrame(d, index=date_range(wdate, periods=range_days))

pdf_name = "Metrics_" + str(wdate) + "_to_" + str(ydate)+ ".pdf"
pdf = PdfPages(pdf_name)

#P & C over time
ts2.plot(secondary_y=["P"])
pdf.savefig()

#Density Plot of Conversion
plt.figure()
d["C"].plot(kind="kde")
pdf.savefig()

#scatter matrix on the data_frame
scatter_matrix(ts, alpha=0.2, figsize=(6, 6), diagonal='kde')
pdf.savefig()

pdf.close()

rawDescription: Errors writing multiple figures to a .pdf


code:
import tkinter

######################
def fileOpen(event):
######################
    print('qwerty')

def makeMenu(parent):
    top = tkinter.Menu(parent)
    parent.config(menu = top)

    file = tkinter.Menu(top, tearoff = False)
    file.add_command(label = 'Open...', command = fileOpen, accelerator = 'ctrl+o')
    top.add_cascade(label = 'File', menu = file)

root = tkinter.Tk()

############################################
root.bind_all('<Control-Key-o>', fileOpen)
############################################

makeMenu(root)

root.mainloop()

rawDescription: how to assign hotkeys?

description: Assign hotkeys


code:
class ClinicalDataForm(forms.ModelForm):
    class Meta:
        model = ClinicalData

    def __init__(self, *args, **kwargs):
        super(ClinicalDataForm, self).__init__(*args, **kwargs)
        approved = self.fields['approved']
        approved.widget = forms.RadioSelect(
            choices=approved.widget.choices)
        approved.initial = '1'

rawDescription: Django: Display NullBooleanField as Radio and default to None


rawDescription: How to group pandas DataFrame entries by date in a non-unique column

description: Group pandas DataFrame entries by date in a non-unique column


rawDescription: Oneline population of dictionary from array in Python


code: globals()['clean']()

rawDescription: How can I resolve a name clash between a defined function and a parameter in another function?

description: Resolve a name clash between a defined function and a parameter in another function


code:
apiResponse =  ApiResponse(
    a = jsonResponse.get('foo', {}).get('bar', {}).get('a', None),
    b = jsonResponse.get('bar', {}).get('foo', {}).get('b', None)
)

rawDescription: What is the pythonic way to handle accessing json values without knowing whether an index exists?


code:
mapper(
    User, t_users,
    properties={
        'followers': relation(
            User,
            secondary=t_follows,
            primaryjoin=(t_follows.c.followee_id==t_users.c.id),
            secondaryjoin=(t_follows.c.follower_id==t_users.c.id),
        ),
        'followees': relation(
            User,
            secondary=t_follows,
            primaryjoin=(t_follows.c.follower_id==t_users.c.id),
            secondaryjoin=(t_follows.c.followee_id==t_users.c.id),
        ),
    },
)

rawDescription: SQLAlchemy Many-to-Many Relationship on a Single Table


rawDescription: Python semantics for unicode ranges involving astral planes


code:
driver = webdriver.Firefox()
driver.get("http://somewebpage.example")
time.sleep(5)

while True:
    try:
        # Edit this to how you're currently scrolling
        driver.execute_script("window.scrollBy(0, 150);")
        button = driver.find_element(By.XPATH, YOUR_BUTTON_XPATH)
        button.click()
        break
    except WebDriverException:
        driver.execute_script("window.scrollBy(0, -100);")
        time.sleep(2)

rawDescription: Selenium is misclicking

description: Selenium is misclicking


code:
argsneeded = ['foo', 'bar']
def whatever(**kwargs):
    if not all(x in kwargs for x in argsneeded):
        raise ValueError('required kwarg is missing')

rawDescription: Python: How to get names of arguments in a list in a lambda?


code:
# let publication be your existing Pets publication instance
cats_tag, created = Tag.objects.get_or_create(title='cats')
publication.tags.add(cats_tag)

rawDescription: How to Update a Many-Many Field in Django

description: Update a Many-Many Field in Django


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

fig = plt.figure()
ax = fig.gca(projection='3d')

# plotting the points
pts = [(0,0,0),(1,0,0),(0,2,0),(0,0,3)]
for p in pts:
    ax.scatter(p[0], p[1], p[2], zdir='z', c='r')

# plotting lines for each point pair
for a, b in itertools.product(pts, pts):
    x = np.linspace(a[0], b[0], 100)
    y = np.linspace(a[1], b[1], 100)
    z = np.linspace(a[2], b[2], 100)
    ax.plot(x, y, z)

ax.legend()
ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 2)
ax.set_zlim3d(0, 3)

plt.show()

rawDescription: Plotting a list of 3D points in SymPy

description: Plotting a list of 3D points in SymPy


code:
p = []
for i in points:
   ...
   p.append(n)
p = np.array(p)

rawDescription: Appending np.arrays to a blank array in Python


code:
from functools import partial

list_f = [partial(f, i=i) for i in range(0, num_cons)]

rawDescription: Build dynamic list of parameterized functions in python


code: #!/usr/bin/env python

rawDescription: How to execute Python file

description: Execute Python file


code:
a = Type_1(1,2,3,4,5)  # making an instance of Type_1
b = Type_2(1,2,3,4,5)  # making an instance of Type_2
a.push(b)   # pushing one to another
b.variable2  # it worked!
a.variable1 # it worked!

rawDescription: Python multi-class functions

description: Python multi-class functions


code:
urlpatterns = patterns("myapp.views",
    url(r'^$', 'index',dict(template_name = 'myapp/index.html'), name = 'home'),
    url(r'^kick-ass-chart/$', 'render_chart', name='myapp_render_chart'),
)

rawDescription: writing urlpattern in django for rendering an image

description: Writing urlpattern in django for rendering an image


code:
from collections import defaultdict
type_dict = defaultdict(list)
for element in self.elements:
    type_dict[element.type()].append(element.dimStr())
return ','.join('%s: %s' for k, v in type_dict.items())

rawDescription: How to use duck typing effectively with inheritance

description: Use duck typing effectively with inheritance


code:
def download(request):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=UserData.csv'
    writer = csv.writer(response)
    writer.writerow(['Date', 'HighBGL', 'LowBGL', 'Weight', 'Height'])
    query = DailyVital.objects.filter(user=request.user)
    for row in query.values_list('entered_at', 'high_BGL', 'low_BGL', 'weight', 'height'):
       writer.writerow(row)
    return response

rawDescription: How would I write a CSV file populated with my sqlite3 db?


code:
try:
    from msvcrt import kbhit
except ImportError:
    import termios, fcntl, sys, os
    def kbhit():
        fd = sys.stdin.fileno()
        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)
        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
        try:
            while True:
                try:
                    c = sys.stdin.read(1)
                    return True
                except IOError:
                    return False
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

rawDescription: Python cross-platform listening for keypresses?


code:
# First read content into an array
# Each item in the array will be a line of the file
with open('filename.txt') as f:
    content = f.readlines()

# Next, parse each line
data = []
for line in content:
    # You might need to split by spaces
    # This takes care of multiple whitespaces, so "data1   data2 data3    data4"
    # Becomes ['data1','data2','data3','data4']
    row = line.split()
    # Or, maybe you will need to split the row up by tabs into an array
    # [] is a list comprehension, strip() will remove extra whitespace
    row = [item.strip() for item in line.split('\t')]
    # Finally, append the row to your data array
    data.append(row)

# Now, print the data back to a file how you'd like
fout = open('output.txt','w')
for row in data:
   # For specific columns
   fout.write('{0} {1} {2} {3}'.format(row[0],row[1],row[7],row[8]))
   # Or, if you just need to remove a couple columns, you might do:
   row.pop(6)
   row.pop(5)
   row.pop(4)
   fout.write(' '.join(row))

rawDescription: Extracting only interesting columns from ASCII table


code:
items = [
    ["Username1","id3"],
    ["Username1", "id4"],
    ["Username1", "id4"],
    ["Username3", "id3"]
]

data = {}
for item in items:
    if data.has_key(item[1]):
        data[item[1]].add(item[0])
    else:
        data[item[1]] = set([item[0]])
print(data)

rawDescription: Python Group Array by Column and Display Unique Values


code:
class SoftwareHelp(Help):
    about_software = models.ForeignKey('Software')

    def save(self, *args, **kwargs):
        self.about_software = 'Help for %s' % self.title
        return super(SoftwareHelp, self).save(*args, **kwargs)

rawDescription: How do I easily create a calculated field in a Django model?

description: Easily create a calculated field in a Django model


code:
import sys

s=raw_input()
k=s.lower()
listaa=[]
for x in k:
    listaa.append(x)
    if x=='a':
        listaa.remove('a')
    if  x=='o':
        listaa.remove('o')
    if x=='y':
        listaa.remove('y')
    if x=='e':
        listaa.remove('e')
    if x=='u':
        listaa.remove('u')
    if x=='i':
        listaa.remove('i')
for a in listaa:
    sys.stdout.write('.%s' % a)

rawDescription: How to print without trailing space in Python

description: Print without trailing space in Python


code:
result = [each[2] for each in people]
print(result)

rawDescription: Grab second tuple in Python list

description: Grab second tuple in Python list


code:
from flask import Flask
from flask import request
from flask import render_template, redirect, url_for, request
APP = Flask(__name__)
@APP.route('/')
def login1():
      return render_template('login1.html')
@APP.route('/login', methods=['GET', 'POST'])
def login():
    error=None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or request.form['password'] != 'admin':
            error = 'Invalid Credentials. Please try again.'
            return redirect(url_for('login1'))
        else:
           return render_template('hello.html', error=error)

if __name__ == '__main__':
      APP.debug=True
      APP.run()

rawDescription: The method is not allowed for the requested URL. in Flask


code:
my_list = ListFlowable([
    ListItem(Paragraph("Line 1", styles['Normal']),
         leftIndent=35, value='circle',
         bulletColor=CMYKColor(0.81, 0.45, 0.53, 0.23)
    ),
    ListItem(Paragraph("Line 2", styles['Normal']),
         leftIndent=35, value='circle',
         bulletColor=CMYKColor(0.81, 0.45, 0.53, 0.23))
],
bulletType='bullet',
start='circle',
leftIndent=10
)

rawDescription: How can I make the bullet appear directly next to the text of an indented list in the reportlab package for python?

description: Make the bullet appear directly next to the text of an indented list in the reportlab package for python


code:
def mostlyVowels(words):
  acc = []
  for word in words.split():
    i = 0
    for char in word.lower():
      if char in 'aeiou': i += 1
      else:               i -= 1
    if i > 0: acc.append(word)
  return acc

rawDescription: Finding out if half the letters in a word are vowels


code:
arr = PixelArray(surface)
arr.replace(fromColor, toColor)
del arr

rawDescription: Pygame - Recolor pixes of a certain color to another using SurfArray (Array slicing issue)


code:
import numpy as np

A1 = np.array([0, 0, 2, 2, 4, 4])
A2 = np.arange(len(A1))
A3 = np.ones(len(A1))*3

new_array = np.zeros(len(A1))

index = (A1 == 2) & (A2 > A3)

new_array[index] = 5
# array([ 0.,  0.,  5.,  5.,  0.,  0.])

rawDescription: Creating new array by comparing arrays

description: Creating new array by comparing arrays


code:
import numpy as np
from enthought.mayavi import mlab

x, y, z = np.ogrid[-3:3:100j, -3:3:100j, -3:3:100j]
F = x**2/3**2 + y**2/2**2 + z**2/4**2 - 1
mlab.contour3d(F, contours = [0])
mlab.show()

rawDescription: Implicit equation and Mayavi

description: Implicit equation and Mayavi


code:
import itertools

[item for item, repeats in itertools.groupby([1, 1, 2, 3, 2, 2, 4, 4, 5])]
#>>> [1, 2, 3, 2, 4, 5]

rawDescription: How to remove from list all successive equal elements?

description: Remove from list all successive equal elements


code:
class CurrentViewApplicationName(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        request.current_app = view_func.__module__.split('.')[0]

rawDescription: How to get the current application name from a context processor?

description: Get the current application name from a context processor


rawDescription: Filter across three tables using Django

description: Filter across three tables using Django


code:
import code
def foo():
  a = 10
  code.interact(local=locals())
  return a
foo()
a

rawDescription: Enter Interactive Mode In Python

description: Enter Interactive Mode In Python


code: mydict = default.copy()

rawDescription: Is there a way to set multiple defaults on a Python dict using another dict?


code: my_defaultdict = collections.defaultdict(lambda : [True,True,True])

rawDescription: How to create a specific default list in defaultdict?

description: Create a specific default list in defaultdict


code:
if int(s, 16) & 2**n:
  whatever

rawDescription: Python Hex String Check If Bit is set

description: Python Hex String Check If Bit is set


code:
import datetime

class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        elif isinstance(obj, datetime.date):
            return obj.isoformat()
        elif isinstance(obj, datetime.timedelta):
            return (datetime.datetime.min + obj).time().isoformat()
        else:
            return super(DateTimeEncoder, self).default(obj)

DateTimeEncoder().encode(object)

rawDescription: Python JSON encoder to support datetime?

description: Python JSON encoder to support datetime


code:
class Sim(object):
    def __init__(self, name):
        self.name = name

names = ['tim','dave','jane']
sims = {}
for name in names:
    sims[name] = Sim(name)

rawDescription: User created classes

description: User created classes


code:
from PIL import Image
import numpy as np

class Pic_Function():
    def __init__(self, picture_path):
        self.picture = Image.open(picture_path)
        self.pixels = self.picture.load()
        self.columns = []
        # is there really no image method to get a numpy array of pixels?
        for i in range(self.picture.size[0]):
            self.columns.append([self.pixels[i,j] for j in range(self.picture.size[1])])
        self.first_black = []
        for i in self.columns:
            try:
                self.first_black.append(self.picture.size[0] - i.index((0,0,0)))
            except ValueError:
                self.first_black.append(None)
        self.max, self.min = max(self.first_black), min([j for j in self.first_black if j != None])

    def at(self, x):
        upper_idx = int(math.ceil(x))
        lower_idx = upper_idx - 1
        try:
            upper = self.first_black[upper_idx]
            lower = self.first_black[lower_idx]
        except IndexError:
            return 0
        if None in [upper, lower]:
            return 0

        up_weight, low_weight = abs(upper-x), abs(lower-x)
        return (up_weight*upper + low_weight*lower)/(up_weight + low_weight)

    def norm_at(self, x, length):
        un_normed = self.at(x*self.picture.size[0]/length)
        return (un_normed - self.min)/self.max

rawDescription: How to turn a hand drawn curve (vector drawing or paint etc..) into a function?

description: Turn a hand drawn curve (vector drawing or paint etc..) into a function


code:
# use range() in Python 3
l = [{'open': False, 'serve': False} for i in xrange(150)]

rawDescription: How to generate a list of 150 cases initialised with a dict in Python?

description: Generate a list of 150 cases initialised with a dict in Python


code:
import urllib2
import lxml.html

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/2010010' \
    '1 Firefox/4.0.1',
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language':'en-us,en;q=0.5',
    'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.7'}

req = urllib2.Request('http://www.amaderforum.com/login.php?do=lostpw', None,
                      headers)
f = urllib2.urlopen(req)
page = f.read()

tree = lxml.html.fromstring(page)
imgurl = "http://www.amaderforum.com/" + \
      tree.xpath(".//img[@id='imagereg']")[0].get('src')

req = urllib2.Request(imgurl, None, headers)
f = urllib2.urlopen(req)
img = f.read()

open('out.jpg', 'wb').write(img)

rawDescription: urllib2 download captcha image

description: Urllib2 download captcha image


code:
from subprocess import check_output
var = check_output('tasklist')

rawDescription: How do I get python to fetch information from command prompt such as 'tasklist'

description: Get python to fetch information from command prompt such as 'tasklist'


code:
def foo(start_index, lista_tuples,list_to_return=list()):

    indeces=[x[1] for x in lista_tuples if x[0]==start_index]
    new_values = list(set(indeces) - set(list_to_return))
    list_to_return.extend(indeces)
    for index in new_values:
              foo(index,lista_tuples,list_to_return)
    return list_to_return

rawDescription: Recursive functions on a list of tuples

description: Recursive functions on a list of tuples


code:
total = 1
for letter in word:
   index = letters.index(letter)
   total *= primes[index]

rawDescription: Coding words as products of integers

description: Coding words as products of integers


code:
import sys
from PyQt4 import QtGui, QtCore

class OutputWrapper(QtCore.QObject):
    outputWritten = QtCore.pyqtSignal(object, object)

    def __init__(self, parent, stdout=True):
        QtCore.QObject.__init__(self, parent)
        if stdout:
            self._stream = sys.stdout
            sys.stdout = self
        else:
            self._stream = sys.stderr
            sys.stderr = self
        self._stdout = stdout

    def write(self, text):
        self._stream.write(text)
        self.outputWritten.emit(text, self._stdout)

    def __getattr__(self, name):
        return getattr(self._stream, name)

    def __del__(self):
        try:
            if self._stdout:
                sys.stdout = self._stream
            else:
                sys.stderr = self._stream
        except AttributeError:
            pass

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        self.setCentralWidget(widget)
        self.terminal = QtGui.QTextBrowser(self)
        self._err_color = QtCore.Qt.red
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout.addWidget(self.terminal)
        layout.addWidget(self.button)
        stdout = OutputWrapper(self, True)
        stdout.outputWritten.connect(self.handleOutput)
        stderr = OutputWrapper(self, False)
        stderr.outputWritten.connect(self.handleOutput)

    def handleOutput(self, text, stdout):
        color = self.terminal.textColor()
        self.terminal.setTextColor(color if stdout else self._err_color)
        self.terminal.moveCursor(QtGui.QTextCursor.End)
        self.terminal.insertPlainText(text)
        self.terminal.setTextColor(color)

    def handleButton(self):
        if QtCore.QTime.currentTime().second() % 2:
            print('Printing to stdout...')
        else:
            sys.stderr.write('Printing to stderr...\n')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 200)
    window.show()
    sys.exit(app.exec_())

rawDescription: Duplicate stdout, stderr in QTextEdit widget


code:
N = 10
n0 = 0
n_array = np.arange(n0, n0 + N, 1)
u = pd.Series(index = n_array)
u[n0] = 1
q = 1.2
# option 1:
u = pd.Series(u[n0]*q**(u.index.values - n0), index = n_array)
# or option 2 with cumprod
u[1:] = q
u = u.cumprod()

rawDescription: Geometric progression using Python / Pandas / Numpy (without loop and using recurrence)


rawDescription: Is it possible to use X-AppEngine-Country within an application


code:
df
swapidx = df['Item1'] < df['Item2']
df1 = df[swapidx]
df2 = df[swapidx^True]
df1
df2
df2[['Item1', 'Item2']] = df2[['Item2', 'Item1']]
df2['Moves'] = df2['Moves']*-1
df2
df3 = df1.append(df2)
df3.groupby(['Item1', 'Item2'], as_index=False).sum()

rawDescription: Calculate pairwise difference from specific columns in a dataframe


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

# sample data
x = np.arange(10)
y = 5*x + 10

# fit with np.polyfit
m, b = np.polyfit(x, y, 1)

plt.plot(x, y, '.')
plt.plot(x, m*x + b, '-')

rawDescription: How to overplot a line on a scatter plot in python?

description: Overplot a line on a scatter plot in python


rawDescription: get current directory - Python

description: Get current directory - Python


rawDescription: Get row of 2d array where min value is in first col


code:
import os
from datetime import datetime
from calendar import timegm
import sys
st_info = os.stat('foo.py')
st_info.st_atime #acces time
st_info.st_mtime #modified time
mtime = st_info.st_mtime
atime = st_info.st_atime
# send over the wire
os.utime('foo.py', (atime, mtime))

rawDescription: Python File Modified Time get and set over socket


code:
class DataItem(object):
    pass

di_one = DataItem()
di_two = DataItem()

rawDescription: python class and instance organization

description: Python class and instance organization


code:
import tucsonScraper
import newyorkScraper

def universalNameAdressGrab(url):
    page = pullPage(url)
    scraper = None

    if 'Tucson.com' in url:
        scraper = tucsonScraper
    elif 'NewYork.com' in url:
        scraper = newyorkScraper
    else:
        raise Exception("No scraper found for url")

    return {'name': scraper.getName(page), 'address': scraper.getAddress(page)}

rawDescription: Making a pythonic decision on developing a web scraper module


code:
class Integerizer(object):
    def __init__(self, value):
        self.value = value
    def __int__(self):
        return self.value
    def __call__(self, *args, **kw):
        return self.value

rawDescription: How to handle & return both properties AND functions missing in a Python class using the __getattr__ function?

description: Handle & return both properties AND functions missing in a Python class using the __getattr__ function


code:
# imports
from matplotlib import pyplot as plt
import matplotlib as mpl
from seaborn.apionly import set_palette
from IPython.display import set_matplotlib_formats

# configure plotting
set_matplotlib_formats('pdf', 'svg')
set_palette('Set1', n_colors=15, desat=None)
mpl.rcParams['figure.figsize']=(12.0,2.0)

rawDescription: Ipython Notebook: Default Initialization Python Code


code:
def foo():
    bar = 42

rawDescription: How can I call a function defined in another function?

description: Call a function defined in another function


code:
import re, collections
sentence_terminator = re.compile(r'(?<=[.!?;])\s*')
class SentenceParser(object):
    def __init__(self, filelike):
        self.f = filelike
        self.buffer = collections.deque([''])
    def next(self):
        while len(self.buffer) < 2:
            data = self.f.read(512)
            if not data:
                raise StopIteration()
            self.buffer += sentence_terminator.split(self.buffer.pop() + data)
        return self.buffer.popleft()
    def __iter__(self):
        return self

rawDescription: Efficient way to read/write/parse large text files (python)


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup('''

    11
    22
    33
    44

''')
soup.find_all('a', {'class': 'some-class'})
soup.find_all('a', {'class': 'some-class', 'href': None})  # <--

rawDescription: Select all elements with class and without attribute using BeautifulSoup4


code:
class AA:
    def __init__(self):
        self.name = "ZZ-top"
        self.flag = False
    def reset(self):
        self.name = "AArdvark"
        self.flag = True

class BB:
    def __init__(self):
        self.num = 11
    def checker(self):
        if self.num > 10:
            test.AA.name = "Toasty"

class test:
    def __init__(self):
        self.AA = AA()
        self.BB = BB()

rawDescription: Alternative to nested classes?

description: Alternative to nested classes


code:
rx = regex.compile(r"(?<!#\d{0,3})c99")
rx.findall("#000c99")
rx.findall("/mysite.com/c99.php")
rx.findall("%20c99.php")
rx.findall("c99?hi=moo")

rawDescription: Backchecking on python regex

description: Backchecking on python regex


code:
lis = [1,-5,10,6,3,-4,-9]
sorted(lis, key=abs, reverse=True)

rawDescription: Sort a list in python

description: Sort a list in python


code:
import os
args=['process_name', 'bla', 'ble']
os.execlp("/bin/echo", *args)

rawDescription: Replace a running python script with os.execl


code:
from matplotlib.ticker import MultipleLocator
locator = MultipleLocator(1)
ax1.xaxis.set_major_locator(locator)
ax1.set_xticklabels(xlabels)

rawDescription: How to set the axis tick to be only major on python

description: Set the axis tick to be only major on python


code:
import os
from logging.handlers import RotatingFileHandler

COMPRESSION_SUPPORTED = {}

try:
   import gzip
   COMPRESSION_SUPPORTED['gz'] = gzip
except ImportError:
   pass

try:
   import zipfile
   COMPRESSION_SUPPORTED['zip'] = zipfile
except ImportError:
   pass

class NewRotatingFileHandler(RotatingFileHandler):

     def __init__(self, *args, **kws):
         compress_mode = kws.pop('compress_mode')

         try:
             self.compress_cls = COMPRESSION_SUPPORTED[compress_mode]
         except KeyError:
             raise ValueError('"%s" compression method not supported.' % compress_mode)

         super(NewRotatingFileHandler, self).__init__(self, *args, **kws)

     def doRollover(self):
         super(NewRotatingFileHandler, self).doRollover()

         # Compress the old log.
         old_log = self.baseFilename + ".1"
         with open(old_log) as log:
             with self.compress_cls.open(old_log + '.gz', 'wb') as comp_log:
                 comp_log.writelines(log)

         os.remove(old_log)

rawDescription: Compact (archive) old log files in python


code: lowByte = lambda b: b & 0xff

rawDescription: How can I replicate the Arduino function lowByte in python?

description: Replicate the Arduino function lowByte in python


code:
from random import randint # Bad practice to import *

money = 100
bet = 2

# Consider revising the below to sets, which are faster for membership tests
d = [0, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35]

repeat = False

for _ in range(100):  # You never use the loop variable, so denote that by naming it _
    a = randint(1, 36) # btw, you have 0 in d but your randint starts from 1...

    if a in d:
        money -= bet
        if repeat:
            bet *= 2
        repeat = True
    else:
        money += bet
        repeat = False

print("Your money",money,"€")

rawDescription: Calcualte bankroll Martingale system

description: Calcualte bankroll Martingale system


code:
import string
[a[1] for a in string.Formatter().parse('{foo}/{bar}')]

rawDescription: How retrieve keyword arguments from a string in python?


code:
def __unicode__(self):
   return u"Profile for %s" % self.user.get_full_name()

rawDescription: Django How to show user's name in his profile in admin console


code:
for name in sorted(namelist):
    print( name )

rawDescription: Sorting lists, not the output I want

description: Sorting lists, not the output I want


code:
import bpy

src_image = bpy.data.images['src']
w, h = src_image.size[0], src_image.size[1]

sum_r = 0
sum_g = 0
sum_b = 0
sum_a = 0

for x in range(w):
    for y in range(h):
        idx = ((y * w) + x) * src_image.channels
        sum_r += src_image.pixels[idx]
        sum_g += src_image.pixels[idx+1]
        sum_b += src_image.pixels[idx+2]
        sum_a += src_image.pixels[idx+3]

pix_count = len(src_image.pixels) / src_image.channels
avg_r = sum_r / pix_count
avg_g = sum_g / pix_count
avg_b = sum_b / pix_count
avg_a = sum_a / pix_count

print('red:{} green:{} blue:{} alpha:{}'.format(avg_r,avg_g,avg_b,avg_a))

rawDescription: Creating custom Blender composition node with Pynodes which iterates over pixels - is it possible?


code: new_obj = random.choice(SHAPES)()

rawDescription: Python: instantiating new instance of class from list of classes


rawDescription: Simple python re lookahead help

description: Simple python re lookahead help


rawDescription: How can I refactor this django query to not select each individual object?

description: Refactor this django query to not select each individual object


code:
qry = DBSession.query(Item)

# ensure that each condition is present using separate condition
for cid in condition_ids:
    qry = qry.filter(Item.conditions.any(Condition.id == cid))

# ensure that other skills are not present:
qry = qry.filter(~Item.conditions.any(~Condition.id.in_(condition_ids)))

rawDescription: Filtering by exact list of IDs instead of "in_" list of IDs


code:
def my_side_effect(*args, **kwargs):
    if args[0] == 42:
        return "Called with 42"
    elif args[0] == 43:
        return "Called with 43"
    elif kwarg['foo'] == 7:
        return "Foo is seven"

mockobj.mockmethod.side_effect = my_side_effect

rawDescription: Python Mock object with method called multiple times


code: main.write("fo.write('text to be ended with a newline command\\n')\n")

rawDescription: Writing a python code that will enter newline commands correctly


code: getattr(obj, 'func')('foo', 'bar', 42)

rawDescription: How to launch getattr function in python with additional parameters?

description: Launch getattr function in python with additional parameters


code:
files = [file for file in os.listdir(filepath) if file.endswith('.txt')]
batchsize = 100
index = 0
remaining = len(files)
while remaining > 0:
    batch = min(remaining, batchsize)
    print('NEW BATCH')
    for file in files[index:index+batch]:
        with open(os.path.join(filepath, file), 'r') as myfile:
            print(' ', file)

    index += batch
    remaining -= batch

rawDescription: How to iterate through a fixed number of files until the last file of the folder?

description: Iterate through a fixed number of files until the last file of the folder


code:
root_pw = wx.GetTextFromUser("Enter Root Password:")
os.system("echo {pw} | sudo -S -p '' {root_cmd}".format(pw=root_pw,root_cmd="apt-get install something"))

rawDescription: wxPython - Getting root sudo access and handling root access

description: WxPython - Getting root sudo access and handling root access


code:
from scrapy.spider import BaseSpider
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item, Field

class Torrent(Item):
    name = Field()

class MySpiderSpider(BaseSpider):
    name = 'MySpider'
    allowed_domains = ['http://sfbay.craigslist.org']
    start_urls = ['http://sfbay.craigslist.org/search/apa?bedrooms=1&srchType=A&s=%d' %n for n in xrange(0, 2500, 100)]

    def parse(self, response):
        x = HtmlXPathSelector(response)
        torrent = Torrent()
        torrent['name'] = x.select("id('toc_rows')/p[2]/span[1]/a/text()").extract()
        return torrent

rawDescription: Can't follow links when web-scraping

description: Can't follow links when web-scraping


rawDescription: Serialization of a pandas DataFrame

description: Serialization of a pandas DataFrame


code: from __future__ import division

rawDescription: Evaluate expression as float in Python

description: Evaluate expression as float in Python


code:
import sys
from StringIO import StringIO

input_text = 'whatever you want the function to read from input()'

old_stdin = sys.stdin
#Reassign stdin to a StringIO object
sys.stdin = StringIO(input_text)

f()

sys.stdin = old_stdin

rawDescription: Is subprocess the only way to provide input to input()?


code:
ax = df['A'].plot()
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
              df['B'].values[np.newaxis],
              cmap='RdYlGn', alpha=0.3)

rawDescription: matplotlib conditional background color in python

description: Matplotlib conditional background color in python


code:
params = urllib.urlencode({
    "rows": "100",
    "fl": "id,name,score,address,city,state,zip",
    "wt": "python",
    "q": "+name:Foo +city:Boston"
})

request = urllib2.urlopen(urllib2.Request("http://locahost:8983/solr/select", params))
response = ast.literal_eval(request.read())
request.close()
return response["docs"]

rawDescription: Can I use Django 1.1 with django-search-lucene for full-text searching, and if so, what resources/links/docs can I reference to get it up and running?

description: Use Django 1.1 with django-search-lucene for full-text searching, and if so, what resources/links/docs can I reference to get it up and running


code:
from pprint import pprint
pprint(dict(dictionary))

rawDescription: Print data in a dictionary nested in a dictionary, in a nice way?


code:
import itertools
import datetime

# Extract the date from the timestamp that is the third item in a line
# (Will be grouping by start timestamp)
def key(s):
    return datetime.date.fromtimestamp(int(s.split()[2]))

with open('in.txt') as in_f:
    for date, group in itertools.groupby(in_f, key=key):
        # Output to file that is named like "1970-01-01.txt"
        with open('{:%Y-%m-%d}.txt'.format(date), 'w') as out_f:
            out_f.writelines(group)

rawDescription: Split data day wise

description: Split data day wise


code: artifact_paths = re.findall(r"^Deploying artifact: .*$", full_string, re.M)

rawDescription: find a set of path within a string using regex in python

description: Find a set of path within a string using regex in python


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.do_grab = tk.BooleanVar()
        cb = tk.Checkbutton(self, text="New window grabs all events",
                            variable=self.do_grab, onvalue=True, offvalue=False)
        cb.pack()
        new_button = tk.Button(self, text="New window", command=self.on_click)
        new_button.pack()

    def on_click(self):
        self.top = tk.Toplevel(self)
        button = tk.Button(self.top, text="dismiss", command=self.top.destroy)
        do_grab = self.do_grab.get()

        if do_grab:
            label = tk.Label(self.top, wraplength=200,
                             text="This window grabs all events")
        else:
            label = tk.Label(self.top, wraplength = 200,
                             text="This window does NOT grab all events")
        label.pack(fill="x")
        button.pack()

        if do_grab:
            self.top.grab_set()

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: tkinter Toplevel window appears not to react to some methods

description: Tkinter Toplevel window appears not to react to some methods


code:
import os
import posixpath

maya_path = posixpath.join('a','b','c')
local_path = os.path.realpath(maya_path)

rawDescription: Handling slashes in python

description: Handling slashes in python


code:
soup = BeautifulSoup.BeautifulSoup('xyz')
[tag.attrs for tag in soup.findAll('a')]

rawDescription: python extracting HTML tag attributes without regular expressions

description: Python extracting HTML tag attributes without regular expressions


code:
deadline = pd.to_datetime(df['Deadline Date'] + ' ' + df['Deadline Time'])
completed = pd.to_datetime(df['Task Completed Date'] + ' ' + df['Task Completed Time'])
completed - deadline

rawDescription: Find 'Time Delayed' using python pandas

description: Find 'Time Delayed' using python pandas


code:
line = 'This,is,a,sample,string'
"sample" in line

rawDescription: Python match a string with regex

description: Python match a string with regex


code:
try:
    # or codecs.open on Python 2
    filedata = open(filename, encoding='UTF-8').read()
except:
    filedata = open(filename, encoding='other-single-byte-encoding').read()

rawDescription: How do I detect if a file is encoded using UTF-8?

description: Detect if a file is encoded using UTF-8


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

class MatrixBrowser(object):

    def __init__(self, matrix, matrix_ax, connections):
        self.matrix = matrix
        self.matrix_ax = matrix_ax
        self.con = connections
        self.index = (0, 0)
        self.rect = patches.Rectangle((0, 0), 1.1, 1.1,
                    linewidth=3, fill=False, visible=False)
        self.con_rects = self.add_connection_rects()

    def add_connection_rects(self):
        max_cons = max([len(_) for _ in self.con.values()])
        rects = []
        for con in range(max_cons):
            con_rect = patches.Rectangle((0, 0), 1.1, 1.1, linewidth=5,
                        fill=False, visible=False, edgecolor='red')
            rects.append(con_rect)
            self.matrix_ax.add_patch(con_rect)
        return rects

    def update_connections(self, event):
        current_ax = event.inaxes
        cx = event.xdata
        cy = event.ydata
        # only if the cursor is on the matrix ax
        if current_ax == self.matrix_ax:
            rx = round(abs(cx))
            ry = round(abs(cy))
            if not self.index == (rx, ry):
                # make every previous rect invisible
                for rect in self.con_rects:
                    rect.set_visible(False)
                cons = self.con.get((rx, ry), [])
                for rect, con in zip(self.con_rects, cons):
                    rect.set_xy((con[0] - 0.55, con[1] - 0.55))
                    rect.set_visible(True)
                self.index = (rx, ry)
            self.rect.set_visible(True)
            self.rect.set_xy((rx - 0.55, ry - 0.55))
        else:
            self.rect.set_visible(False)
        plt.draw()

def main(matrix, connections):
    fig, ax = plt.subplots()
    im = ax.matshow(matrix, aspect='auto', cmap=plt.cm.winter)
    plt.colorbar(im, use_gridspec=True)
    browser = MatrixBrowser(matrix, ax, connections)
    ax.add_patch(browser.rect)
    fig.canvas.mpl_connect('motion_notify_event', browser.update_connections)
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    matrix = np.random.rand(15, 15) * 10
    connections = {(0, 0): [(1, 1), (2, 2), (10, 2), (8, 5)],
                   (3, 2): [(3, 3)],
                   (14, 14): [(0, 0), (0, 14), (14, 0)]}
    main(matrix, connections)

rawDescription: Interactive visualization of connections between cells in a matrix


code:
import networkx as nx

G = nx.balanced_tree(10,10)

rawDescription: Create a tree data using networkx in python


rawDescription: pyramid checkboxes

description: Pyramid checkboxes


code:
import wx
class myframe(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(1000,700))

        self.TitlePanel = wx.Panel(self, size=(350, 400))
        self.TitlePanel.SetBackgroundColour("green")

        self.newPanel = wx.Panel(self, size=(300, 250))
        self.newPanel.SetBackgroundColour("black")
        self.newPanel.Hide()

        self.imgPanel = wx.Panel(self, size=(300, 250))
        self.imgPanel.SetBackgroundColour("red")

        self.modulePanel=wx.Panel(self, size=(350, 250))
        self.modulePanel.SetBackgroundColour("blue")

        self.TCPanel=wx.Panel(self, size=(300, 250))
        self.TCPanel.SetBackgroundColour("yellow")

        self.myGridSizer = wx.GridBagSizer(1,1)
        self.myGridSizer.SetEmptyCellSize((0, 0))
        self.myGridSizer.Add(self.TitlePanel, pos=(0, 0), span=(4,8), flag=wx.EXPAND)
        self.myGridSizer.Add(self.imgPanel, pos=(0, 10), span=(4,8), flag=wx.ALL)
        self.myGridSizer.Add(self.modulePanel, pos=(10, 0), span=(1,8), flag=wx.ALL)
        self.myGridSizer.Add(self.TCPanel, pos=(10, 10), span=(4,8), flag=wx.ALL)

        self.text1 = wx.StaticText(self.TitlePanel, label="This is a test run",style=2,size=(350,-1))
        font = wx.Font(18, wx.DECORATIVE, wx.ITALIC,wx.BOLD, wx.NORMAL)
        self.text1.SetFont(font)

        self.titleSizer = wx.BoxSizer()
        self.titleSizer.Add(self.text1, flag=wx.TOP|wx.LEFT|wx.ALIGN_RIGHT,border=10)
        self.TitlePanel.SetSizer(self.titleSizer)

        self.SetSizer(self.myGridSizer)

        self.text1.Bind(wx.EVT_LEFT_DCLICK, self.hideMe)
        self.imgPanel.Bind(wx.EVT_LEFT_DCLICK, self.showMe)

    def hideMe(self, event):
        self.TCPanel.Hide()
        self.myGridSizer.Replace(self.TCPanel, self.newPanel)
        self.newPanel.Show()
        self.Layout()

    def showMe(self, event):
        self.newPanel.Hide()
        self.myGridSizer.Replace(self.newPanel, self.TCPanel)
        self.TCPanel.Show()
        self.Layout()

if __name__ == "__main__":
    app = wx.App()
    region = myframe()
    region.Show()
    app.MainLoop()

rawDescription: Replace an Existing layout with new layout with wxPython


code:
class Tile:
    def __init__(self, type):
        self.items = []
        self.type = type

rawDescription: Python: variable scope and encapsulation of a list


code: nodes = xmlTemplate .xpath('/InventoryData/Table[@Name="InvComputer"]/Column[@Name="Hostname"]')

rawDescription: I want to add a value to an existing XML object/tree in python


code:
while running:
    #filter events here
    gtk.main_iteration(true)

rawDescription: Where is the PyGTK event stack?

description: Where is the PyGTK event stack


code:
import re
s = "StringText someText Wwwwww SomeOtherText OtherText SOMETextMore etc etc etc"
def replacement(match):
  return match.group(1).lower()
re.sub(r'([sS]\w+)', replacement, s)

rawDescription: Python re: how to lowercase some words

description: Python re: how to lowercase some words


code:
def permutate(table, block):
    """Permutate this block with the specified table"""
    def index(x):
        return block[x]
    ret = []
    for x in table:
        ret.append(index(x))
    return ret

rawDescription: Understand the map function in Python - Index reassignment


rawDescription: Accessing model field attributes in Django


code:
msg = EmailMessage(subject, html_content, from_email, [to])
msg.content_subtype = "html"  # Main content is now text/html
msg.send()

rawDescription: How do I send an email in Django with a certain mimetype?

description: Send an email in Django with a certain mimetype


code: print("As so your name is {}, your quest is {} ".format(name,quest))

rawDescription: String Formatting with python3

description: String Formatting with python3


rawDescription: How to remove duplicate items from a list using list comprehension?

description: Remove duplicate items from a list using list comprehension


code:
import simplejson as json
json.dumps({})
json.dumps({'asdf':1,'poi':[2,3,4,{'qwer':5}]})

rawDescription: How Do I code this in python with simplejson


code:
class Pomodoro_app(Tk):
    def add_task(self):
        global time
        time = StringVar()
        time.set("Start")
        task_content = askstring(title = 'Add a Task', prompt = "Input a task")
        task_label   = Label(self, text = task_content, font = ("Arial, 12")).grid(column = 0, row = self.next_row)
        task_start_button = Button(self, textvariable = time, command = lambda: self.start_working(task_content)).grid(column = 1, row = self.next_row)
        #                                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        self.next_row += 1

    def start_working(self, task_name):
        print('start working', task_name)

    def createWidgets(self):
        self.welcome_label   = Label(self, text = "Welcome to the Challenge!", font = ("Arial, 12")).grid(column = 0, row = 0, columnspan = 2)
        self.add_task_button = Button(self, text = "Add Task", width = 20, command = self.add_task).grid(column = 0 , columnspan = 2)

    def __init__(self):
        """GUI Initiation"""
        Tk.__init__(self)
        self.createWidgets()
        """window Initiation"""
        self.resizable(False, False)
        x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
        y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
        self.geometry('250x400+%d+%d' % (x, y))
        self.next_row = 3

rawDescription: Using Tkinter to program an application need add buttons with same function. How to identify which button I clicked and change the line automatically?


code:
name = input('Enter your name: ')
print("Welcome", name)

rawDescription: Ask the user for its name using raw_input


code: "select %(tableName)s.somefield, count(*) from %(tableName)s WHERE %(tableName)s.TimeStamp > %(fromDate)s and %(tableName)s.EndTimeStamp < %(to_data)s group by %(tableName)s.ProviderUsername;" %{'tableName':tableName, 'fromDate':fromDate, 'to_data':to_data}

rawDescription: Efficient way to format string

description: Efficient way to format string


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

''' send_input for python 3, from jh45dev@gmail.com

code from Daniel F is adapted here. The original is at:
http://mail.python.org/pipermail/python-win32/2005-April/003131.html

SendInput sends to the window that has the keyboard focus.
That window must not be minimized.

There seem to be some strange limitations with user32.SendInput()
Here is what happened in my testing (on Vista sp2).

 [edit: It is OK if I work from a folder within my profile.
 These problems happened when working on another partition.
 File permissions were OK, so do not know what blocked SendInput.]

1
I opened Notepad from the Start menu,
then in Notepad opened test.txt,
and all worked fine.

2
I opened Notepad by opening test.txt in Explorer.
find_window() found Notepad, but user32.SendInput() had no effect.
If Notepad was minimized, it did not get restored or focussed.

The same happened with SciTE and Notepad2.

Another strangeness:
For SciTE I had to put in the whole window title, eg "test.txt - SciTE",
but for Notepad and Notepad2, only the app name, eg "Notepad".

'''

import ctypes as ct
from win32con import SW_MINIMIZE, SW_RESTORE
from win32ui import FindWindow, error as ui_err
from time import sleep

class cls_KeyBdInput(ct.Structure):
    _fields_ = [
        ("wVk", ct.c_ushort),
        ("wScan", ct.c_ushort),
        ("dwFlags", ct.c_ulong),
        ("time", ct.c_ulong),
        ("dwExtraInfo", ct.POINTER(ct.c_ulong) )
    ]

class cls_HardwareInput(ct.Structure):
    _fields_ = [
        ("uMsg", ct.c_ulong),
        ("wParamL", ct.c_short),
        ("wParamH", ct.c_ushort)
    ]

class cls_MouseInput(ct.Structure):
    _fields_ = [
        ("dx", ct.c_long),
        ("dy", ct.c_long),
        ("mouseData", ct.c_ulong),
        ("dwFlags", ct.c_ulong),
        ("time", ct.c_ulong),
        ("dwExtraInfo", ct.POINTER(ct.c_ulong) )
    ]

class cls_Input_I(ct.Union):
    _fields_ = [
        ("ki", cls_KeyBdInput),
        ("mi", cls_MouseInput),
        ("hi", cls_HardwareInput)
    ]

class cls_Input(ct.Structure):
    _fields_ = [
        ("type", ct.c_ulong),
        ("ii", cls_Input_I)
    ]

def find_window( s_app_name ):

    try:
        window1 = FindWindow(  None, s_app_name,)
        return window1
    except ui_err:
        pass
    except:
        raise

    try:
        window1 = FindWindow( s_app_name, None, )
        return window1
    except ui_err:
        return None
    except:
        raise

def make_input_objects( l_keys ):

    p_ExtraInfo_0 = ct.pointer(ct.c_ulong(0))

    l_inputs = [ ]
    for n_key, n_updown in l_keys:
        ki = cls_KeyBdInput( n_key, 0, n_updown, 0, p_ExtraInfo_0 )
        ii = cls_Input_I()
        ii.ki = ki
        l_inputs.append( ii )

    n_inputs = len(l_inputs)

    l_inputs_2=[]
    for ndx in range( 0, n_inputs ):
        s2 = "(1, l_inputs[%s])" % ndx
        l_inputs_2.append(s2)
    s_inputs = ', '.join(l_inputs_2)

    cls_input_array = cls_Input * n_inputs
    o_input_array = eval( "cls_input_array( %s )" % s_inputs )

    p_input_array = ct.pointer( o_input_array )
    n_size_0 = ct.sizeof( o_input_array[0] )

    # these are the args for user32.SendInput()
    return ( n_inputs, p_input_array, n_size_0 )

    '''It is interesting that o_input_array has gone out of scope
    by the time p_input_array is used, but it works.'''

def send_input( window1, t_inputs, b_minimize=True ):

    tpl1 = window1.GetWindowPlacement()
    was_min = False
    if tpl1[1] == 2:
        was_min = True
        window1.ShowWindow(SW_RESTORE)
        sleep(0.2)

    window1.SetForegroundWindow()
    sleep(0.2)
    window1.SetFocus()
    sleep(0.2)
    rv = ct.windll.user32.SendInput( *t_inputs )

    if was_min and b_minimize:
        sleep(0.3) # if the last input was Save, it may need time to take effect
        window1.ShowWindow(SW_MINIMIZE)

    return rv

# define some commonly-used key sequences
t_ctrl_s = (  # save in many apps
    ( 0x11, 0 ),
    ( 0x53, 0 ),
    ( 0x11, 2 ),
)
t_ctrl_r = (  # reload in some apps
    ( 0x11, 0 ),
    ( 0x52, 0 ),
    ( 0x11, 2 ),
)

def test():

    # file > open; a non-invasive way to test
    t_ctrl_o = ( ( 0x11, 0 ), ( 0x4F, 0 ), ( 0x11, 2 ), )

    # writes "Hello\n"
    # 0x10 is shift.  note that to repeat a key, as with 4C here, you have to release it after the first press
    t_hello = ( ( 0x10, 0 ), ( 0x48, 0 ), ( 0x10, 2 ), ( 0x45, 0 ), ( 0x4C, 0 ), ( 0x4C, 2 ), ( 0x4C, 0 ), ( 0x4F, 0 ), ( 0x0D, 0 ), )

    l_keys = [ ]
    ## l_keys.extend( t_ctrl_o )
    l_keys.extend( t_hello )
    l_keys.extend( t_ctrl_s )

    ## s_app_name = "SciTE"
    ## s_app_name = "(Untitled) - SciTE"
    s_app_name = "test.txt - SciTE"
    ## s_app_name = "Notepad2"
    ## s_app_name = "Notepad"

    window1 = find_window( s_app_name )
    if window1 == None:
        print( "%r has no window." % s_app_name )
        input( 'press enter to close' )
        exit()

    t_inputs = make_input_objects( l_keys )

    n = send_input( window1, t_inputs )

    ## print( "SendInput returned: %r" % n )
    ## print( "GetLastError: %r" % ct.windll.kernel32.GetLastError() )
    ## input( 'press enter to close' )

if __name__ == '__main__':
    test()

rawDescription: SendKeys for Python 3.1 on Windows

description: SendKeys for Python 3.1 on Windows


code:
import wx
from wx.lib import sized_controls

class TestFrame(sized_controls.SizedFrame):
    def __init__(self, *args, **kwargs):
        super(TestFrame, self).__init__(*args, **kwargs)
        contents_pane = self.GetContentsPane()
        self.files = {}
        for number in range(1, 5):
            label = 'file{}'.format(number)
            ctrl = wx.CheckBox(contents_pane, label=label)
            self.files[label] = ctrl

        btn_output = wx.Button(contents_pane, label='btn_output')
        btn_output.Bind(wx.EVT_UPDATE_UI, self.btn_update)

    def btn_update(self, event):
        enable = all(ctrl.IsChecked() for ctrl in self.files.values())
        event.Enable(enable)

app = wx.App(False)
test_frame = TestFrame(None)
test_frame.Show()
app.MainLoop()

rawDescription: What event should I bind to before enabling a button in wxPython?


code:
class UserCreateView(CreateView):
    model = UserMeta
    fields = [
        'auth', # This is the hidden input that I want to autofill
        'email',
        'city',
    ]
    template_name = 'forms/user_create.html'

    def get_initial(self):
        return {"auth": self.kwargs.get("pk")}

rawDescription: Django - fill createview input from url <pk>


code:
if not setdict:
    return 0  # max(empty_setdict) raise a `ValueError`
return max(sum(map(len, v)) + len(v) - 1 if v else 0
           for v in setdict.itervalues())

rawDescription: Longest set in a dict of sets

description: Longest set in a dict of sets


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.statusBar()
        self.toolbar = self.addToolBar('toolbar')
        action = QtGui.QWhatsThis.createAction(self)
        action.setStatusTip('Enter what\'s this mode')
        self.toolbar.addAction(action)
        widget = QtGui.QGroupBox(self)
        layout = QtGui.QVBoxLayout(widget)
        self.setCentralWidget(widget)
        for name in 'one two three four'.split():
            checkbox = QtGui.QCheckBox('Checkbox %s' % name, self)
            checkbox.setToolTip('Tooltip for checkbox %s' % name)
            checkbox.setWhatsThis("""
                What\'s this text:

                Checkbox %s

                link to main help
                """ % (name, name))
            checkbox.installEventFilter(self)
            layout.addWidget(checkbox)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.WhatsThisClicked:
            print(event.href())
        return QtGui.QMainWindow.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 250, 200)
    window.show()
    sys.exit(app.exec_())

rawDescription: radio button and display widgets on designer-qt4

description: Radio button and display widgets on designer-qt4


code: re.findall(r'\b\d+\b', "5 1 inch c5 bolts 10")

rawDescription: how to extract numbers from a string ignoring number-letter mixtures

description: Extract numbers from a string ignoring number-letter mixtures


code:
Item.objects.filter(
    sale__sale_date=date.today()
).annotate(
    count = Count('sale')
)

rawDescription: Django aggregation and following foreign key relations


code:
env.remote_interrupt = True
env.LOG = '<path to log>'

@task
def log():
    assert(env.remote_interrupt == True)
    with settings(warn_only=True):
        sudo("tail -n 50 -f " + env.LOG)

rawDescription: Reading logs with fabric

description: Reading logs with fabric


rawDescription: How to provide a negative condition in Case/When clause while using Django ORM?

description: Provide a negative condition in Case/When clause while using Django ORM


code:
def opt_arguments(func):
    def meta_wrapper(*args, **kwargs):
        if len(args) == 1 and callable(args[0]):
            return func(args[0])
        else:
            def meta_func(inner_func):
                return func(inner_func, *args, **kwargs)
            return meta_func
    return meta_wrapper

rawDescription: No Argument Decorator Decorator?

description: No Argument Decorator Decorator


code:
class A(object):
  y = 1
  x = 0
  def __call__(self, x):
    self.x = x
    return self.x + self.y

b = A()
b.y = 4
b(2)
b.z = 5
import dill
_b = dill.dumps(b)
b_ = dill.loads(_b)

b_.z
b_.x
b_.y
A.y = 100
c = A()
_c = dill.dumps(c)
c_ = dill.loads(_c)
c_.y

rawDescription: Pickle both class variables and instance variables?


code:
def parse(self,response):
    sel = Selector(response)
    sites = sel.xpath('//tbody/tr')
    for site in sites:
        item = EvolutionmItem()
        item['title'] = site.xpath('td/div[not(contains(., "Sticky:") or contains(.,"ANNOUNCEMENT"))]/a[contains(@id,"thread_title")]/text()').extract()
        item['url'] = u''. join( site.xpath('td[contains(@id,"threadtitle")]/div/a[contains(@href,"http://forums.evolutionm.net/sale-engine-drivetrain-power/")]/@href').extract())
        item['poster'] = site.xpath('td[contains(@id,"threadtitle")]/div[@class="smallfont"]/span/text()').extract()
        item['status'] = site.xpath('td[contains(@id,"threadtitle")]/div/span[contains(@class,"highlight")]').extract()

    yield Request(url = item['url'], meta = {'item': item}, callback=self.parse_additional_info)

def parse_additional_info(self, response):
    #extract additional info
    yield item

rawDescription: How can I parse additional URLs extracted with xpath in scrapy?

description: Parse additional URLs extracted with xpath in scrapy


code:
try:
    _count = int(open("/tmp/counter").read())
except IOError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    open("/tmp/counter", "w").write("%d" % _count)

import atexit
atexit.register(savecounter)

rawDescription: Taking the signal from close event of terminal in Python


code: map(lambda x: int(x) if x%1==0 else x, mylist)

rawDescription: Issue with integer numbers when reading from existing workbook


code:
a = [1, 2, 3]
b = [[1], [2], [3]]
any(isinstance(i, list) for i in a)
any(isinstance(i, list) for i in b)

rawDescription: Python check if a list is nested or not

description: Python check if a list is nested or not


code:
#shifts by 4 bits and converts to 8-bit image
img = img.point(lambda i: i * 16, "L")

rawDescription: python convert 12 bit image encoded in a string to 8 bit png

description: Python convert 12 bit image encoded in a string to 8 bit png


code:
import urllib3

http = urllib3.PoolManager()
url = '...'
headers = urllib3.util.make_headers(basic_auth='abc:xyz')
r = http.request('GET', url, headers=headers)

rawDescription: authentication with urllib3

description: Authentication with urllib3


code:
def sort_by_subdict(dictionary, subdict_key):
    return sorted(dictionary.items(), key=lambda k_v: k_v[1][subdict_key])

Lesson = {'Math':{'Rating':11, 'Desc':'Exercises 14 and 19 page 157', 'TimeLeftTask':7}, 'English':{'Rating':23, 'Desc':'Exercise 5 page 204', 'TimeLeftTask':2}}
print(sort_by_subdict(Lesson, 'Rating'))

rawDescription: how to print a dictionary sorted by a value of a subdictionary?

description: Print a dictionary sorted by a value of a subdictionary


code:
old_handler =signal(SIGINT, SIG_DFL)
# call main
signal(SIGINT, old_handler)

rawDescription: profiling fuse-python

description: Profiling fuse-python


code:
def answer(p):
    p = p[IP]
    send(IP(dst=p.src, src=p.dst)/TCP(dport=p.sport, sport=p.dport,
                                      ack=p.seq + 1, flags='SA'))

sniff(filter='tcp and tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn',
      prn=answer, store=False)

rawDescription: How can I use scapy to make a port appear open?

description: Use scapy to make a port appear open


rawDescription: Extract arbitrary rectangular patches from image in python


code:
class jsonEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, db.GeoPt):
            return {'lat': obj.lat, 'lon': obj.lon}
        else:
            return simplejson.JSONEncoder.default(self, obj)

rawDescription: Python nested json object being serialize as str


code:
import matplotlib.pyplot as plt

plt.hlines(7, 0, 2, linestyles='dashed')
plt.hlines(11, 0, 2, linestyles='dashed')
plt.hlines(10, 0, 2, linestyles='dashed')
plt.hlines(8, 0, 2, linestyles='dashed')
plt.annotate(
    '', xy=(1, 10), xycoords='data',
    xytext=(1, 8), textcoords='data',
    arrowprops={'arrowstyle': '<->'})
plt.annotate(
    'D = 1', xy=(1, 9), xycoords='data',
    xytext=(5, 0), textcoords='offset points')

# alternatively,
# plt.text(1.01, 9, 'D = 1')

plt.show()

rawDescription: Plotting distance arrows in technical drawing


code: ' '.join("Please \n don't \t hurt \x0b me.".split())

rawDescription: Remove whitespace in Python using string.whitespace


code:
from fabric.api import execute

local_function_1()
execute(remote_function)
local_function_2()

rawDescription: Wait until process in remote server finishes using Fabric


code:
from bottle import Bottle, run, route, request

app = Bottle()

@app.route('/listener')
def my_listener():
    data = request.query.your_data
    #do_something_with_data(data)
    return data

run(app, host="0.0.0.0", port=8080)

rawDescription: How do I get data from a url callback

description: Get data from a url callback


code:
#!/usr/bin/env python

import os
import os.path

import jpype

# or wherever your java is installed
os.environ['JAVA_HOME'] = "/usr/lib64/jvm/default-java"

root = os.path.abspath(os.path.dirname(__file__))

SX_JAR = os.path.join(root, 'SX.jar')

options = [
    '-Djava.class.path=%s' % SX_JAR
]

jpype.startJVM(jpype.getDefaultJVMPath(), *options)

WorkBook = jpype.JClass('com.smartxls.WorkBook')
ChartShape = jpype.JClass('com.smartxls.ChartShape')
ChartFormat = jpype.JClass('com.smartxls.ChartFormat')
Color = jpype.JClass('java.awt.Color')

workbook = WorkBook()

workbook.setText(0,1,"Jan")
workbook.setText(0,2,"Feb")
workbook.setText(0,3,"Mar")
workbook.setText(0,4,"Apr")
workbook.setText(0,5,"Jun")

workbook.setText(1,0,"Comfrey")
workbook.setText(2,0,"Bananas")
workbook.setText(3,0,"Papaya")
workbook.setText(4,0,"Mango")
workbook.setText(5,0,"Lilikoi")

for col in range(1, 5 + 1):
    for row in range(1, 5 + 1):
        workbook.setFormula(row, col, "RAND()")
workbook.setText(6, 0, "Total")
workbook.setFormula(6, 1, "SUM(B2:B6)")
workbook.setSelection("B7:F7")
# auto fill the range with the first cell's formula or data
workbook.editCopyRight()

left = 1.0
top = 7.0
right = 13.0
bottom = 31.0

# create chart with it's location
chart = workbook.addChart(left,top,right,bottom)
chart.setChartType(ChartShape.Column)
# link data source, link each series to columns(true to rows).
chart.setLinkRange("Sheet1!$a$1:$F$6", False)
# set axis title
chart.setAxisTitle(ChartShape.XAxis, 0, "X-axis data")
chart.setAxisTitle(ChartShape.YAxis, 0, "Y-axis data")
# set series name
chart.setSeriesName(0, "My Series number 1")
chart.setSeriesName(1, "My Series number 2")
chart.setSeriesName(2, "My Series number 3")
chart.setSeriesName(3, "My Series number 4")
chart.setSeriesName(4, "My Series number 5")
chart.setTitle("My Chart")

# set plot area's color to darkgray
chartFormat = chart.getPlotFormat()
chartFormat.setSolid()
chartFormat.setForeColor(Color.DARK_GRAY.getRGB())
chart.setPlotFormat(chartFormat)

# set series 0's color to blue
seriesformat = chart.getSeriesFormat(0)
seriesformat.setSolid()
seriesformat.setForeColor(Color.BLUE.getRGB())
chart.setSeriesFormat(0, seriesformat)

# set series 1's color to red
seriesformat = chart.getSeriesFormat(1)
seriesformat.setSolid()
seriesformat.setForeColor(Color.RED.getRGB())
chart.setSeriesFormat(1, seriesformat)

# set chart title's font property
titleformat = chart.getTitleFormat()
titleformat.setFontSize(14*20)
titleformat.setFontUnderline(True)
chart.setTitleFormat(titleformat)

workbook.write("./Chart.xls")

jpype.shutdownJVM()

rawDescription: Python: Creating Excel worksheets with charts


code:
from itertools import chain, izip_longest
a = [1]
b = []
list(chain(*izip_longest(a, b, fillvalue='foo')))

rawDescription: Python itertools chain: possible to fill the shorter iterable with None


code:
import inspect
from flask import Flask

def expose(f):
    """Decorator that flags a method to be exposed"""
    f._exposed_method = True
    return f

class FlaskOfCherryPy(Flask):
    """Custom flask that allows cherrypy's expose decorator"""
    def quickstart(self, root_handler, *args, **kwargs):
        self._process_root_handler(root_handler)
        self.run(*args, **kwargs)

    def _process_root_handler(self, root_handler):
        # Prime the recursive processing
        root_url = []
        self._process_a_handler(root_handler, root_url)

    def _process_a_handler(self, current_handler, url_stack):
        # This gives a list of all the members of current_handler
        members = inspect.getmembers(current_handler)
        for name, value in members:
            # You probably want to skip things that start with a _ or __
            if name.startswith('_'):
                continue

            # Check if the method is decorated
            is_exposed_method = getattr(value, '_exposed_method', False)

            # If it's a callable with the _exposed_method attribute set
            # Then it's an exposed method
            if is_exposed_method and callable(value):
                self._add_exposed_url(url_stack, name, value)
            else:
                new_stack = url_stack[:]
                new_stack.append(name)
                self._process_a_handler(value, new_stack)

    def _add_exposed_url(self, url_stack, name, view_func):
        copied_stack = url_stack[:]

        if name != 'index':
            copied_stack.append(name)

        url = "/%s" % "/".join(copied_stack)

        if name == 'index':
            copied_stack.append(name)

        view_name = "_".join(copied_stack)
        self.add_url_rule(url, view_name, view_func)

class Root(object):
    @expose
    def index(self):
        return 'my app'

class Greeting(object):
    def __init__(self, name, greeting):
        self.name = name
        self.greeting = greeting

    @expose
    def index(self):
        return '%s %s!' %(self.greeting, self.name)

    @expose
    def again(self):
        return '%s again, %s!' %(self.greeting, self.name)

if __name__ == '__main__':
    root = Root()
    root.hello = Greeting('Foo', 'Hello')
    root.bye = Greeting('Bar', 'Bye')
    app = FlaskOfCherryPy(__name__)
    app.quickstart(root)

rawDescription: Can Flask provide CherryPy style routing?


code:
with open("cert.der", "rb") as f:
    der = f.read()

import OpenSSL.crypto
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, der)
pkey = x509.get_pubkey()
dir(pkey)
pkey.bits()
pkey.type() == OpenSSL.crypto.TYPE_RSA

rawDescription: Simple DER Cert Parsing in python

description: Simple DER Cert Parsing in python


code: b = [[i] for i in a]

rawDescription: How to make a list with elements to list with list with only one element?

description: Make a list with elements to list with list with only one element


code:
from sqlalchemy import types

class StrippedString(types.TypeDecorator):
    '''
    Returns CHAR values with spaces stripped
    '''

    impl = types.String

    def process_bind_param(self, value, dialect):
        "No-op"
        return value

    def process_result_value(self, value, dialect):
        "Strip the trailing spaces on resulting values"
        return value.rstrip()

    def copy(self):
        "Make a copy of this type"
        return StrippedString(self.impl.length)

rawDescription: SQLAlchemy Columns result processing

description: SQLAlchemy Columns result processing


code:
class split_cmap(colors.Colormap):
    def __init__(self, cmap_a, cmap_b, split=.5):
        '''Makes a split color map cmap_a is the low range,
           cmap_b is the high range
           split is where to break the range
        '''
        self.cmap_a, self.cmap_b = cmap_a, cmap_b
        self.split = split

    def __call__(self, v):
        if v < self.split:
            return self.cmap_a(v)
            # or you might want to use v / self.split
        else:
            return self.cmap_b(v)
            # or you might want to use (v - self.split) / (1 - self.split)

    def set_bad(self,*args, **kwargs):
        self.cmap_a.set_bad(*args, **kwargs)
        self.cmap_b.set_bad(*args, **kwargs)

    def set_over(self, *args, **kwargs):
        self.cmap_a.set_over(*args, **kwargs) # not really needed
        self.cmap_b.set_over(*args, **kwargs)

    def set_under(self, *args, **kwargs):
        self.cmap_a.set_under(*args, **kwargs)
        self.cmap_b.set_under(*args, **kwargs) # not really needed

    def is_gray(self):
        return False

rawDescription: stacking colormaps

description: Stacking colormaps


code:
import numpy
a = numpy.array([[1, 0, 1], [0, 1, 1], [0, 1, 0]])
numpy.transpose(numpy.nonzero(a))

rawDescription: pythonic way to get index,column for value == 1

description: Pythonic way to get index,column for value == 1


code:
from subprocess import Popen, PIPE

args = ['mysqldump', '-u', 'UNAME', '-pPASSWORD', '--add-drop-database', '--databases', 'DB']

with open(FILENAME, 'wb', 0) as f:
    p1 = Popen(args, stdout=PIPE)
    p2 = Popen('gzip', stdin=p1.stdout, stdout=f)
p1.stdout.close() # force write error (/SIGPIPE) if p2 dies
p2.wait()
p1.wait()

rawDescription: python subprocess and mysqldump

description: Python subprocess and mysqldump


code:
cols = []
for i, col in enumerate(desc):
    if col[0].startswith('word'):
        cols.append(i)

rawDescription: Trying to decipher Python list comprehension


code:
import fnmatch
import os

def find(base_dir, some_string):
    matches = []
    for root, dirnames, filenames in os.walk(base_dir):
        for filename in fnmatch.filter(filenames, some_string):
            matches.append(os.path.join(root, filename))

    return matches

files = find('.', '*.png')
new_files = ['-'.join(ele.split('/')[1:]) for ele in files]

for idx, ele in enumerate(files):
    os.rename(ele, new_files[idx])

rawDescription: Renaming files recursively to make the filename a concatenation of their path


code: data = dict(line.lower().rstrip().rsplit(' ', 1) for line in inFile)

rawDescription: Can a dict be initialized and appended to with split()?


code:
def f(): {'a': 3}
import dis
dis.dis(f)

rawDescription: Why doesn't re-assignment to __builtins__.dict affect creation of new dictionary objects?


code:
def duck(sound, position, duration, gain=-15.0, fade_duration=500):
    """
    sound - an AudioSegment object
    position - how many milliseconds into the sound the duck should
        begin (this is where overlaid audio could begin, the fade down
        will happen before this point)
    duration - how long should the sound stay quiet (milliseconds)
    gain - how much quieter should the sound get (in dB)
    fade_duration - how long sound the fades last (in milliseconds)
    """

    # this part is from the beginning until the end of the ducked section
    first_part = sound[:position+duration]
    first_part = first_part.fade(to_gain=gain, end=position, duration=fade_duration)

    # this part begins where the fade_up happens (will just fade in)
    second_part = sound[position+duration:]
    second_part = second_part.fade(from_gain=gain, start=0, duration=fade_duration)

    return first_part + second_part

for timing, phrase in phrases.items():
    fileToAdd = pydub.AudioSegment.from_file(rep+"/"+str(timing)+".wav")

    finalFile = duck(finalFile, position=timing*1000, duration=len(fileToAdd))

    finalFile = finalFile.overlay(fileToAdd, position=timing*1000)

rawDescription: Bad quality after multiple fade effect with pydub


code:
class ExtractTransformMixin(object):

    def long_running_extract_transform(self, chunkify=False):
        pass

class LoadTask(Task):

    def long_running_load(self):
        pass

    def run(self, results):
        self.long_running_load(results)

class ETLTask(ExtractTransformMixin, Task):

    def run(self):
        load_results = ResultSet([])
        for chunk in long_running_extract_transform(chunkify=True):
            load_results.add(LoadTask().delay(chunk))
        return load_results

rawDescription: Celery: Asynchronously Retrieve Partial Results from Previous Task


code:
r = re.compile(r'\b(?:{})\b\s*(.*?),'.format('|'.join(map(re.escape, keywords))))
r.findall(s)
s = "I want a car Mercedes Benz,but its costly, so I'll get car Volkswagen Beetle, as it is cheap."
r.findall(s)

rawDescription: Regex to print contents between dynamic word and a comma


code:
import zipfile
path = "example/path.epub"
epub = zipfile.ZipFile(open(path))
epub.namelist()
file = epub.open('some_file.txt')
file.read()

rawDescription: Django. Retrieving and opening a zip file from HDD


code: price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))])

rawDescription: Allow only positive decimal numbers

description: Allow only positive decimal numbers


code:
import re
from bs4 import BeautifulSoup

soup = BeautifulSoup(html)

pattern = re.compile(r"UID_(\w+)\-SRC_\d+")
id = soup.find("div", id=pattern)["id"]

uid = pattern.match(id).group(1)
print(uid)

rawDescription: Scraping data from the tag names in python


code:
idx = df.columns.str.startswith('Col')
df['total'] = df.iloc[:,idx].sum(axis=1)

rawDescription: Summing up values for rows per columns starting with 'Col'


code:
class custom_sale_order(models.Model):
    _inherit='sale.order'

    time1 = fields.Date('TIme1')
    time2 = fields.Date('TIme2')

    @api.model
    def create(self, values):
        # here we call to the parent create method
        res = super(custom_sale_order, self).create(values)

        # here we create a record in the demo model
        # and we can access to the values of the current model
        self.env['demo'].create({
            'time3': values['time1'],
            'time4': values['time2']
        })

        return res

rawDescription: How to create a record in a model while creating a record in another model in odoo

description: Create a record in a model while creating a record in another model in odoo


code:
import string
import random
from itertools import islice

chars = string.printable + string.whitespace
# make infinite generator of random chars
random_chars = iter(lambda: random.choice(chars), '')
with open('output_file','w', buffering=102400) as fout:
    fout.writelines(islice(random_chars, 1000000)) # write 'n' many

rawDescription: Python: My script will not allow me to create large files


code:
import itertools

from nose.loader import TestLoader
from nose import run
from nose.suite import LazySuite

paths = ("/path/to/my/project/module_a",
         "/path/to/my/project/module_b",
         "/path/to/my/project/module_c")

def run_my_tests():
    all_tests = ()
    for path in paths:
        all_tests = itertools.chain(all_tests, TestLoader().loadTestsFromDir(path))
    suite = LazySuite(all_tests)
    run(suite=suite)

if __name__ == '__main__':
    run_my_tests()

rawDescription: python nosetests equivalent of unittest Testsuite in the test file

description: Python nosetests equivalent of unittest Testsuite in the test file


code:
s=input('Enter S')
e=input('Enter E')
A=[]
for x in range (s,e):
 A.append(x)
 if len(A)==3:
  print(A[0],A[1],A[2])
  del A[0:3]

rawDescription: Create a numeric string using three variables


code:
def get_max_val_key(data):
    max_value = None
    for key in data:
        if max_value is None or max_value < data[key]:
            max_value = data[key]
            max_key = key
    return max_key

data = {'a':11, 'b':12}
print(get_max_val_key(data))

rawDescription: Python getting the key of the highest value in dictionary, without using inbuilt functions


code:
# Before main loop
human_files = ["human1.png", "human2.png"]
human_sprites = [pygame.image.load(filename).convert_alpha() for filename in human_files]
human1_index = 0

...

# During main loop
if (human1_position.left <= 555):
    human1_position = human1_position.move(2, 0)  # move first human
    human1_index = (human_index + 1) % len(human_sprites) # change sprite
else:
    move = STOP
    human1_index = 0
human1 = human_sprites[human1_index]
screen.blit(human1, human1_position)
pygame.display.update()

rawDescription: Alternate an image while it's moving in Pygame


code:
class MyModelView(BaseModelView):
    column_list = ('name', 'last_name', 'email')
    form_widget_args = {
        'email':{
            'disabled':True
        }
    }

rawDescription: Readonly text field in Flask-Admin ModelView


rawDescription: Fill matrix with transposed version

description: Fill matrix with transposed version


code:
def postalValidate(S):
    # first, delete all spaces
    S = ''.join(S.split())

    # the remainder must be of the form L#L#L# where L are letters (in either lower or upper case) and # are numbers.
    # If S is not a valid postal code, return the boolean False.
    if len(S) != 6:
        return False
    if not (all(S[i].isalpha() for i in [0, 2, 4]) and
            all(S[i].isdigit() for i in [1, 3, 5])):
        return False

    # If S is valid, return a version of the same postal code in the nice format L#L#L# where each L is capital.
    return S.upper()

rawDescription: Python, nested loops into a function break - pass - continue - return


code:
accounts_table = sa.Table('accounts_table', sa.MetaData(),
    sa.Column('id', sa.Integer),
    sa.Column('name', sa.String(100)),
    sa.Column('create_date', sa.Date),
    schema='phone'
)

rawDescription: Alembic bulk_insert to table with schema


code: import wx.lib.agw.speedmeter

rawDescription: import a tkinter widget in wxpython application as a panel

description: Import a tkinter widget in wxpython application as a panel


code:
for i in range(0, len(my_list)):
    my_list[i]["name"] = "Just an example string"
    for j in range(0, len(my_list[i]["type"])):
        my_list[i]["type"][j] = "Type example"

rawDescription: Update list element in python

description: Update list element in python


code:
import contextlib
@contextlib.contextmanager
def argv_tmp():
    tmp = sys.argv
    sys.argv = []
    try:
        yield
    finally:
        sys.argv = tmp

with argv_tmp():
    from ROOT import *

rawDescription: How can a function set the value of a variable without returning the value of that variable?


code:
lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

students = [lloyd,alice,tyler]

def average(data):
    return sum(data) / float(len(data))

def compute_grades(students):
    for student in students:
        print('-'*23)
        for key, value in student.items():
            if isinstance(value, str):
                formatted_value = value
            else:
                formatted_value = average(value)
            print("%s: %s" % (key.title(), formatted_value))

compute_grades(students)

rawDescription: Python Dictionaries - Calling the definition


code:
class Result(models.Model):
     user = models.ForeignKey(User)
     paper = models.ForeignKey(ExamPaper)
     question = models.ForeignKey(Question)
     marks = models.IntegerField()
     result = models.CharField()

     class Meta:
         unique_together = (("user", "paper", "question"), )

rawDescription: Django model with 3 many to many fields

description: Django model with 3 many to many fields


code:
university = forms.TypedChoiceField(
    label="Select your university",
    choices=UNIVERSITIES,
    empty_value="--- youre empty value here ---",
)

rawDescription: How to change the default selected option in a Django ChoiceField?

description: Change the default selected option in a Django ChoiceField


code:
...
c.execute('select * from your_table')
for i, row in enumerate(c):
    # inefficienctly write each row to a new file using index as name
    with open('{}.txt'.format(i), 'w') as f:
        f.write('{}'.format(row))
...

rawDescription: Saving each row of SQL query result as text file


code:
def moves_three(n, a=0, b=1, c=2):
    first_entry = True
    stack = [(first_entry, n, a, b, c)]
    output = []
    while stack:
        first_entry, n1, a1, b1, c1 = stack.pop()
        if n1 == 1:
            output.append((a1, c1))
        elif first_entry:
            stack.append((False, n1, a1, b1, c1))
            stack.append((True, n1-1, a1, c1, b1))
        else:
            output.append((a1, c1))
            stack.append((True, n1-1, b1, a1, c1))
    return tuple(output)

rawDescription: How to convert this non-tail-recursion function to a loop or a tail-recursion version?

description: Convert this non-tail-recursion function to a loop or a tail-recursion version


code: color = surface.get_at(pygame.mouse.get_pos()) # get the color of pixel at mouse position

rawDescription: Pygame get color of pixel where cursor is located


code: x1, x2, x3, x4 = raw_input("Input number as xxxx-xxxx-xxxx-xxxx").split('-')

rawDescription: How to query an input in Python without outputting a new line (cont.)

description: Query an input in Python without outputting a new line (cont.)


code:
a={'a':1,'b':2,'c':3}
key,value = 'c',3                # Key and value present
key in a and value == a[key]
key,value = 'b',3                # value absent
key in a and value == a[key]
key,value = 'z',3                # Key absent
key in a and value == a[key]

rawDescription: Way to check if items in dict

description: Way to check if items in dict


code:
from __future__ import division

class Fraction(object):

    def __init__(self, num, den):
        self.num, self.den = num, den

    # the built-in function float(obj) calls obj.__float__()
    def __float__(self):
        """float(self): Return a float approximating the fraction."""
        return self.num / self.den

    # Python 2.6/2.7/3.x print() function and Python 2 print statement
    # call str(obj), which calls obj.__str__()
    def __str__(self):
        """str(self): Return a string representing the fraction."""
        return str(float(self))

rawDescription: Make object return float value python

description: Make object return float value python


code:
import itertools
my_List = [1, 2, 3, 4]
for xs in itertools.combinations_with_replacement(my_List, 3):
    print(xs)

rawDescription: Get all combination with n -length from a list


code:
import Tkinter as tk
import tkMessageBox
def ask_quit():
    if tkMessageBox.askokcancel("Quit", "You want to quit now? *sniff*"):
        # close your serial here
        root.destroy()
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", ask_quit)
root.mainloop()

rawDescription: tkinter "x" performing ser.close() on exit

description: Tkinter "x" performing ser.close() on exit


rawDescription: Determine if a group within a regex match is a number


code:
f = open('my_file')
print(f.read())
# in bash: echo 'more data' >> my_file
print(f.read())

rawDescription: Can I read new data from an open file without reopening it?

description: Read new data from an open file without reopening it


rawDescription: python module to decode OSX plist integer dates?

description: Python module to decode OSX plist integer dates


rawDescription: How to convert list pairs into tuple pairs

description: Convert list pairs into tuple pairs


code: output.split()[1].rsplit(".", 1)[0]

rawDescription: Pull a string out of a string (split?)

description: Pull a string out of a string (split?)


code:
from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')

# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
fox.save_screenshot('screenshot.png') # saves screenshot of entire page
fox.quit()

im = Image.open('screenshot.png') # uses PIL library to open image in memory

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']

im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image

rawDescription: How to take partial screenshot with Selenium WebDriver in python?

description: Take partial screenshot with Selenium WebDriver in python


code:
import urllib2
f = urllib2.urlopen("http://dalkescientific.com")
f.headers.items()
f.headers["Content-Length"]

rawDescription: I am downloading a file using Python urllib2. How do I check how large the file size is?


rawDescription: Accessing the last element in the list in python


code:
from collections import defaultdict

def make_index(data,key,value=lambda x:x):
    d=defaultdict(list)
    for item in data:
        d[key(item)].append(value(item))
    return d

rawDescription: indexing an array

description: Indexing an array


code:
# Here I'm just mapping very simply, you can definitely use regex or something for your case if you have a lot of classes
df
# Break between X (independent variables) and y (dependent, class)
# Now you can do your fit etc...

rawDescription: Create decision trees with pandas and scikit learn using binary matrix/occurance matrix


code:
date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5):
    date += datetime.timedelta(days=1)
    print(date)

rawDescription: How to increment the day in datetime? Python

description: Increment the day in datetime? Python


code:
class Shows(models.Model) :
    title = models.TextField(primary_key=True)
    description = models.TextField()
    image = models.TextField()
    class Meta:
        db_table = 'shows'
    def __str__(self):
        return self.title

class Episode(models.Model) :
    show = models.ForeignKey(Show, related_name="episodes")
    title = models.TextField(primary_key=True)
    link = models.TextField()
    show_title = models.ForeignKey(Shows)

    class Meta:
        db_table = 'episodes'
    def __str__(self):
        return self.title

rawDescription: Django models, one to many relationship with back reference [how]