code: self.dist_time_label.setText("total distance = {0} \ntotal survey time = {1} ".format(self.dist_total_disp, self.time_total_disp))

rawDescription: display result in UI

description: Display result in UI


code:
def longest_ascending(s):
    matches = []
    current = [s[0]]
    for index, character in enumerate(s[1:]):
        if character >= s[index]:
            current.append(character)
        else:
            matches.append(current)
            current = [character]
    matches.append(current)
    return "".join(max(matches, key=len))

rawDescription: Comparing characters in a string sequentially in Python


code: d = con[db][col].find_one()

rawDescription: pymongo specify variable in connection string

description: Pymongo specify variable in connection string


code:
import os.path
filename = "E:/test/my_code/content/dir/disp_temp_2.hgx"
name = os.path.basename(filename).split('.')[0]

rawDescription: python:extract certain part of string

description: Python:extract certain part of string


code:
import matplotlib.pyplot as plt

fig, big_axes = plt.subplots( figsize=(15.0, 15.0) , nrows=3, ncols=1, sharey=True)

for row, big_ax in enumerate(big_axes, start=1):
    big_ax.set_title("Subplot row %s \n" % row, fontsize=16)

    # Turn off axis lines and ticks of the big subplot
    # obs alpha is 0 in RGBA string!
    big_ax.tick_params(labelcolor=(1.,1.,1., 0.0), top='off', bottom='off', left='off', right='off')
    # removes the white frame
    big_ax._frameon = False

for i in range(1,10):
    ax = fig.add_subplot(3,3,i)
    ax.set_title('Plot title ' + str(i))

fig.set_facecolor('w')
plt.tight_layout()
plt.show()

rawDescription: Row titles for matplotlib subplot

description: Row titles for matplotlib subplot


code:
user_inp = "username"
pass_inp = "password"

username = driver.find_element_by_css_selector("input[tabindex='1']")
password = driver.find_element_by_css_selector("input[tabindex='2']")

username.send_keys(user_inp)
password.send_keys(pass_inp)

rawDescription: Selenium form input with random id with python


rawDescription: Different handling of NaN and -9999.0 in numpy array when plotting


code:
import struct
a=b'\xca\xfe\xba\xbe' # let's say I just received these bytes
struct.unpack(">I", a)
# -> (3405691582,)
struct.unpack(">I", a)[0]
# -> 3405691582
hex(struct.unpack(">I", a)[0])
# -> '0xcafebabe' - exactly what I expected.

rawDescription: Python 3 buffer / bytes manipulation

description: Python 3 buffer / bytes manipulation


rawDescription: Applying pandas Timestamp() call to each item of a numpy array


code:
import re

teststrs = ["my_id", "Id_number", "my_id_rocks", "my_idea"]

replace_with_upper = "id"

def toUpper(match):
    return match.group(1).upper()

for test_me in teststrs:
    test_me = re.sub("(?<![a-z])({})(?![a-z])".format(replace_with_upper), toUpper, test_me, flags=re.IGNORECASE)
    print(test_me)

rawDescription: Find and replace words in string

description: Find and replace words in string


code:
from datetime import datetime

base_date = "2015-01-01"
data = ["2015-01-23", "2015-01-04", "2015-01-03"]
format = "%Y-%m-%d"

base = datetime.strptime(base_date, format)
diff = [(datetime.strptime(d, format) - base).days for d in data]
# diff == [22, 3, 2]

rawDescription: In python, how to calculate how many days a particular date exceeds the "base date"?


code:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
x = [50,500,1500,2500];
y = [72,414,1,13]
ax1.plot(x, y, 'bo')
plt.show()

rawDescription: Plotting Pearson Correlation Coefficient with matplotlib


rawDescription: Python Social auth redirecting to the same URL


code:
client = smbclient.SambaClient(server="servername", share="sharename",
    username="foo", password="bar", domain="baz")
f = smb.open('/path/to/file')
data = f.read()
f.close()

rawDescription: Read Remote File with Access Permissions


code:
def parse_version(v):
    if v in ('latest', 'active', 'basic'):
        return v
    else:
        return int(v)   # this will error if v is non-numeric, causing the
                        # parser to reject the argument

parser.add_argument(
    '-v',
    dest='version',
    help="The version (latest/active/basic or numerical version)",
    required=False,
    default='latest',
    type=parse_version
)

rawDescription: How to pass an int or string to a command line argument

description: Pass an int or string to a command line argument


rawDescription: How to return index of lists in Python

description: Return index of lists in Python


code:
ssim_group = ['S1200', 'S1300']
query = '''select WIPMessageCnt from waferdata where recipename in ('%s') and equipment = ? and runtype = ? order by  stopts desc limit 1''' % ("','".join(ssim_group))

rawDescription: Python list of String to SQL IN parameter


code:
import time

def app(environ, start_response):

    start_response('200 OK', [('Content-Type', 'text/plain')])

    def content():
        yield ''.join(('First bit of content', '.' * 18000, '\n'))
        time.sleep(5)
        yield 'Second bit of content'
    return content()

import waitress
waitress.serve(app, host='0.0.0.0', port=8080)

rawDescription: Is there a wsgi server that will do progressive Transfer-Encoding: chunked


code:
def getchar(string, char):
    ...
    return string, char

...

newstring, newchar = getchar(string, char)

rawDescription: Change value of function arguments in Python


code:
class Score(db.Model):
    __tablename__ = 'scores'
    item_id  = db.Column(db.Integer(), primary_key=True)
    score1 = db.Column(db.Integer(), nullable=False)
    score2 = db.Column(db.Integer(), nullable=False)
    score3 = db.Column(db.Integer(), nullable=False)
    score4 = db.Column(db.Integer(), nullable=False)

    @hybrid_method
    def total_score(self, fields):
        return sum(getattr(self, field) for field in fields)

    @total_score.expression
    def total_score(cls, fields):
        return sum(getattr(cls, field) for field in fields)

fields = ['score1', 'score2']
scores = db.session.query(Score.item_id, Score.total_score(fields).label('total_score')).order_by('total_score')
final_output = [score._asdict() for score in scores]

rawDescription: SqlAlchemy (Postgres + Flask ) : How to sum multiple columns?


code:
# Number of uniformly ditributed random numbers
n = 2000

def func_vec(x1s, x2s):
    return x1s * x1s + 4 * x2s * x2s

np.random.seed()
x1s = np.random.uniform(-1, 1, n)
x2s = np.random.uniform(-1, 1, n)
ys = func_vec(x1s, x2s)

fig = plt.figure(22)

# Scatter
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x1s, x2s, color = 'g', s = 2, edgecolor = 'none')
ax1.set_ylim([-1,1])
ax1.set_xlim([-1,1])

# Contour
xi = np.linspace(-1,1,20)
yi = np.linspace(-1,1,20)
zi = griddata((x2s, x1s), ys, (xi[None,:], yi[:,None]), method = 'cubic')
ax1.contour(xi, yi, zi, 6, linewidths = 1, colors = ('#0000ff', '#0099ff', '#009999', '#999900', '#ff9900', '#ff0000'))

# 3D visualization
ax2 = fig.add_subplot(1, 2, 2, projection = '3d')
X, Y = np.meshgrid(xi, yi)
ax2.plot_wireframe(X, Y, zi, rstride = 1, cstride = 1)
ax2.view_init(28, -144)

plt.show()

rawDescription: Plotting contour and wireframe plots with Matplotlib


code:
g = pd.TimeGrouper(timedelta_for_grouping)
ts.groupby(g).filter(lambda x: len(x) >= 3).groupby(g).transform('median')

rawDescription: Stop Pandas TimeGrouper from forming incomplete groups


code:
from celery.task import Task
from celery.registry import tasks
from celery.signals import task_prerun

_precalc_table = {}

class PowersOfTwo(Task):

    def run(self, x):
        if x in _precalc_table:
            return _precalc_table[x]
        else:
            return x ** 2
tasks.register(PowersOfTwo)

def _precalc_numbers(**kwargs):
    if not _precalc_table: # it's empty, so haven't been generated yet
        for i in range(1024):
            _precalc_table[i] = i ** 2

# need to use registered instance for sender argument.
task_prerun.connect(_precalc_numbers, sender=tasks[PowerOfTwo.name])

rawDescription: How can I set up Celery to call a custom initialization function before running my tasks?

description: Set up Celery to call a custom initialization function before running my tasks


code:
import requests
response = requests.get("http://api.gigatools.com/search.json", params={'api_key': 'XXXX', 'twitter_username': 'djflash4eva'})
print(response.status_code)
print(response.text)

rawDescription: Python - GigaTools API - json

description: Python - GigaTools API - json


code:
setup(name='MyStuff',
      version='1.0',
      install_requires=['progressbar'],
      # ...
)

rawDescription: How to specify dependencies when creating the setup.py file for a python package

description: Specify dependencies when creating the setup.py file for a python package


code:
import time

Start_Time = time.time()
#execute script
Execution_Time = time.time() - Start_Time

rawDescription: Way to calculate the execution time difference of two python scripts using sage


code:
d = {'hand_R_item':'hand_R_node', 'hand_L_item':'hand_L_node', 'hips_item':'hips_node', 'body_item':'body_node'}
reg = re.compile(r'\$"(\w*?)"')
command = '''objs = [$"hand_R_item", $"hand_L_item", $"hips_item"]
for obj in objs:
    cmds.select(add = True)
    cmds.parent(obj, $"body_item")
'''

# Replace the group 1, with corresponding value from dict
reg.sub(lambda m: d[m.group(1)], command)

rawDescription: Regex findall and replace with dictionary


code:
import os

env = os.environ.copy()
env['DISPLAY'] = ':0.0'

p1 = subprocess.Popen(["python","/home/src/upload.py"] + s[1:3],
                      env=env, stdout=subprocess.PIPE)
p2 = subprocess.Popen(["python","/home/src/download.py"] + s[1:3],
                      env=env, stdout=subprocess.PIPE)

rawDescription: Python - how do i add the long command to the subprocess, when i am applything in one line the whole command is not working


code:
import mechanize
br = mechanize.Browser()
br.open("http://www.speech.sri.com/projects/srilm/download.html")
br.select_form(nr = True)
br['name'] = 'Hans Meier'
br['org'] = 'Meier AG'
br['email'] = 'hans.meier.org'
br['address'] = 'Baslerstrasse 32'
br['file'] = ['/project/srilm/srilm-1.6.0.tar.gz']
form_submission = br.submit()
with open('srilm.tgz', 'w') as f:
    f.write(form_submission.read())

rawDescription: Ruby mechanize script in python

description: Ruby mechanize script in python


code:
# Parsing
res = sqlparse.parse('select * from "someschema"."mytable" where id = 1')
res
stmt = res[0]
stmt.to_unicode()  # converting it back to unicode
# This is how the internal representation looks like:
stmt.tokens

rawDescription: SQL Parsing library for Python

description: SQL Parsing library for Python


code:
from StringIO import StringIO
f = StringIO()
thumb.save(f, ext)
s.put(self.filename+ext, f.getvalue())

rawDescription: In python, how would I open a PIL or Imagemagick Image as a file


code: import yaml

rawDescription: Using YAML in GAE environment

description: Using YAML in GAE environment


code:
from datetime import datetime, timedelta
dt = datetime.strptime(...)
if dt > datetime.now():
    dt -= timedelta(years = 100)

rawDescription: Python strptime parsing year without century: assume prior to this year?


code:
dc = DataCursor(...) # what ever aruguements you give it
# bunch of code
dc.annotation.remove()
del dc
plt.draw() # need to redraw to make remove visible

rawDescription: Python and Remove annotation from figure


code:
authors = [('A', "Aho"), ('W', "Weinberger"), ('K', "Kernighan")]
option = get_option()
while option not in (x[0] for x in authors):
    option = get_option()

rawDescription: Python - input from list of tuples

description: Python - input from list of tuples


code: soup.find_all(lambda tag: tag.name == 'p' and not tag.attrs)

rawDescription: How do I pull <p> tags without attributes using Beautiful Soup?

description: Pull <p> tags without attributes using Beautiful Soup


code:
urls = set()
def download(mainPage):  # mainPage is a link
    global urls
    links = getHrefLinks(mainPage)
    for l in links:
        if l not in urls:
            urls.add(l) #instead of append
            downPage(l)

rawDescription: how to avoid duplicate download urls in my python spider program?

description: Avoid duplicate download urls in my python spider program


code:
import math
def number_of_bits(n):
    return int(math.log(n, 2)) + 1

rawDescription: Count bits of a integer in Python

description: Count bits of a integer in Python


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

inputbox.send_keys('Buy peacock feathers')
inputbox.send_keys(Keys.ENTER)

table = WebDriverWait(driver, 10).until(
    EC.text_to_be_present_in_element((By.CSS_SELECTOR, "table#id_list_table tr td"), "Buy peacock feathers")
)

rawDescription: Force Selenium in Python to wait until the browser is done loading


code:
test_csv = csv.DictWriter(
    test_f,
    delimiter='|',
    lineterminator='\n',  # <--------
    fieldnames=['1', '2'])

rawDescription: Python3 DictWriter using CRLF instead of LF on Linux


code:
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime

with open("pathtoyourfiel/data.csv") as f:
    #read file to a list of lines
    content = f.readlines()

    #split each line at ","
    data = [line.split(",") for line in content]
    #convert date string to datetime (assuming format is correct)
    dateStrings = [datetime.strptime(d[0], "%d %b %Y") for d in data]
    #convert datetime to matplotlib.date
    dates = matplotlib.dates.date2num(dateStrings)

    #extract G value from split list, cast to int
    g = [int(d[1]) for d in data]

    #get max and min
    maxValue = max(g)
    minValue = min(g)
    #get the date at the index of max/min
    maxDate = dateStrings[g.index(maxValue)]
    minDate = dateStrings[g.index(minValue)]

    #set formatter for the date on the x axis
    plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%m/%d/%Y'))
    plt.plot(dates, g)
    plt.show()

rawDescription: plot graph and find maximum value

description: Plot graph and find maximum value


code:
def main():
    oldimage = loadLastImage()

    while True:
        image=screenGrab()
        if not equal(image,oldimage):
            dosomething()
            saveLastImage(image) # this is the opposite of loadLastImage()
            oldimage=image

# this is the more accepted way of running main
# because it still allows your code to be loaded as module
if __name__ == "__main__":
    main()

rawDescription: Initalize variable in loop - use global variable?


code:
from collections import defaultdict
d = defaultdict(int)
with open("chat.txt") as f:
    for line in f:
        id, data = line.split(None, 1)
        d[id] += data.lower().count("optimus")

rawDescription: Count occurence of a word by ID in python


code:
def move(self, deltaX, deltaY):
    """deltaX and deltaY are floats"""
    self.x += deltaX
    self.y += deltaY

rawDescription: Does returning a constructor with new parameters overwrite the instance object?


code:
class DepartmentService(object):
    def get_groups_by_department(self, dept_id):
        ...
    def add_group_to_department(self, dept_id, group):
        ...

class GroupService(object):
     def get_department(self, dept_id):
        ...

     def add_to_department(self, dept_id, group):
        ...

rawDescription: Python Service Layer

description: Python Service Layer


code:
from celery.exceptions import Ignore

@app.task
def do_something(with_this):

    # store the state and result manually
    # the SUCCESS state is set by this method
    app.backend.mark_as_done(
        do_something.request.id,
        the_data_to_store
    )

    # we can also use update_state which calls
    # backend.store_result just like mark_as_done
    # but we have to set the state in this case
    do_something.update_state(
        state = celery.states.SUCCESS,
        meta = the_data_to_store
    )

    # ignore the task so no other state is recorded
    # like what was happening with my function in the question
    # the task will still be acknowledged
    raise Ignore()

rawDescription: How to manually mark a Celery task as done and set its result?

description: Manually mark a Celery task as done and set its result


code:
import pexpect
p = pexpect.spawn('python')
while True:
    try:
        p.expect('\n>>> ')
        print(p.before)
        p.sendline(raw_input('>>> '))
    except pexpect.EOF:
        break

rawDescription: ipython: Can I provide input to a shell command

description: Ipython: Can I provide input to a shell command


code:
fig = plt.figure(figsize=(1.0,1.0))
ax = fig.add_axes([0.0, -0.2, 1.2, 1.2])
plt.contour(zi,15,linewidths=0.1,colors='k')
plt.contourf(zi,15,cmap=plt.cm.jet)
ax.set_ylim(ax.get_ylim()[::-1])
ax.set_axis_off()
plt.savefig(file1, dpi=256)

rawDescription: Remove axes from a figure

description: Remove axes from a figure


code:
features = Feature.gql("ORDER BY date_created")

if (self.request.get("add_a_new_feature") == "true"):
    if (Feature.gql("WHERE feature_name=:1 ORDER BY last_modified DESC LIMIT 1", NEW_FEATURE_NAME).count() == 0):
        new_feature = Feature(feature_name=NEW_FEATURE_NAME)
        new_feature.put()
        features.append(new_feature)
...

if (features.count() > 0):
    features_list = features.fetch()
    for feature in features_list:
        ... # the list now contain the new_feature at the end

rawDescription: How do I update a query from Google App Engine NDB?

description: Update a query from Google App Engine NDB


code:
import xml.etree.ElementTree as ET
tree = ET.parse(source)
root = tree.getroot()
ET.tostring(root)

rawDescription: Get string source of Python xml ElementTree


code:
def get_port(self):
    if not self._started.is_set():
        raise RuntimeError("You can't call run_port before thread start.")
    if not self._event.wait(1):
        raise RuntimeError("Couldn't get port after a while.")
    return self.port

rawDescription: What is correct way of creating threaded zeromq socket?


code:
from scrapy.loader import ItemLoader
from scrapy.utils.python import flatten

class MyItemLoader(ItemLoader):
    def add_xpath_and_css(self, field_name, xpaths, csss, *processors, **kw):
        # get the xpath results first
        xpath_results = flatten([self.selector.xpath(xpath) for xpath in xpaths])

        # for every xpath result apply a css selector
        values = flatten([xpath_result.css(css).extract() for xpath_result in xpath_results for css in csss])

        self.add_value(field_name, values, *processors, **kw)

rawDescription: Combine Xpath and CSS Selectors in Item Loader


code: element = driver.find_element_by_xpath("id('detailPCTtableHeader')/tbody/tr[position()=10 or position()=11]/td[2]/div/span/span[1]")

rawDescription: Python / Selenium - using a conditional in an xpath


code:
from collections import defaultdict

d = defaultdict(list)
with open('input.txt') as f:
    for line in f.readlines():
        data = line.split()
        d[data[0]].extend(data[1:])

with open('output.txt', 'w') as f:
    for key, value in d.iteritems():
        f.write(
            '%(key)s %(value)s\n'
            % {'key': key, 'value': " ".join(sorted(value))}
        )

rawDescription: Python group similar lines in file onto one line


code:
from datetime import timedelta

start_date = timezone.now().date()
end_date = start_date + timedelta( days=1 )
Entry.objects.filter(created__range=(start_date, end_date))

rawDescription: Compare date and datetime in Django

description: Compare date and datetime in Django


code:
import json
payload={'text': 'bi ba buzemann!',
         'nouns': ['streetlight', 'situation'],
         'states': ['solid', 'fluid']
        }
requests.post(url, data=json.dumps(payload))

rawDescription: http.server: decoding POST request to JSON

description: Http.server: decoding POST request to JSON


code:
class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')

    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'

rawDescription: Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?


code:
import sqlite3
conn = sqlite3.connect(':memory:')

rawDescription: in-memory database in Python

description: In-memory database in Python


code:
def show_tabs():
    print('\t'.join(['v'] * 8))
    for i in range(1, 33):
        print(''.join(map(lambda j: str(j)[-1], range(1, i))), 'tab to here', sep='\t')

show_tabs()

rawDescription: Concatenating \t python gives irregular spacing


code:
tolerance = 1e-15
def clean_complex(c):
  real,imag = c.real, c.imag
  if -tolerance < real < tolerance:
    real = 0
  if -tolerance < imag < tolerance:
    imag = 0
  return complex(real,imag)

clean_complex( cmath.exp(cmath.log(-1)) )

rawDescription: Python thinks Euler has identity issues (cmath returning funky results)


code:
paginated = Item.query.paginate(1, 3, False)
results = {
    "records": paginated.items,
    "num_pages": paginated.pages,
    "total_count": paginated.total
}

return json.dumps(results, cls=AlchemyEncoder)

rawDescription: Adding literal_column to Flask-SQLAlchemy query


code:
class Child(db.Model):
  pass

  def __init__(self,
               parent=None,
               key_name=None,
               _app=None,
               _from_entity=False,
               **kwds):
    if not parent:
      raise ValueError('parent is required.')
    super(Did, self).__init__(parent=parent, key_name=key_name, app=_app,
                              _from_entity=_from_entity, **kwds)

rawDescription: Require an entity parent in google app engine


code:
import sys, os
from PyQt4 import QtCore, QtGui
app=QtGui.QApplication(sys.argv)

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self):
        QtCore.QAbstractTableModel.__init__(self)
        self.items=['One','Two','Three','Four','Five','Six','Seven']

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.items)
    def columnCount(self, index=QtCore.QModelIndex()):
        return 1

    def data(self, index, role):
        if not index.isValid() or not (0<=index.row()<len(self.items)):
            return QtCore.QVariant()

        item=str(self.items[index.row()])

        if role==QtCore.Qt.UserRole:
            return item
        if role==QtCore.Qt.DisplayRole:
            return item
        if role==QtCore.Qt.TextColorRole:
            return QtCore.QVariant(QtGui.QColor(QtCore.Qt.white))
        if role == QtCore.Qt.BackgroundRole:
            if index.row()%2:
                return QtCore.QVariant(QtGui.QColor("#242424"))
            else:
                return QtCore.QVariant(QtGui.QColor(QtCore.Qt.black))

    def headerData(self, column, orientation, role=QtCore.Qt.DisplayRole):
        if role!=QtCore.Qt.DisplayRole:   return QtCore.QVariant()
        if orientation==QtCore.Qt.Horizontal: return QtCore.QVariant('My Column Name')

class TableView(QtGui.QTableView):
    def __init__(self, parent=None):
        super(TableView, self).__init__(parent)
        self.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)

        myModel=TableModel()
        self.setModel(myModel)

        appStyle="""
        QTableView
        {
            background-color: black;
            gridline-color:grey;
            color: black;
        }
        QTableView::item
        {
            color: white;
        }
        QTableView::item:hover
        {
            color: black;
            background: #ffaa00;
        }
        QTableView::item:focus
        {
            color: black;
            background: #0063cd;
        }
        """
        self.setStyleSheet(appStyle)

view=TableView()
view.show()
sys.exit(app.exec_())

rawDescription: How to alternate background color of a table view using QSS?

description: Alternate background color of a table view using QSS


code:
sql = "INSERT INTO {} ({}) VALUES ({})".format(table, ','.join(columns), ','.join('[%s]' * len(columns)))
# Generates: INSERT INTO my_table (column1,column2) VALUES (?,?)
cursor.execute(sql, values)

rawDescription: Python 3.4 transmiting table, columns and values as variables using MySQLdb


code:
def view(request):
    results = cache.get(request.user.id)
    if not results:
        results = do_a_ton_of_work()
        cache.set(request.user.id, results)

rawDescription: What are the specifics and conditions to django auto-caching query sets


code:
import os
import tempfile
import subprocess

def ocr(path):
    temp = tempfile.NamedTemporaryFile(delete=False)

    process = subprocess.Popen(['tesseract', path, temp.name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    process.communicate()

    with open(temp.name + '.txt', 'r') as handle:
        contents = handle.read()

    os.remove(temp.name + '.txt')
    os.remove(temp.name)

    return contents

rawDescription: Python OCR Module in Linux?

description: Python OCR Module in Linux


code:
i=0
numbers = []
while i < 6:
    print("At the top i is %d" % i)
    numbers.append(i)

    i = i + 1
    print("Numbers now: ", numbers)
    print("At the bottom i is %d" % i)
    input() # add it here for example.

print("The numbers: ")

for num in numbers:
    print(num)

rawDescription: How to pause a loop print in python

description: Pause a loop print in python


rawDescription: remove element if it has a certain string in it

description: Remove element if it has a certain string in it


code:
moduleName = "foo"
__import__(moduleName, globals(), locals(), ['*'])

rawDescription: How to import * with __import__

description: Import * with __import__


code:
x = np.array([1,2,3,4,5])
constant = 3
x[:,None] + np.arange(constant)

rawDescription: Vectorize np.arange or equivalent

description: Vectorize np.arange or equivalent


code:
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(your_html_string)
soup.findAll("div", {"class": "mp3-info"})
# Now extract the text

rawDescription: Extracing song length and size from HTML using Python


code:
from django.contrib.gis.geos import *
from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
from geoapp import SouthTexasCity
pnt = fromstr('POINT(-96.876369 29.905320)', srid=4326)
qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))

rawDescription: GeoDjango query PointField by coords

description: GeoDjango query PointField by coords


code:
def start(times=5):
    t.insert(END, 'Hello\n')
    if times > 1:
        root.after(1000, lambda: start(times-1))

rawDescription: How to show 'Hello' once a second instead of showing five 'Hello' altogether in this program?

description: Show 'Hello' once a second instead of showing five 'Hello' altogether in this program


code:
#!/usr/bin/env python3
import cv2
import numpy as np
Path = 'data/lena.jpg'
image_float_size = 400.0
image_int_size = int(image_float_size)
color = [0,255,0]
rectangle = False

def on_event(event,x,y,flags,param):
    global draw_image
    global startpointx,startpointy,rectangle
    if event == cv2.EVENT_LBUTTONDOWN:
        rectangle = True
        startpointx = x
        startpointy = y
        print('Down',x,y) #debugging
        draw_image = resized.copy()
        cv2.rectangle(draw_image,(x,y),(x,y),(0,255,0))

    elif event == cv2.EVENT_LBUTTONUP:
        rectangle = False
        print('Up',x,y)
        draw_image = resized.copy()
        cv2.rectangle(draw_image,(startpointx,startpointy),(x,y),(0,255,0))

    elif event == cv2.EVENT_MOUSEMOVE:
        if rectangle:
            print('Move',startpointx,startpointy,x,y)#debugging
            draw_image = resized.copy()
            cv2.rectangle(draw_image,(startpointx,startpointy),(x,y),(0,255,0))

# Read the image and convert it into gray
image = cv2.imread(Path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# resize the image
ration = image_float_size / gray_image.shape[1]
dim = (image_int_size,int(gray_image.shape[0]*ration))
resized = cv2.resize(gray_image, dim, interpolation = cv2.INTER_AREA)
draw_image = resized.copy()

# set window for the image
cv2.namedWindow('window')

# mouse callback
cv2.setMouseCallback('window',on_event)

while True:
    cv2.imshow('window', draw_image)
    ch = 0xFF & cv2.waitKey(1)
    if ch == 27:
        break

cv2.destroyAllWindows()

rawDescription: Opencv draw a rectangle in a picture were never shown


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

from PyQt4 import QtGui, QtCore

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

        self.items = dict(zip(
            [   "Parent {0}".format(x)
                for x in range(3)
                ],
            [
                [ "Child {0} - {1}".format(x, y)
                    for y in range(3)
                    ]
                for x in range(3)
                ]
        ))

        self.comboBoxChild = QtGui.QComboBox(self)

        self.comboBoxParent = QtGui.QComboBox(self)
        self.comboBoxParent.addItems(self.items.keys())
        self.comboBoxParent.currentIndexChanged[str].connect(self.on_comboBoxParent_currentIndexChanged)
        self.comboBoxParent.setCurrentIndex(1)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.comboBoxParent)
        self.layoutVertical.addWidget(self.comboBoxChild)

    @QtCore.pyqtSlot(str)
    def on_comboBoxParent_currentIndexChanged(self, index):
        items = self.items[str(index)]

        self.comboBoxChild.clear()
        self.comboBoxChild.addItems(items)

if __name__ == "__main__":
    import sys

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

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

    sys.exit(app.exec_())

rawDescription: Pyqt - How to change combobox data because of another combobox data?


code:
import Image
import numpy as np

im = Image.open('test.pgm')

# Convert to grayscale (single 8-bit band), if it's not already...
im = im.convert('L')

# "data" is a uint8 (0-255) numpy array...
data = np.asarray(im)

rawDescription: Quickest way to extract the bits of the colors in a .pgm image?


code:
from collections import Counter
L = [['x','a'], ['y','b'], ['z','a']]
freq = Counter(y for x, y in L)
[[x, y, freq[y]] for x, y in L]

rawDescription: Python Beginner - How to generate a list and frequency from another list


code:
from smtplib import SMTPException, SMTPAuthenticationError
import string
import base64
import sspi

# NTLM Guide -- http://curl.haxx.se/rfc/ntlm.html

SMTP_EHLO_OKAY = 250
SMTP_AUTH_CHALLENGE = 334
SMTP_AUTH_OKAY = 235

def asbase64(msg):
    return string.replace(base64.encodestring(msg), '\n', '')

def connect_to_exchange_as_current_user(smtp):
    """Example:
    >>> import smtplib
    >>> smtp = smtplib.SMTP("my.smtp.server")
    >>> connect_to_exchange_as_current_user(smtp)
    """

    # Send the SMTP EHLO command
    code, response = smtp.ehlo()
    if code != SMTP_EHLO_OKAY:
        raise SMTPException("Server did not respond as expected to EHLO command")

    sspiclient = sspi.ClientAuth('NTLM')

    # Generate the NTLM Type 1 message
    sec_buffer=None
    err, sec_buffer = sspiclient.authorize(sec_buffer)
    ntlm_message = asbase64(sec_buffer[0].Buffer)

    # Send the NTLM Type 1 message -- Authentication Request
    code, response = smtp.docmd("AUTH", "NTLM " + ntlm_message)

    # Verify the NTLM Type 2 response -- Challenge Message
    if code != SMTP_AUTH_CHALLENGE:
        raise SMTPException("Server did not respond as expected to NTLM negotiate message")

    # Generate the NTLM Type 3 message
    err, sec_buffer = sspiclient.authorize(base64.decodestring(response))
    ntlm_message = asbase64(sec_buffer[0].Buffer)

    # Send the NTLM Type 3 message -- Response Message
    code, response = smtp.docmd("", ntlm_message)
    if code != SMTP_AUTH_OKAY:
        raise SMTPAuthenticationError(code, response)

rawDescription: SMTP through Exchange using Integrated Windows Authentication (NTLM) using Python


code:
cols = ['a', 'b', 'c']
csv.writerow([''] + cols)
for name, values in data.iteritems():
    csv.writerow([name] + [values.get(c, 0) for c in cols])

rawDescription: create python array from dict of dicts

description: Create python array from dict of dicts


code:
infile = open(listfile,'r')
filecontent = infile.readlines()
infile.close()
array1 = []
array2 = []
for line in filecontent:
    tmp = line.strip().split(':')
    array1.append(tmp[0])
    array2.append(tmp[1])

rawDescription: How to read data from text file in Python using a colon delimeter

description: Read data from text file in Python using a colon delimeter


code:
import sys
print('\n'.join(sys.path))

rawDescription: Working with Import Statements in OSX Mavericks


code:
import shutil

def move(destination, depth=None):
    if not depth:
        depth = []
    for file_or_dir in os.listdir(os.path.join([destination] + depth, "\\")):
        if os.path.isfile(file_or_dir):
            shutil.move(file_or_dir, destination)
        else:
            move(destination, os.path.join(depth + [file_or_dir], "\\"))

rawDescription: Flatten complex directory structure in Python


code:
class UploadPhoto(APIView):
    #authentication_classes = (TokenAuthentication,)
    permission_classes = ()#(IsAuthenticated,)

    def put(self, request, username):

        user = User.objects.get(username = username)
        userprofile = UserProfile.objects.get(user= user)
        photo = PhotoSerializer(userprofile,data = request.data)
        photo.is_valid(raise_exception=True)
        photo.save()

        return Response(status= status.HTTP_200_OK)

rawDescription: UploadPhoto To Django Rest Framework

description: UploadPhoto To Django Rest Framework


code:
class InvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice

    def __init__(self, *args, **kwargs):
        super(InvoiceForm, self).__init__(*args, **kwargs)
        # get the customer ID somehow
        my_customer = Customer.objects.get(id=CUSTOMER_ID)
        self.initial['name'] =  my_customer.name
        self.initial['surname'] = my_customer.surname
        self.initial['email'] = my_customer.email

class InvoiceAdmin(admin.ModelAdmin):
    form = InvoiceForm

rawDescription: Get initial data relatively to selected ForeignKey in Django ModelAdmin


code:
import argparse
import os
import glob

version = "0.1.1"

parser = argparse.ArgumentParser(
    description = 'cldir: clear a directory from .meta and other unwanted files')

# arguments list

parser.add_argument('-v', '--version', action='version', version = version)

parser.add_argument('-d', '--directory', default=os.path.expanduser('~/downloads'),
                    help='directory to be cleaned')

parser.add_argument('-e', default='meta', help='extension')

args = parser.parse_args()
print(args)
path = os.path.join(args.directory)
files = glob.glob(path + '*.{}'.format(args.e))

if len(files) == 0:
    print('No .meta files found in ~/downloads')
else:
    for f in files:
        os.remove(f)
    print('%d file(s) deleted' %len(files))

rawDescription: Using argparse arguments in different ways


code:
#!/usr/bin/python3.4
class A(object):
    def __init__(self):
        print("A constructor")

class B(A):
    def __init__(self):
        if self.__class__ == B:
            A.__init__(self)
        print("B constructor")

class C(A):
    def __init__(self):
        if self.__class__ == C:
            A.__init__(self)
        print("C constructor")

class D(B,C):
    def __init__(self):
        B.__init__(self)        #
        C.__init__(self)        # if B constructor should be
        A.__init__(self)        # called before of C constructor
        print("D constructor")  #

#        C.__init__(self)       #
#        B.__init__(self)       # if C constructor should be
#        A.__init__(self)       # called before of B constructor
#        print("D constructor") #

if __name__ == "__main__":
    d = D()

rawDescription: Python3.4 multi inheritance call specific constructors


code:
lst =  [72, 101, 108, 108, 111]
str(bytearray(lst))
''.join(chr(x) for x in lst)

rawDescription: Convert a list with characters to a string (Python)


code:
import django.utils.translation.trans_real as trans
from django.utils.thread_support import currentThread

def isactive():
  return currentThread() in trans._active

rawDescription: Django: How to detect if translation is activated?


code:
import re
s = '....00.3276021,,,constString1=31;garbage=00:00:00.0090000;constString2=16;garbage2=00.00...'
re.search('constString1=(\d+);', s).group(1)
re.search('constString2=(\d+);', s).group(1)

rawDescription: Extracting an integer between = and ;

description: Extracting an integer between = and ;


rawDescription: Change list to json format in Python

description: Change list to json format in Python


rawDescription: os.stat() on Windows

description: Os.stat() on Windows


code:
import datetime, pytz

datetime.datetime.now(pytz.timezone('Asia/Jerusalem')).strftime('%z')

# returns '+0300' (because 'now' they have DST)

pytz.timezone('Asia/Jerusalem').localize(datetime.datetime(2011,1,1)).strftime('%z')

# returns '+0200' (because in January they didn't have DST)

rawDescription: get UTC offset from time zone name in python

description: Get UTC offset from time zone name in python


code:
# -*- coding: utf-8 -*-
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.maximize_window()
driver.get('http://www.swiggy.com/bangalore')

# wait for input to appear and make a search
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.ID, "pac-input"))).send_keys("Koramangala")

# wait for suggestions to appear
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.pac-container div.pac-item")))

# choose the first suggestion
suggestions = driver.find_elements_by_css_selector("div.pac-container div.pac-item")
suggestions[0].click()

# wait for results to load
wait.until(EC.visibility_of_element_located((By.ID, "restaurants")))

# TODO: extract results

rawDescription: Submitting value in a Google powered form while scraping


code:
A=[0]*len(matrix)
B=[0]*len(matrix)
C=[0]*len(matrix)
for i in range(len(matrix)):
    full_array = np.fromstring(matrix[i], dtype=float, sep=" ")
    A[i]=full_array[0]
    B[i]=full_array[1]
    C[i]=full_array[2]

rawDescription: From a large text file to a sparse matrix with Python


code:
def get_img(html):
    soup = BeautifulSoup(html)
    img_box = []
    imgs = soup.find_all('div', class_= 'pthumb')

    for img in imgs:
        img_box.append(get_domain(BASE_URL) + img.img['src'])

    my_path = '/home/<username>/Desktop'  # use whatever path you like
    for img in img_box:
        urllib.request.urlretrieve(img, os.path.join(my_path, os.path.basename(img)))

rawDescription: Save image from url to special folder

description: Save image from url to special folder


code:
import shapely
from shapely.geometry.point import Point
p = Point(0, 0)
circle = p.buffer(1.0)
list(circle.exterior.coords)

rawDescription: Draw an ellipse using Shapely

description: Draw an ellipse using Shapely


code:
from django.contrib.auth.models import User

user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

rawDescription: create a django form object and save it

description: Create a django form object and save it


rawDescription: Define Python function and print output in terminal


rawDescription: Django returning said rows in a queryset


code:
a
sorted(a)

rawDescription: the order in which result of a set is printed in Python

description: The order in which result of a set is printed in Python


code:
from fn import _
list(map(_ * 2, range(5)))

rawDescription: Python analog for Groovy's it?

description: Python analog for Groovy's it


code:
count = ((min < X) & (X < max) &
         (min < Y) & (Y < max) &
         (min < Z) & (Z < max)).sum()

rawDescription: Count elements in a box

description: Count elements in a box


code:
df
df.max()
df['B'].max()
df.idxmax()

rawDescription: Pandas DataFrame Retrieve Value from Column


code:
var1= input("First name")
# keep asking for a first name if var1 has non alphabet chars
while not var1.isalpha():
    var1= input("First name")

var2= input("Last name")
# keep asking for a first name if var2 has non alphabet chars
while not var2.isalpha():
    var2= input("Last name")

print(var1, var2)

rawDescription: Loopback to input if number is entered

description: Loopback to input if number is entered


code:
import pdb
pdb.set_trace()

rawDescription: Nose or pytest drop in to interactive console when running tests


code:
class SerialReader(object):
    def __init__(self, source):
        super(SerialReader, self).__init__()
        self.source = source

    def next(self):
        """Provide next piece of data from the serial source."""
        # If we have no more data, we have to raise StopIteration exception
        if self.source.at_end():
            raise StopIteration
        else:
            return self.source.read()

    def __iter__(self):
        return self

reader = SerialReader(some_serial_source)

for data in reader:
    do_something_with_data(data)

rawDescription: how to treat input as a generator

description: Treat input as a generator


code:
import matplotlib.pyplot as plt

fig, ((ax1a, ax2a), (ax3a, ax4a)) = plt.subplots(2, 2)

ax1b = ax1a.twinx()
ax2b = ax2a.twinx()
ax3b = ax3a.twinx()
ax4b = ax4a.twinx()

ax1a.set_ylabel('ax1a')
ax2a.set_ylabel('ax2a')
ax3a.set_ylabel('ax3a')
ax4a.set_ylabel('ax4a')
ax1b.set_ylabel('ax1b')
ax2b.set_ylabel('ax2b')
ax3b.set_ylabel('ax3b')
ax4b.set_ylabel('ax4b')

plt.tight_layout()
plt.show()

rawDescription: Python: Suplots with secondary-axis

description: Python: Suplots with secondary-axis


code:
pillowName = driver.find_element_by_css_selector(".pillow-name").text
firstWord = pillowName.split()[0]

rawDescription: How to print just first name instead of full using beautiful soup python

description: Print just first name instead of full using beautiful soup python


code:
with mpl.rc_context():
    mpl.rc('axes', color_cycle=['#0000FF', '#FF6600'])
    dta = sm.datasets.sunspots.load_pandas().data[['SUNACTIVITY']]
    dta.index = pd.DatetimeIndex(start='1700', end='2009', freq='A')
    res = sm.tsa.ARMA(dta, (3, 0)).fit()
    fig, ax = plt.subplots()
    ax = dta.ix['1950':].plot(ax=ax)
    fig = res.plot_predict('1990', '2012', dynamic=True, ax=ax,
                           plot_insample=False)

rawDescription: python statsmodels ARMA plot_predict

description: Python statsmodels ARMA plot_predict


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

numdays = 5
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(hours=x) for x in range(0, numdays*24)]

data = np.random.rand(len(date_list))

fig, ax = plt.subplots(1, 1)
ax.plot(date_list, data)
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(mdates.HourLocator())
fig.autofmt_xdate()

plt.draw()
plt.show()

rawDescription: X-axis ticks will not update when zoom or pan


code:
#!/usr/bin/python
# Program: Parsing, Aggregating & Sorting text file in Python
# Developed By: Pratik Patil
# Date: 22-08-2015

import pprint;

# Open file & store the contents in a dictionary object
file = open("names.txt","r");
file_contents=eval(file.readlines().pop(0));

# Extract all lists from file contents
file_contents_values=file_contents.values();

# Extract Unique Years & apply segregation
year=sorted(set(map(lambda x:x[0], file_contents_values)));
file_contents_values_grouped_by_year = [ [y[1] for y in file_contents_values if y[0]==x ] for x in year];

# Create Final Dictionary by combining respective keys & values
output=dict(zip(year, file_contents_values_grouped_by_year));

# Apply Sorting based on ranking
for NameRank in output.values():
    NameRank.sort(key=lambda x: int(x.split()[1]));

# Print Output by ascending order of keys
pprint.pprint(output);


code:
import re
import itertools as it

with open('zipcode','r') as z:
    zipcode_pat=re.compile('({0})'.format('|'.join(line.rstrip() for line in z)),
                        re.IGNORECASE)
with open('city','r') as c:
    city_pat=re.compile('({0})'.format('|'.join(line.rstrip() for line in c)),
                      re.IGNORECASE)

def gitone(seq):
    for match in seq:
        if match:
            yield match.group(1)
        else:
            yield 'Missing'

with open('address','r') as f:
    f1,f2=it.tee(f,2)
    zipcodes=gitone(zipcode_pat.search(line) for line in f1)
    cities=gitone(city_pat.search(line) for line in f2)
    for city,zipcode in it.izip(cities,zipcodes):
        print('{c} {z}'.format(c=city,z=zipcode))

# Riverside 12034
# Santa clara 93453
# Missing Missing
# O'Fallon Missing

rawDescription: Extraction from a string in R or Python

description: Extraction from a string in R or Python


code:
from copy import deepcopy
listB = deepcopy(listA)

rawDescription: reverse method mutating input

description: Reverse method mutating input


code:
from numpy import arange,linspace,argmin
vals = arange(30).reshape(2,5,3) #your N-dimensional input, like array([2,4])
lGrid = linspace(0.1, 8, 50)
result = argmin(abs(lGrid-vals[...,newaxis]),axis=-1)

rawDescription: Grid search: Get index that corresponds best to value (for a whole matrix)


code:
def copy_image(f):
    assert os.path.exists(f), "file does not exist"
    image = gtk.gdk.pixbuf_new_from_file(f)

    clipboard = gtk.clipboard_get()
    clipboard.set_image(image)
    clipboard.store()

rawDescription: Pasting image to clipboard in python in linux


code:
#!/usr/bin/env python

import web

urls = (
  '/', 'index'
)

class index:
    def GET(self):
        # redirect to the static file ...
        raise web.seeother('/static/index.html')

app = web.application(urls, globals())

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

rawDescription: How to serve file in webpy?

description: Serve file in webpy


code:
import Tkinter as tk
import tkFileDialog
import datetime

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.windows = []
        menubar = tk.Menu(self)
        self.configure(menu=menubar)
        fileMenu = tk.Menu(self)
        fileMenu.add_command(label="New...", command=self.new_window)
        fileMenu.add_command(label="Save All", command=self.save_all)
        menubar.add_cascade(label="Window", menu=fileMenu)
        label = tk.Label(self, text="Select 'New' from the window menu")
        label.pack(padx=20, pady=40)

    def save_all(self):
        # ask each window object, which is acting both as
        # the view and controller, to save it's data
        for window in self.windows:
            window.save()

    def new_window(self):
        filename = tkFileDialog.askopenfilename()
        if filename is not None:
            self.windows.append(TileWindow(self, filename))

class TileWindow(tk.Toplevel):
    def __init__(self, master, filename):
        tk.Toplevel.__init__(self, master)
        self.title("%s - Tile Editor" % filename)
        self.filename = filename
        # create an instance of a TileSet; all other
        # methods in this class can reference this
        # tile set
        self.tileset = TileSet(filename)
        label = tk.Label(self, text="My filename is %s" % filename)
        label.pack(padx=20, pady=40)
        self.status = tk.Label(self, text="", anchor="w")
        self.status.pack(side="bottom", fill="x")

    def save(self):
        # this method acts as a controller for the data,
        # allowing other objects to request that the
        # data be saved
        now = datetime.datetime.now()
        self.status.configure(text="saved %s" % str(now))

class TileSet(object):
    def __init__(self, filename):
        self.data = "..."

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: tkinter and GUI programming methods

description: Tkinter and GUI programming methods


code:
from ctypes import string_at
from sys import getsizeof
from binascii import hexlify
# create a dummy object, just to get a memory location
a = 0x7fff
# and use it as a pivoting point to access other locations
offset = 100
print(hexlify(string_at(id(a)+offset, getsizeof(a))))

rawDescription: How to get garbage values in python

description: Get garbage values in python


code:
from numpy.lib.stride_tricks import as_strided

m = 3
n = 4
X = np.arange(m*n).reshape((m,n))

sz = X.itemsize
Xi = as_strided(X, shape=(m,n,n), strides=(n*sz, sz, 0))
Xj = as_strided(X, shape=(m,n,n), strides=(n*sz, 0, sz))

rawDescription: Numpy "multi meshgrid"

description: Numpy "multi meshgrid"


code:
root = get_nodes.mmnode_plus.factory('somenodes.xml')

tests = [
    (root, {'skip_traversal': False, 'skip_as_child': True, 'skip_as_parent': False, 'is_leaf': False}),
    (root[0], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False, 'is_leaf': False}),
    (root[1], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}),
    (root[1][0], {'skip_traversal': True}),
    (root[0][0], {'is_leaf': False, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False}),
    (root[0][0][0], {'is_leaf': True, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}),
    (root[0][4], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}),
    (root[0][7], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}),
]

i = 0
for (node, states) in tests:
    for test_state, exp_result in states.iteritems():

        input = node.__getattribute__(test_state)()
        errstr = "expected %s, not %s for state %s of node %s" % (input, exp_result, test_state, repr(node))

        locals()['foo' + str(i)] = type('foo' + str(i), (unittest.TestCase,),
            {'input': input, 'exp_result': exp_result, 'errstr': errstr, 'testme': lambda self: self.assertEqual(self.input, self.exp_result, self.errstr)})
        i += 1

rawDescription: Make pyunit show output for every assertion


rawDescription: Bypass django form validation on new form instance


code:
def find_chr(s,char):
    i=0
    step = len(char)
    for j in range(len(s)+1):
        ch = s[j:j+step]
        if ch==char:
            return (i)
            break
        i+=1
    return -1

def find_str(s,x):
    i=0
    if x in s:
        return find_chr(s,x)
    else:
        return -1

rawDescription: finding the index of the first letter of a sub string in the main string

description: Finding the index of the first letter of a sub string in the main string


code:
from Tkinter import *

master = Tk()

def callback():
   listbox.insert(END, "Click!")

b = Button(master, text="OK", command=callback)
listbox = Listbox(master)
b.pack()
listbox.pack()

mainloop()

rawDescription: tkinter event binding to button

description: Tkinter event binding to button


code:
plt.scatter(x, y)
plt.yscale('log')
plt.gca().invert_yaxis()
plt.show()

rawDescription: PyPlot reverse y-axis and logarithmic

description: PyPlot reverse y-axis and logarithmic


code:
rows = np.arange(a.shape[0])
cols = np.arange(a.shape[1])
a[rows[:, None], cols, b]

rawDescription: Numpy Mutidimensional Subsetting

description: Numpy Mutidimensional Subsetting


code:
import requests

url = 'http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1&paramid=4221'
user = 'test'
password = 'test5'

# Takes care of the HTTP authentication
data = requests.get(url, auth=(user, password))
json_data = data.json()

rawDescription: Python program reading URL

description: Python program reading URL


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_string)
# To find just 'Uge##' or 'uge##', as specified in the question:
urls = [el["href"] for el in soup.findAll("a", href=re.compile("[Uu]ge\d+"))]
# To find without regard to case at all:
urls = [el["href"] for el in soup.findAll("a", href=re.compile("(?i)uge\d+"))]

rawDescription: Finding urls containing a specific string


rawDescription: ArcPy, Python- Splitting a string on multiple occurrences of a hyphen


code:
sum_x = 0
sum_y = 0
count = 0
for x in range(0, 10):
  for y in range(0, 20):
    if image[x][y] == '#':
      sum_x += x
      sum_y += y
      count += 1
centre_x = sum_x / count # this will truncate; round or use float if you want
centre_y = sum_y / count

rawDescription: image processing python of a ball

description: Image processing python of a ball


code: set(folder for folder, subfolders, files in os.walk('/') for file_ in files if os.path.splitext(file_)[1] == '.png')

rawDescription: Python: Get Folder containing specific files extension


rawDescription: python munkres.py cost matrix

description: Python munkres.py cost matrix


code:
outfile = open("/path/to/file", "w")
[...]
outfile.write([...])

rawDescription: Is there a FileIO in Python?

description: Is there a FileIO in Python


code:
for key, value in config.iteritems():
    # Customize key here, for example transform 'text_height' to 'TextHeight' or
    # use 'key.title()' to obtain titlecased keys...
    setattr(self, key, value)

rawDescription: Assigning attributes values from a dictionary


code:
class Important(StackLayout):
    def NoInspiration(self, smile):
        print("Received: {}".format(smile))

    def AddFancy(self):
        print(self.ids) # only returns {'boxy': <weakproxy at 0000000002D119A8 to BoxLayout at 0000000002D026A8>}
        self.ids.boxy.add_widget(FancyButton(text='f', imp = self)) # no need to use a factory

rawDescription: Kivy rule inherence with add_widget()

description: Kivy rule inherence with add_widget()


code:
out_indices = []
in_indices = []

for x, (p, d) in enumerate(edges):
    if d == 'O':
        out_indices.append(x)
    elif d == 'I':
        in_indices.append(x)

rawDescription: Finding indices of two different groups in a python list into two lists


code:
def f(a,b):
    """Adds a and b."""
    return a+b
f.__doc__

rawDescription: How does ply.lex extract the regular expression from each token definition function?


code:
for i in range(10):
    digits = Label(new_window, text=str(i+1))
    shoes_label = Label(new_window, text=list_of_shoes[i])
    digits.grid(row=i, column=0)
    shoes_label.grid(row=i, column=1)

new_window.mainloop()

rawDescription: Tkinter for loop counter

description: Tkinter for loop counter


code:
import pandas as pd

data = pd.read_csv("test_rand.csv")
fare = pd.read_csv("test_fare.csv")

merged = pd.merge(data, fare, how='left', on=['medallion', 'hack_license', 'pickup_datetime'])
merged.to_csv("merged.csv", index=False)

rawDescription: csvjoin on multiple columns

description: Csvjoin on multiple columns


code:
import numpy as np
import matplotlib.pyplot as plt
#--------------------------------
def points(x,y,n): # Plot n points symmetrically aligned about axes
    dx=0.03  # define distance between individual dots
    m = 1-(n%2) # ensure symmetrical alignment for odd or even number of dots
    while(m<n):
        plt.scatter(x+(dx*m),y,color = 'k', marker = 'o', s=50, zorder=1)
        plt.scatter(x-(dx*m),y,color = 'k', marker = 'o', s=50, zorder=1)
        m+=2
    return
#--------------------------------
def histogram(b): # count number of data points in each bin
    for col in range(0,2):
        count = np.unique(b[:,col], return_counts=True)
        for n in range(0,np.size(count[col])):
            points(col,count[0][n], count[1][n])
    return
#-------------------------------
def partition(a,bins): # partition continuous data into equal sized bins for plotting
    lo = np.min(a)
    hi = np.max(a)
    rng = hi-lo
    step = rng/float(bins-1)

    for col in range (0,2):
        for row in range (0,int(np.size(a,axis=0))):
            for n in range (0,bins):
             if (a[row,col] <= (lo + (step / 2) + n * step)):
                 b[row,col] = (lo + (n * step))
                 break
    return(b)
#--------------------------------
def lines(b): # draw 'before' and 'after' lines between paired data points + median line
    for row in range (0,int(np.size(a,axis=0))):
        plt.plot([0,1],[b[row,0], b[row,1]], c='k',zorder=0, lw=1, alpha=0.3)
        plt.plot ([0,1],[np.median(b[:,0]),np.median(b[:,1])],c='r',zorder=2, lw=2, alpha=1)
    return
#================================
# MAIN
# Dummy paired continuous data (...or import from spreadsheet as a numpy array)\;
a = np.array([
 [1.62,1.53,1.42,1.39,1.11,1.20,0.99,0.88,0.60,0.65,0.52,0.49,0.43,0.41,0.31], # before
[0.8,0.7,0.52,0.61,0.44,0.43,0.49,0.33,0.44,0.39,0.20,0.29,0.37,0.19,0.00] ]) # after

bins = 10 # choose total number of bins to categorise data into
ax=plt.axes()

a = a.transpose()
b=a # make a copy of the input data matrix to write categorised data to
b = partition(a,bins) # partition continuous data into bins
lines(b) # draw lines between mid points of each bin and draw median line
histogram(b) # draw histograms centered at mid points of each bin

# Make general tweaks to plot appearance here:
plt.xticks([0,1], ['OUT', 'IN'], fontsize=14)
plt.ylabel('stimulation threshold (mA)',fontsize=13)
plt.text(0.8,1.3,'All patients',fontsize=13)
ax.patch.set_facecolor('white') # set background colour for plot area (default = white)
ax.spines['top'].set_visible(False)   # remove default upper axis
ax.spines['right'].set_visible(False) # remove default right axis
plt.tick_params(axis='both',which='both',direction = 'out',top='off', right = 'off',labeltop='off') # remove tick marks from top & right axes
plt.xlim(-0.6,1.6)
plt.ylim(0,1.7)

plt.show()

rawDescription: Parallel axis dot plot with vertical histograms for paired samples


code:
with open('receipts_10.csv', 'rU') as csvfile:
    reader = csv.reader(csvfile, delimiter=';')
    outfile = 'somefile.csv'
    ofile = open(outfile,"wb")
    writer = csv.writer(ofile,delimiter=";")

    for row in reader:
        response = requests.post(site, params={'appReceiptNum':row})
        soup = BeautifulSoup(response.text)
        status = soup.find("h4")
        statusString = status.text
        writer.writerow(statusString)

rawDescription: Write url request output to a csv in Python


rawDescription: Remove string between 2 characters from text string


code:
with open(testingFolder + "zca_whitening_testdata.csv", 'wb') as fp:
    writer = csv.writer(fp)

    temp_list = []

    temp_list.append("label")

    for j in range(0,aux_data.shape[1]-1):
        header = "pixel"+str(j)
        temp_list.append(header)

    writer.writerow(temp_list)

    for i in range(0, aux_data.shape[0]):
        writer.writerow(aux_data[i,:].tolist())

rawDescription: Python , Using Astype partially on the array


code:
def xy(st):
    my_list,st1 =[],''
    for x in st:
        if x in 'aeiou':
            st1 += 'xy'+x
        elif x in 'cbdgfhkjmlnqpsrtwvyxz':
            my_list.append(x)
            st1 += x
    return my_list,st1

my_string="how now brown cow"
xy(my_string)

rawDescription: Python: Creating a new list that is dependent on the content of another list


code:
image_plane_widget1 = engine.scenes[0].children[1].children[0].children[0]
image_plane_widget1.ipw.origin = array([  0.5,  21. ,   0.5])
image_plane_widget1.ipw.point1 = array([  0.5,  21. ,  50.5])
image_plane_widget1.ipw.point2 = array([ 50.5,  21. ,   0.5])
image_plane_widget1.ipw.origin = array([  0.5,  21. ,   0.5])
image_plane_widget1.ipw.point1 = array([  0.5,  21. ,  50.5])
image_plane_widget1.ipw.point2 = array([ 50.5,  21. ,   0.5])

rawDescription: How do I adjust the slice_index of a cut plane in Mayavi?

description: Adjust the slice_index of a cut plane in Mayavi


code:
df1
df2
df2.groupby("ID").agg(" | ".join)
df1.merge(df2.groupby("ID").agg(" | ".join), left_on = "ID", right_index=True, how="left")

rawDescription: Python Panda Concat Multiple Rows

description: Python Panda Concat Multiple Rows


code:
xy_chart = pygal.XY(stroke=False)
xy_chart.title = 'A Made Up Correlation Between Search Engines'
xy_chart.add('Group A', [{'value': (0, 0), 'label': 'google', 'xlink':'http://www.google.com'}, {'value': (22, 2), 'tooltip': 'bing', 'xlink':'http://www.bing.com'}])
xy_chart.add('Group B', [{'value': (12, 20), 'label': 'yahoo', 'xlink':'http://www.yahoo.com'}, {'value': (33, 12), 'tooltip': 'duckduckgo', 'xlink':'http://www.duckduckgo.com'}])
xy_chart.render()

rawDescription: How to define points' labels using Pygal Scatterplot, pygal.XY?

description: Define points' labels using Pygal Scatterplot, pygal.XY


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread
import matplotlib.cbook as cbook

np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,10.0,15)

datafile = cbook.get_sample_data('lena.jpg')
img = imread(datafile)
plt.scatter(x,y,zorder=1)
plt.imshow(img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
plt.show()

rawDescription: Adding a background image to a plot with known corner coordinates


code:
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _

rawDescription: Multiple imports in python as the same keyword


code:
class DemoSerializer(serializers.Serializer):

    def to_representation(self, instance):
        data = super(DemoSerializer, self).to_representation(instance)

        instance_type = data["type"]

        if field_last_modified < last_modified:
            data.pop("field")

        return data

rawDescription: Selectively display Django REST serializer fields


code: c_solutions = [sol[c] for sol in solutions]

rawDescription: Sympy - get access to the single parts of the solution of solve()


code:
from readline import rl as readline
readline.mode.show_all_if_ambiguous("on")

rawDescription: pyreadline configuration through script

description: Pyreadline configuration through script


code:
model = QtGui.QStandardItemModel(0,3) # three columns

model.setHorizontalHeaderLabels( [ "Column 0", "Column 1", "Column 3"] )

rawDescription: How to create columns header and its labels with QTableView

description: Create columns header and its labels with QTableView


code:
def letter_guess():
    words="testing"
    letter_s = input("please enter a letter")
    if letter_s in "testing":
        print("true")
    else:
        print("false")

letter_guess()

rawDescription: Script works fine without function. Turning it into one makes the program fail


code:
import tkinter as tk
import ttk

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.size=5
        self.vars = {}
        for i in range(self.size):
            self.vars[i] = tk.StringVar()
            entry = ttk.Entry(self, textvariable=self.vars[i])
            entry.pack(side="top", fill="x")
            self.vars[i].trace("w", self.callback)

        # this entry will show the other values as a list
        self.e0Var = tk.StringVar()
        self.e0 = ttk.Entry(self, textvariable=self.e0Var)
        self.e0.pack(side="top", fill="x", pady=(4,0))

        # call the callback once to establish the initial value
        self.callback()

    def callback(self, *args):
        values = []
        for i in range(self.size):
            values.append(self.vars[i].get())
        # make a comma separated list and store in e0Var
        self.e0Var.set(str(values))

app = App()
app.mainloop()

rawDescription: Python Tkinter - Place several entries within a for


rawDescription: Connect PySide to a signal using QSignalMapper and an instance method


rawDescription: Efficient repeated substring replace with Python


code:
import unicodedata

validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)

def removeDisallowedFilenameChars(filename):
    cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
    return ''.join(c for c in cleanedFilename if c in validFilenameChars)

rawDescription: Turn a string into a valid filename in Python


code:
import matplotlib.pyplot as plt
from collections import OrderedDict

fig,(ax1,ax2) = plt.subplots(1,2)

Testdic1 =OrderedDict([('Exploit', 14664), ('Botnet', 123), ('Virus', 52)])
Testdic2 =OrderedDict([('Botnet', 1252), ('Virus', 600), ('XSS', 452)])

list1 = list(Testdic1.items())
list2 = list(Testdic2.items())

n1 = len(list1)
n2 = len(list2)

values1 = [v for l,v in list1]
values2 = [v for l,v in list2]

ax1.barh(range(n1),values1,align='center', fc='#80d0f1', ec='w')
ax2.barh(range(n2),values2,align='center', fc='#80d0f1', ec='w')

# ====================================
# Here's where we change colors
# ====================================
for i,(label,val) in enumerate(list1):
    if label.title() in Testdic2:
        pass # leave it blue
    else:
        ax1.patches[i].set_color('g')
for i,(label,val) in enumerate(list2):
    if label.title() in Testdic1:
        pass # leave it blue
    else:
        ax2.patches[i].set_color('r')
# ====================================

ax1.set_yticks(range(n1))
ax2.set_yticks(range(n2))

for i, (label, val) in enumerate(list1):
    ax1.annotate(label.title(), xy=(10, i), fontsize=10, va='center')

for i, (label, val) in enumerate(list2):
    ax2.annotate(label.title(), xy=(10, i), fontsize=10, va='center')

ax1.invert_yaxis()
ax2.invert_yaxis()

plt.show()

rawDescription: Matplotlib change the bar color if a condition is met


rawDescription: How to make QRadioButton self centric

description: Make QRadioButton self centric


code: help(hasattr)

rawDescription: How to get information about a function and call it

description: Get information about a function and call it


rawDescription: Split string on portion of matched regular expression (python)


code:
import numpy as np
import matplotlib.pyplot as plt
y, x = np.ogrid[-1.5:1.5:200j, -1.5:1.5:200j]
f = (x**2 + y**2)**4 - (x**2 - y**2)**2

plt.figure(figsize=(9,4))
plt.subplot(121)
extent = [np.min(x), np.max(x), np.min(y), np.max(y)]
cs = plt.contour(f, extent=extent, levels=[0.1],
     colors=["b", "r"], linestyles=["solid", "dashed"], linewidths=[2, 2])

plt.subplot(122)
# get the points on the lines
for c in cs.collections:
    data = c.get_paths()[0].vertices
    plt.plot(data[:,0], data[:,1],
        color=c.get_color()[0],  linewidth=c.get_linewidth()[0])

plt.show()

rawDescription: Solving for zeroes in interpolated data in numpy/matplotlib


rawDescription: How can I plot just the data with no borders using pylab

description: Plot just the data with no borders using pylab


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

def set_text(txt):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(txt, win32clipboard.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()

set_text(u"喵萌茶会字幕组][10月新番.exe")

rawDescription: python win32clipboard not working for unicode characters

description: Python win32clipboard not working for unicode characters


rawDescription: syncing 2 arrays into another (nodal connectivity)

description: Syncing 2 arrays into another (nodal connectivity)


code:
response = br.open("www.linknotonpagethatiwanttogoto.com")
page = response.read()

rawDescription: Injecting HTML into a page using Mechanize


code:
import sys
from cgi import escape
try:
    import __builtin__ as builtins
except ImportError: # Python 3
    import builtins

def html_displayhook(value):
    if value is None:
        return
    text = escape(repr(value)) # <-- make html-safe text
    sys.stdout.write(text)
    sys.stdout.write("\n")
    builtins._ = value

sys.displayhook = html_displayhook

rawDescription: How to Understand and Parse the Default Python Object Representations


code:
import ctypes
from ctypes import windll, wintypes

class GUID(ctypes.Structure):
    _fields_ = [
         ('Data1', wintypes.DWORD),
         ('Data2', wintypes.WORD),
         ('Data3', wintypes.WORD),
         ('Data4', wintypes.BYTE * 8)
    ]

    def __init__(self, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8):
        """Create a new GUID."""
        self.Data1 = l
        self.Data2 = w1
        self.Data3 = w2
        self.Data4[:] = (b1, b2, b3, b4, b5, b6, b7, b8)

    def __repr__(self):
        b1, b2, b3, b4, b5, b6, b7, b8 = self.Data4
        return 'GUID(%x-%x-%x-%x%x%x%x%x%x%x%x)' % (
                   self.Data1, self.Data2, self.Data3, b1, b2, b3, b4, b5, b6, b7, b8)

# constants to be used according to the version on shell32
CSIDL_PROFILE = 40
FOLDERID_Profile = GUID(0x5E6C858F, 0x0E22, 0x4760, 0x9A, 0xFE, 0xEA, 0x33, 0x17, 0xB6, 0x71, 0x73)

def expand_user():
    # get the function that we can find from Vista up, not the one in XP
    get_folder_path = getattr(windll.shell32, 'SHGetKnownFolderPath', None)
    if get_folder_path is not None:
        # ok, we can use the new function which is recomended by the msdn
        ptr = ctypes.c_wchar_p()
        get_folder_path(ctypes.byref(FOLDERID_Profile), 0, 0, ctypes.byref(ptr))
        return ptr.value
    else:
        # use the deprecated one found in XP and on for compatibility reasons
       get_folder_path = getattr(windll.shell32, 'SHGetSpecialFolderPathW', None)
       buf = ctypes.create_unicode_buffer(300)
       get_folder_path(None, buf, CSIDL_PROFILE, False)
       return buf.value

rawDescription: An alternative to os.path.expanduser("~")?


code:
for (x, y), element in np.ndenumerate(np.array([[i for i in "egg"] for j in range(3)])):
    print(x, y, element)

rawDescription: Python enumerate through 2D array in numpy


code:
from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()

rawDescription: How can I run an external command asynchronously from Python?

description: Run an external command asynchronously from Python


code:
import time

t1 = time.time()

# code goes here

print('Took {} seconds'.format(time.time() - t1))

rawDescription: What is the best way to find how long it took for a python script to finish executing without adding any extra over head?


code:
header.version = read_field(edf, 8);
header.patinfo = read_field(edf, 80);

rawDescription: Should we avoid repetitive code in C++ in order to be "Pythonic", and how?


code:
d = dict.fromkeys(range(100))
keys = random.sample(list(d), 10)
keys
values = [d[k] for k in keys]

rawDescription: how to randomly choose multiple keys and its value in a dictionary python

description: Randomly choose multiple keys and its value in a dictionary python


code:
class AddTask(webapp2.RedirectHandler):
    def get(self, project_id):
        project = Project.get_by_id(int(project_id))

app = webapp2.WSGIApplication([
    ...
    (r'/projects/(\d+)/tasks/add', AddTask),
])

rawDescription: Python path manipulation

description: Python path manipulation


code:
pattern = re.compile(r'^Hello (.*?) BGC$')
s = 'Hello People BGC'
pattern.match(s).group(1)
pattern.sub("OTR", s)

rawDescription: Finding out unknown matched words

description: Finding out unknown matched words


code:
from PIL import Image
import os
for filename in filelist:
    basename, ext = os.path.splitext(filename)
    if ext.lower() == ".png":
        continue
    img = Image.open(filename)
    img.save(basename + ".png")

rawDescription: Python image conversion

description: Python image conversion


code:
import numpy as np

class MyClass:

    __array_priority__ = 0

    def __init__(self, data):
        self.arr = np.array(data)

    def __array__(self):
        return self.arr

    def __radd__(self, other):
        return "MyClass radd"

a = np.array([1])
b = MyClass([2])

# low priority (or no priority), numpy array addition
assert isinstance(a + b, np.ndarray)

# higher priority, your addition
MyClass.__array_priority__ = 1
assert a + b == "MyClass radd"

rawDescription: How to force "a+b" to always call "b.radd(a)" when a is numpy array, and b is my type?

description: Force "a+b" to always call "b.radd(a)" when a is numpy array, and b is my type


rawDescription: How to remove floats of a list of lists?

description: Remove floats of a list of lists


code:
def expand(node, hcList):
    if node.hasTreasure:
         hcList.append(node)
    if node.end():
         return hcList
    return expand(node.next(), hcList)

hcList = expand(startnode, [])
hcList.filter() # not sure why this was in the OP

rawDescription: Pass list by reference in python through recursion


code: imagedb = Imagedb(key_name = self.user.name)

rawDescription: Overwritting Data in App Engine

description: Overwritting Data in App Engine


code:
import re
s = """set policy id 1508 from "TEST" to "OPR"  "10.2.197.3/32" "ARG-VCENTER-SRV-1" "ANY" permit

set policy id 1508

exit

set policy id 1507 from "CMS-SrvFarm" to "DMZ"  "CMS-SRV5(10.2.90.14)" "THR-CMS-SRV-0" "TCP-123" permit

set policy id 1507

set service "TCP-37"

exit"""
m = re.findall(r'set(?:(?!exit).)*', s, re.DOTALL)
m

rawDescription: Get everything between start and end word


code:
import json
data = ('Hello')
json.dumps(data)
data = ('Hello', 'There')
json.dumps(data)
data = {'message': 'Hello'}
json.dumps(data)

rawDescription: How to convert an string to json in Python

description: Convert an string to json in Python


code:
def compare(File1,File2):
    with open(File1,'r') as f:
        d=set(f.readlines())

    with open(File2,'r') as f:
        e=set(f.readlines())

    open('file3.txt','w').close() #Create the file

    with open('file3.txt','a') as f:
        for line in list(d-e):
           f.write(line)

rawDescription: Python - Compare 2 files and output differences


code:
import os, sys, unittest, lucene
lucene.initVM()

baseDir = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path.append(baseDir)

import lia.searching.ScoreTest
from lucene import System

System.setProperty("index.dir", os.path.join(baseDir, 'index'))
unittest.main(lia.searching.ScoreTest)

rawDescription: Python - Library that compute relevance score for text search


code:
def matrix(m, a, b):
    return m[a][b] # element b from list a in list m

rawDescription: How to index into nested lists?

description: Index into nested lists


code:
import subprocess

etcd = subprocess.Popen('etcd') # continue immediately
next_cmd_returncode = subprocess.call('next_cmd') # wait for it
# ... run more python here ...
etcd.terminate()
etcd.wait()

rawDescription: Pythonic way to detach a process?

description: Pythonic way to detach a process


code:
def markCluster(items, threshold):
    k = 1
    clusters = [items]
    maxdist = diameter(items)
    while maxdist > threshold:
        k += 1
        clusters = Kmc(items, k)
        maxdist = max(diameter(c) for c in clusters)
    return clusters

rawDescription: put stockprices into groups when they are within 0.5% of each other

description: Put stockprices into groups when they are within 0.5% of each other


code:
def set_all_volume(sounds,mult):
    for sound in sounds:
        vol = sound.get_volume()
        sound.set_volume(min(vol*mult,1.0))

rawDescription: Setting volume globally in pygame.Sound module


code:
it = pool.imap_unordered(fnc, some_list)
for result in it:
    it._cond.acquire()
    for x in result:
        yield x
    it._cond.release()

rawDescription: Python's multiprocessing and memory

description: Python's multiprocessing and memory


code:
import pylab as plt
import numpy as np
my_image1 = np.linspace(0, 10, 10000).reshape(100,100)
my_image2 = np.sqrt(my_image1.T) + 3
subplot(1, 2, 1)
plt.imshow(my_image1, vmin=0, vmax=10, cmap='jet', aspect='auto')
plt.subplot(1, 2, 2)
plt.imshow(my_image2, vmin=0, vmax=10, cmap='jet', aspect='auto')
plt.colorbar()

rawDescription: Imshow subplots with the same colorbar

description: Imshow subplots with the same colorbar


code:
for i in range(n):
    for j in range(o):
        if j < len(newStringList) and i < len(newStringList[j]) :
              orderedList.append(newStringList[j][i])

rawDescription: Avoid 'index not in range' on nested loops encrypting chunks of string


code:
editor = QsciScintilla()
editor.insertAt(text, line, index)

rawDescription: Adding a line of text

description: Adding a line of text


code:
class MyForm(forms.Form):
    categories = forms.CharField(
            required=False,
            widget=forms.SelectMultiple(choices=CATEGORY_VALUE),
            label="Categories"
        )
    additional_item_ship_cost = forms.CharField(
            required=False,
            max_length=10,
            label="Additional Item Ship Cost"
        )

rawDescription: How would you properly break this line to match pep8 rules?


code:
from shapely.geometry import box
from itertools import combinations

codes = ["A", "B", "C"]
d = dict(zip(codes, data))
prev = codes[0]
matched, out = set(), []
for p1, p2 in combinations(codes, 2):
    if d[p1].intersects(d[p2]):
        out.append((p1, p2))
        matched.update([p1, p2])
    # when p1 is a new letter, we have tried all combs for that prev
    # if prev is not in matched it did not intersect any other so
   # add it as a single tuple and add to matched to avoid dupes
    elif p1 != prev and prev not in matched:
        out.append(tuple(prev,))
        matched.add(prev)
    prev = p1
# catch the last letter
if p2 not in matched:
    out.append(tuple(p2,))
print(out)
[('A', 'C'), ('B',)]

rawDescription: test if geometry items intersects in python list

description: Test if geometry items intersects in python list


code:
d = {i:v for q in [d1,d2,d3] for i,v in q.iteritems() if v != ''}
d

rawDescription: Merge two (or more) identical dictionaries having just one value in common - in Python


rawDescription: How can I convert a string representation of binary notation to actual binary notation

description: Convert a string representation of binary notation to actual binary notation


code:
from PyQt4 import QtCore, QtGui

app = QtGui.QApplication([])

data = QtCore.QMimeData()
url = QtCore.QUrl.fromLocalFile('c:\\foo.file')
data.setUrls([url])

app.clipboard().setMimeData(data)

rawDescription: PyQT - copy file to clipboard

description: PyQT - copy file to clipboard


code:
import glob
import collections

counter = collections.Counter()
for py_filename in glob.glob('*.py'):
  with open(py_filename) as f:
    linecount = sum(1 for line in f)
  counter[linecount//10] += 1

for i,n in sorted(counter.items()):
  print('{}-{}: {}'.format(i * 10, (i + 1) * 10 - 1, n))

rawDescription: Limitless count for occurrences in a list


code:
from string import ascii_lowercase as alphabet

def cipher(plaintext, shift):
   # Build a lookup table between the alphabet and the shifted alphabet.
   table = dict(zip(alphabet, alphabet[shift:] + alphabet[0:shift]))
   # Convert each character to its shifted equivalent.
   # N.B. This doesn't handle non-alphabetic characters
   return ''.join(table[c] for c in plaintext.lower())

rawDescription: Programming in Python; writing a Caesar Cipher using a zip() method


rawDescription: save with multipe digits bit show two

description: Save with multipe digits bit show two


code:
from jpype import *

jvm = None

def start_jpype():
    global jvm
    if (jvm is None):
        cpopt="-Djava.class.path={cp}".format(cp=classpath)
        startJVM(jvmlib,"-ea",cpopt)
        jvm="started"

rawDescription: Are there any distributed machine learning libraries for using Python with Hadoop?


code:
ts = ['20140101', '20140102', '20140105', '20140106', '20140107']
xs = pd.Series(data=range(len(ts)), index=pd.to_datetime(ts))
fig, ax = plt.subplots()
xs.plot(use_index=False)
ax.set_xticklabels(pd.to_datetime(ts))
ax.set_xticks(range(len(ts)))
fig.autofmt_xdate()
plt.show()

rawDescription: How to make pandas's Series only plot the data in index?

description: Make pandas's Series only plot the data in index


code: save_msg = str(msg)

rawDescription: Python - print/save the email before sending using smtplib


rawDescription: Drop extraneous decimal places when using Python's decimal.Decimal


code:
from haystack.query import SearchQuerySet
SearchQuerySet().filter(content='abra')
SearchQuerySet().filter(content='abra').count()

rawDescription: Getting raw results from Django Haystack


code:
from math import pi

print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower()
while response not in ["vol", "sa"]:
    print("Please enter a correct statement.")
    response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower()

radius, height = [float(part) for part in raw_input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]

r2 = radius ** 2
SA = 2 * pi * r2 + 2 + pi * radius * height
volume = pi * r2 * height

decimal_places = int(raw_input("How many decimal places do you want it to?: "))

if response=="vol":
    print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))
    verify = raw_input("Do you want to find out the surface area (type in Yes or No): ")
    if verify.lower() == "yes":
       print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))

if response =="sa":
    print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
    verify = raw_input("Do you want to find out the volume (type in Yes or No): ")
    if verify.lower() == "yes":
        print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))

rawDescription: Why does Python suddenly stop if the input is Yes?


code:
import shutil
shutil.copyfileobj(fd, self.wfile)

rawDescription: Python BaseHTTPServer serving files faster


code:
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogx(range(100))
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_major_formatter(ScalarFormatter())
#ax.yaxis.set_major_formatter(ScalarFormatter()) # for the y axis

fig.show()

rawDescription: Python - matplotlib modify xticks for a "loglog" plot


code:
with open('/path/to/file', 'r') as f:
    array = []
    for line in f:
        timestamp = int(line.split('|')[0].strip())
        array.append((timestamp, line))

array.sort()

rawDescription: Sorting Array in Python

description: Sorting Array in Python


code:
pipeline = Pipeline([
  ('features', FeatureUnion([
    ('ngram_tf_idf', Pipeline([
      ('counts_ngram', CountVectorizer()),
      ('tf_idf_ngram', TfidfTransformer())
    ])),
    ('pos_tf_idf', Pipeline([
      ('pos', POSTransformer()),
      ('counts_pos', CountVectorizer()),
      ('tf_idf_pos', TfidfTransformer())
    ])),
    ('measure_features', MeasureFeatures())
  ])),
  ('classifier', LinearSVC())
])

rawDescription: How to fit different inputs into an sklearn Pipeline?

description: Fit different inputs into an sklearn Pipeline


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

class MyAni(object):
    def __init__(self, size=4800, peak=1.6):
        self.size = size
        self.peak = peak
        self.fig = plt.figure()
        self.x = np.arange(self.size)
        self.y = np.zeros(self.size)
        self.y[0] = self.peak
        self.line, = self.fig.add_subplot(111).plot(self.x, self.y)

    def animate(self, i):
        self.y[i - 1] = 0
        self.y[i] = self.peak
        self.line.set_data(self.x, self.y)
        return self.line,

    def start(self):
        self.anim = animation.FuncAnimation(self.fig, self.animate,
            frames=self.size, interval=20, blit=False)

if __name__ == '__main__':
    ani = MyAni()
    ani.start()

    plt.show()

rawDescription: Simple Matplotlib animate not working

description: Simple Matplotlib animate not working


code:
import pandas as pd
import numpy as np

data = pd.DataFrame(np.random.randn(2000,784))

panel = pd.Panel(data.values.reshape(2000, 28, 28))

# In [49]: q.panel[42].shape
# Out[49]: (28, 28)

# In [51]: q.panel
# Out[51]:
# <class 'pandas.core.panel.Panel'>
# Dimensions: 2000 (items) x 28 (major_axis) x 28 (minor_axis)
# Items axis: 0 to 1999
# Major_axis axis: 0 to 27
# Minor_axis axis: 0 to 27

rawDescription: dataframe change size and the convert to panel python

description: Dataframe change size and the convert to panel python


code:
import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))

rawDescription: Pythonic way to find maximum value and its index in a list?


code:
doha_ra = {}

for i in search_string_list:
    switch = True
    while switch == True:
        search.send_keys(i)
        ret.send_keys(Keys.RETURN)
        try:
            addr = browser.find_element_by_xpath("//table/tbody/tr[2]/td[2]")
            ra = browser.find_element_by_xpath("//table/tbody/tr[4]/td[2]")
            doha_ra[addr.text] = ra.text
            switch = False
        except:
            pass
        search.clear()

rawDescription: selenium 'Modal dialog present' -- I beg to differ

description: Selenium 'Modal dialog present' -- I beg to differ


code:
temp1 = set([])
temp2 = set([])

dict1 = dict()
dict2 = dict()

for key, value in zip([tuple(l[1:3]) for l in list1], list1):
    dict1.setdefault(key, list()).append(value)

for key, value in zip([tuple(l[1:3]) for l in list2], list2):
    dict2.setdefault(key, list()).append(value)

for key in dict1:
    if key in dict2:
        temp1.update(dict1[key])
        temp2.update(dict2[key])

rawDescription: Filtering two lists by comparing all items to eachother with numpy or tabular


code:
lst = ['paragraph 1','paragraph 2','paragraph 3']
corpus = Corpus(documents=[Document(x) for x in lst])

rawDescription: How to use Python list?

description: Use Python list


code:
s = "combination.py"
[s[i:i+3] for i in range(len(s)-2)]

rawDescription: For every string get unique combination of 3 chars (together)


rawDescription: Efficiently accessing indices: is storing indices in a dict the fastest way?


code:
def in_ipython():
    try:
        __IPYTHON__
    except NameError:
        return False
    else:
        return True

rawDescription: Detecting when a python script is being run interactively in ipython


code:
subq_read = (session.query(
                Post.id,
                func.count(Read.id).label("total_read")
            ).
            outerjoin(Post.Reads).
            group_by(Read.post_read)
            ).subquery()

subq_vote = (session.query(
                Post.id,
                func.sum(Vote.user_vote).label("total_votes")
            ).
            outerjoin(Post.Votes).
            group_by(Vote.post_read)
            ).subquery()

posts = (session.query(
            Post,
            subq_read.c.total_read,
            subq_vote.c.total_votes,
        ).
        outerjoin(subq_read, subq_read.c.id == Post.id).
        outerjoin(subq_vote, subq_vote.c.id == Post.id)
        .group_by(Post)
        )

rawDescription: Sqlalchemy using func with outerjoin on multiple tables


rawDescription: checking whether tuple in the list in python

description: Checking whether tuple in the list in python


code:
black = [0,0,0]
Thres = 50
h,w = img.shape[:2]
black = 0
not_black = 0
for y in range(h):
    for x in range(w):
        pixel = img[y][x]
        d = math.sqrt((pixel[0]-0)**2+(pixel[1]-0)**2+(pixel[2]-0)**2)
        if d<Thres:
            black = black + 1
        else:
            not_black = not_black +1

rawDescription: opencv python detecting color of object is white or black

description: Opencv python detecting color of object is white or black


code:
original_tuple_value = [('hello'),('all'),('long')]
numpy_array_value = np.array([3,8,2])
map(tuple,np.column_stack((original_tuple_value,numpy_array_value)))

rawDescription: Concatenate a tuple with a value that is on a numpy array


code: from constants import *

rawDescription: Constants in a python package

description: Constants in a python package


code: sorted(the_list, key = lambda x: int(x.split("_")[1]))

rawDescription: Sort list of strings by integer suffix in python


rawDescription: Python populate list from a string with separator


rawDescription: django product of annotate

description: Django product of annotate


code:
import Tkinter
import ttk

class MakeGUI(object):
    def __init__(self,root):
        self.root = root
        self.root.title(u"Title")
        ## build frame
        self.mainframe = ttk.Frame(self.root, padding=(6, 6, 12, 12))
        self.mainframe.grid(sticky='nwse')
        for column in range(3):
            self.mainframe.columnconfigure(column, weight=1)
        self.mainframe.rowconfigure(1, weight=1)

        ## text labels
        ttk.Label(self.mainframe, text=u"Label Title", anchor='center',
                font=("Helvetica", 32)).grid(in_=self.mainframe,
                        column=0, row=0, columnspan=3, sticky="ew")

        self.lfdata = ttk.Labelframe(self.mainframe, padding=(6, 6, 12, 12),
                text='Labelframe')
        self.lfdata.grid(column=0, columnspan=3, row=1, sticky='nsew')
        info = (u"Source Filename", u"Source Text", u"Converted Text",
                u"Cleaned Source", u"Cleaned Converted", u"Details")
        for i, item in enumerate(info):
            ttk.Label(self.lfdata, text=u"%s:" % item).grid(in_=self.lfdata,
                    column=0, row=i, sticky='w')

        ## buttons
        btn = (u"Close", u"Next", u"Prev")
        for i, item in enumerate(btn):
            ttk.Button(self.mainframe, text=item).grid(in_=self.mainframe,
                    column=i, row=3)

def main():
    root = Tkinter.Tk()
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    makeGUI = MakeGUI(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Python & ttk Using labelFrames to clean up a frame


code:
from docx import Document
from docx.shared import Inches

document = Document()

p = document.add_paragraph()
r = p.add_run()
r.add_text('Good Morning every body,This is my ')
r.add_picture('/tmp/foo.jpg')
r.add_text(' do you like it?')

document.save('demo.docx')

rawDescription: Add an image in a specific position in the document (.docx) with Python?


code: answer = map(lambda x: x[0][x[1]], zip(data, info)) # [2, 0, 4]

rawDescription: Extracting values from indices without using loops


code: ttest_ind(df[df['Treatment'] == 'a']['Performance'], df[df['Treatment'] == 'b']['Performance'])

rawDescription: Transforming a Dataframe for statsmodels t-test


code:
from django.db.models import Sum

User.objects.annotate(total_viewed=Sum('sample__viewed'),
                      total_likes=Sum('sample__likes'),
                      total_abc=Sum('sample__abc'))

rawDescription: How i can use aggregation in django

description: How i can use aggregation in django


rawDescription: Python Turtle: How to use the write function to join an integer and a string with the integer coming from a list


code:
height_r_t = np.ma.masked_where(repelling_force_prefactor == 0, height_r_t)
repelling_forces = np.ma.exp(-(height_r_t/potential_steepness))

rawDescription: Efficient math operations on parts of "sparse" numpy arrays


code:
import pylab as pl
import numpy as np

x = np.arange(4)
y1, y2 = [1,2,1,1], [2,3,1,1.5]

pl.bar(x+0.2,y2, width=0.45, color='g', zorder=1)
_, caplines, _ = pl.errorbar(x+0.4,y2,fmt=None, yerr=0.75, ecolor='r',
            lw=2, capsize=10., mew = 3, zorder=2)

pl.bar(x,y1,width=0.45, zorder=3)
pl.errorbar(x+0.2,y1,fmt=None, yerr=0.5, ecolor='r',
            lw=2, capsize=10., mew = 3, zorder=4)

for capline in caplines:
    capline.set_zorder(2)

pl.savefig('err.png')

rawDescription: Matplotlib: Adjusting z-levels of errorbars in barchart


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

# make a weird continuous function
r, t = np.random.random((100,)), np.arange(0, 100, .01)
y = sum(r[3*i+0]*np.sin(r[3*i+1]*t + 10*r[3*+2]) for i in range(10))

# generate the masked array
mask = ma.masked_less(y, 1.1)

plt.plot(t, y, 'k', linewidth=3)
plt.plot(t, mask, 'r', linewidth=3.2)
plt.show()

rawDescription: Plot: color all larger than different color


rawDescription: python scientific notation with forced leading zero

description: Python scientific notation with forced leading zero


code:
import datetime

def checkdate(date):

    try:
        datelist = date.split('/')
        datetime.datetime(year=int(datelist[2]), month=int(datelist[1]),day=int(datelist[0]))
        return True
    except:
        return False

rawDescription: Checking the format/contents of a string


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

dst_ports = [22, 53223, 40959, 80, 3389, 23, 443, 35829, 8080, 4899, 21320, 445, 3128, 44783, 4491, 9981, 8001, 21, 1080, 8081, 3306, 8002, 8090]
dst_port_count = [5005, 145, 117, 41, 34, 21, 17, 16, 15, 11, 11, 8, 8, 8, 6, 6, 4, 3, 3, 3, 1, 1, 1]

fig = plt.figure(figsize=(12, 4))

# aesthetics and data
plt.grid()
x = np.arange(1, len(dst_ports)+1)
plt.bar(x, dst_port_count, align='center')
plt.xticks(x, dst_ports, rotation=45)

# labels
plt.title('Number of connections to port')
plt.xlabel('Destination Port')
plt.ylabel('Connection Attempts')

rawDescription: Python display specific values on x-axis using matplotlib


code:
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
objs = bucket.objects.filter(Prefix='/myprefix')
for obj in objs:
    pass

rawDescription: Boto3: grabbing only selected objects from the S3 resource


code:
UI = int(input("Enter a number [1-100]: "))

while UI != random:

        if UI > random:

            print ("Too High")
            UI = int(input("Enter a number [1-100]: "))
            continue

        elif UI < random:
            print ("Too Low")
            UI = int(input("Enter a number [1-100]: "))
            continue

rawDescription: IndentationError: unindent does not match any outer indentation level- elif UI < random


code:
class StatusField(FlagsField):
  name = '4 bit status'
  def __init__(self, name):
    FlagsField.__init__(self, name, 0, 4, ["a", "b", "c", "d"])

class TotalStatus(Packet):
  name = "8 bit status"
  fields_desc = [
    StatusField("axis0"),
    StatusField("axis1"),
  ]

rawDescription: Building scapy packets with PacketFields shorter than 8 bits


code:
with open(scriptPath, 'r') as inp:
    for line in inp:
        if line == 'GO\n':
            c.execute(sqlQuery)
            sqlQuery = ''
        elif 'PRINT' in line:
            disp = line.split("'")[1]
            print(disp, '\r')
        else:
            sqlQuery = sqlQuery + line
inp.close()

rawDescription: Follow up: Execute .sql files from python


code:
# urls.py
urlpatterns = patterns('blog.views',
    url(r'^test/$', 'views.testPage', {'template_name': 'signup/test1.html'}),
    url(r'^$', 'views.testPage', {'template_name': 'signup/test2.html'}),
)

# views.py
def testPage(request, template_name):
    # code goes here
    return render_to_response(template_name, context_instance=RequestContext(request))

rawDescription: Template switch within render to response


code:
line = ("Kathick Kumar, Bangalore who was a great person and lived from 29thMarch 1980 - 21 Dec 2014")
import re
regex = re.compile('(.*)(?:Bangalore)')
result = regex.search(line)
print(result.group(0))

rawDescription: Extracting using a string pattern in Regex- Python


code:
import random

_memomask = {}

def hash_function(n):
  mask = _memomask.get(n)
  if mask is None:
    random.seed(n)
    mask = _memomask[n] = random.getrandbits(32)
  def myhash(x):
    return hash(x) ^ mask
  return myhash

rawDescription: hash functions family generator in python

description: Hash functions family generator in python


rawDescription: hangman graphics blank word creation and space removal

description: Hangman graphics blank word creation and space removal


rawDescription: Automatically return verbose results in Python unittest?


code:
def default_float_format( x):
    return '{:.2%}'.format(x)

class A:

  def __init__(self, params):
    # ...
    # by default printing all float values as percentages with 2 decimals
    self.format_functions = {float: default_float_format}
  def __str__(self):
    # uses self.format_functions to format output
    pass

a = A(1)
pickle.dumps(a)

rawDescription: pickling class method

description: Pickling class method


code:
class Whatever:

    #constructor
    def __init__(self):
        self._x=None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        if isinstance(value, datetime): #silly example
            self._x = value
        else:
            raise ValueError('Was expecting a date')

rawDescription: set methods in Python, are they necessary?

description: Set methods in Python, are they necessary


code:
import xml.parsers.expat

# handler functions for parser events, and housekeeping.
class handler :
   def __init__(self, current_parser) :
      #tag of interest
      self.TARGET_TAG = "w:t"

      #set up parser
      self.parser = current_parser
      self.parser.StartElementHandler  = self.start_element
      self.parser.EndElementHandler    = self.end_element
      self.parser.CharacterDataHandler = self.char_data

      self.target_tag_met = False
      self.index = None

   def start_element(self, name, attrs):
      self.target_tag_met = (name == self.TARGET_TAG)

   def end_element(self, name) :
      self.target_tag_met = False

   def char_data(self, data):
      if self.target_tag_met :
         self.index = self.parser.CurrentByteIndex

#open file in binary mode for robuster byte offsets.
xmlFile = open("so_test.xml", 'rb')

p = xml.parsers.expat.ParserCreate()
h = handler(p)

p.ParseFile(xmlFile)
print (h.index)

rawDescription: Python lxml - get index of tag's text

description: Python lxml - get index of tag's text


rawDescription: converting text written in 1/8th format to numbers/digits in python

description: Converting text written in 1/8th format to numbers/digits in python