code:
def start_requests(self):
        script = """
        function main(splash)
            assert(splash:autoload("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"))
            assert(splash:go(splash.args.url))

            local js = [[
                var $j = jQuery.noConflict();
                $j('#USER').val('frankcastle');
                $j('#password').val('punisher');
                $j('.button-oblong-orange.button-orange a').click();
                $j('body').empty() // clear body, otherwise the wait_for footer will always be true
            ]]

            assert(splash:runjs(js))

            function wait_for(splash, condition)
                while not condition() do
                    splash:wait(0.05)
                end
            end

            wait_for(splash, function()
                return splash:evaljs("document.querySelector('#footer') != null")
            end)

            return {
                html = splash:html()
            }
        end
        """
        splash_meta = {'splash': {'endpoint': 'execute', 'args': {'wait': 0.5, 'lua_source': script}}}

        for url in self.start_urls:
            yield scrapy.Request(url, self.after_login, meta=splash_meta)

rawDescription: ScrapyJS - How to properly wait for page load?


code: values = np.random.binomial(1, p)

rawDescription: Python numpy generate an array of random binary values according to probabilities


rawDescription: Fast hamming distance computation between binary numpy arrays


code:
import lzma

# open input file as binary and read input data
with open(inputFilename, 'rb') as iFile:
    iData = iFile.read()

# compress data
oData = lzma.compress(iData)

# open output file as binary and write compressed data
with open(outputFilename, 'wb') as oFile:
    oFile.write(oData)

rawDescription: Tarfile create xz file

description: Tarfile create xz file


code:
input = raw_input('Command: ')
if 'inv' in input:
    invcheck()

rawDescription: Text Adventure - Checking Inventory

description: Text Adventure - Checking Inventory


code:
total = 0.0
count = 0
for line in (fhand):
    line = line.rstrip()
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    else:
        n = float(line[line.find(":") + 1:])
        total += n
        count = count + 1

print (total / count)

rawDescription: calling sum() on a list of numbers extrcted from a document

description: Calling sum() on a list of numbers extrcted from a document


code:
# create an empty list
a = [];
# take limt as input
lim = raw_input("Enter limit")

# this is python style of for loop
# here i will start from 0 and will go upto limit
for i in range (0, int(lim)):
    # take input from user one by one and append to list
    elem = raw_input("")
    a.append(int(elem))

rawDescription: how to dynamically insert data in a list in python

description: Dynamically insert data in a list in python


code:
min_date = cur.fetchone()[0]
min_date = min_date if min_date is not None else default_value

rawDescription: How to override NULL value from aggregate query using MySQLdb module in python?

description: Override NULL value from aggregate query using MySQLdb module in python


rawDescription: How to pass a constant value as a result of condition in python dataframe using "where " function in one line

description: Pass a constant value as a result of condition in python dataframe using "where " function in one line


code:
with open('crap3.txt') as inData:
    for line in inData:
        line = line.strip()
        name, year = line.split('\t', 1)
        print(year)

rawDescription: Print column using python

description: Print column using python


code:
class NoParsingFilter(logging.Filter):
    def filter(self, record):
        return not record.getMessage().startswith('parsing')

logger.addFilter(NoParsingFilter())

rawDescription: logging with filters

description: Logging with filters


code:
cols = []
joins = []
insp = inspection.inspect(DNAExtractionProtocol)
for name, col in insp.columns.items():
    cols.append(col.label(name))
for name, rel in insp.relationships.items():
    alias = aliased(rel.mapper.class_, name=name)
    joins.append((alias, rel.class_attribute))
    for col_name, col in inspection.inspect(rel.mapper).columns.items():
        #the id column causes double entries, as it is mapped once on the parent table (related_table_id) and once on the child table (table_id)
        if col.key != "id":
            aliased_col = getattr(alias, col.key)
            cols.append(aliased_col.label("{}_{}".format(name, col_name)))

    sub_insp = inspection.inspect(rel.mapper.class_)
    for sub_name, sub_rel in sub_insp.relationships.items():
        if "contains" not in sub_name:
            sub_alias = aliased(sub_rel.mapper.class_, name=name+"_"+sub_name)
            joins.append((sub_alias, sub_rel.class_attribute))
            for sub_col_name, sub_col in inspection.inspect(sub_rel.mapper).columns.items():
                print(sub_alias, sub_col.key, '###')
                #the id column causes double entries, as it is mapped once on the parent table (related_table_id) and once on the child table (table_id)
                if sub_col.key != "id":
                    sub_aliased_col = getattr(sub_alias, sub_col.key)
                    cols.append(sub_aliased_col.label("{}_{}_{}".format(name, sub_name, sub_col_name)))

sql_query = session.query(*cols).select_from(DNAExtractionProtocol)
for join in joins:
    sql_query = sql_query.outerjoin(*join)
sql_query = sql_query.filter(DNAExtractionProtocol.code == code)

rawDescription: Join all related tables in SQLAlchemy

description: Join all related tables in SQLAlchemy


rawDescription: Convert zero-padded bytes to UTF-8 string


code:
sq = (session.query(A.pk.label('a_pk'), func.count(C.pk).label('num_cees'))
      .outerjoin(B).outerjoin(C).group_by(A.pk)
      .having(func.count(C.pk) == 5) # toggle-comment-line
      ).subquery('c_count')

q = (session.query(A)
     .join(sq, A.pk == sq.c.a_pk)
     # .filter(sq.c.num_cees == 5) # toggle-comment-line
     )

rawDescription: Filter by grandchildren count in SQLAlchemy


code: z = [y.index(i) for i in x]

rawDescription: Finding the indices of the values of one list in another list


code:
import StringIO
import tarfile

archive = tarfile.open(tarname, mode='w')
for _ in range(some_number):
    content = get_content()
    s = StringIO.StringIO()
    s.write(content)
    s.seek(0)
    tarinfo = tarfile.TarInfo(name="my filename")
    tarinfo.size = len(s.buf)
    archive.addfile(tarinfo=tarinfo, fileobj=s)

archive.close()

rawDescription: Add file to tar archive without saving it first


code:
groups = df.groupby(['Name','Type'])
mad = groups['Cost'].transform(lambda x: x.mad())
dif = groups['Cost'].transform(lambda x: np.abs(x - x.mean()))
df2 = df[dif <= 3*mad]

rawDescription: Computing MAD(mean absolute deviation) GroupBy Pandas


code: items = tree.xpath("*[local-name(.) = 'a_tag_goes_here']")

rawDescription: Parse xbrl file in python

description: Parse xbrl file in python


rawDescription: How can i remove an item from a list that is located just before a certain index?

description: Remove an item from a list that is located just before a certain index


code:
def register(cls: type):
    assert issubclass(cls, A)

rawDescription: Python type hinting: how to tell X is a subclass for Foo?


code:
def plotter(y1,y2,y1name,y2name):
    averageY1=float(sum(y1)/len(y1))
    averageY2=float(sum(y2)/len(y2))
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(y1,'b-',linewidth=2.0)
    ax1.set_xlabel("SNo")
    # Make the y2-axis label and tick labels match the line color.
    ax1.set_ylabel(y1name, color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')
    ax1.axis([0,len(y2),0,max(y1)+50])

    ax2 = ax1.twinx()

    ax2.plot(y2, 'r-')
    ax2.axis([0,len(y2),0,max(y2)+50])
    ax2.set_ylabel(y2name, color='r')
    for tl in ax2.get_yticklabels():
        tl.set_color('r')
    plt.title(y1name + " vs " + y2name)
    #plt.fill_between(y2,1,y1)
    plt.grid(True,linestyle='-',color='0.75')

    plt.savefig(y1name+"VS"+y2name+".png",dpi=200)

rawDescription: x axis with duplicate values (loading profile) plot in matplotlib

description: X axis with duplicate values (loading profile) plot in matplotlib


code:
from collections import Counter
import sys
import math

n = int(input())
s1 = input()
s = Counter(s1)

if all(e <= n/4 for e in s.values()):
    print(0)
    sys.exit(0)

result = math.inf
out = 0
for mnum in range(n):
    s[s1[mnum]] -= 1
    while all(e <= n/4 for e in s.values()) and out <= mnum:
        result = min(result, mnum - out + 1)
        s[s1[out]] += 1
        out += 1

print(result)

rawDescription: Bear and Steady gene - code optimisation(python)


code:
style = ttk.Style()
style.configure(".", font=('Helvetica', 8), foreground="white")
style.configure("Treeview", foreground='red')
style.configure("Treeview.Heading", foreground='green') #<----

rawDescription: How to edit the style of a heading in Treeview (Python ttk)

description: Edit the style of a heading in Treeview (Python ttk)


code:
import os.path
import mimetypes

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

class FileHandler(tornado.web.RequestHandler):
    def get(self, path):
        if not path:
            path = 'index.html'

        if not os.path.exists(path):
            raise tornado.web.HTTPError(404)

        mime_type = mimetypes.guess_type(path)
        self.set_header("Content-Type", mime_type[0] or 'text/plain')

        outfile = open(path)
        for line in outfile:
            self.write(line)
        self.finish()

def main():
    tornado.options.enable_pretty_logging()
    application = tornado.web.Application([
        (r"/(.*)", FileHandler),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

rawDescription: Is There a Tornado Equivalent of SimpleHTTPServer?


rawDescription: Permutations of Digits in Python

description: Permutations of Digits in Python


rawDescription: a indexing question of ndarray

description: A indexing question of ndarray


code:
for i, element in enumerate(addOffset):
    if element > 126:
        addOffset[i] = element + 94

rawDescription: How can you tell if numbers in a list are bigger than 126? If it is bigger the program needs to add 94 to it

description: Tell if numbers in a list are bigger than 126? If it is bigger the program needs to add 94 to it


rawDescription: Change some levels in a MultiIndex

description: Change some levels in a MultiIndex


rawDescription: Execution of python scripts like udev/rules.d, cron.d or /apt/source.d


code:
import re, ahocorasick,random,time

# search N words from dict
N=3

#file from http://norvig.com/big.txt
with open("big.txt","r") as f:
    text = f.read()

words = set(re.findall('[a-z]+', text.lower()))
search_words = random.sample([w for w in words],N)

A = ahocorasick.Automaton()
for i,w in enumerate(search_words):
    A.add_word(w, (i, w))

A.make_automaton()
#test time for ahocorasic
start = time.time()
print("ah matches",sum(1 for i in A.iter(text)))
print("aho done in ", time.time() - start)

exp = re.compile('|'.join(search_words))
#test time for re
start = time.time()
m = exp.findall(text)
print("re matches",sum(1 for _ in m))
print("re done in ",time.time()-start)

rawDescription: Extract emoticons from a text

description: Extract emoticons from a text


rawDescription: python list by value not by reference

description: Python list by value not by reference


code:
import pandas as pd

pd.read_csv('test.txt', sep='\s\s+', header=4)

rawDescription: Reading dates and data from a file (Python)


code:
def n_dims(dims, start, stop):
    if dims == 1:
            return list(map(lambda x: [x], range(start, stop)))
    else:
            p = n_dims(dims - 1, start, stop)
            a = []
            for i in range(start, stop):
                    a += [j + [i] for j in p]
            return a

rawDescription: Creating N-Dimensional "Permutation" Matrix


code:
xmlfile = open('trb-1996-219.xml', 'rb')
headers = {'content-type': 'application/xml'}
r = requests.put(url, data=xmlfile, headers=headers, auth=HTTPDigestAuth("*", "*"))

rawDescription: Upload a large XML file with Python Requests library


code:
from subprocess import Popen, PIPE

process = Popen([r'path/to/process', 'arg1', 'arg2', 'arg3'], stdin=PIPE, stdout=PIPE)

to_program = "something to send to the program's stdin"
while process.poll() == None:  # While not terminated
    process.stdin.write(to_program)

    from_program = process.stdout.readline()  # Modify as needed to read custom amount of output
    if from_program == "something":  # send something new based on stdout
       to_program = "new thing to send to program"
    else:
       to_program = "other new thing to send to program"

print("Process exited with code {}".format(process.poll()))

rawDescription: Interact with standard input/output of another process


code:
def is_palindrome(s):
    if s == '':
        return True
    else:
        if (ord(s[0]) - ord(s[len(s)-1])) == 0:
            # v-- forgot this here
            return is_palindrome(s[1:len(s)-1])
        else:
            return False

rawDescription: python: recursive check to determine whether string is a palindrome

description: Python: recursive check to determine whether string is a palindrome


code:
from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7],
                '%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')

rawDescription: String to datetime

description: String to datetime


code:
list = [[0 for x in range(4)] for x in range(4)]

# 1. make 4 zeros, slap brackets around it
# 2. make 4 of these lists put it in a list

rawDescription: I want to understand how multi dimensional lists work in python


code:
class Foo(object):
    def __init__(self): pass

x = Foo()

rawDescription: Can an object inspect the name of the variable it's been assigned to?


code: myapp.settings = __import__(SETTINGS_MODULE_NAME, globals(), locals(), [], -1)

rawDescription: Django's Settings Magic

description: Django's Settings Magic


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

def generate_data():
    X = np.arange(25)
    Y = X**2 * np.random.rand(25)
    return X,Y

def update(data):
    mat[0].set_xdata(data[0])
    mat[0].set_ydata(data[1])
    return mat

def data_gen():
    while True:
        yield generate_data()

fig, ax = plt.subplots()
X,Y = generate_data()
mat = ax.plot(X,Y,'o')
ani = animation.FuncAnimation(fig, update, data_gen, interval=500,
                              save_count=10)

ani.save('animation.mp4')
plt.show()

rawDescription: Step by step showing 2D/3D add/remove points


code:
import some_module
data = some_module.__loader__.get_data("path/in/archive/file.txt")

rawDescription: How can I load data files in a Jython module?

description: Load data files in a Jython module


code:
import win32com.client
import inspect, os

def update_toc(docx_file):
    word = win32com.client.DispatchEx("Word.Application")
    doc = word.Documents.Open(docx_file)
    doc.TablesOfContents(1).Update()
    doc.Close(SaveChanges=True)
    word.Quit()

def main():
    script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    file_name = 'doc_with_toc.docx'
    file_path = os.path.join(script_dir, file_name)
    update_toc(file_path)

if __name__ == "__main__":
    main()

rawDescription: Update the TOC (table of content) of MS Word .docx documents with Python


code: max(MyCount.keys(), key=int)

rawDescription: Get max key in dictionary

description: Get max key in dictionary


code:
# create the top-level parser
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='foo help')
subparsers = parser.add_subparsers(help='sub-command help')
# create the parser for the "a" command
parser_a = subparsers.add_parser('a', help='a help')
parser_a.add_argument('bar', type=int, help='bar help')
# create the parser for the "b" command
parser_b = subparsers.add_parser('b', help='b help')
parser_b.add_argument('--baz', choices='XYZ', help='baz help')
# parse some argument lists
parser.parse_args(['a', '12'])
parser.parse_args(['--foo', 'b', '--baz', 'Z'])

rawDescription: Parsing command-line arguments similar to archlinux pacman


code: links = dict((name(link), link) for link in parsed_links)

rawDescription: Filter List of Strings By Keys

description: Filter List of Strings By Keys


code:
class Player(object):
    # ...

    @property
    def clubs(self):
        result = []
        for name in self.club_names:
            result.append(all_clubs.get(name))
        return result

rawDescription: Organizing Python objects for retrieval

description: Organizing Python objects for retrieval


code:
with open('somefile.txt', 'rt') as f:
  print('Hello World!', file=f)

rawDescription: Writing python function outputs to .txt file


code:
import unittest
import mox

class HttpStorageTest(mox.MoxTestBase):

  def setUp(self):
    self.httpstorage = HttpStorage()

  def test_download(self):
    self.mox.StubOutWithMock(urllib2, "urlopen")
    test_file = open("testfile")
    urllib2.urlopen(mox.IgnoreArg()).AndReturn(test_file)

    self.mox.ReplayAll()
    feedback = self.httpstorage.download(test_input, test_output)
    self.assertEqual(feedback, True)

rawDescription: How to unit test this code with pymox?

description: Unit test this code with pymox


code:
text = 'If JOHN would be married to PETER, then MARY would probably be unhappy'
names = ['JOHN', 'LARRY', 'PETER', 'MARY']
[text.find(name) for name in names]

rawDescription: SequenceMatcher: Recording no match just once?


code:
result = pd.merge(df, df2, on='bin').query('cut_min <= perc < cut_max'); result
result = result[['bin', 'id', 'perc', 'result']]
result.sort('id')

rawDescription: Using Python Pandas to bin data in one df according to bins defined in a second df


code:
_environ = dict(os.environ)

...

os.environ.clear()
os.environ.update(_environ)

rawDescription: Python - temporarily modify the current process's environment


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

class Form(QDialog):
    """ Just a simple dialog with a couple of widgets
    """
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.setWindowTitle('Just a dialog')
        self.lineedit = QLineEdit("Write something and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.connect(self.lineedit, SIGNAL("returnPressed()"),
                     self.update_ui)

    def update_ui(self):
        self.browser.append(self.lineedit.text())

if __name__ == "__main__":
    import sys, time

    app = QApplication(sys.argv)

    # Create and display the splash screen
    splash_pix = QPixmap('conti.jpg')

    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    # adding progress bar
    progressBar = QProgressBar(splash)

    splash.setMask(splash_pix.mask())

    splash.show()
    for i in range(0, 100):
        progressBar.setValue(i)
        t = time.time()
        while time.time() < t + 0.1:
           app.processEvents()

    # Simulate something that takes time
    time.sleep(2)

    form = Form()
    form.show()
    splash.finish(form)
    app.exec_()

rawDescription: How can i add a progress bar in splash screen pyqt4

description: Add a progress bar in splash screen pyqt4


code:
import dateutil.parser
yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
yourdate.year
yourdate.month
yourdate.day

rawDescription: Converting datetime to strptime

description: Converting datetime to strptime


code:
class Car(object):
    """Car example with weight and speed."""
    def __init__(self):
        self._weight = None # internal value
        self.speed = None

    @property
    def weight(self):
        return self._weight

    @weight.setter
    def weight(self, the_weight):
        self._weight = the_weight - 10 # or whatever here

rawDescription: Automatic function call on instance variable of Python class?


code: Foo.query(Foo.key == ndb.Key(Foo, '11nNpmkaQk3iJ1kIFNQXAM')).get(keys_only=True)

rawDescription: Google NDB: How to Make a Keys Only Query By Id


code:
def custom_files(members):
    for tarinfo in members:
        if os.path.splitext(tarinfo.name)[1] != ".html":
            yield tarinfo

tar = tarfile.open("sample.tar.gz")
tar.extractall(members=custom_files(tar))
tar.close()

rawDescription: Python tarfile extractall except files matching string


code:
def save(self, *args, **kwargs):
    if self.pk is None:
        prev_quote = Quote.objects.latest()
        #logic to generate quote number using date and prev_quote
        self.quotenumber = new_quote_number
        fixed = self.quotenumber[:9]   # Qyyyymmdd component
        n = int(self.quotenumber[9:])  # nnnn component
        for x in itertools.count(n):
            try:
                super(Post, self).save(*args, **kwargs)
            except IntegrityError:
                self.quotenumber = fixed + str(n+1).zfill(4)
            else:
                break
    else:
        super(Post, self).save(*args, **kwargs)

rawDescription: How do folks generate custom unique numbers when saving a model?


code: array = variable[1:-1].split(',')

rawDescription: Convert string of list to python list

description: Convert string of list to python list


code:
import unittest

from google.appengine.api import taskqueue
from google.appengine.ext import deferred
from google.appengine.ext import testbed

class TaskQueueTestCase(unittest.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()

        # root_path must be set the the location of queue.yaml.
        # Otherwise, only the 'default' queue will be available.
        self.testbed.init_taskqueue_stub(root_path='tests/resources')
        self.taskqueue_stub = self.testbed.get_stub(
            testbed.TASKQUEUE_SERVICE_NAME)

    def tearDown(self):
        self.testbed.deactivate()

    def testTaskAddedToQueue(self):
        taskqueue.Task(name='my_task', url='/url/of/my/task/').add()
        tasks = self.taskqueue_stub.get_filtered_tasks()
        assert len(tasks) == 1
        assert tasks[0].name == 'my_task'

rawDescription: No api proxy found for service "taskqueue"


code: value = [int(v.GetValue()) for v in (self.val1, self.val2, self.val3, self.val4)]

rawDescription: For loop and list - syntax

description: For loop and list - syntax


code:
from lxml.html.soupparser import parse
import urllib

url = 'http://directory.ccnecommunity.org/reports/rptAccreditedPrograms_New.asp?sort=institution'
page = parse(urllib.request.urlopen(url))
unis = page.xpath('//tr/td[@valign="top" and @style="width: 50%;padding-right:15px"]/h3/text()')

rawDescription: Python3 scraper. Doesn't parse the xpath till the end


code:
import numpy as np
import cv2
im = cv2.imread('Photos/test.jpg')
im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)

ball_ycrcb_mint = np.array([0, 90, 100],np.uint8)
ball_ycrcb_maxt = np.array([25, 255, 255],np.uint8)
ball_ycrcb = cv2.inRange(im_ycrcb, ball_ycrcb_mint, ball_ycrcb_maxt)
#cv2.imwrite('Photos/output2.jpg', ball_ycrcb) # Second image
areaArray = []
count = 1

contours, _ = cv2.findContours(ball_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
    area = cv2.contourArea(c)
    areaArray.append(area)

#first sort the array by area
sorteddata = sorted(zip(areaArray, contours), key=lambda x: x[0], reverse=True)

#find the nth largest contour [n-1][1], in this case 2
secondlargestcontour = sorteddata[1][1]

#draw it
x, y, w, h = cv2.boundingRect(secondlargestcontour)
cv2.drawContours(im, secondlargestcontour, -1, (255, 0, 0), 2)
cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 2)
cv2.imwrite('Photos/output3.jpg', im)

rawDescription: Python & OpenCV: Second largest object

description: Python & OpenCV: Second largest object


code:
def package_installed(pkg_name):
    """ref: http:superuser.com/questions/427318/#comment490784_427339"""
    cmd_f = 'dpkg-query -l "%s" | grep -q ^.i'
    cmd = cmd_f % (pkg_name)
    with settings(warn_only=True):
        result = run(cmd)
    return result.succeeded

def yes_install(pkg_name):
    """ref: http://stackoverflow.com/a/10439058/1093087"""
    run('apt-get --force-yes --yes install %s' % (pkg_name))

def make_sure_memcached_is_installed_and_running():
    if not package_installed('memcached'):
        yes_install('memcached')
    with settings(warn_only=True):
        run('/etc/init.d/memcached restart', pty=False)

rawDescription: In Fabric, how can I check if a Debian or Ubuntu package exists and install it if it does not?


code:
strs =  "Hello,World,Good,Morning"
spl = strs.split(',')
spl
func(*spl)

rawDescription: Variable number of arguments in python

description: Variable number of arguments in python


code:
def print_list(table):
    for line in table:
       print(str(line[0]) + " kms, $" + str(line[1]))

with open(input("Enter file name: ")) as f:
    table = []
    for line in f:
        line = line.rstrip().split(",")
        line[0] = int(line[0])
        line[1] = float(line[1])
        table.append(line)

    table.sort(key=lambda line: line[1])
    print_list(table)

rawDescription: How to implement Selection Sort within a list in Python?

description: Implement Selection Sort within a list in Python


rawDescription: Python ORM to NumPy arrays

description: Python ORM to NumPy arrays


code: arr = np.array([RandomCell() for item in range(9)]).reshape(3,3)

rawDescription: initialize objects in numpy matrix

description: Initialize objects in numpy matrix


code:
import os
import files
wanted_file = "file1.py"
# name of module plus contained function
wanted_name = os.path.splitext(wanted_file)[0]
# if you do this many times, you can skip the import lookup after the first hit
if not hasattr(files, wanted_name):
    module = __import__('files.' + wanted_name)
    setattr(files, wanted_name, module)
else:
    module = getattr(files, wanted_name)
fctn = getattr(module, wanted_name)
text = 'print this...'
fctn(text)

rawDescription: Convert string to function in python

description: Convert string to function in python


rawDescription: pandas: combine two columns in a DataFrame

description: Pandas: combine two columns in a DataFrame


code:
def getUsers(flagged, points):
    users = session.query(User)
    if points is not None:
        users = users.filter(User.points > points)
    if flagged:
        users = users.filter(User.flagged == True)
    return users

rawDescription: Ading more AND expressions to a query?

description: Ading more AND expressions to a query


code:
infile = "old.txt"
outfile = "new.txt"

delete_word = ["rainbow"]
lines = [1] #List of lines you want to delete the word from
fin = open(infile)
fout = open(outfile, "w+")
line_count = 0
for line in fin:
      line_count += 1
      for word in line.split():
            if word in delete_word and line_count in lines:
                line = line.replace(word, "")
      fout.write(line)
fin.close()
fout.close()

rawDescription: Need to delete a specific word from a specific line in Python


code:
from tkinter import *

root = Tk()

num1 = IntVar()
num2 = IntVar()
total = IntVar()
def update_total(*severalignoredargs):
    total.set(num1.get() + num2.get())

num1.trace('w',update_total)
num2.trace('w',update_total)

entry1 = Entry(root,textvariable=num1)
entry1.pack()

entry2 = Entry(root,textvariable=num2)
entry2.pack()

total_label = Label(root,textvariable=total)
total_label.pack()

root.mainloop()

rawDescription: How to update Tkinter Label widget?

description: Update Tkinter Label widget


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

x = np.arange(0, 1000, 100)
# As a placeholder for your calculation...
y = np.cos(x / 100.0)

plt.plot(x, y, marker='o', mfc='red')
plt.show()

rawDescription: How to use values inside range()

description: Use values inside range()


rawDescription: Getting code that would self build a python data structure


code:
@section.before_request
def my_method():
    do_stuff

rawDescription: Flask: How to run a method before every route in a blueprint?


code:
cmd = [
    "Message %s",
    "Param %s"
    ]
msg = "foo"
param = "bar"
newcmd = [item % par for item,par in zip(cmd, (msg,param))]
newcmd

rawDescription: Python: Update list parameters

description: Python: Update list parameters


code: mainlist = [line.strip() for line in f if "New changes" not in line]

rawDescription: Read a file, skip unwanted lines & add into a List


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

import pyaudio
import wave

#define stream chunk
chunk = 1024

#open a wav format music
f = wave.open(r"/usr/share/sounds/alsa/Rear_Center.wav","rb")
#instantiate PyAudio
p = pyaudio.PyAudio()
#open stream
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
                channels = f.getnchannels(),
                rate = f.getframerate(),
                output = True)
#read data
data = f.readframes(chunk)

#paly stream
while data != '':
    stream.write(data)
    data = f.readframes(chunk)

#stop stream
stream.stop_stream()
stream.close()

#close PyAudio
p.terminate()

rawDescription: how to play wav file in python?

description: Play wav file in python


rawDescription: String Slicing Python

description: String Slicing Python


rawDescription: picking out elements based on complement of indices in Python pandas

description: Picking out elements based on complement of indices in Python pandas


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

data = np.array([[8,  15,  1, 65, 79],
                 [45, 22, 60, 43, 16],
                 [3,  75, 90, 11, 14],
                 [89, 32, 27, 59, 99],
                 [62,  5, 54, 92, 81]])
nrows, ncols = data.shape
# Generate 1-based row indicies, similar to your table
row = np.vstack(ncols * [np.arange(nrows) + 1]).T

x, y = row.flatten(), data.flatten()

xbins = np.arange(nrows+1) + 0.5
plt.hist2d(x, y, bins=(xbins, 10), cmap=plt.cm.Reds)
plt.show()

rawDescription: Python matplotlib frequency pixel map

description: Python matplotlib frequency pixel map


code:
def remove_item(xs, value):
    if is_empty(xs):
        return xs
    elif head(xs) == value:
        return tail(xs) # or remove_item(tail(xs), value) to remove all
    else:
        return cons(head(xs), remove_item(tail(xs), value))

rawDescription: "Removing" a node from a functional linked list


code:
def edit(request):
    initial = {
       0: {'subject': 'Hello', 'sender': 'user@example.com'},
       1: {'message': 'Hi there!'}
       }
    wiz = FormWizard([form1,form2,form3],initial_dict = initial)
    return wiz(request)

rawDescription: Formwizards for editing in Django

description: Formwizards for editing in Django


code:
import matplotlib.pyplot as plt
import numpy.random as random
from multiprocessing import Pool

def do_plot(number):
    fig = plt.figure(number)

    a = random.sample(1000)
    b = random.sample(1000)

    # generate random data
    plt.scatter(a, b)

    plt.savefig("%03d.jpg" % (number,))
    plt.close()

    print("Done ", number)

if __name__ == '__main__':
    pool = Pool()
    pool.map(do_plot, range(4))

rawDescription: Saving multiple matplotlib figures with multiprocessing


rawDescription: Use urllib.urlretrieve and ignore proxy

description: Use urllib.urlretrieve and ignore proxy


rawDescription: lines of code within a class in python?

description: Lines of code within a class in python


code:
import numpy
A = numpy.array([1, 7, 1000, 1500])
B = numpy.array([True, False, True, True, False, True, False, False])
A[B.cumsum() - 1]

rawDescription: Constructing piecewise function from changepoints in Numpy


code:
import sys, csv
writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerows(data)

rawDescription: What is the best way to print a table with delimiters in Python


code:
import random

f=open('/tmp/names.txt', 'r')
array=f.readlines()  # read all lines
f.close()  # release file
array_len = len(array)
for index in range(array_len):
    swap = random.randrange(array_len - 1)
    swap += swap >= index
    array[index], array[swap] = array[swap], array[index]
f=open('/tmp/shuffle.txt', 'w')  # open dst file
f.write("".join(array))  # save shuffled names
f.close() # release - close file

rawDescription: Program that shuffles

description: Program that shuffles


code:
from tkinter import *

def calc_result():
    noname = int(entry_3.get()) / int(entry_2.get())
    enheter = int(entry_1.get()) / int(entry_2.get())
    label_4 =Label(root, text='Result, ' + str(enheter))
    label_4.grid(row=5, sticky=SE)

root = Tk()

root.wm_title("DiabetesC")

label_1 =Label(root, text='Kolhydrater')
label_2 =Label(root, text='Insulin igår?')
label_3 =Label(root, text='Regel, 330/500?')

label_version =Label(root, text='DiabetesC v.0.0.1 made by Pantburken')

entry_1 = Entry(root)
entry_2 = Entry(root)
entry_3 = Entry(root)

button_1 = Button(root, text='Räkna ut!', command=calc_result)

label_version.grid(row=0, column=1)

label_1.grid(row=1, sticky=E)
label_2.grid(row=2, sticky=E)
label_3.grid(row=3, sticky=E)

entry_1.grid(row=1, column=1)
entry_2.grid(row=2, column=1)
entry_3.grid(row=3, column=1)

button_1.grid(row=4, sticky=E)
root.mainloop()

rawDescription: How do I put "calculating abilities" into TKinter entrys?

description: Put "calculating abilities" into TKinter entrys


rawDescription: regular expressions and a special character by itself

description: Regular expressions and a special character by itself


rawDescription: replacing parts of string using regular expression match in python

description: Replacing parts of string using regular expression match in python


code:
if not os.path.isfile(att_path) :
        for files in att_path:
            data = content.replace(" ", ",") #replaces if the delimiter is anything other than a ",".
            fp = open(att_path+".csv", 'wb')
            fp.write(data)
            fp.close()

rawDescription: Download data from unread emails into separate files Python


code:
from PIL import Image, ImageDraw, ImageFont
from coverage import coverage

cov = coverage()
cov.load()
total = cov.report()

# total = 79.0

im = Image.new("RGB", (120, 20))
fnt = ImageFont.load_default()
d = ImageDraw.Draw(im)

d.text((10, 5), "coverage:", fill=(255, 255, 255), font=fnt)
d.rectangle([(80, 0), (150, 20)], fill=(220, 0, 0))
d.text((90, 5), "{:.0f}%".format(total), fill=(0, 0, 0), font=fnt)

rawDescription: Python coverage badges, how to get them?

description: Python coverage badges, how to get them


code:
import shutil
import datetime

###   Variable Definitions
from System import Environment
data_dir_base = Environment.GetEnvironmentVariable('LMSRVSHARED')
xfer_dir = data_dir_base + "tenant1\\xfer\\"
source_file = xfer_dir + "CRM_DIALER_UPLOAD.txt"
now = datetime.datetime.now()
date = now.strftime("%Y%m%d_%H%M%S")
new_folder = xfer_dir + "Uploads\\"
dest = new_folder + 'CRM_DIALER_UPLOAD' + '_' + str(date) + '.txt'

###   Main Script
shutil.copy(source_file, dest)

rawDescription: Copy file from one folder to another and then rename using current date/time and new file ext using PowerShell or Python script


code:
class UserAdmin(BaseUserAdmin):
    def get_fieldsets(self, request, obj=None):
        fieldsets = list(super(UserAdmin, self).get_fieldsets(request, obj))
        # update the `fieldsets` with your specific fields
        fieldsets.append(
            ('Personal info', {'fields': ('bdate', 'website', 'location')}))
        return fieldsets

rawDescription: How to inherit fields from User in Django admin using custom user?

description: Inherit fields from User in Django admin using custom user


code:
# settings.py
AUTH_PROFILE_MODULE = 'myapp.UserProfile'

# myapp/models.py
class UserProfile(models.Model):
    CLASS_CHOICES = (
        (0, 'Yellow User'),
        (1, 'Green User'),
    )
    user_class = models.IntegerField(choices=CLASS_CHOICES)
    user = models.OneToOneField(User)

class Interaction(models.Model):
    u1 = models.ForeignKey(User, related_name='u1s')
    u2 = models.ForeignKey(User, related_name='u2s')
    date = models.DateField()

rawDescription: Improving run time of simple query

description: Improving run time of simple query


code:
soup = BeautifulSoup('<script>a</script>baba<script>b</script>')
[s.extract() for s in soup('script')]
soup

rawDescription: Can I remove script tags with BeautifulSoup?

description: Remove script tags with BeautifulSoup


code:
def split_by_newline(text):
    ''' Split text by new lines '''
    return text.splitlines()

def split_by_indentation(text):
    ''' Detect paragraphs by indentations '''
    # ...

def take_first_sencence(paragraph):
    ''' Expect a single paragraph, return its first sentence'''
    # ...

def take_first_sentences(text, paragraph_policy=split_by_newline):
    for paragraph in paragraph_policy(text):
        yield take_first_sentence(paragraph)

rawDescription: how to judge a paragraph in automatic abstract?

description: Judge a paragraph in automatic abstract


code:
# This is not a full working example, just a starting point
# for downloading images in different formats.

import subprocess
import Image

def image_as_png_pdf(request):
  output_format = request.GET.get('format')
  im = Image.open(path_to_image) # any Image object should work
  if output_format == 'png':
    response = HttpResponse(mimetype='image/png')
    response['Content-Disposition'] = 'attachment; filename=%s.png' % filename
    im.save(response, 'png') # will call response.write()
  else:
    # Temporary disk space, server process needs write access
    tmp_path = '/tmp/'
    # Full path to ImageMagick convert binary
    convert_bin = '/usr/bin/convert'
    im.save(tmp_path+filename+'.png', 'png')
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename
    ret = subprocess.Popen([ convert_bin,
                            "%s%s.png"%(tmp_path,filename), "pdf:-" ],
                            stdout=subprocess.PIPE)
    response.write(ret.stdout.read())
  return response

rawDescription: Downloading and zipping files from amazon


code:
food = "ask not what your country can do for you ask what you can do for your country"
food2 = food.split()
print(food)

word = input("Enter Word: ")

for (num, x) in enumerate(food2):
    if word == x:
        print ("Your word is in position ",num+1,"!")

rawDescription: Unexpected printed output with simple program doing string comparisons


code:
import argparse

## This function takes the 'extra' attribute from global namespace and re-parses it to create separate namespaces for all other chained commands.
def parse_extra (parser, namespace):
  namespaces = []
  extra = namespace.extra
  while extra:
    n = parser.parse_args(extra)
    extra = n.extra
    namespaces.append(n)

  return namespaces

argparser=argparse.ArgumentParser()
subparsers = argparser.add_subparsers(help='sub-command help', dest='subparser_name')

parser_a = subparsers.add_parser('command_a', help = "command_a help")
## Setup options for parser_a

## Add nargs="*" for zero or more other commands
argparser.add_argument('extra', nargs = "*", help = 'Other commands')

## Do similar stuff for other sub-parsers

rawDescription: How to parse multiple sub-commands using python argparse?

description: Parse multiple sub-commands using python argparse


code:
from celery.task.control import discard_all
discard_all()

rawDescription: close() or join() equivalent for celery jobs (python)?

description: Close() or join() equivalent for celery jobs (python)


code:
# assuming you have the contents read from the file split into this list:
lines = content.splitlines()

indicestoremove=[]
for index in range (2,6): # or whatever range of lines you want to trim -
                          # remember indices start from 0 for the first line
    if lines[index] == '':
        indicestoremove.append(index)

# remove in reverse order, as pop() changes the index of items later in the list
for index in sorted(indicestoremove, reverse=True):
    lines.pop(index)

f = open('filename')
for line in lines:
  f.write("%s\n" % line)

rawDescription: How to remove specific empty lines from multi line strings in python?

description: Remove specific empty lines from multi line strings in python


code:
header = next(file1)
for line1, line2 in zip(file1, file2):
    ...

rawDescription: Move only 1 of two iterators in zip Python the first time


code:
import unittest

class BaseTestCase(unittest.TestCase):
    my_dict = {'hello': 'world'}

class TestCase1(BaseTestCase):
    def test_my_dict_key(self):
        self.assertTrue('hello' in self.my_dict)

class TestCase2(BaseTestCase):
    def test_my_dict_value(self):
        self.assertTrue('world' in self.my_dict.values())

rawDescription: how to share a variable across modules for all tests in py.test

description: Share a variable across modules for all tests in py.test


code:
from rpy2.robjects.lib.ggplot2 import ggplot, \
                               aes_string, \
                               geom_histogram, \
                               element_blank, \
                               theme_bw, \
                               theme
from rpy2.robjects import r

nogrid_x_theme = theme(**{'panel.grid.major.x': element_blank(),
                         'panel.grid.minor.x': element_blank()})
iris = r('iris')
p = ggplot(iris) + geom_histogram(aes_string(x = 'Sepal.Width'))
p += theme_bw() + nogrid_x_theme
p.plot()

rawDescription: Turning off ggplot2 grids in rpy2

description: Turning off ggplot2 grids in rpy2


code:
def eliminate(s, bad_characters):
    for item in bad_characters:
        s = s.replace(item, '')
    return s

rawDescription: Remove items in a sequence from a string Python


rawDescription: How to change to a different line of file in for loop

description: Change to a different line of file in for loop


code:
L = [...]
while any(isinstance(i, list) for i in L):
   L = [j for i in L for j in (i if isinstance(i, list) else [i])]

result = sum(L)

rawDescription: Summing nested lists without recursion in python


code:
def repl(m):
  if m.group(0) == ' ':
    return '%20'
  else:
    return ','

re.sub(',? +', repl, "single, single, double word, single  word, also      single")

rawDescription: Evaluate string from user to comma separated words string


code:
df3 = pd.concat([df1, df2], join = "outer", axis=1)
df4 = df3.b.sum(axis=1)

rawDescription: Merge pandas dataframe, with column operation


code: cde = form.save(commit=True)

rawDescription: Django: Get the id you just received from forms in views (not yet saved)


code:
def removebackslash(source):
    while(source.find('\\') != -1):
        startback = source.find('\\')
        endback = source[startback:].find(' ') + startback + 1
        source = source[0:startback] + source[endback:]
    return source

rawDescription: Can't get single \ in python

description: Can't get single \ in python


code:
from sqlalchemy import *
db = create_engine('sqlite:///people.db')

metadata = MetaData()

user = Table('people', metadata,
Column('ID', Integer, primary_key = True),
Column('name', String(16), nullable = False),
Column('area', String(16)),
Column('job', String(60))
)

rawDescription: Python 3.3.2 - How to Set Out a Small Database?


code: [re.findall(r'[A-Za-z_\'-]+[^-\d\(\)\']', line) for line in s.split('\n')]

rawDescription: Parse out elements from a pattern

description: Parse out elements from a pattern


code: return 'graphs/documents/{0}/email/{1}_{2}'.format(instance.owner.id, now, filename)

rawDescription: How to get current user in django model?

description: Get current user in django model


rawDescription: Remove border from html table created via pandas


code:
import moduleB

moduleB.some_variable = 'foo'

rawDescription: Overriding module-level variables

description: Overriding module-level variables


code:
import compiler, inspect
import re # for testing
compiler.parse(inspect.getsource(re))

rawDescription: python: get the abstract syntax tree of imported function?

description: Python: get the abstract syntax tree of imported function


code:
objects = {4: oven, 8: delta_t_pause, 15: caliberBox}
if senderid in objects:
    obj = objects[senderid](data)

rawDescription: Object instance evocation by provided variable


code:
class Account:
    def __init__(self,id=0):
        self.__id = id
        self.__balance = 0
        self.__annualInterestRate = 0

    def getid(self):
        return self.__id

    def getbalance(self):
        return self.__balance

    def getannualInterestRate(self):
        return self.__annualInterestRate

    def setid(self,id):
        self.__id = id

    def setbalance(self, balance):
        self.__balance = balance

    def setannualInterestRate(self, rate):
        self.__annualInterestRate = rate

    def getMonthlyInterestRate(self):
        return self.__annualInterestRate/12

    def getMonthlyInterest(self):
        return self.__balance * self.getMonthlyInterestRate()

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
            return True
        else:
            return False

rawDescription: Withdrawing method for a class in python


code:
new_list = [s + ' letter' for s in mylist[:-1]] + mylist[-1:]
new_list

rawDescription: Python: looping through a list?

description: Python: looping through a list


code:
class Upper(Packet):
    name = "UpperLayer"
    fields_desc = [
        ConditionalField(IntField("Field",0xABCDEF00),
                         lambda pkt: hasattr(pkt.underlayer,"src") and pkt.underlayer.src == "1.2.3.4")
                   ]

rawDescription: Accessing a lower layers fields with lambda function in Scapy


code:
from itertools import islice
with open('target.txt', 'w') as target:
    f1, f2 = open('f1.txt'), open('f2.txt')
    while True:
        ls1 = islice(f1, 32)
        if not ls1:
            # will not happen in this case
            target.write('\n' + f2.read())
            break
        ls2 = islice(f2, 64)
        if not ls2:
            target.write('\n' + f1.read())
            break
        target.write('\n'.join('\n'.join(ls) for ls in [ls1, ls2]))
    f1.close()
    f2.close()

rawDescription: how to sequentially read two txt files and write into a new file in python?

description: Sequentially read two txt files and write into a new file in python


code:
v = g.vs[12]
g.delete_vertices(...)
g.vs[v.index] == v

rawDescription: Python igraph vertex indices

description: Python igraph vertex indices


code:
d = { 't':'ch' , 'r' : 'gh'}
s = ' Text to replace '
import re
pattern = '|'.join(map(re.escape, d))
re.sub(pattern, lambda m: d[m.group()], s)

rawDescription: Grouping the characters and performing substitution


code:
from dateutil import parser
parser.parse("There's a date 09-21 in here", fuzzy=True)

rawDescription: Is there a Python module to detect month or day in string?


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

years = [2004, 2005, 2006, 2007]

sales = [1000, 1170, 660, 1030]

ax.plot(years, sales)
ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%d'))

plt.show()

rawDescription: How to set x-axis labels on a figure plotted using matplotlib's pyplot?

description: Set x-axis labels on a figure plotted using matplotlib's pyplot


rawDescription: How can I find the square matrix of a lower triangular numpy matrix? (with a rotated upper triangle)

description: Find the square matrix of a lower triangular numpy matrix? (with a rotated upper triangle)


code:
sample_dict = {'test': ['a', 'b', 'c', 'd', 'e']}

def replace_item(sample_dict, item, new_item):
    list = sample_dict['test']
    list[list.index(item)] = new_item

replace_item(sample_dict, 'd', 'f')
# {'test': ['a', 'b', 'c', 'f', 'e']}

rawDescription: Given a dictionary, how to replace an item in the list?


code:
a
lis
a[np.arange(len(a)), lis]

rawDescription: Index a numpy array using a list in a pythonic way


code:
import random
sources = ['a', 'b', 'c', 'd']      # you said 4 strings
result = [random.choice(sources)]

while len(result) < 16:             # you said you need 16 elements
    elem = random.choice(sources)
    if elem != result[-1]:
        result.append(elem)

rawDescription: Enforcing "no 2 same contiguous elements" in random list generation


code:
secsAfterADEpoch = float(your_weird_time) / 10000000.0 # seconds since jan 1st 1601
ADToUnixConvertor = ((1970-1601) * 365.242190) * 86400 # unix epoch - AD epoch * number of tropical days * seconds in a day
unixified = (secsAfterADEpoch-ADToUnixConvertor)+31800 # unix Timestamp version of AD timestamp + correction time

rawDescription: UNIX time is too long

description: UNIX time is too long


code:
import BaseHTTPServer, SimpleHTTPServer
import ssl

SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map['.my_ext'] = 'application/pkcs7-mime'
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='Certificates.pem', server_side=True)
httpd.serve_forever()

rawDescription: SimpleHTTPServer adding multiple handlers


code:
while True:
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(text ,(x , y))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        elif event.type == KEYDOWN or event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit(0)

    if  pygame.key.get_pressed()[K_LEFT]:
        x -= 15

    if  pygame.key.get_pressed()[K_RIGHT]:
        x += 14

    if  pygame.key.get_pressed()[K_UP]:
        y -= 15

    if  pygame.key.get_pressed()[K_DOWN]:
        y += 15
    pygame.display.update()

rawDescription: How do I make a game object move continuously as long as the key is pressed?

description: Make a game object move continuously as long as the key is pressed


code:
numpy.savetxt('savetxt.csv', Myresult, header=' '.join(Myheader) + '\n', newline='',
              comments='')

rawDescription: Error in writing two arrays into a CSV file, one header in string and other numpy.float array


code:
import urllib2
from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen("http://www.daisuki.net/us/en/anime/watch.GUNDAMUNICORNRE0096.13142.html"), "lxml")
Name = soup.title.string

" - ".join(Name.replace('#', "").split(" - ")[1::-1])

rawDescription: Python Rearrange & remove character from html page title


code:
events = client.events().list(calendarId='primary',
                              timeMin='2011-12-22T09:00:00Z',
                              timeMax='2011-12-22T22:00:00Z').execute()

rawDescription: How can I determine the current event in Google Calendar using Python?

description: Determine the current event in Google Calendar using Python


code:
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
    """
    Get a form Field for a ManyToManyField.
    """
    # If it uses an intermediary model that isn't auto created, don't show
    # a field in admin.
    if not db_field.rel.through._meta.auto_created:
        return None    # return something suitable for your needs here!
    db = kwargs.get('using')

    if db_field.name in self.raw_id_fields:
        kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
        kwargs['help_text'] = ''
    elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
        kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))

rawDescription: Django Admin - Displaying Intermediary Fields for M2M Models


code:
import collections,json,os.path
winners = collections.Counter()
for logFile in logFiles:
    with open(os.path.join("logs", logFile), 'r') as jsonf:
        jsonData = json.load(jsonf)
    winner = str(jsonData[6]['winner'])
    winners[winner] += 1
winnerList = list(winners.keys())
bestPlayers = winners.most_common()

rawDescription: Set dict value to the number of times it's inserted python?


rawDescription: wxPython: how to get screen x/y for line in a RichTextCtrl?

description: WxPython: how to get screen x/y for line in a RichTextCtrl


rawDescription: Plotting a 3d surface from a list of tuples in matplotlib


code:
i = 0
while i < len(mylist):
    if i + 1 < len(mylist) and '@' in mylist[i+1]:
        name = mylist[i]
        email = mylist[i+1]
        i+=1
    else:
        email = ''
        name = mylist[i]

    print(name)
    print(email)
    i+=1

rawDescription: Compare and assign value in Python list

description: Compare and assign value in Python list


code:
def filter_isolated_cells(array, struct):
    """ Return array with completely isolated single cells removed
    :param array: Array with completely isolated single cells
    :param struct: Structure array for generating unique regions
    :return: Array with minimum region size > 1
    """

    filtered_array = np.copy(array)
    id_regions, num_ids = ndimage.label(filtered_array, structure=struct)
    id_sizes = np.array(ndimage.sum(array, id_regions, range(num_ids + 1)))
    area_mask = (id_sizes == 1)
    filtered_array[area_mask[id_regions]] = 0
    return filtered_array

# Run function on sample array
filtered_array = filter_isolated_cells(square, struct=np.ones((3,3)))

# Plot output, with all isolated single cells removed
plt.imshow(filtered_array, cmap=plt.cm.gray, interpolation='nearest')

rawDescription: Removing completely isolated cells from Python array?


code:
class MyModel(models.Model):
    tags = TagField(blank=False)

rawDescription: How do I make tags required with django-tagging?

description: Make tags required with django-tagging


code:
fns = [(lambda x,y = y: x == y) for y in range(10)]
map(lambda x: x(1), fns)

rawDescription: Generating families of lambda functions

description: Generating families of lambda functions


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

fig, ax1 = plt.subplots(1,1)
ax1.set_xlabel('x')
ax1.set_ylabel('y')

# plot something
x = np.linspace(0.01, 10*np.pi, 1000)
y = np.sin(x)/x
ax1.plot(x, y)

# add a twin axes and set its limits so it matches the first
ax2 = ax1.twinx()
ax2.set_ylabel('1/y')
ax2.set_ylim(ax1.get_ylim())

# apply a function formatter
formatter = mticker.FuncFormatter(lambda x, pos: '{:.3f}'.format(1./x))
ax2.yaxis.set_major_formatter(formatter)

plt.show()

rawDescription: Plotting a second scaled y axis in matplotlib from one set of data


code:
def clearfile(filename):
    out_file = open('%s_%s%s' %(os.path.splitext(filename)[0], 'ok', os.path.splitext(os.path.basename(filename))[1]) , 'a')
    for row in (open (filename, 'r')).readlines():
        if row[0][0]!= '\n' and riga[0][0]!='(' :
            out_file.write(riga)
    out_file.close()
    return out_file

rawDescription: Filter rows from text file

description: Filter rows from text file


code:
import win32evtlog

outfile = open('NTLog.log', 'w')
server = 'SERVER_Name'
logtype = 'Security'
hand = win32evtlog.OpenEventLog(server, logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)
count = 0
while count != total:
    events = win32evtlog.ReadEventLog(hand, flags,0)
    if events:
        for event in events:
            data = event.StringInserts
            if data:
                outfile.write(data[0])

rawDescription: Python WMI moniker problem

description: Python WMI moniker problem


code: dict2 = {k: k for k in dict1}

rawDescription: Creating a dictionary with values identical to keys from another dictionary


code:
# do all the stuff to set up the api_key, get a `User` object, etc.

def is_document_i_want(document):
    return document.author == "Me"

urls = [document.get_download_url() for document in user.all()
        if is_document_i_want(document)]

for url in urls:
    path = urllib.parse.urlparse(url).path
    name = os.path.basename(path)
    u = urllib.request.urlopen(url)
    with open(name, 'w') as f:
        f.write(u.read())
    print('Wrote {} as {}'.format(url, name))

rawDescription: How to automate downloading .txt files from Scribd.com

description: Automate downloading .txt files from Scribd.com


code:
from IPython.core.display import HTML
HTML("""
<style>

div.cell { /* Tunes the space between cells */
margin-top:1em;
margin-bottom:1em;
}

div.text_cell_render h1 { /* Main titles bigger, centered */
font-size: 2.2em;
line-height:1.4em;
text-align:center;
}

div.text_cell_render h2 { /*  Parts names nearer from text */
margin-bottom: -0.4em;
}

div.text_cell_render { /* Customize text cells */
font-family: 'Times New Roman';
font-size:1.5em;
line-height:1.4em;
padding-left:3em;
padding-right:3em;
}
</style>
""")

rawDescription: How to change the font size and color of markdown cell in Ipython (py 2.7) notebook

description: Change the font size and color of markdown cell in Ipython (py 2.7) notebook


code:
import re
o = re.compile(r'''
\btext1\b |
\btext2\b |
\btext3\b
''', flags=re.VERBOSE)
o.search('text1')
o.search('text2')
o.search('text3')
o.search('text4')

rawDescription: python splitting regexp patterns on multiple lines

description: Python splitting regexp patterns on multiple lines


code:
from Tkinter import *

myGui=Tk()
myGui.geometry("200x100")
myGui.title("basicGUI")
myGui.configure(bg="gray")

eV=''

entry = Entry(width=10)
entry.pack()

def btnWork():
    eV = entry.get()
    myEmpty.config(text=eV)

myBtn=Button(text="getVar", command=btnWork)
myBtn.pack()

myEmpty = Label(text=eV, width=10)
myEmpty.pack()

myGui.mainloop()

rawDescription: Why is this Python 2.7 code generating excessive labels?


code:
import bert
bert.decode(bert.encode([u"x", "x"]))
bert.decode(bert.encode({"x":[u"x", "x"]}))

rawDescription: Python save serialization that correctly handles str/unicode?


code:
from datetime import datetime

dVal = datetime.strptime('10/22/1984', '%m/%d/%Y')

rawDescription: Convert string into datetime type

description: Convert string into datetime type


code:
class MyDialog(QtGui.QDialog):
    # ...
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)

        # when you want to destroy the dialog set this to True
        self._want_to_close = False

    def closeEvent(self, evnt):
        if self._want_to_close:
            super(MyDialog, self).closeEvent(evnt)
        else:
            evnt.ignore()
            self.setWindowState(QtCore.Qt.WindowMinimized)

rawDescription: QDialog - Prevent Closing in Python and PyQt


code:
def make_property(i, dict):
    def fget(self):
        return i

    dict['f%d' % i] = property(fget)

class Test(object):
    def __metaclass__(name, bases, dict):
        for i in range(5):
            make_property(i, dict)

        return type(name, bases, dict)

rawDescription: Dynamic function with local variables

description: Dynamic function with local variables


rawDescription: Django: How to use stored model instances as form choices?


code: processed = mark_boundaries(frame, segments==some_segment)

rawDescription: Detecting border pixel of a segmentation label


code: d = collections.defaultdict(lambda: [0, []])

rawDescription: Can python dictionary comprehension be used to create a dictionary of substrings and their locations?


code:
from flask import request

tags = request.form.get('tags', []) # Where tags is a list of new tags

mongo_collection.update(
    {'_id': ObjectId('4ff1c0d0dec94126a2000000')},
    {'$pushAll': {'tags': tags}},
    )

rawDescription: Adding tags to mongodb records from flask application


code:
from django.core.validators import validate_email
from django import forms

...
if request.method == "POST":
    try:
        validate_email(request.POST.get("email", ""))
    except forms.ValidationError:
        ...

rawDescription: Django: How to check if something is an email without a form


code:
import Image
import numpy as np
x = np.array([[1., 2.], [3., 4.]])
im = Image.fromarray(x)
list(im.getdata())
[im.getpixel(x) for x in [(0,0), (0,1), (1,0), (1,1)]]

rawDescription: the data from PIL's getpixel & getdata are not the same?

description: The data from PIL's getpixel & getdata are not the same


code:
from django.forms.widgets import ClearableFileInput

class MyClearableFileInput(ClearableFileInput):
    initial_text = 'currently'
    input_text = 'change'
    clear_checkbox_label = 'clear'

class EditProfileForm(ModelForm):
    image = ImageField(label='Select Profile Image',required = False, widget=MyClearableFileInput)

rawDescription: How to rename currently, Clear and Change labels in ImageField of Django

description: Rename currently, Clear and Change labels in ImageField of Django


code:
import matplotlib.pyplot as plt
ind = (1,2,3)
width = 0.8
fig,a = plt.subplots()
p1 = a.bar(ind,ind)
a.xaxis.set_visible(False)
a.yaxis.set_visible(False)
plt.show()

rawDescription: How to remove axis in pyplot.bar?

description: Remove axis in pyplot.bar


code:
import code
import readline
import rlcompleter

# do something here

vars = globals()
vars.update(locals())
readline.set_completer(rlcompleter.Completer(vars).complete)
readline.parse_and_bind("tab: complete")
shell = code.InteractiveConsole(vars)
shell.interact()

rawDescription: Keyboard shortcuts broken running interactive Python Console from a script


code:
s=mlab.surf(xx,yy,zz,colormap='GnBu')
lut = s.module_manager.scalar_lut_manager.lut.table.to_array()
ilut = lut[::-1]
# putting LUT back in the surface object
s.module_manager.scalar_lut_manager.lut.table = ilut
# forcing to update the figure once we have changed the LUT
mlab.draw()
mlab.view()

rawDescription: invert colormap in mlab

description: Invert colormap in mlab


code:
import collections
foo = collections.deque(maxlen=3)
foo.append(1)
foo.append(2)
foo.append(3)
foo
foo.append(4)
foo

rawDescription: Is this even possible?

description: Is this even possible


code:
#try a function
def func_tim():
    bob = True
    while bob == True:
        #define vars
        a = int(input('Please insert a number: '))
        b = int(input('Please insert a second number: '))

        if a == b:
            print('nice and equal')
            bob = False
        elif b > a:
             print('b is picking on a!')
        else:
            print('a is picking on b!')
#call a function
func_tim()

rawDescription: Beginner python - stuck in a loop

description: Beginner python - stuck in a loop


code:
class Meta:
    abstract = True

rawDescription: Django - Is it possible in a intermediate table to use an inherited ForeignKey for the target model?


code:
raw_message = """From: Santa Claus <santa@aintreal.no>
To: Some Dude <some@du.de>
Subject: I have lost your presents.

Dude, i am so sorry.
"""

import email
msg = email.message_from_string(raw_message)
print(msg['Subject'])  # "I have lost your presents."

rawDescription: python email.parser: extract header from email

description: Python email.parser: extract header from email


code:
#1:
df[df['rating']>0.5]
#2:
df.query('name in ("John", "Mary")')
#3:
df.query('name in ("John", "Mary") and rating > 0.5')

rawDescription: Advanced Python Pandas Dataframe Selection


rawDescription: PyQt treeview edit text on doubleclick

description: PyQt treeview edit text on doubleclick


code:
class Node(object):
    def __init__(self, element):
        self.element = element
        self.left = self.right = None

    @classmethod
    def tree(cls, element, left, right):
        node = cls(element)
        node.left = left
        node.right = right
        return node

rawDescription: What to return in Factory Methods?

description: What to return in Factory Methods


code:
n = 5
from math import floor, log
n = 5
(n & (1 << np.arange(int(floor(log(n, 2) + 1))))) > 0
n = 8
(n & (1 << np.arange(int(floor(log(n, 2) + 1))))) > 0
n = 514
(n & (1 << np.arange(int(floor(log(n, 2) + 1))))) > 0

rawDescription: numpy Boolean array represenation of an integer

description: Numpy Boolean array represenation of an integer


code:
def main():
    q = Queue.Queue()
    for i in range(3):
        t = threading.Timer(1, run_function, [q, i])
        t.start()

    while True:
        item = q.get()
        save_to_disk(item)
        q.task_done()

def run_function(q, i):
    t = threading.Timer(1, run_function, [q, i])
    t.start()
    q.put(function_with_delay(i))

rawDescription: Run multiple functions every second, write result to file


code:
pkt_str = str(pkt)
pkt_str

rawDescription: Converting hex to ascii while reading packets in scapy -- Python


code:
import re
text = file('filename').read()
numbers = re.findall(r'([0-9.]+) hrs ([0-9]+) miles', text)
hours = sum(float(x[0]) for x in numbers)
miles = sum(int(x[1]) for x in numbers)

rawDescription: Python to search for add numbers intelligently


rawDescription: mysql_fetch_array or mysql_fetch_object for python?

description: Mysql_fetch_array or mysql_fetch_object for python


code: raw_id_fields = ('zipcode',)

rawDescription: Django admin hangs (until timeout error) for a specific model when trying to edit/create


rawDescription: Print result right after each unit test

description: Print result right after each unit test


code:
#print 'path: ',path
#print 'body:',body

rawDescription: Check the solr query generated by haystack


code:
from paramiko import SSHClient

# Set up the proxy (forwarding server) credentials
proxy_hostname = 'your.proxy.hostname'
proxy_username = 'proxy-username'
proxy_port = 22

# Instantiate a client and connect to the proxy server
proxy_client = SSHClient()
proxy_client.load_host_keys('~/.ssh/known_hosts/')
proxy_client.connect(
    proxy_hostname,
    port=proxy_port,
    username=proxy_username,
    key_filename='/path/to/your/private/key/'
)

# Get the client's transport and open a `direct-tcpip` channel passing
# the destination hostname:port and the local hostname:port
transport = proxy_client.get_transport()
dest_addr = ('0.0.0.0', 8000)
local_addr = ('127.0.0.1', 1234)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)

# Create a NEW client and pass this channel to it as the `sock` (along with
# whatever credentials you need to auth into your REMOTE box
remote_client = SSHClient()
remote_client.load_host_keys(hosts_file)
remote_client.connect('localhost', port=1234, username='remote_username', sock=channel)

# `remote_client` should now be able to issue commands to the REMOTE box
remote_client.exec_command('pwd')

rawDescription: Paramiko: Port Forwarding Around A NAT Router


code:
import arcpy

# A list of .dbf, .csv, and FGDB tables
tables = [r'C:\path\to\your.gdb\fgdb_table',
          r'C:\path\to\your\csv_table.csv',
          r'C:\path\to\your\dbf_table.dbf']

# Perform the deletion
for table in tables:
    arcpy.Delete_management(table)

rawDescription: What's the code for dropping or deleting a table in arcpy?


code:
dates = num2date(rootgrp.variables['time'][:],units=rootgrp.variables['time'].units)
var1=rootgrp.variables['var1']
var2=rootgrp.variables['var2']

cpy = cStringIO.StringIO()

for timeindex, time in enumerate(dates):

    validtimes=np.empty(var1[timeindex].size, dtype="object")
    validtimes.fill(time)

    #  Transponse and stack the arrays of parameters
    #    [a,a,a,a]        [[a,b,c],
    #    [b,b,b,b]  =>     [a,b,c],
    #    [c,c,c,c]         [a,b,c],
    #                      [a,b,c]]

    a = np.hstack((
              validtimes.reshape(validtimes.size,1),
              stationnames.reshape(stationnames.size,1),
              var1[timeindex].reshape(var1[timeindex].size,1),
              var2[timeindex].reshape(var2[timeindex].size,1)
    ))

    # Fill the cStringIO with text representation of the created array
    for row in a:
            cpy.write(row[0].strftime("%Y-%m-%d %H:%M")+'\t'+ row[1] +'\t' + '\t'.join([str(x) for x in row[2:]]) + '\n')

conn = psycopg2.connect("host=postgresserver dbname=nc user=user password=passwd")
curs = conn.cursor()

cpy.seek(0)
curs.copy_from(cpy, 'ncdata', columns=('validtime', 'stationname', 'var1', 'var2'))
conn.commit()

rawDescription: Load PostgreSQL database with data from a NetCDF file


code: {{ news.description|truncatewords:50 }}

rawDescription: how to show first 50 words of a text field in django template

description: Show first 50 words of a text field in django template


code:
def compare(first, second):
    result = []

    for x in first:
        result.append([])
        for y in second:
            result[-1].append(1 if x >= y else 0)

    result = [list(i) for i in zip(*result)]

    return result

rawDescription: Python compare rows and columns of a table


code:
from mksfunction import mks_create_sandbox
import os.path

if not os.path.exists('home/build/test/new_sandbox/project.pj'):
    mks_create_sandbox()

rawDescription: calling an outside function in python

description: Calling an outside function in python


code:
class Program():

    def run(self):
        while 1:
            try:
                self.do_something()
            except KeyboardInterrupt:
                break

    def do_something(self):
        print("Doing something")

# usage:

a = Program()
a.run()

# will print a lot of statements

# if you hit CTRL+C it will stop
# then you can run it again with a.run()

rawDescription: Pause Python program on the fly (and resume)


rawDescription: changing float format to have both decimals and commas

description: Changing float format to have both decimals and commas


rawDescription: Editing MS Word header with win32com

description: Editing MS Word header with win32com


code:
import paramiko
import time
import sys

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port=Port, username=usr,password=Psw)

transport = ssh.get_transport()
session = transport.open_session()
session.setblocking(0) # Set to non-blocking mode
session.get_pty()
session.invoke_shell()

# Send command
session.send('watch -n1 ps\n')

# Loop for 10 seconds
start = time.time()
while time.time() - start < 10:
  if session.recv_ready():
    data = session.recv(512)

    sys.stdout.write(data)
    sys.stdout.flush() # Flushing is important!

  time.sleep(0.001) # Yield CPU so we don't take up 100% usage...

# After 10 seconds, send ^C and then close
session.send('\x03')
session.close()
print

rawDescription: How to send control signals using paramiko in python?

description: Send control signals using paramiko in python


code:
texture.mag_filter = 'nearest'
texture.min_filter = 'nearest'

rawDescription: Kivy Interpolation on Canvas

description: Kivy Interpolation on Canvas


code:
data = (('BCG', 'OPV 0', 'Hep-B 1'), ...)
unique = len(set(x for inner in data for x in inner))

rawDescription: find count of individual items in a nested tuple in python

description: Find count of individual items in a nested tuple in python


code:
class MyProcess(multiprocessing.Process):
    def __init__(self, num, exit_cond): ### new code
        super(MyProcess, self).__init__()
        self.num = num
        self.exit_cond = exit_cond ### new code

    def run(self):
        self.thread1 = Thread(target=print_all_the_things, args=("a", self.num))
        self.thread2 = Thread(target=print_all_the_things, args=("b", self.num))
        self.thread1.daemon=True ### new code
        self.thread2.daemon=True ### new code

        self.thread1.start()
        self.thread2.start()
        self.exit_cond.wait() ### new code

procs = {}
exit_cond = multiprocessing.Event() ### new code

for a in range(2):
    procs[a] = MyProcess(a, exit_cond)
    procs[a].start()

time.sleep(5)

exit_cond.set() ### new code
for a in range(2):
    procs[a].join()

rawDescription: Python - Using threads within multiprocessing


code:
for line in open(filename, 'r'):
    item = line.rstrip() # strip off newline and any other trailing whitespace
    ...

rawDescription: Reading a .DAT file in python?

description: Reading a .DAT file in python


rawDescription: How to find text between two markers

description: Find text between two markers


code:
import web
from facepy import GraphAPI
from urlparse import parse_qs

url = ('/', 'index')

app_id = "YOUR_APP_ID"
app_secret = "APP_SECRET"
post_login_url = "http://0.0.0.0:8080/"

user_data = web.input(code=None)

if not user_data.code:
    dialog_url = ( "http://www.facebook.com/dialog/oauth?" +
                               "client_id=" + app_id +
                               "&redirect_uri=" + post_login_url +
                               "&scope=publish_stream" )

    return "<script>top.location.href='" + dialog_url + "'</script>"
else:
    graph = GraphAPI()
    response = graph.get(
        path='oauth/access_token',
        client_id=app_id,
        client_secret=app_secret,
        redirect_uri=post_login_url,
        code=code
    )
    data = parse_qs(response)
    graph = GraphAPI(data['access_token'][0])
    graph.post(path = 'me/feed', message = 'Your message here')

rawDescription: How to get Facebook access token using Python library?

description: Get Facebook access token using Python library


code:
from tkinter import *

root = Tk()

mods = {
    0x0001: 'Shift',
    0x0002: 'Caps Lock',
    0x0004: 'Control',
    0x0008: 'Left-hand Alt',
    0x0010: 'Num Lock',
    0x0080: 'Right-hand Alt',
    0x0100: 'Mouse button 1',
    0x0200: 'Mouse button 2',
    0x0400: 'Mouse button 3'
}

root.bind( '<Key>', lambda e: print( 'Key:', e.char,
                                     'Mods:', mods.get( e.state, None )))

root.mainloop()

rawDescription: check if modifier key is pressed in tkinter

description: Check if modifier key is pressed in tkinter


code: result = np.append(result, np.atleast_2d(i), axis=0)

rawDescription: Numpy append: Automatically cast an array of the wrong dimension


code:
from django.utils.html import strip_tags

strip_tags(string_value)

rawDescription: How to strip html/javascript from text input in django

description: Strip html/javascript from text input in django


rawDescription: Passing array of strings as parameter in python ctypes


code:
class Connection(models.Model):
    input = BaseInput()

rawDescription: Django polymorphism in view

description: Django polymorphism in view


code:
import os
import mimetypes
from django.http import StreamingHttpResponse
from django.core.servers.basehttp import FileWrapper

def download_file(request):
   the_file = '/some/file/name.png'
   filename = os.path.basename(the_file)
   chunk_size = 8192
   response = StreamingHttpResponse(FileWrapper(open(the_file), chunk_size),
                           content_type=mimetypes.guess_type(the_file)[0])
   response['Content-Length'] = os.path.getsize(the_file)
   response['Content-Disposition'] = "attachment; filename=%s" % filename
   return response

rawDescription: Serving large files ( with high loads ) in Django


code:
import types
help(types.ModuleType)
mymod = types.ModuleType("MyMod")
mymod

rawDescription: How do I instantiate a module in Python

description: Instantiate a module in Python


code: parser._optionals.title = "my mandatory arguments, they are actually optionals, but I'll check for their presence"

rawDescription: How to change the text "optional arguments" in argparse

description: Change the text "optional arguments" in argparse


code:
import os
def content_file_name(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s_%s.%s" % (instance.user.id, instance.questid.id, ext)
    return os.path.join('uploads', filename)

rawDescription: Django File Upload and Rename

description: Django File Upload and Rename


rawDescription: Replace pairs of characters at start of string with a single character


code:
import subprocess
subprocess.call(["ssconvert","sample.xlsx","sample.csv"],cwd="pathtoyourfile") # pathtoyourfile must contain the xlsx and csv files

rawDescription: How to execute ssconvert command using subprocess in python

description: Execute ssconvert command using subprocess in python


code:
import sys
from PyQt4 import QtGui
import urllib

app = QtGui.QApplication(sys.argv)
app.setStyle('Cleanlooks')

progressx = QtGui.QProgressBar()
progressx.show()

url = "http://l3cdn.riotgames.com/ShellInstaller/EUNE/LeagueofLegends_EUNE_Installer_9_15_2014.exe"
name = url.split('/')[-1]
def report(count, blockSize, totalSize):
    global percent
    percent = int(count*blockSize*100/totalSize)

    sys.stdout.write("\r%d%%" % percent + ' complete')
    progressx.setValue(percent)

    QtGui.QApplication.processEvents()

urllib.urlretrieve(url, name, reporthook=report)
sys.exit(app.exec_())

rawDescription: PyQt4 crash with progress bar

description: PyQt4 crash with progress bar


code:
import uuid
user_filename = uuid.uuid4()
csv_filename = user_filename+'.csv'
png_filename = user_filename+'.png'

rawDescription: Deal with generated files for multiple users simultaneously


code: sum(x is not None for x in (param_a, param_b, param_c)) == 1

rawDescription: In Python, how to ensure only one value is true?


code:
sub = session.query(
    Child.parent_id,
    func.max(Child.child_timestamp).label('child_latest')
).group_by(Child.parent_id
).subquery()

parents = session.query(Parent
).join((sub, sub.c.parent_id == Parent.id)
).filter(sub.c.child_latest.between(lower_date, upper_date)
).all()

rawDescription: How to filter a sqlalchemy query by a column in latest child item

description: Filter a sqlalchemy query by a column in latest child item


code:
class SurveyForm(forms.Form):
    questions = _create_questions('How is my restaurant?',
                                  'How is the Food?',
                                  'How is the service?')

    def __init__(self, *args, **kwargs):
        # Create the form as usual
        super(SurveyForm, self).__init__(*args, **kwargs)

        # Add custom form fields dynamically
        for question in questions:
             self.fields[question[0]] = forms.ChoiceField(label=question[1],
                                                          widget=forms.RadioSelect(),
                                                          choices=answers_select)
    @classmethod
    def _create_questions(cls, *questions):
        return [(str(index), question) for index, question in enumerate(questions)]

rawDescription: How to use Django form fields multiple times in a GET or POST

description: Use Django form fields multiple times in a GET or POST


code: newSockObj = socket.socket(_sock=sock)

rawDescription: Python _socket.socket vs socket._socketobject, how to convert from one to the other


code:
import itertools
# assuming that `bits` is your array of bits (0 or 1)
# ordered from LSB to MSB in consecutive bytes they represent
# e.g. bits = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1] will give you bytes = [128,255]
bytes = [sum([byte[b] << b for b in range(0,8)])
            for byte in zip(*(iter(bits),) * 8)
        ]
# warning! if len(bits) % 8 != 0, then these last bits will be lost

rawDescription: In Python, how to convert array of bits to array of bytes?


code:
from threading import Timer
import sys

def scheduled_task(arg):
    print("\ntask complete arg %s!\n"%(arg))

def run_scheduled_task(arg):
    timer = Timer(10, scheduled_task, [arg])
    timer.start()

done = False
while not done:
    user_input = input("Give me some input (exit to stop): ")
    if user_input == 'exit':
        print('Exiting')
        done = True
    else:
        run_scheduled_task(user_input)

rawDescription: Running a python function after a certain time passes. Using Threading Timer, however it only runs once and then stops


code:
if not table.find_one({ "_id": data['_id'], "stuff": {"$elemMatch": {keyvalue: { "$exists" : True }}}}):
    table.update({ "_id": data['_id'] }, { "$push": { "stuff": { keyvalue: 1 }}})
else:
    table.update({ "_id": data['_id'], "stuff": { "$elemMatch": { keyvalue: { "$exists" : True}}}}, { "$inc": { "stuff.$." + keyvalue: 1}})

rawDescription: Updating a value of dictionary in list of dictionaries in a collection using PyMongo


code:
index = 0
while index < len(s) - n + 1:
    if s[index] == s[index+n-1]:
        return pal_length(s[index+1:index+n-1], n-2)
    index += 1
return False

rawDescription: Palindrome with Recursion

description: Palindrome with Recursion


rawDescription: In lxml, how do I remove a tag but retain all contents?


code:
class ExpiryDateField(forms.MultiValueField):
    """
    Form field that validates credit card expiry dates.
    """

    default_error_messages = {
        'invalid_month': _(u'Please enter a valid month.'),
        'invalid_year': _(u'Please enter a valid year.'),
        'date_passed': _(u'This expiry date has passed.'),
    }

    def __init__(self, *args, **kwargs):
        today = date.today()
        error_messages = self.default_error_messages.copy()
        if 'error_messages' in kwargs:
            error_messages.update(kwargs['error_messages'])
        if 'initial' not in kwargs:
            # Set default expiry date based on current month and year
            kwargs['initial'] = today
        months = [(x, '%02d (%s)' % (x, date(2000, x, 1).strftime(MONTH_FORMAT))) for x in xrange(1, 13)]
        years = [(x, x) for x in xrange(today.year, today.year + 15)]
        fields = (
            forms.ChoiceField(choices=months, error_messages={'invalid': error_messages['invalid_month']}),
            forms.ChoiceField(choices=years, error_messages={'invalid': error_messages['invalid_year']}),
        )
        super(ExpiryDateField, self).__init__(fields, *args, **kwargs)
        self.widget = ExpiryDateWidget(widgets=[fields[0].widget, fields[1].widget])

    def clean(self, value):
        expiry_date = super(ExpiryDateField, self).clean(value)
        if date.today() > expiry_date:
            raise forms.ValidationError(self.error_messages['date_passed'])
        return expiry_date

    def compress(self, data_list):
        if data_list:
            try:
                month = int(data_list[0])
            except (ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_month'])
            try:
                year = int(data_list[1])
            except (ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_year'])
            try:
                day = monthrange(year, month)[1] # last day of the month
            except IllegalMonthError:
                raise forms.ValidationError(self.error_messages['invalid_month'])
            except ValueError:
                raise forms.ValidationError(self.error_messages['invalid_year'])
            return date(year, month, day)
        return None

rawDescription: Django form split into two drop down (selects)


code:
import os
import subprocess

os.environ['ORACLE_HOME'] = "/home/user1/oracle/client"
subprocess.call("printenv") #prints whole environment, see the ORACLE_HOME there

rawDescription: set oracle_home in unix from python script

description: Set oracle_home in unix from python script


rawDescription: Suppose I have three weighted choices: how do I randomly select one?


code:
import dill

class A(object):
  pass

b = A()

id(b)
id(dill.loads(dill.dumps(b)))

rawDescription: Python multiprocessing: object identifier unique across processes


code:
import urllib2
u = urllib2.urlopen('http://google.com')
dir(u)  # useful in seeing what's there, see also help(u)
u.geturl()
u.url

rawDescription: python - open url and retrieve changed url

description: Python - open url and retrieve changed url


code:
import numpy as np
import h5py
from scipy.stats import pearsonr

# Create the dataset
h5 = h5py.File("data.h5",'w')
h5["test"] = np.random.random(size=(24000,316))
h5.close()

# Compute dot products
h5 = h5py.File("data.h5",'r+')
A  = h5["test"][:]

N   = A.shape[0]
out = h5.require_dataset("pearson", shape=(N,N), dtype=float)

for i in range(N):
    out[i] = [pearsonr(A[i],A[j])[0] for j in range(N)]

rawDescription: Pearson correlation on big numpy matrices


code:
import json
a = json.loads('{"repositories":["docker1","myImage","repo123"]}')
a['repositories']

rawDescription: How can I split comma separated words wrapped in quotes efficiently in Python?

description: Split comma separated words wrapped in quotes efficiently in Python


code:
arr = [10,9,9,7,10]
counter = {}
for elm in arr:
    try:
        counter[elm] += 1
    except KeyError:
        counter[elm] = 1

counter
srt = sorted(counter.items(), key=lambda x: x[1], reverse=True)
maxitem, maxcount = srt[0]
most_frequents = [maxitem]
for rec in srt[1:]:
    if rec[1] == maxcount:
        most_frequents.append(rec[0])
    else:
        break

most_frequents

rawDescription: Python - taking most frequent element from array/converting numpy array to std array


rawDescription: python: split string after a character

description: Python: split string after a character


code:
import psycopg2

f_cm = open('cm.sql', 'r')

constr = "dbname='mydb' user= 'pgsql' host='127.0.0.1'"
db = psycopg2.connect(constr)
st = db.cursor()

copy = "COPY mytable(col1,col2, col3) FROM STDIN with csv"
st.copy_expert(sql=copy, file=f_cm)

db.commit()
st.close()
db.close()

rawDescription: Quoted separator cursor copy_from in python


code:
class DynamicComboBoxes(QtGui.QWidget):
    def __init__(self, parent=None):
        super(DynamicComboBoxes, self).__init__(parent)
        vbox = QtGui.QVBoxLayout(self)
        spinbox = QtGui.QSpinBox(self)
        spinbox.setRange(0,10)
        spinbox.valueChanged.connect(self.onChangeValue)
        vbox.addWidget(spinbox)
        self.grid = QtGui.QGridLayout()
        self.itemlist = []
        vbox.addLayout(self.grid)
        vbox.addStretch(1)

    def onChangeValue(self, val):
        for label, combobox in self.itemlist:
            label.deleteLater()
            combobox.deleteLater()
        self.itemlist = []
        for i in range(val):
            label = QtGui.QLabel('This is Label {}'.format(i))
            combobox = QtGui.QComboBox()
            self.grid.addWidget(label, i, 0)
            self.grid.addWidget(combobox, i, 1)
            self.itemlist.append([label, combobox])

rawDescription: Python PyQt Creating comboboxes depending on the number user selected on spinbox


code:
def __unicode__(self):
    return 'Comment %s - to  a %s - %s' % (self.pk, self.content_type, self.content_object.__unicode__(), self.timestamp)

rawDescription: Django GenericForeignKey in the admin

description: Django GenericForeignKey in the admin


code:
if db_name in ['local', 'admin']:
    continue

rawDescription: Is it possible to remove default databases and system.indexes in MongoDB


code:
def match_compare_key(self):
    """The match compare key for sorting.

    Current implementation:

    1.  rules without any arguments come first for performance
        reasons only as we expect them to match faster and some
        common ones usually don't have any arguments (index pages etc.)
    2.  The more complex rules come first so the second argument is the
        negative length of the number of weights.
    3.  lastly we order by the actual weights.

    :internal:
    """

rawDescription: Are Python flask order of routes defined?


code:
from suds.transport.http import HttpTransport as SudsHttpTransport

class WellBehavedHttpTransport(SudsHttpTransport):
    """HttpTransport which properly obeys the ``*_proxy`` environment variables."""

    def u2handlers(self):
        """Return a list of specific handlers to add.

        The urllib2 logic regarding ``build_opener(*handlers)`` is:

        - It has a list of default handlers to use

        - If a subclass or an instance of one of those default handlers is given
            in ``*handlers``, it overrides the default one.

        Suds uses a custom {'protocol': 'proxy'} mapping in self.proxy, and adds
        a ProxyHandler(self.proxy) to that list of handlers.
        This overrides the default behaviour of urllib2, which would otherwise
        use the system configuration (environment variables on Linux, System
        Configuration on Mac OS, ...) to determine which proxies to use for
        the current protocol, and when not to use a proxy (no_proxy).

        Thus, passing an empty list will use the default ProxyHandler which
        behaves correctly.
        """
        return []

client = suds.client.Client(my_wsdl, transport=WellBehavedHttpTransport())

rawDescription: Suds ignoring proxy setting

description: Suds ignoring proxy setting


code:
from os import path
resources_dir = path.join(path.dirname(__file__), 'resources')

rawDescription: Relative file paths in Python packages

description: Relative file paths in Python packages


code:
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
F = your_function(X.ravel(), Y.ravel())
CS = plt.contour(X, Y, F.reshape(X.shape))
plt.clabel(CS, inline=1, fontsize=10)

rawDescription: 2D plot using 1D arrays without griddata()


code: [x for x in ['a', 'b'] for y in range(100)]

rawDescription: python: convenient way to create list of strings of repeated elements

description: Python: convenient way to create list of strings of repeated elements


code:
class LikeResource(ModelResource):
    profile = fields.ToOneField(ProfileResource, 'profile',full=True)
    post = fields.ToOneField(PostResource,'post')

    class Meta:
        queryset = Like.objects.all()
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()
        resource_name = 'like'
        filtering = {
            'post': 'exact',
            'profile':'exact',
        }

rawDescription: How to put Product to Cart via tasytpie API?

description: Put Product to Cart via tasytpie API


code:
import wx
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg

class GraphFrame(wx.Frame):
    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, size=(300,300))
        figure = Figure()
        fc = FigureCanvasWxAgg(self, -1, figure)
        axes = figure.add_subplot(111)
        figure.tight_layout()
        self.Show(True)

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    graphframe = GraphFrame(None)
    app.MainLoop()

rawDescription: How to reduce margins in a matplotlib figure placed on a wxpython panel?

description: Reduce margins in a matplotlib figure placed on a wxpython panel


code:
import inspect

inspect.getfile(some_func)

rawDescription: Python: Find which version of a function I'm using


code:
def transform_result(self, data):
    type_map = defaultdict(list)
    for entry in data:
        type_map[entry['type'], entry['writable']].append({
            'id': entry['id'],
            'tag': entry['tag'],
        })
    ret = []
    for (k_type, k_writable), value in type_map.items():
        ret.append({
            'type': k_type,
            'writable': k_writable,
            'tags': value,
        })
    return ret

rawDescription: Python defaultdict - add another key?

description: Python defaultdict - add another key


code:
from collections import defaultdict

sums = defaultdict(float)
for c, a, b in regions:
    sums[a, b] += c
result = [(csum, a, b) for (a, b), csum in sums.iteritems()]

rawDescription: Sum tuples if identical values

description: Sum tuples if identical values


code:
from sympy.abc import x, y
z = 3*x + 4*y
z.coeff(x)

rawDescription: compute x-component of vector in sympy

description: Compute x-component of vector in sympy


code:
trs = driver.find_elements_by_xpath("//table/tbody/tr")
max = 0
i = 0
for index, tr in enumerate(trs):
    if max < int(tr.get_attribute('index')):
        max = int(tr.get_attribute('index'))
        i = index

max = trs[i]

# If there are more than one elements with the same max value
maxs = driver.find_elements_by_xpath("//table/tbody/tr[@index='" + str(max) + "']")

rawDescription: How can I find an element with maximum index using selenium-python

description: Find an element with maximum index using selenium-python


code:
f.seek(10)
f.read(1)

rawDescription: How do I read one and only one byte from a binary file at a specified position?

description: Read one and only one byte from a binary file at a specified position


code:
from collections import Counter
from itertools import chain

v1 = ['product1','product2','product3']
v2 = ['product3','product1','product5','product7','product10']
v3 = ['product1','product10']

c = Counter(chain(v1, v2, v3))
# more space-efficient than Counter(v1 + v2 + v3)
# Counter({'product1': 3, 'product10': 2, 'product3': 2, 'product7': 1, 'product5': 1, 'product2': 1})

c['product10']
# 2

rawDescription: Counting total number of element occurrences in different length vectors


code:
cols = ['col0', 'col1', 'col2'] # the columns you want to load
for col in cols:
    data = pandas.read_csv(..., usecols=[col], squeeze=True)
    # format column data etc.

rawDescription: Iterate through csv by column

description: Iterate through csv by column


code: [x for x in my_list if not any(c.isdigit() for c in x)]

rawDescription: Remove strings from a list that contains numbers in python


code:
def worker( chromosome ) :
  chrom_path = "{}/{}.fasta".format(target, chromosome )
  return call_lastz(chrom_path, fasta)

if __name__ == '__main__' :
  pool = multiprocessing.Pool(processes=cores)
  alignments = pool.map( worker, chromosomes )
  pool.close()
  pool.join()

rawDescription: Using python multiprocess - start a new function on a process immediately after finishing (more jobs than cores)


code:
sys.path[0:0] = ['.', '..']

from elftools.common.py3compat import bytes2str
from elftools.elf.elffile import ELFFile

# 128k flash for the ATXmega128a4u
flashsize = 128 * 1024

def __printSectionInfo (s):
    print ('[{nr}] {name} {type} {addr} {offs} {size}'.format(
                nr = s.header['sh_name'],
                name = s.name,
                type = s.header['sh_type'],
                addr = s.header['sh_addr'],
                offs = s.header['sh_offset'],
                size = s.header['sh_size']
                                                              )
           )

def process_file(filename):
    print('In file: ' + filename)
    with open(filename, 'rb') as f:
        # get the data
        elffile = ELFFile(f)
        print ('sections:')
        for s in elffile.iter_sections():
            __printSectionInfo(s)
        print ('get the code from the .text section')
        textSec = elffile.get_section_by_name(b'.text')
        # prepare the memory
        flashMemory = bytearray(flashsize)
        # the text section
        startAddr = textSec.header['sh_addr']
        val = textSec.data()

        flashMemory[startAddr:startAddr+len(val)] = val

        # print memory

        print('finished')

if __name__ == '__main__':
    process_file('firmware.elf')

rawDescription: Getting the memory layout out of an (avr)elf file by useing python + pyElftools


code:
new_array = my_array.astype(type('float', (float,), {}))
type(new_array[0])

rawDescription: How to convert a numpy array from 'float64' to 'float'

description: Convert a numpy array from 'float64' to 'float'


rawDescription: How to remove all 0 from a dictionary in python?

description: Remove all 0 from a dictionary in python


code:
import math

speed = 5
angle = math.radians(90)    # Remember to convert to radians!
change = [speed * math.cos(angle), speed * math.sin(angle)]

rawDescription: python convert degrees to change in x and change in y

description: Python convert degrees to change in x and change in y


code:
import random
random_numbers = [ random.random() for _ in xrange(N) ]

rawDescription: Creating a list containing 30k numbers

description: Creating a list containing 30k numbers


code: name_sorta = name_sorta.split()

rawDescription: Why is split breaking up my words into characters


code:
def readfile(filepath):
    with open(filepath, 'r') as f:
        return f.read().splitlines()

audio = readfile('Key Words\Audio.txt')
calls = readfile('Key Words\Calls.txt')
charging = readfile('Key Words\Charging.txt')

rawDescription: How to open multiple files without repeating the code

description: Open multiple files without repeating the code


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

class MyHeap(object):
   def __init__(self, initial=None, key=lambda x:x):
       self.key = key
       if initial:
           self._data = [(key(item), item) for item in initial]
           heapq.heapify(self._data)
       else:
           self._data = []

   def push(self, item):
       heapq.heappush(self._data, (self.key(item), item))

   def pop(self):
       return heapq.heappop(self._data)[1]

rawDescription: Python heapq with custom compare predicate


code:
import wx
a = wx.App(redirect=False)
my_str = wx.GetTextFromUser("Enter A Number!")
base = {'x':16,'b':2,'o':8}.get(my_str[1].lower(),10)
int_val = int(my_str,base)
hex_str = hex(int_val)
bin_str = bin(int_val)

msg = """
User Entered:%s
Int:%s
Hex:%s
Bin:%s"""%(my_str,int_val,hex_str,bin_str)
wx.MessageBox(msg)

rawDescription: Binary and WxPython

description: Binary and WxPython


code:
class Ball:
   def __init__(self, x, y, radius, color):
      self.x = x
      self.y = y
      self.radius = radius
      self.color = color
      self.dx = 0
      self.dy = 5

   def draw_ball(self, screen):
      pygame.draw.ellipse(screen, self.color,
         pygame.Rect(self.x, self.y, self.radius, self.radius))

   def update_ball(self):
      self.x += self.dx
      self.y += self.dy

   def test_collide_top_ball(self, top_height):
      if (self.y >= top_height):
         self.dy *= -1

   def test_collide_bottom_ball(self, coll_height):
      if (self.y >= coll_height):
         self.dy *= -1

rawDescription: Why isn't the ball bouncing back?

description: Why isn't the ball bouncing back


rawDescription: Copying lists: editing copy without changing original