code:
from django.db import connection, models
qn = connection.ops.quote_name

class ProjectfundingdetailManager(models.Manager):
    def latest_by_project(self):
        project_model = self.model._meta.get_field('project').rel.to

        names = {'project': qn(project_model._meta.db_table),
                 'pfd': qn(self.model._meta.db_table),
                 'end_date': qn(self.model._meta.get_field('end_date').column),
                 'project_id': qn(self.model._meta.get_field('project').column),
                 'pk': qn(self.model._meta.pk.column),
                 'p_pk': qn(project_model._meta.pk.column)}

        sql = """SELECT pfd.%(pk)s FROM %(project)s AS p
                 JOIN %(pfd)s AS pfd ON p.%(p_pk)s = pfd.%(project_id)s
                 WHERE pfd.%(end_date)s =
                     (SELECT MAX(%(end_date)s) FROM %(pfd)s
                      WHERE %(project_id)s = p.%(p_pk)s)
              """ % names

        cursor = connection.cursor()
        cursor.execute(sql)
        return self.model.objects.filter(id__in=[r[0] for r
                                                 in cursor.fetchall()])

rawDescription: Django ORM Query to limit for the specific key instance


code:
weights = alpha * weights
weights[1, 1] = weights[1, 1] + 1

for i in range(5):
    u = convolve(u, weights)
    print(u)

rawDescription: Weighted sum of adjacent values in numpy array


code:
a = range(10)
for j in range(i*2, len(a), i):
    a[j] = a[j] * (i - 1) / i

rawDescription: changing values in a list while looping through it?

description: Changing values in a list while looping through it


code:
def log_request(fn):
    def decorated_get(self):
        logging.debug("request object:", self.request)
        return fn(self)
    return decorated_get

class MyHandler(webapp. RequestHandler):
    @log_request
    def get(self):
        self.response.out.write('hello world')

rawDescription: Accessing function arguments from decorator


code:
cur.execute("sp_insertItem(%s, %s, %s, %s::t_document)",
    ['Name', 'Phone', 'Address', ('Title', 'Metadata', 'Data')])

rawDescription: psycopg2 + stored procedure + compound type

description: Psycopg2 + stored procedure + compound type


code:
import requests

url='https://www.verizonwireless.com/vzw/browse/tradein/ajax/deviceSearch.jsp?act=models&car=Verizon&man=Apple&siz=large'
# Put your own contact info in next line
headers = {'User-agent':'MyBot/0.1 (+user@example.com)'}
r = requests.get(url, headers=headers)
print(r.json()['models'][0]['name'])

rawDescription: Python-Can't Pull JSON Format from JSON Source


code: from sys import argv, stdout

rawDescription: how import statement executes in python?

description: How import statement executes in python


code:
class ActivityForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ActivityForm, self).__init__(*args, **kwargs)
        if 'initial' in kwargs:
            self.fields['participants'].queryset = Member.objects.filter(group=initial.group)
    class Meta:
        model = Activity

rawDescription: Django ModelForm Field Filtering with multiple model dependancies


code:
#!/usr/bin/env python

import gtk

pixmap_rc = """
pixmap_path "/home/foo/images"
style "bar" {
    bg_pixmap[NORMAL] = "logo.svg"
} widget "*foo" style "bar"
"""

color_rc= """
style "bar" {
    bg[NORMAL] = "Hot Pink"
} widget "*foo" style "bar"
"""

def main ():
    window = gtk.Window()
    window.set_decorated(False)
    window.connect("destroy", gtk.main_quit)

    window.set_name("foo")
    gtk.rc_parse_string(color_rc)

    window.show_all()
    gtk.main()

if __name__ == "__main__":
    main ()

rawDescription: How to decorate a GTK window like eg. the gnome-panel?

description: Decorate a GTK window like eg. the gnome-panel


code:
def scrub(obj, bad="_this_is_bad"):
    if isinstance(obj, dict):
        for k in obj.keys():
            if k == bad:
                del obj[k]
            else:
                scrub(obj[k], bad)
    elif isinstance(obj, list):
        for i in reversed(range(len(obj))):
            if obj[i] == bad:
                del obj[i]
            else:
                scrub(obj[i], bad)

    else:
        # neither a dict nor a list, do nothing
        pass

rawDescription: python - recursively deleting dict keys?

description: Python - recursively deleting dict keys


code:
a = SomeClass()
b = SomeChildOfA()
c = SomeThirdPartyThingAlsoWithItems()

update_status(a, "beep")
update_status(b, "bop")
update_status(c, "Vote for Bernie Sanders!")

rawDescription: Python: is using decorator to change method arguments a bad thing?


rawDescription: Create list with for loop for incrementing IP address


rawDescription: How do I perform math operations on dates and sort them in Python?

description: Perform math operations on dates and sort them in Python


code:
bool( Foo.objects.filter(user=user) )
# calls __nonzero__, evaluates, converts all fields to python objects
# and stores in queryset._result_cache

Foo.objects.filter(user=user).exists()
# stores nothing, and query only returns one row.
# less data from DB and less python overhead generating django model instances.

rawDescription: Django: Any difference between `QuerySet.__nonzero__` and `QuerySet.exists`?


code:
for key in my_dict:
    x = my_dict[key]

rawDescription: Lua's "Generic For Loop" for Python?

description: Lua's "Generic For Loop" for Python


rawDescription: Element by element comparison in tuple to return set of sets - python


code:
def merge(self, line):
    return ([x for x in line if x] + ([0] * len(line)))[:len(line)]

rawDescription: Unsure how to use List Comprehension on a loop


code:
if inf is not sys.stdin:
    inf.close()

rawDescription: Read from File, or STDIN

description: Read from File, or STDIN


code:
for i in range(len(studentList)):
    alist = studentList[i]
    printGender(alist)

rawDescription: Is this code simplified? Should I use more functions?


code:
slug = ["snakes", "snake-s" ] # in the real world this is generated from directory structure on disk

# build the query
query = MyModel.objects
if hasattr(slug, "__iter__"):
    q_list = []
    for s in slug:
        q_list.append(Q(slug=s))
    query = query.filter(reduce(operator.or_, q_list))
else:
    query = query.filter(slug=slug)

rawDescription: Best practices method of implementing a django OR query from an iterable?


code: cid = lSoupPage.find('link', rel='canonical')['href'].rpartition('=')[-1]

rawDescription: Fetch News Data from right Scrollbar using Beautifulsoup


code:
np.in1d(Shop_Products, ['Cheese', 'Bread']).nonzero()
np.in1d(Shop_Products, ['Bread', 'Cheese']).nonzero()

rawDescription: How to find in a parent string list, the indexes corresponding to a child string list

description: Find in a parent string list, the indexes corresponding to a child string list


code:
import timeit
timeit.repeat(tupleunpack)
timeit.repeat(chainedassignment)
timeit.repeat(multiline)

rawDescription: Unpack assignment vs chained assignment

description: Unpack assignment vs chained assignment


code:
def dfs(graph, start, target, visited=None):
    if start == target:
        return True
    if visited is None:
        visited = set()
    visited.add(start)

    found = False
    for n in (set( graph[start] ) - visited):
        if target == n:
            return True
        found = dfs(graph, n, target, visited)
    return found

rawDescription: How to stop depth-first search when the target vertex of the graph is found?

description: Stop depth-first search when the target vertex of the graph is found


code:
import utils
from modules.layer4 import layer4

rawDescription: Importing sub-sub-packages within a Python application


code:
item["code"] = "{country}-{region}-{location}".format(country=item["country"],
                                                      region=item["region"],
                                                      location=item["location"])

rawDescription: concatenating scraped data in scrapy

description: Concatenating scraped data in scrapy


code:
from werkzeug.routing import AnyConverter

languages = ['en', 'pt']

def translate_url(word, language):
    if language == 'pt' and word == 'about':
        return 'sobre'
    return word

class TranslateConverter(AnyConverter):

    def __init__(self, map, item):
        AnyConverter.__init__(self, map, *[translate_url(item, language)
                                           for language in languages])

app.url_map.converters['tr'] = TranslateConverter

@app.route('/<lang_code>/<tr(about):about>')
def about(about):
    pass

rawDescription: Format canonical URL structure correctly with URL Processors


code:
if spam:
    do_eggs()
elif ham:
    do_eggs()

rawDescription: Quick question regarding format of if-elif statements


code: self.after_id = self.after(100, lambda: self.updateTimer(canvas, flag, timer))

rawDescription: Break out of a Python after loop using a messagebox


code:
[...]
# Compatibility function to cast str to bytes objects
if issubclass(ipaddr.Bytes, str):
    _cb = ipaddr.Bytes
else:
    _cb = lambda bytestr: bytes(bytestr, 'charmap')
[...]

rawDescription: Create ipaddr-py IPv6Address from byte string


code:
def do_voroni(entry, seeds):
    entry.generate_voronoi_diagram(seeds)
    return entry

rawDescription: Parallel Processing - Pool - Python

description: Parallel Processing - Pool - Python


rawDescription: Python: print unicode string stored as a variable


code: sqlContext.sql("SELECT percentile(x, 0.5) FROM df")

rawDescription: How to find median using Spark

description: Find median using Spark


code: settings['something']

rawDescription: Pyramid: sending miscellaneous config to the application factory


code:
import re
s = "Ab ab"
re.sub(r"(\w)b (\w)b", r"\1d \2d", s)

rawDescription: Search for string in file while ignoring id and replacing only a substring


code:
s = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3'
re.sub(r'\btitle:\w+\b', '', s, re.I)

rawDescription: Python regex matching pattern not surrounded by double quotes


code:
data = np.loadtxt("data.dat", usecols=(0,1))
t = data[:,0]
u = data[:,1]

tdiff = t[1:]-t[:-1]
plt.hist(tdiff)

new_times = np.linspace(min(t), max(t), len(t))
new_data = np.interp(new_times, t, u)

t, u = new_times, new_data

FFT = sy.fft(u)
freqs = syfp.fftfreq(len(u), dt)

# then plot as above

rawDescription: How to calculate frequency of a give wave and time

description: Calculate frequency of a give wave and time


rawDescription: What's the most pythonic way to load a matrix in ijv/coo/triplet format?


code: fb_user = facebook.get_user_from_cookie(request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)

rawDescription: Integrate facebook login in google app engine with python


code: item = [s for s in mylist if "Height" in s.split()]

rawDescription: Python - Search a list item that contains a string (match case)


code:
x
numpy.argsort(x)
x[numpy.argsort(x)]

rawDescription: Using groupby on a function

description: Using groupby on a function


rawDescription: Dropping a single (sub-) column from a MultiIndex


code: result_list = [x for x in super_list if any(y in x for y in my_list)]

rawDescription: Extract the elements from a super list using the textual information available in sub list


code:
a = numpy.empty(shape=(4,), dtype=object)
a[0] = Register()  # etc.

rawDescription: Objects array with numpy

description: Objects array with numpy


code:
# spawns new thread to communicate with remote
# executes whoami which exits pretty fast
stdin, stdout, stderr = ssh.exec_command("whoami")
time.sleep(5)  # main thread waits 5 seconds
# command already finished, exit code already received
#  and set by the exec_command thread.
# therefore the loop condition is not met
#  as exit_status_ready() already returns True
#  (remember, remote command already exited and was handled by a different thread)
while not stdout.channel.exit_status_ready():
    if stdout.channel.recv_ready():
        stdoutLines = stdout.readlines()

rawDescription: Do you have to check exit_status_ready if you are going to check recv_ready()?


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

connStr = (
    r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' +
    r'DBQ=C:\Users\Public\Database1.accdb'
    )
db = pypyodbc.connect(connStr)

qry = """INSERT INTO text_file_data ([Letter], [Number], [Batch], [Year], [Parcel], [Amount])
    VALUES (?,?,?,?,?,?)"""

crsr = db.cursor()
with open (r"C:\Users\Gord\Desktop\stuff.txt", "r") as pipeFile:
    for line in pipeFile:
        crsr.execute(qry, line.split("|"))
db.commit()
db.close()

rawDescription: import text file to Access 2003 database using Python

description: Import text file to Access 2003 database using Python


code:
for i in results:
    send_to_database(i)

rawDescription: Python-saving while loop results

description: Python-saving while loop results


code:
from google.appengine.ext.webapp import template

# Your code...
template_string = "Hello World"
my_template = template.Template(template_string)

# `context` is optional, but will be useful!
# `context` is what will contain any variables, etc. you use in the template
rendered_output = template.render(context)

# Now, do what you like with `rendered_output`!

rawDescription: how to render django template from code instead of file

description: Render django template from code instead of file


code:
from datetime import datetime
datetime.now()

rawDescription: insert current time into mongo using pymongo

description: Insert current time into mongo using pymongo


code: any(my_function(x) and False for x in sequence)

rawDescription: "exists" keyword in Python?

description: "exists" keyword in Python


code:
def get_session():
    engine = create_engine('mysql://root:root@localhost/my_db')

    Base.metadata.create_all(engine)
    Base.metadata.bind = engine

    db_session = sessionmaker(bind=engine)

    return db_session()

rawDescription: Python multiprocessing pool hangs on map call


code:
def GetTorrentClass(slots_iterable):
    class Torrent(object):
        __slots__ = slots_iterable
    return Torrent

rawDescription: change __slots__ dynamically

description: Change __slots__ dynamically


code: lines = "\n".join([item for row in table for item in row])

rawDescription: Creating multi line text string from list of lists


code:
import pandas as pd
import random

md = list()
md.append({'request_id': 1, 'p': random.random()})
md.append({'request_id': 2, 'p': random.random()})
md.append({'request_id': 1, 'q': random.random()})
md.append({'request_id': 2, 'q': random.random()})
md.append({'request_id': 1, 'r': random.random()})
md.append({'request_id': 2, 'r': random.random()})
df = pd.DataFrame(md).set_index('request_id')
df = pd.concat([df[col].dropna() for col in df.columns], axis=1)
print(df)

rawDescription: Pandas Dataframe: Reduce Diagonal Sub-Frame to Single Row or How to Fill a Dataframe Piece by Piece


code:
import matplotlib.cbook as mc
import numpy as np
import datetime as dt

def using_genfromtxt(fname):
    data = np.genfromtxt(fname, dtype=None)

    orig_desc=data.dtype.descr
    view_desc=orig_desc[:2]+[('date','|S22')]+orig_desc[4:]
    new_desc=orig_desc[:2]+[('date','|O4')]+orig_desc[4:]

    newdata = np.empty(data.shape, dtype=new_desc)
    fields=data.dtype.names
    fields=fields[:2]+fields[4:]
    for field in fields:
        newdata[field] = data[field]

    newdata['date']=np.vectorize(mkdate)(data.view(view_desc)['date'])
    # print(mc.report_memory())

    return newdata

# using_csv('example4096.txt')
# using_genfromtxt('example4096.txt')

rawDescription: Python array of datetime objects from numpy ndarray


code:
@check_requirments
def pdf(request) :
    """
    Download a PDF
    """
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=new.pdf'

    pdf = MyPdf(response)
    pdf.add_first_page()
    pdf.add_second_page()
    pdf.add_disclosures()
    pdf.build()

    return response

rawDescription: Django and reportlab issue for dynamic report


rawDescription: wxpython button event running before click

description: Wxpython button event running before click


code:
from itertools import takewhile
res = list(takewhile(lambda L: None not in L, izip_longest(*iters)))
# [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

rawDescription: How to loop n items at a time but not stepping only 1 each time? python

description: Loop n items at a time but not stepping only 1 each time? python


rawDescription: How to replace only the first n elements in a numpy array that are larger than a certain value?

description: Replace only the first n elements in a numpy array that are larger than a certain value


rawDescription: Pandas: Generate a histogram/pivot against timeseries data


code: config = yaml.load(config_file) or {}

rawDescription: Loading empty dictionary when YAML file is empty (Python 3.4)


rawDescription: Simple python regex groups can't parse date


code: #!/usr/bin/env python

rawDescription: How to run python in different directory?

description: Run python in different directory


rawDescription: Pandas dataframe get first row of each group


code:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DATA_ROOT = os.path.join(BASE_DIR, '../../../Data', 'MyAppData')

# To get absolute path
DATA_ROOT = os.path.abspath(os.path.join(BASE_DIR, '../../../Data', 'MyAppData'))

rawDescription: Referencing relative directories outside of project


code: [d.update((k, {1:"Yes", 0:"No"}[v]) for k, v in d.iteritems() if v in (1,0) and k in ("is_diabetic", "is_inpatient")) for d in result]

rawDescription: Updating values for only certain keys in a list of dicts in python


code:
for x in fh1, fh2, fh3:
    x.seek(fh.tell())

rawDescription: Is there a way to shallow copy an existing file-object?


code:
from shapely.ops import transform
projected_geometry = transform(m,geometry_object)

rawDescription: Python / shapely: Calculate Polygon area in planar units (e.g. square-meters)


code:
row = soup.find('big', text=re.compile('Current\s*Weather')).find_parent('tr')
while True:
    row = row.find_next_sibling('tr')
    cells = row.find_all('td')
    if len(cells) != 2:
        break
    label, value = (cell.get_text().strip() for cell in cells)
    print(label, value, sep=': ')

rawDescription: Trying to get data with BeautifulSoup

description: Trying to get data with BeautifulSoup


code:
from django_extensions.utils import uuid

def forwards(self, orm):
    for item in orm['mypp.myclass'].objects.all():
        if not item.uuid:
            item.uuid = uuid.uuid4() #creates a random GUID
            item.save()

def backwards(self, orm):
    for item in orm['mypp.myclass'].objects.all():
        if item.uuid:
            item.uuid = None
            item.save()

rawDescription: UUID field added after data already in database. Is there any way to populate the UUID field for existing data?


code: sorted_dist_idcs = dist.argsort(kind='mergesort', axis=None)

rawDescription: python - combining argsort with masking to get nearest values in moving window

description: Python - combining argsort with masking to get nearest values in moving window


code:
def x (y ):
    b =2
    if y ==b :
        bar (y )

rawDescription: Python code reflection and modification

description: Python code reflection and modification


rawDescription: Using Django Count() with conditional lookup types


code:
if last_key and last_key != key:
    sys.stdout.write("%s\t%s\n" % (last_key,tot_cnt))

rawDescription: How to get the Reducer to emit only duplicates

description: Get the Reducer to emit only duplicates


code: mySizer = wx.BoxSizer(wx.VERTICAL)

rawDescription: BoxSizer issue: Not expanding to fit contents of StaticText


rawDescription: How to glob for iterable element

description: Glob for iterable element


rawDescription: Python/Regex - Match .#,#. in String

description: Python/Regex - Match .#,#. in String


code:
h = '''
link1

link2
link3
'''

from bs4 import BeautifulSoup
soup = BeautifulSoup(h)
print(soup.select('a[href]'))

rawDescription: beautifulsoup - how to find tags starting with certain attribute?

description: Beautifulsoup - how to find tags starting with certain attribute


code:
for cls in vars()['Foo'].__subclasses__():
    print(cls.__base__)
# <class '__main__.Foo'>
# <class '__main__.Foo'>

rawDescription: How can I find all subclasses of a given class in Python?

description: Find all subclasses of a given class in Python


code: hxs = lxml.html.document_fromstring(requests.get("http://www.imdb.com/title/" + id).content)

rawDescription: crawling imdb database using python and lxml

description: Crawling imdb database using python and lxml


rawDescription: For element in list of tuples, return other element in tuple


code:
import requests
from lxml import etree

URL = 'http://corp.sec.state.ma.us/CorpWeb/CorpSearch/CorpSearch.aspx'

def get_fields():
    res = requests.get(URL)
    if res.ok:
        page = etree.HTML(res.text)
        fields = page.xpath('//form[@id="Form1"]//input')
        return { e.attrib['name']: e.attrib.get('value', '') for e in fields }

rawDescription: How to start a query from a static website?

description: Start a query from a static website


code:
KEYS_TO_EXPORT = ["id", "dateTime", "title", "channel.title"]
item = {"id": 1, "channel": {"title": "nailed_it"}}
this_row = []
for export_key in KEYS_TO_EXPORT:
    try:
        value = item
        for key in export_key.split("."):
            value = value[key]
        this_row.append(str(value).encode('utf-8'))
    except KeyError:
        this_row.append("")

rawDescription: How do I serialise JSON keys in a Python list?

description: Serialise JSON keys in a Python list


rawDescription: Merging two dictionaries while keeping the original


rawDescription: How to play multiple mp3 files one after the other using pygame?

description: Play multiple mp3 files one after the other using pygame


code:
def var_counter(someexpr, v):
    tor = someexpr.operator()
    if tor is None:
        return int(v in someexpr.variables())
    else:
        return sum(var_counter(operand, v) for operand in someexpr.operands())

rawDescription: Converting Sage symbolic Expression to string


code:
import csv

reader = csv.reader(open('C:\Python33\excel.csv', newline=''), delimiter=' ', quotechar='|')
text_file = open("output.txt", "w")

lines = []
for row in reader:
    lines.append(', '.join(row))

output = ", ".join(lines)
print(output)

rawDescription: Removing a comma after list ends

description: Removing a comma after list ends


code:
from sklearn.feature_extraction import DictVectorizer
dv = DictVectorizer()
X = dv.fit_transform(samples)
X

rawDescription: handling too many categorical features using scikit-learn

description: Handling too many categorical features using scikit-learn


code:
def Test():
    print(Test)

rawDescription: Python - Using function in parent from child


code:
g = gt.Graph()
g.add_vertex(10)
g.new_vertex_property('int').a

rawDescription: Setting default property value in graph_tool


code:
import operator

def f(probabilities):
    return ireduce(operator.add, 0, probabilities)

print(list(f([0.2, 0.3,0.1,0.4])))
# [0.2, 0.5, 0.6, 1.0]

rawDescription: Python list comprehension

description: Python list comprehension


code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp
import scipy.integrate as integrate

#dummy input from the streamplot demo
y, x = np.mgrid[-3:3:100j, -3:3:100j]
vx = -1 - x**2 + y
vy = 1 + x - y**2

#dfun = lambda x,y: [interp.griddata((x,y),vx,np.array([[x,y]])), interp.griddata((x,y),vy,np.array([[x,y]]))]
dfunx = interp.interp2d(x[:],y[:],vx[:])
dfuny = interp.interp2d(x[:],y[:],vy[:])
dfun = lambda xy,t: [dfunx(xy[0],xy[1])[0], dfuny(xy[0],xy[1])[0]]

p0 = (0.5,0.5)
dt = 0.01
t0 = 0
t1 = 1
t = np.arange(t0,t1+dt,dt)

streamline=integrate.odeint(dfun,p0,t)

#plot it
plt.figure()
plt.plot(streamline[:,0],streamline[:,1])
plt.axis('equal')
mymask = (streamline[:,0].min()*0.9<=x) & (x<=streamline[:,0].max()*1.1) & (streamline[:,1].min()*0.9<=y) & (y<=streamline[:,1].max()*1.1)
plt.quiver(x[mymask],y[mymask],vx[mymask],vy[mymask])
plt.show()

rawDescription: Integrating a vector field (a numpy array) using scipy.integrate


code:
t = 'Would you like {to get|having|+to have} responses to your questions    sent {up to|+to|on} you via email?'
pprint.pprint(extract_choices(t))
('Would you like ___ responses to your questions sent ___ you via email?',
[{'having': False, 'to get': False, 'to have': True},
 {'on': False, 'to': True, 'up to': False}])

rawDescription: Python - Multiple choice markup parsing

description: Python - Multiple choice markup parsing


code:
if card1 == "yes":
    # you are calling the function and passing the result to thread!
    card1thread = Thread(target = cardf1())
    card1thread.start()

rawDescription: Basic Python Threading Behavior

description: Basic Python Threading Behavior


code:
def some_func():
    yield from map(other_func, re.finditer(regex, string))

rawDescription: Apply function for objects from "yield from" in python


code:
sdata = "GET http://google.co.ug/ HTTP/1.1\r\n"
sdata += "Host: google.co.ug\r\n"
sdata += "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0\r\n"
sdata += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
sdata += "Accept-Language: en-us,en;q=0.5\r\n"
sdata += "Accept-Encoding: gzip, deflate\r\n"
sdata += "Proxy-Connection: keep-alive\r\n"
sdata += "\r\n"

rawDescription: why is python script failing to download webpages through a proxy

description: Why is python script failing to download webpages through a proxy


code:
import os
print(os.popen("sw_vers -buildVersion").read().strip())

rawDescription: python finding mac os build number

description: Python finding mac os build number


code:
lot = [('hello', 25), ('hell', 4), ('bell', 4)]
lot.sort(key=lambda r: r[0])
lot.sort(key=lambda r: r[1], reverse=True)
lot

rawDescription: How to sort a python list bidirectionally, by numbers in descending order and by alphabets in ascending order?

description: Sort a python list bidirectionally, by numbers in descending order and by alphabets in ascending order


code:
s = "\u8fea\u514b"
type(s)
s.decode('unicode-escape')
new_s = unicode(s, 'unicode-escape')
type(new_s)
new_s

rawDescription: convert a string that is utf-8 code to real unicode string

description: Convert a string that is utf-8 code to real unicode string


code:
answer = {}
for i,char in enumerate(ascii_lowercase):
    answer[char] = i+1

rawDescription: Iterating over a list while incrementing another variable at the same time


code:
def get_model_dict(model):
    return dict((column.name, getattr(model, column.name))
                for column in model.__table__.columns)

rawDescription: How to get column and values dictionary in SQLAlchemy model?

description: Get column and values dictionary in SQLAlchemy model


code:
from lxml import etree

parser = etree.XMLParser(remove_comments=False)
tree = etree.parse("input.xml", parser=parser)
root = tree.getroot()

for c in root.findall(".//string[@name='name']"):
    root.remove(c)

tree.write("output.xml")

rawDescription: How can I use python to remove xml node

description: Use python to remove xml node


code:
from collections import Counter

c = Counter(List2)

from copy import deepcopy

# iterate over a copy of List1
for ind, ele in enumerate(deepcopy(List1)):
    # iterate over the sub elements
    for sub_ele in ele:
        # keep original object and add objects * frequency new objects
        List1[ind].extend([sub_ele] * c[sub_ele])

print(List1)

rawDescription: How to compare two unequal lists and append matching elements value back to the first List

description: Compare two unequal lists and append matching elements value back to the first List


code:
mem_file = cStringIO.StringIO()
screen.save(mem_file, 'jpeg')
data = mem_file.getvalue()

rawDescription: Python:How can I get screenshot data in PIL.ImageGrab?


code: matplotlib.pyplot.scatter( range(0,10), range(0,10), c=range(0,10) )

rawDescription: Convert a list into 2-D array in python

description: Convert a list into 2-D array in python


code:
if args.resize is True:
    for object in my_objects:
        object.do_resize()
elif args.resize:
    my_objects[args.resize].do_resize()

rawDescription: Is there a way to create argument in python's argparse that returns true in case no values given


code:
edit()
startEdit()

rawDescription: Anyone tried Cluster automation with WLST?


code: stop_names = [a.xpath('text()').lstrip() for a in doc.cssselect('li a')]

rawDescription: lxml classic: Get text content except for that of nested tags?

description: Lxml classic: Get text content except for that of nested tags


rawDescription: for information retrieval course using python, accessing given tf-idf weight

description: For information retrieval course using python, accessing given tf-idf weight


code:
def do_something_with_globals(**kwargs):
    for k,v in kwargs.items():
        globals()[k+'_in'] = v

rawDescription: Python change function input name internaly


code:
import itertools
output = list(itertools.islice(q, 3, 7))

rawDescription: Use slice notation with collections.deque


code:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
app = QtWidgets.QApplication(sys.argv)
print(QtGui.QImageWriter.supportedImageFormats())

rawDescription: How to save Qimage with 'jpeg' format in PyQt?

description: Save Qimage with 'jpeg' format in PyQt


code:
maxvalue = 3000

lastvalue = 0
newcum = []
for row in df.iterrows():
    thisvalue =  row[1]['TimeDelta'] + lastvalue
    if thisvalue > maxvalue:
        thisvalue = 0
    newcum.append( thisvalue )
    lastvalue = thisvalue

rawDescription: Python pandas cumsum() reset after hitting max


code: qs_sorted = sorted(qs, key=lambda x: x.time_created)

rawDescription: How Do I Select From Two Different Tables in Django?


code: from app.forms import my_form1, my_form2, my_form3

rawDescription: Django form names

description: Django form names


code: "one two three"

rawDescription: MongoDB: Transform PHP code to Python code


code:
d.append(4)      # b and d still point to the same list object, which is
                 # now [1, 2, 3, 4]
print(b)         # prints [1, 2, 3, 4] -- how could it not?

rawDescription: When does python know an initialization is a copy, so that change at one place automatically changes another place?


code:
class Root(dict):
    # this is the root factory, you can set an __acl__ here for all resources
    __acl__ = [
        (Allow, 'admin', ALL_PERMISSIONS),
    ]
    def __init__(self, request):
        self.request = request
        self['foos'] = FooContainer(self, 'foos')
        self['bars'] = BarContainer(self, 'bars')

class FooContainer(object):
    # set ACL here for *all* objects of type Foo
    __acl__ = [
    ]

    def __init__(self, parent, name):
        self.__parent__ = parent
        self.__name__ = name

    def __getitem__(self, key):
        # get a database connection
        s = DBSession()
        obj = s.query(Foo).filter_by(id=key).scalar()
        if obj is None:
            raise KeyError
        obj.__parent__ = self
        obj.__name__ = key
        return obj

class Foo(object):
    # this __acl__ is computed dynamically based on the specific object
    @property
    def __acl__(self):
        acls = [(Allow, 'u:%d' % o.id, 'view') for o in self.owners]
        return acls

    owners = relation('FooOwner')

class Bar(object):
    # allow any authenticated user to view Bar objects
    __acl__ = [
        (Allow, Authenticated, 'view')
    ]

rawDescription: Pyramid authorization for stored items

description: Pyramid authorization for stored items


code:
import scipy
X = scipy.rand(9,4)
Y = X.reshape(9,4,1).repeat(4096,2)

rawDescription: numpy: extending arrays along a new axis?

description: Numpy: extending arrays along a new axis


code: ' '.join(w for w in re.split("["+"\\".join(d)+"]", s) if w)

rawDescription: Python removing delimiters from strings

description: Python removing delimiters from strings


rawDescription: Break pandas DataFrame column into multiple pieces and combine with other DataFrame


code:
import math
def perfect_sq(n):
    return n == int(math.sqrt(n)) * int(math.sqrt(n))

rawDescription: Python Program on Perfect Squares

description: Python Program on Perfect Squares


code:
class MyClass:
   def __init__(self, create = True):
      if create:
         self.child = MyClass(False)

mc = MyClass()

rawDescription: create instance of a class in the same class's definition in python

description: Create instance of a class in the same class's definition in python


code: [ str(x).zfill(5) for x in range(10) ]

rawDescription: How do you create a list of values in Python within a certain range?

description: Create a list of values in Python within a certain range


code: a[tuple(k)]

rawDescription: Manipulating indices to 2d numpy array

description: Manipulating indices to 2d numpy array


rawDescription: Reformat CSV file using Python and Pandas, (AWK)?


code: end_timestamp = start_timestamp + datetime.timedelta(7)

rawDescription: Converting Twitter time zone and performing searches


code:
start_time_format = '%Y-%m-%d %H:%M:%S'
datetime.datetime.fromtimestamp(mt).strftime(start_time_format)

rawDescription: Python : INPUT a microtime float, RESULT a formatted datetime


code:
df = DataFrame(randn(10,2),columns=list('ab'))
df

rawDescription: How to store formulas, instead of values, in pandas DataFrame

description: Store formulas, instead of values, in pandas DataFrame


code: [sum(tup) for tup in li]

rawDescription: Sum of elements stored inside a tuple

description: Sum of elements stored inside a tuple


rawDescription: Python - printing % from division

description: Python - printing % from division


code: movielist = ' ' + '\n '.join(movie)

rawDescription: Beginner not sure how to join lists while scraping


rawDescription: python tkinter calender, placing the numbers

description: Python tkinter calender, placing the numbers


code: media = models.FileField(upload_to='message/%Y/%m/%d/', null=True, blank=True)

rawDescription: Django Rest get file from FileField url

description: Django Rest get file from FileField url


code:
from collections import defaultdict

processed = defaultdict(list)

for char, value in data:
    processed[char].append(value)

rawDescription: How to Search data from a list of Key-Value pair that it is in list or not


code: data_frame['time-it-took'] = data_frame['t1'] - data_frame['t0']

rawDescription: Calculated column in pandas dataframe

description: Calculated column in pandas dataframe


code:
# remove annoying characters
chars = {
    '\xc2\x82' : ',',        # High code comma
    '\xc2\x84' : ',,',       # High code double comma
    '\xc2\x85' : '...',      # Tripple dot
    '\xc2\x88' : '^',        # High carat
    '\xc2\x91' : '\x27',     # Forward single quote
    '\xc2\x92' : '\x27',     # Reverse single quote
    '\xc2\x93' : '\x22',     # Forward double quote
    '\xc2\x94' : '\x22',     # Reverse double quote
    '\xc2\x95' : ' ',
    '\xc2\x96' : '-',        # High hyphen
    '\xc2\x97' : '--',       # Double hyphen
    '\xc2\x99' : ' ',
    '\xc2\xa0' : ' ',
    '\xc2\xa6' : '|',        # Split vertical bar
    '\xc2\xab' : '<<',       # Double less than
    '\xc2\xbb' : '>>',       # Double greater than
    '\xc2\xbc' : '1/4',      # one quarter
    '\xc2\xbd' : '1/2',      # one half
    '\xc2\xbe' : '3/4',      # three quarters
    '\xca\xbf' : '\x27',     # c-single quote
    '\xcc\xa8' : '',         # modifier - under curve
    '\xcc\xb1' : ''          # modifier - under line
}
def replace_chars(match):
    char = match.group(0)
    return chars[char]
return re.sub('(' + '|'.join(chars.keys()) + ')', replace_chars, text)

rawDescription: efficiently replace bad characters

description: Efficiently replace bad characters


code:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

import bisect

def find_ge(a, low, high):
    i = bisect.bisect_left(a, low)
    g = bisect.bisect_right(a, high)
    if i != len(a) and g != len(a):
        return a[i:g]
    raise ValueError

rawDescription: How to count elements between two values in sorted list?

description: Count elements between two values in sorted list


rawDescription: Set values in matrix to 1 where index matches value


rawDescription: Counter with filter or subtract or similar


rawDescription: Problems with IMAP in Gmail with Python

description: Problems with IMAP in Gmail with Python


code:
{{ name }}
{{ email }}
{{ body }}

rawDescription: How to use django-contact-form (third-party app)?

description: Use django-contact-form (third-party app)


code:
import timeit
def parse_datetime():
    date1, time1 = '2012-09-08', '12:23:33'
    date2, time2 = '2012-09-08', '12:23:33'
    dt1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
    dt2 = datetime.datetime.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
    (dt1 - dt2).total_seconds()

def parse_time():
    d1 = time.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
    d2 = time.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
    seconds1 = time.mktime(d1)
    seconds2 = time.mktime(d2)
    seconds1 - seconds2

timeit.timeit('test()', 'from __main__ import parse_datetime as test', number=10000)
timeit.timeit('test()', 'from __main__ import parse_time as test', number=10000)

rawDescription: what's the fastest way of converting a string time stamp into epoch time with python?

description: What's the fastest way of converting a string time stamp into epoch time with python


code:
class UserFollowing(models.Model):
    user = models.ForeignKey(User, related_name='following')
    following = models.ForeignKey(User, related_name='followed_by')

rawDescription: django add relationships to user model

description: Django add relationships to user model


rawDescription: Python randomly delegating values from one list to another


code: dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

rawDescription: Pandas Merge - How to avoid duplicating columns


rawDescription: Mix two arrays. Simple. Python

description: Mix two arrays. Simple. Python


rawDescription: Optimized way for finding the number which satisfies specific conditions


code:
with open("commentsfordjango.txt", "rb") as f:
    for line in f.read().decode("utf-8").splitlines():
        cursor.execute("INSERT INTO polls_poll (commenttext, pos, neu, neg) VALUES (%s, 0, 0, 0)", line)

rawDescription: Unicode in a Django-powered site

description: Unicode in a Django-powered site


code:
import random
from liblas import file as lasfile
from collections import defaultdict

def world2Pixel_Id(x, y, X_Min, Y_Max, xDist, yDist):
    col = int((x - X_Min) / xDist)
    row = int((Y_Max - y) / yDist)
    return (col, row)

def random_grouped_samples(infile, n, X_Min, Y_Max, xDist, yDist):
    """Select up to n points *per group* from infile"""

    groupcounts = defaultdict(int)
    samples = defaultdict(list)

    for p in lasfile.File(inFile, None, 'r'):
        id = world2Pixel_Id(p.x, p.y, X_Min, Y_Max, xDist, yDist)
        i = groupcounts[id]
        r = random.randint(0, i)

        if r < n:
            if i < n:
                samples[id].insert(r, p)  # add first n items in random order
            else:
                samples[id][r] = p  # at a decreasing rate, replace random items

        groupcounts[id] += 1

    return samples

rawDescription: Python increase performance of random.sample


code:
button = browser.find_by_css("button.dropdown-menu")
button[0].click()

rawDescription: Splinter browser automation select option


code:
print(filter(lambda x: len(x) > avg, words))
print(list(filter(lambda x: len(x) > avg, words)))

rawDescription: Python: Lambda function

description: Python: Lambda function


code:
with file('partsList.txt', 'w') as myfile:
    data = {'names': names, 'ingredients': ingredients, 'volumes': volumes, 'category': category}
    json.dump(data, myfile)

rawDescription: Saving BOM (parts list) for multiple builds to a file in Python


code:
image = np.random.randint(0,255,(30,30,3)).astype('uint8')
image = np.random.randint(0,255,(300,300,3)).astype('uint8')
image = np.random.randint(0,255,(3000,3000,3)).astype('uint8')

rawDescription: Thresholded pixel indices of a NumPy array


code:
from itertools import product, islice
list_of_aa = ["A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"]
for combo in islice(product(list_of_aa, repeat=3), 5):
    print(''.join(combo))
for combo in islice(product(list_of_aa, repeat=3), 1000, 1005):
    print(''.join(combo))
for combo in islice(product(list_of_aa, repeat=3), 2000, 2005):
    print(''.join(combo))

rawDescription: Create list with combinations of 3 elements of other list with repetitions


code:
class Point(object):
    def __init__(self,x=0,y=0):
        self.data=[x, y]

    def __str__(self):
        return "point(%s,%s)"%(self.x,self.y)

    def __getitem__(self,item):
        return self.data[item]

    def __setitem__(self, idx, value):
        self.data[idx] = value

    @property
    def x(self):
        return self.data[0]

    @property
    def y(self):
        return self.data[1]

rawDescription: __setitem__ implementation in Python for Point(x,y) class


code:
import textwrap

def my_function(s):
    first, *rest = s.splitlines(keepends=True) # the first line is special
    return first + textwrap.dedent(''.join(rest))

rawDescription: Strip common indentation from the beginning of each line similar to what pydoc help does with docstrings


rawDescription: Sum corresponding elements of multiple python dictionaries


code: 'artistName:Axwell /\\\\ Ingrosso'

rawDescription: Escaping backslash in Python requests

description: Escaping backslash in Python requests


rawDescription: python regex to capture a pattern which appear an unknown number of times

description: Python regex to capture a pattern which appear an unknown number of times


code:
s = 'extra-root, May 15, 2024, Entry, abcd: efgh, ds:sd'
[i for i in s.split(',') if ':' in i][0]
next(i for i in s.split(',') if ':' in i)

rawDescription: working with regex

description: Working with regex


code: [x+'/'+y for y in 'ab' for x in '012']

rawDescription: What's wrong with this nested list comprehension?


code:
from pandas import read_csv
d = read_csv('data.csv', thousands=',')

rawDescription: Python data wrangling issues

description: Python data wrangling issues


rawDescription: How to create dictionary of dictionaries from a dataframe using python's pandas

description: Create dictionary of dictionaries from a dataframe using python's pandas


code:
from sqlalchemy import Integer

class DivisibleInteger(Integer):
    class comparator_factory(Integer.Comparator):
        def div(self, other):
            return self.op('div')(other)

rawDescription: MySQL and SQLAlchemy integer diversion in WHERE clause


code: pqr_version = string[string.index('pqr')+3] #This will give 201

rawDescription: Split a paragraph into lines

description: Split a paragraph into lines


code: u'print "hello world"\nthree = 1+2\nIn[len(In)-1]'

rawDescription: IPython notebook read string from raw text cell


rawDescription: GTK - How to style a button in headerbar?


code: repost_pid, repost_permalink, repost_domain, repost_title, repost_submitter = row

rawDescription: Python: Assign variables from array

description: Python: Assign variables from array


code: indexes

rawDescription: Classify elements of a numpy array using a second array as reference


rawDescription: How can I generalize my pandas data grouping to more than 3 dimensions?

description: Generalize my pandas data grouping to more than 3 dimensions


rawDescription: obtaining last value of dataframe column without index

description: Obtaining last value of dataframe column without index


code:
words = rep.split()   # the default is to split at whitespace
loc = words[-1]
uni = ' '.join(words[:-1])

rawDescription: how to get string values using index method in Python

description: Get string values using index method in Python


code:
class MyListManager(models.Manager):
    def select_diff(self):
        return self.get_queryset().extra(...)

class MyList(models.Model):
    objects = MyListManager()

rawDescription: DRY Django querysets

description: DRY Django querysets


code:
self.PAUSED = False

while True:
    for event in pygame.event.get():
        if event.type==KEYDOWN:
            if event.key==K_q:
                self.PAUSED = not self.PAUSED

    if not self.PAUSED:

        x+=movex
        y+=movey
        screen.fill((r,0,0))
        screen.blit(bif,(0,0))
        screen.blit(player,(x,y))

        pygame.display.update()

rawDescription: Pygame pause key

description: Pygame pause key


code:
m2 = sps.coo_matrix(np.ones((1000,1000)))
m2
sps.issparse(m2)

rawDescription: Scipy.sparse test for sparse matrix returns False for a diagonal matrix. Why?


code:
import bpy

bpy.ops.object.select_all(action='DESELECT')
bpy.ops.mesh.primitive_uv_sphere_add()
sphere = bpy.context.object

for i in range(-1000, 1000, 2):
    ob = sphere.copy()
    ob.location.y = i
    #ob.data = sphere.data.copy() # uncomment this, if you want full copies and no linked duplicates
    bpy.context.scene.objects.link(ob)
bpy.context.scene.update()

rawDescription: more efficient Python scripting in Blender3D

description: More efficient Python scripting in Blender3D


code:
from subprocess import *

date = Popen(['date'], stdout=PIPE)
Popen(["wc", "-w", "/dev/fd/%d" % date.stdout.fileno()])

rawDescription: use subprocess.Popen to run a unix tool that requires multiple input redirects

description: Use subprocess.Popen to run a unix tool that requires multiple input redirects


code:
url = 'https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html'
result = []

for i in range(4):
    soup = BeautifulSoup(urllib.urlopen(url).read())
    links = soup('a')
    for link in links:
        result.append(link)
    try:
        third_link = links[2]['href']
    except IndexError:  # less than three links
        break
    else:
        url = third_link
        print(url)

rawDescription: My loop isn't running

description: My loop isn't running


code:
import site
site.addsitedir("./lib")

rawDescription: Creating a lib directory in Google App Engine and adding it to sys.path


code:
mask = dst > 0.9*dst.max()
out = np.column_stack((np.argwhere(mask),dst[mask]))

rawDescription: Python how to loop through an array in numpy at C speed and store some positions


code: [[di['date'], di['adj_close']] for di in d]

rawDescription: Convert pandas json for highstock data format in a angularjs controller


code:
async def main():
    p = Periodic(lambda: print('test'), 1)
    try:
        print('Start')
        await p.start()
        await asyncio.sleep(3.1)

        print('Stop')
        await p.stop()
        await asyncio.sleep(3.1)

        print('Start')
        await p.start()
        await asyncio.sleep(3.1)
    finally:
        await p.stop()  # we should stop task finally

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: How can I periodically execute a function with asyncio?

description: Periodically execute a function with asyncio


rawDescription: Convert a recursive function into Non recursive in Python


code:
def testTCPClient(self):
    j = lambda x: "".join(x)

    server = Connection("", 5555)
    server.start()
    client.run()
    sleep(3)
    data = j(server.new_data())
    self.assertTrue("login" in data)
    sleep(2)
    server.send("login approve")
    sleep(2)
    data = j(server.new_data())
    self.assertTrue("after_login" in data)
    server.send("logout")
    sleep(2)
    data = j(server.new_data())
    self.assertTrue("received_logout" in data)
    server.close()
    self.assertTrue("disconnected" in client.logs)

rawDescription: Control TCP server in Python

description: Control TCP server in Python


code:
L = ['abc','def','ghi']

for e in L:
    with open('outfile.txt', 'a') as outfile:
        print (e, file=outfile)

rawDescription: Write data retrieved from for loop

description: Write data retrieved from for loop


code:
index = {}
for k, vv in d.iteritems():
    for v in vv:
        index.setdefault(v, []).append(k)

rawDescription: Find duplicates in a list of lists with tuples


code: sorted(mylist, key=lambda d: (month_to_index[d['month'][:3]], d['month'][-4:]))

rawDescription: list of dictionary Sorting in python

description: List of dictionary Sorting in python


code:
class MyIterable(object):
    def __iter__(self):
        return iter([1, 2, 3])

class MyMapping(collections.Mapping):
    def __iter__(self):
        return iter('123')
    def __getitem__(self, item):
        return int(item)
    def __len__(self):
        return 3

rawDescription: Change what the *splat and **splatty-splat operators do to my object


code:
from time import sleep
result = some_task.apply_async(args=myargs)
while not result.ready():
    sleep(0.5)
result_output = result.get()

rawDescription: Stop the thread until the celery task finishes


code:
line = "a=1"
constantsMap = {}
key,val = line.split("=", 1)
constantsMap[key] = val
constantsMap

rawDescription: Using a list as key-value pair to be inserted


code: print(sum(1 for char in myString))

rawDescription: Reading the length of a string without using a built-in function?


rawDescription: Print a dict sorted by values

description: Print a dict sorted by values


code:
import subprocess

def write_to_clipboard(string):
    p = subprocess.Popen(['clip'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    p.communicate(input=string)

rawDescription: How do I use Tkinter and allow my application to keep the focus?

description: Use Tkinter and allow my application to keep the focus


code:
labeled_words = [('neg', ['watching', 'by', 'myself', 'tweetdebate', 'not']), ('pos',     ['here', 'we', 'go', 'tweetdebate', 'tweetdebate'])]
stemmedWords = []
for label, words in labeled_words:
    stemmed = []
    for word in words:
        stemmed.append(porter2.stem(word))
    stemmedWords.append((label,stemmed))

rawDescription: Stem words of complex structure

description: Stem words of complex structure


token_type: Bearer

rawDescription: Google OAuth2 - how to change expires_in or token_expiry value?


code:
def countEmergency(self, card_ids, duration=None):
    cnt = 0
    for card in card_ids:
        if card.emergency_level != 'first':
            continue
        if duration is not None and card.duration <= duration:
            continue
        cnt += 1
    return cnt

rawDescription: Python - adding conditions in if only they are specified (domain)?


code:
with open('highscores.txt', 'rb') as f:
    reader = csv.reader(f)
    def convert_row(row):
        return [float(row[0])] + [int(value) for value in row[1:]]
    scores = (convert_row(row) for row in reader)
    top10 = heapq.nlargest(10, scores, key=operator.itemgetter(-1))
for record in top10:
    print('time: {} | moves: {} | penalties: {} | score: {}'.format(*record))

rawDescription: How to display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)

description: Display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)


code: file = open('text.txt', 'r')

rawDescription: How to check how many times a word appears in a text file

description: Check how many times a word appears in a text file


code:
df = pd.DataFrame([1, 7, 9, 5], columns=['A'])
df

rawDescription: Recursive definitions in Pandas

description: Recursive definitions in Pandas


code:
item_list = ["Non-Tradable Ubersaw", "Screamin' Eagle", "'Non-Craftable Spy-cicle"]
not_allowed = {"Non-Tradable", "Non-Craftable"}

rawDescription: Check if string contains any elements from list


code:
x.__class__ = Child
print(x.nmbrMovies)
# 0

rawDescription: change the superclass of object in Python

description: Change the superclass of object in Python


code:
def timerEvent(self, evt):
        # get the cpu percentage usage
        result = self.get_cpu_usage()
        # append new data to the datasets
        self.user.append(result[0])
        # update lines data using the lists with new data
        self.l_user.set_data(range(len(self.user)), self.user)
        # force a redraw of the Figure
        self.fig.canvas.draw()
           #else, we increment the counter
        self.cnt += 1

rawDescription: matplotlib axes formatting

description: Matplotlib axes formatting


code:
from wx import EmptyIcon
icon = EmptyIcon()
icon.CopyFromBitmap(your_wxBitmap)

rawDescription: Create an icon in memory with win32 in python


code:
class General_Form(Form):
    def validate(self):
        if not Form.validate(self):
            return False
        return True

rawDescription: python-flask how to generate a boolean list in a form

description: Python-flask how to generate a boolean list in a form


code:
def unstack(df, keyword):
    d = getattr(df, keyword).str.split(expand=True).stack

rawDescription: Passing an argument as a attribute in a function?


code:
def foo():
  nums = []
  for x in range(0,10):
    nums.append(x)
  return nums

rawDescription: Why are integers immutable in Python?

description: Why are integers immutable in Python


code:
arr2 = np.arange(4).reshape(2, 2)
arr2
arr2 = arr2.reshape(2, 2, 1)
arr2
arr*arr2

rawDescription: How to make a matrix of arrays in numpy?

description: Make a matrix of arrays in numpy


rawDescription: Call a Python function from a Jinja template


code: mask

rawDescription: Reading chunks of csv file in Python using pandas


code:
class JSONFieldSubClass(JSONField):
    __metaclass__ = models.SubfieldBase

rawDescription: Django custom field with multiple inheritance


code:
from itertools import product
import six

varied_dict = {
'logdist_weight': [0.0, 1.0],
'pipeline_root': ['vsmany'],
'sv_on': [True, False, None]
}

def all_dict_combinations(varied_dict):
       tups_list = [[(key, val) for val in val_list]
             for (key, val_list) in six.iteritems(varied_dict)]
       dict_list = [dict(tups) for tups in product(*tups_list)]
       return dict_list

dict_list = all_dict_combinations(varied_dict)

rawDescription: for each loop with undefined number of inside loops

description: For each loop with undefined number of inside loops


rawDescription: Extract Values from CSV file to then multiply with values from other CSV? Python


code:
from django.http import JsonResponse
def follow_user(request, user_profile_id):
    profile_to_follow = get_object_or_404(UserProfile, pk=user_profile_id)
    user_profile = request.user.userprofile
    data = {}
    if profile_to_follow.follows.filter(id=user_profile.id).exists():
        data['message'] = "You are already following this user."
    else:
        profile_to_follow.follows.add(user_profile)
        data['message'] = "You are now following {}".format(profile_to_follow)
    return JsonResponse(data, safe=False)

rawDescription: How to follow on a button click in Django?

description: Follow on a button click in Django


code:
import dis
def x(e, a, b=0, *c, d=0, **f):
    print(a, b, c, d, e, f)

dis.dis(x)

rawDescription: Strange behaviour when creating a function directly from CodeType and FunctionType in python


code:
score_function = lambda word: 0 if len(word) < 3 or (word not in badwords) else 1
score = lambda tweet: sum(score(lower(word)) for word in tweet.split())

rawDescription: A fast and efficient, not-so complex word content filter


code:
from bs4 import BeautifulSoup

links = {}
soup = BeautifulSoup(page)

for link in soup.select('a[href^=http://pluzz.francetv.fr/videos/]'):
    title = link.get_text().strip()
    if title and title not in (u'Voir cette  vidéo', u'Lire la vidéo'):
        url = link['href']
        links.setdefault(url, []).append(title)

rawDescription: Python BeautifulSoup extracting titles according to id


code:
url = "http://www.optiker-bode.de/brillenauswahl/marken"
page=urllib.request.urlopen(url)

soup = BeautifulSoup(page.read())

kw = "optiker"
#seite = obj_det.get('result',{}).get('website')
try:
    #req = urllib.request.urlopen(seite).read()
    #soup = BeautifulSoup(req, "html.parser")
    desc = soup.find("meta",attrs={"name":"description"}).get("content")
    title = soup.title.string
except:
    title = "Zugriff verweigert"
    desc = "Zugriff verweigert"
kwindesc = kw in desc.lower()
kwintitle = kw in title.lower()
print(title)
print(desc)
print(kwindesc)
print(kwintitle)
print("-----")

rawDescription: Find String (Keyword) in title and description using Beautifulsoup?


code:
def processChunk(f, pos, chunk_size):
    f.seek(pos)
    s = binascii.hexlify(f.read(chunk_size))
    print(s)

rawDescription: Reading a binary file on backwards using python


code: {{ photo.category_image }}

rawDescription: Auto Incrementing natural keys with django / postgres


code:
with open("another.txt") as another_file:
    for lin in another_file:
        ...

rawDescription: python nested loop using loops and files

description: Python nested loop using loops and files


code:
df_names=('Home', 'Work', 'Park')
for df_name in df_names:
    df = globals()[df_name]
    df.columns = [col_name+'_{}'.format(df_name) for col_name in df.columns]

rawDescription: Renaming pandas data frame columns using a for loop


code:
google_news_articles.push({
    date:           each_article.find('.date').text(),
    outlet_domain:  strip(each_article.find('.outlet_domain').text()),
    title:          each_article.find('.title').text(),
    link:           each_article.find('.title').attr('href')
});

rawDescription: Send JSON list from Javascript to Django Backend and parsing it properly


code: max(l_one + l_two)

rawDescription: Python find min & max of two lists

description: Python find min & max of two lists


code:
url = "http://www.tripadvisor.com/Hotels-g60713-San_Francisco_California-Hotels.html"
page=urllib.request.urlopen(url)

soup = BeautifulSoup(page.read())
#print(soup)
for myValue3 in soup.findAll("a",attrs={ "class" : "pageNum" }):
    try:
        print("the value of page " + myValue3.get("data-page-number") + " is: " + myValue3.get("href").split("#ACCOM_OVERVIEW")[0])
    except:
        print("error")

rawDescription: Scraping different values (cookies?) under the same url


rawDescription: How to loop backwards in python?

description: Loop backwards in python


code:
x = set((b,c,d,e,f,g,h,i,j,k,l,...))
if a in x:
    ...
if y in x:
    ...

rawDescription: How to check if a variable is the same as at least one of two other variables?

description: Check if a variable is the same as at least one of two other variables


code: teamid = json.loads(playerdata1[0])

rawDescription: Parsing json element

description: Parsing json element


code:
import csv
from collections import OrderedDict

filename = 'test.csv'
aDict = OrderedDict()

with open(filename, 'rb') as f:
    csvReader = csv.reader(f)
    fields = next(csvReader)
    for row in csvReader:
        temp = OrderedDict(zip(fields, row))
        key = temp.pop("key")
        aDict[key] = temp

import json  # just to create output
print(json.dumps(aDict, indent=4))

rawDescription: How to build a nested ordered dict from a csv?

description: Build a nested ordered dict from a csv


rawDescription: Python- insert a character into a string


code:
arr = np.array(a)
N = arr.max()
Nr = np.arange(N)
diffs = (N - arr)//2
out = (((arr + diffs)[:,None] > Nr) & (diffs[:,None] <= Nr)).astype(int)

rawDescription: Numpy create matrix with values in specific locations


code:
a = [[1,2], [3,4]] # a list of mutable elements
b = a[:]
c = list(a)

rawDescription: Elements of the original list changes when a deep copy of changes


code:
X, Y, Z = grid(x, y, z)
plt.contourf(X, Y, Z)

rawDescription: Make contour of scatter

description: Make contour of scatter


rawDescription: Stopping a Reduce() operation mid way. Functional way of doing partial running sum


code:
from sqlalchemy import literal

User.query.filter(literal(search_string).contains(User.name))

rawDescription: SQLAlchemy substring is in string

description: SQLAlchemy substring is in string


rawDescription: Numpy, Reading from File with no delimiter but fixed pattern


code:
def process_group(group):
    group = list(group)
    common = dict(functools.reduce(set.intersection, (set(d.items()) for d in group)))
    def filterkeys(member):
        return {k: v for k, v in member.items() if k not in common}
    results = list(map(filterkeys, group))
    query = common.pop('query')
    return {'query': query,
            'otherstuff': [common],
            'results': list(results)}

rawDescription: Correct use of a fold or reduce function to long-to-wide data in python or javascript?


code:
soup = BeautifulSoup(html, "html.parser")

for label in soup.find_all("span", class_="pl"):
    value = label.find_next_sibling("span", class_="attrs")
    value = label.next_sibling.strip() if not value else value.get_text(strip=True)

    label = label.get_text(strip=True).strip(":")
    print(label, value)

rawDescription: Python: failed to get all the text in all the <span> tags using BeautifulSoup


code: type, size = type_and_size('char[5]')

rawDescription: get datatype length in python by parsing a string

description: Get datatype length in python by parsing a string


code:
s = "asd#1-2#qwe"
[i for i, c in enumerate(s) if c=='#']

rawDescription: How to find a index of an item in a string?

description: Find a index of an item in a string


code:
mask = ((aaa > bbb) & (aaa.shift() < bbb))
mask = mask.shift(-1).fillna(False)
pos[mask] = 12

rawDescription: Conditionally changing elements of Pandas Dataframe in a more Pythonic way


rawDescription: Getting svg stored in a variable in jinja2


code:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
p.x = 2

rawDescription: Copying a list in python

description: Copying a list in python


code: result = sorted(merged, key=lambda i: (i[5], i[0]))

rawDescription: Django turn lists into one list

description: Django turn lists into one list


code:
# assign conf as a dict()
# assign rev and repo as variables
import os
os.system('%s log --revision %s %s' % (conf['svnlook'], rev, repo))

rawDescription: What is the equivalent in python to this code line in perl $conf{svnlook} log --revision $rev $repo


code:
def permute(prefix, tree):
    def flatten(branch):
        #print 'flatten', branch
        results = [ ]
        if type(branch) is list:
            parts = [ ]
            for part in branch:
                if type(part) is basestring:
                    if part:
                        parts.append([part])
                else:
                    parts.append(flatten(part))

            index = map(lambda x: 0, parts)
            count = map(len, parts)
            #print 'combining', parts, index, count
            while True:
                line = map(lambda i: parts[i][index[i]],
                       range(len(parts)))
                line = '/'.join(line)
                #print '1:', line
                results.append( line )
                curIndex = len(parts)-1
                while curIndex >= 0:
                    index[curIndex] += 1
                    if index[curIndex] < count[curIndex]:
                        break
                    index[curIndex] = 0
                    curIndex -= 1
                if curIndex < 0:
                    break
        elif type(branch) is tuple:
            for option in branch:
                if type(option) is basestring:
                    if len(option):
                        #print '2:', option
                        results.append( option )
                else:
                    results.extend(flatten(option))
        else:
            #print '3:', branch
            results.append( branch )
        return results

    return map(lambda x: prefix + x, flatten(tree))

rawDescription: How to avoid redundancy when sending commands via pexpect?

description: Avoid redundancy when sending commands via pexpect


code:
if __name__=='__main__':
    a=myClass()
    b=myClassSecond()
    aa=Thread(target=a.run)
    bb=Thread(target=b.run)
    ...

rawDescription: Multithreading with two infinite while functions


code:
for x in range(10):
    print(next(cycled_list))

rawDescription: Cycle Through List Items

description: Cycle Through List Items


code:
indices = np.arange(9)
np.random.shuffle(indices)
lats = lats[indices]
lons = lons[indices]
vals = vals[indices]
lats
lons
vals

rawDescription: Fill 2D numpy array from three 1D numpy arrays


code:
is_maximum = [True] * len(points)
for i, j in pairs:
    if points[i][2] < points[j][2]:
        is_maximum[i] = False
    elif points[j][2] < points[i][2]:
        is_maximum[j] = False
localCoordinateMaxima, = np.nonzero(is_maximum)

rawDescription: Efficient double iteration over array

description: Efficient double iteration over array


code:
triu = np.triu(a)
tril = np.tril(a)

rawDescription: How to compare diagonally opposed element of a multidimensional array with numpy

description: Compare diagonally opposed element of a multidimensional array with numpy


code:
for i in s.split('\n') :
  d.setdefault(i[:7],[]).append(i)
d

rawDescription: Compare Characters Within a String

description: Compare Characters Within a String


code: ans_list[ans_list != tree.ans_ind]

rawDescription: Python what does this code do? list = list[ list != value]


code:
def nsmallest(series, n, invert=lambda x: -1 * x):
    count = 0
    heap = []
    for e in series:
        if count < n:
            count += 1
            hp.heappush(heap, (invert(e), e))
        else:
            # keeps heap size fixed
            hp.heappushpop(heap, (invert(e), e))
    # note: heap[0][1] is largest, remove inverted priorities
    return [h[1] for h in heap]

rawDescription: looking for an inverted heap in python

description: Looking for an inverted heap in python


code:
import os
# Tell the RPi to use the TFT screen and that it's a touchscreen device
os.putenv('SDL_VIDEODRIVER', 'fbcon')
os.putenv('SDL_FBDEV'      , '/dev/fb1')
os.putenv('SDL_MOUSEDRV'   , 'TSLIB')
os.putenv('SDL_MOUSEDEV'   , '/dev/input/touchscreen')

rawDescription: Run PyGame program without booting to Desktop Raspberry Pi


code: [[0 for j in range(2)] for i in range(2)]

rawDescription: Deepcopy on nested referenced lists created by list multiplication does not work


code:
points=np.arange(12,dtype=float).reshape(4,3)
vectors=[np.array([1,0,0],dtype=float),np.array([0,1,1],dtype=float)]
u=np.array(vectors)
points
u
d=np.dot(points, u.T)
d
v2=np.diag(np.inner(u,u))
d/v2

rawDescription: Translating Numpy code into C#

description: Translating Numpy code into C#


rawDescription: Kill a port that is listening with regex


code:
import collections

result = collections.OrderedDict()

with open("test_blast.txt", 'r') as fh_in:
    for line in fh_in:
        col = line.split()
        if len(col)<2: continue
        if not col[0] in result:
            result[col[0]] = ()
        result[col[0]] += (col[1],)

rawDescription: how to insert multiple values to a single unique key in python

description: Insert multiple values to a single unique key in python


code:
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    print(request.environ['HTTP_ACCEPT'])

    new_environ = request.environ.copy()
    new_environ['HTTP_ACCEPT'] = 'test'

    with app.request_context(new_environ):
        print(request.environ['HTTP_ACCEPT'])

    print(request.environ['HTTP_ACCEPT'])
    return 'Hello, World!'

app.run()

rawDescription: Call view with modified environ from within other view


code: np.where(arr > threshold, 255, 0)

rawDescription: What's the fastest way to threshold a numpy array?


code:
'She said: "Not so fast!"'
"Won't you come with us?"

rawDescription: String creation: Differences between two syntaxes ' ' and " "?


code:
class A:
    def __init__(self):
        self.obj = libA.A_new()

    def __enter__(self):
        return self

    def __exit__(self):
        libA.delete_A(self.obj)

    def some_func(self):
        libA.A_someFunc(self.obj)

with A() as a:
    # Do some work
    a.some_func()

rawDescription: Python ctypes, C++ object destruction

description: Python ctypes, C++ object destruction


rawDescription: Python How to get 1st element of date token


code:
class BaseProtocol:
    """
    This is the abstract superclass of all protocols.

    Some methods have helpful default implementations here so that they can
    easily be shared, but otherwise the direct subclasses of this class are more
    interesting, L{Protocol} and L{ProcessProtocol}.
    """
    connected = 0
    transport = None

    def makeConnection(self, transport):
        """Make a connection to a transport and a server.

        This sets the 'transport' attribute of this Protocol, and calls the
        connectionMade() callback.
        """
        self.connected = 1
        self.transport = transport
        self.connectionMade()

rawDescription: How do Twisted python Factory and Protocol interfaces work?


code:
def pr(text):
  print(text)

def frun(func, *func_args):
  func(*func_args)

frun(pr, *pr_args)

rawDescription: send arguments for function arguments in python

description: Send arguments for function arguments in python


code:
from __future__ import division
[[set(i).pop(),round(sum(j)/len(j),0)] for i,j in [zip(*i) for i in data]]

rawDescription: PYTHON: Finding the average of values of a nested list


code: [(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]]

rawDescription: append match to new list and delete match from original list

description: Append match to new list and delete match from original list


rawDescription: Changing One dict value changes all values


code:
def sum(n):
    ...

rawDescription: if Python doesn't support method overloading, then why does this method overload work while this other does not?

description: If Python doesn't support method overloading, then why does this method overload work while this other does not


code:
day_counts = Post.objects.filter(author=someuser).values('posted_day').annotate(
                                       dailycount=Count('posted_day')).order_by()

rawDescription: How do I get the number of posts on each day with annotation in Django?

description: Get the number of posts on each day with annotation in Django


code: df = stack_df.unstack(level=0)

rawDescription: How to keep dates as index and inner join keys in multiple excel files

description: Keep dates as index and inner join keys in multiple excel files


code:
df = df.merge(MvT101group, left_on=['Order'], right_index=True, how='left')
df = df.merge(MvT102group, left_on=['Order'], right_index=True, how='left')

rawDescription: How should I subtract two dataframes and in Pandas and diplay the required output?


code: new_list = [i for i in aList if len(i) < 4 and len(i) > 0]

rawDescription: Write a Python function that returns the sublist of strings that contain fewer than 4 characters


code:
n = int(s)
len_s = len(s)
ord_0 = ord('0')
di = ord(s[i])-ord_0
dj = ord(s[j])-ord_0
pi = 10**(len_s-(i+1))
pj = 10**(len_s-(j+1))
s = '{:0{width}d}'.format(n + (dj-di)*pi + (di-dj)*pj, width=len_s)

rawDescription: Python Swap two digits in a number?

description: Python Swap two digits in a number


rawDescription: How can I search a nested dictionary with specific constraints in mind

description: Search a nested dictionary with specific constraints in mind


code:
from itertools import groupby
[[k, len(list(g))] for k, g in groupby("baaaaab")]

rawDescription: count letter and show in list

description: Count letter and show in list


code:
def body(self, master):
    self.title('Enter New Password')
    Label(self.interior(), text='Old Password:').grid(row=0, sticky=W)
    Label(self.interior(), text='New Password:').grid(row=1, sticky=W)
    Label(self.interior(), text='Enter New Password Again:').grid(row=2, sticky=W)
    self.oldpw = Entry(self.interior(), width = 16, show='*')
    self.newpw1 = Entry(self.interior(), width = 16, show='*')
    self.newpw2 = Entry(self.interior(), width = 16, show='*')

    self.oldpw.grid(row=0, column=1, sticky=W)
    self.newpw1.grid(row=1, column=1, sticky=W)
    self.newpw2.grid(row=2, column=1, sticky=W)

rawDescription: Can't cope with Dialog and Gridgeometry manager


rawDescription: Make special diagonal matrix in Numpy

description: Make special diagonal matrix in Numpy


code: [mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]

rawDescription: Inserting values into specific locations in a list in Python


code:
def f(a, b):
    return b - b.multiply(a)

rawDescription: Comparing two scipy.sparse matrices in python


code: column_elms = [E("table-column",{"column-width":"41mm"})] * COLUMNS

rawDescription: Why are my Python arguments not unpacking?


code:
var1 = "Exposure"
settings = [var1 , "0", random_time(var1)]

rawDescription: How to reference an element of a list inside itself?

description: Reference an element of a list inside itself


code:
output
beer

rawDescription: Python: find if a given regular expression is present in a file


code:
blacklist = set(['.jpg', '.jpeg', '.png'])
filtered = [elem for elem in li if elem not in blacklist]

rawDescription: FIltering more then one string with list comprehension


code:
import itertools

all1ts = sorted(itertools.chain(((m, "m1") for m in m1),
                                ((w, "w1") for w in w1)))

all1tsr = [row+(i,) for i,row in enumerate(all1ts)]

rawDescription: ranking tuples with ties

description: Ranking tuples with ties


code:
# create the Grid
G = NP.zeros((m, n, r), dtype='uint')
# now from the container that holds your rgb tuples, create *three* m x n arrays,
# one for each item in your rgb tuples
# now just map the r values (1st itm in each rgb tuple) to the 3D grid
G[:,:,0] = r_vals
G[:,:,1] = g_vals
G[:,:,2] = b_vals
G.shape

rawDescription: Efficiently re-shaping a numpy ndarray from 2-D to 3-D based on elements from 2-D


code:
#!/usr/bin/env python

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from functools import wraps
import signal
import sys

signal.signal(signal.SIGINT, signal.SIG_DFL)

class SetAdder:
    def __init__(self):
        self.clear()

    def clear(self):
        self.value = set()

    def aggregate(self, other):
        send = not self.value
        self.sent = True
        self.value.add(other)
        return send

# This class decorator adds nameSlot, nameAuxSignal, nameAuxSlot, and
# name_manager.  Signals should be connected to nameSlot.  They will cause
# the function 'name' to be called with aggregated values.
def aggregated_slot_class_decorator(list_):
    def class_decorator(cls):
        for manager_type, name, *args in list_:
            signal_name = name + "AuxSignal"
            slot_a_name = name + "Slot"
            slot_b_name = name + "AuxSlot"
            manager_name = name + "_manager"

            def slot_a(self, *args_):
                manager = getattr(self, manager_name)
                if manager.aggregate(*args_):
                    print("Sending")
                    getattr(self, signal_name).emit()

            def slot_b(self):
                manager = getattr(self, manager_name)
                getattr(self, name)(manager.value)
                manager.clear()

            setattr(cls, slot_a_name,
                    pyqtSlot(cls, *args, name=slot_a_name)(slot_a))
            setattr(cls, slot_b_name,
                    pyqtSlot(cls, name=slot_b_name)(slot_b))

            orig_init = cls.__init__
            def new_init(self, *args_, **kwargs):
                orig_init(self, *args_, **kwargs)
                getattr(self, signal_name).connect(getattr(self, slot_b_name),
                                                   Qt.QueuedConnection)
                setattr(self, manager_name, manager_type())
            cls.__init__ = new_init
            #setattr(cls, signal_name, pyqtSignal())
        return cls
    return class_decorator

@aggregated_slot_class_decorator([(SetAdder, 'test', int)])
class A(QObject):
    def __init__(self):
        super().__init__()

    testAuxSignal = pyqtSignal()

    def test(self, value):
        print("Received", value)

class B(QObject):
    signal = pyqtSignal(int)

a = A()
b = B()

b.signal.connect(a.testSlot)

for i in range(10):
    b.signal.emit(i % 5)

app = QApplication(sys.argv)
sys.exit(app.exec_())

rawDescription: Python decorator to aggregate PyQt signals


code: s = sorted(s, key = lambda x: (x[1], x[2]))

rawDescription: Sort a list by multiple attributes?

description: Sort a list by multiple attributes


code: sentence = 'Your new contact email {} has been confirmed'.format(address)

rawDescription: How to account for string formatting in Python variable assignment?

description: Account for string formatting in Python variable assignment


code:
import ctypes
d = ctypes.cdll.LoadLibrary('dll/path')

createNativeObj = d.createNativeObj
createNativeObj.restype = ctypes.c_void_p
callFunc = d.callFunc
callFunc.argtypes = [ctypes.c_void_p]

obj = createNativeObj()
callFunc(obj)

rawDescription: accessing ctypes returned object's methods

description: Accessing ctypes returned object's methods


code:
for n, s in enumerate(strings):
    if findWholeWord(s)(line) != None:
        # do something with n here?
        print (jd['user_id'], jd['text'])
        break

rawDescription: Python iterative loop

description: Python iterative loop


code: param1[:,None] + 3*(param2[None,:]/2)

rawDescription: Building 3D arrays in Python to replace loops for optimization


rawDescription: Python: How to distinguish between inherited methods


code:
zooklogger.info("steps:: Actual Steps :: %s, Workflow Path :: %s, Host Path :: %s",
                steps, wf_path, status_path)

rawDescription: How to log in a specifc format in Python using logger?

description: Log in a specifc format in Python using logger


code:
new_provider = Provider(form.rssfeed.data)
db.session.add(new_provider)
db.session.commit()

rawDescription: Flask-SQLAlchemy: How to conditionally insert or update a row


code: from my_module import my_function_with_global_var

rawDescription: Modifying global variables in Python unittest framework


rawDescription: Pandas merging a Dataframe and a series

description: Pandas merging a Dataframe and a series


code:
data = {'jsonKey': None}
str(data)
json.loads(str(data))

rawDescription: converting json to string in python

description: Converting json to string in python


code: userLength = int(input ("Please tell us how long word you want to play : "))

rawDescription: Length function in python is not working the way I want to


code:
r_mean = 1.0
r_vol = 3.0
p = 2.0
rule = np.array([1.0, 100.0, 10000.0])
n = 8
dataset = np.random.normal(r_mean/(p*rule), r_vol/rule/np.sqrt(p), size=(n, len(rule)))
dataset

rawDescription: Numpy - Matrix Generation from list comprehension


code:
desired_length = 500
results = np.empty(desired_length)
for i in range(desired_length):
    results[i] = i**2

rawDescription: Optimal way to append to numpy array

description: Optimal way to append to numpy array


code:
import sys
import asyncio
from websockets import connect

class EchoWebsocket:
    def __await__(self):
        # see: http://stackoverflow.com/a/33420721/1113207
        return self._async_init().__await__()

    async def _async_init(self):
        self._conn = connect("wss://echo.websocket.org")
        self.websocket = await self._conn.__aenter__()
        return self

    async def close(self):
        await self._conn.__aexit__(*sys.exc_info())

    async def send(self, message):
        await self.websocket.send(message)

    async def receive(self):
        return await self.websocket.recv()

async def main():
    echo = await EchoWebsocket()
    try:
        await echo.send("Hello!")
        print(await echo.receive())  # "Hello!"
    finally:
        await echo.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: How can I implement asyncio websockets in a class?

description: Implement asyncio websockets in a class


rawDescription: python. How to find whether a text contains zero.?

description: Python. How to find whether a text contains zero.


rawDescription: How can I disable logging while running unit tests in Python Django?

description: Disable logging while running unit tests in Python Django


code: ps = subprocess.Popen(["ssh", "-o", "BatchMode=yes", "-l", "mygroup", server, "df -k /some/directory"], stdout=subprocess.PIPE)

rawDescription: subprocess timeout when exceeds a certain time limit

description: Subprocess timeout when exceeds a certain time limit


rawDescription: replace all 0's in a list with numpy.nan

description: Replace all 0's in a list with numpy.nan


rawDescription: scrape using xpath and domdocuments

description: Scrape using xpath and domdocuments


code:
class Object(metaclass=Singleton):
    def __init__(self, arg=None):
        print("creating instance with arg:", arg)

rawDescription: Passing arguments to singletons in python


rawDescription: How to get indices of non-diagonal elements of a numpy array?

description: Get indices of non-diagonal elements of a numpy array


code:
def write_to_all_servers(self, string_to_write):
    for key, sock in self.servers.items():
        if sock is not None:
            sock.write(string_to_write)

rawDescription: Client-side Socket on Python, how to contact multiple server?


code:
# @keyparam scale Scale factor.  If given, the result for each
#    pixel is divided by this value.  The default is the sum
#    of the kernel weights.
# @keyparam offset Offset.  If given, this value is added to the
#    result, after it has been divided by the scale factor.

rawDescription: Image embossing in Python with PIL -- adding depth, azimuth, etc


code:
import pandas as pd
import numpy as np
dates = pd.date_range('2015', periods=200, freq='D')

rand = np.random.RandomState(42)
i1 = np.sort(rand.permutation(np.arange(len(dates)))[:5])
i2 = np.sort(rand.permutation(np.arange(len(dates)))[:5])

df1 = pd.DataFrame({'Code': rand.randint(0, 2, 5),
                    'Date': dates[i1],
                    'val1':rand.rand(5)})
df2 = pd.DataFrame({'Code': rand.randint(0, 2, 5),
                    'Date': dates[i2],
                    'val2':rand.rand(5)})

rawDescription: How to merge two data frames based on nearest date

description: Merge two data frames based on nearest date


code:
scores
sorted(scores.keys(), reverse = True)

rawDescription: Sorted() function Python

description: Sorted() function Python


code:
version-2
filter_id = 4567
q = (session.query(Table3.id.label("t3_id"))
    .join(Table2)
    .filter(Table2.table1_id == filter_id)
    )
sq = q.subquery()
q = (session.query(Table3)
    .filter(Table3.id.in_(sq))
    )
q.delete(synchronize_session=False)

rawDescription: SQLAlchemy - delete grandchildren

description: SQLAlchemy - delete grandchildren


rawDescription: Python Pandas: remove entries based on the number of occurrences


code:
b = B.objects.get(id=1)
b.name_id # the value stored in the 'name' database column
b.name # the related 'A' instance

rawDescription: Non-primary foreign keys in Django

description: Non-primary foreign keys in Django


code:
import numpy
help(numpy)

# Returned documentation containing:
# FILE
# /usr/lib/python2.7/dist-packages/numpy/__init__.py

rawDescription: Finding function declarations in Ubuntu on Python


code: max_key, max_value = max(d.items(), key = lambda x: len(set(x[1])))

rawDescription: Dictionary with lists as values - find longest list


code:
data = output.read()
print(data)

rawDescription: how to read command output from serial device using python

description: Read command output from serial device using python


code:
import matplotlib.backends.backend_agg as backend
from matplotlib.figure import Figure

# The pylab figure manager will be bypassed in this instance. `plt.gca()`
# can't access the axes created here.
fig = Figure()
canvas = backend.FigureCanvas(fig)
ax = fig.add_subplot(111)

rawDescription: Prevent matplotlib statefulness

description: Prevent matplotlib statefulness


code:
def condensed_to_pair_indices(n,k):
    x = n-(4.*n**2-4*n-8*k+1)**.5/2-.5
    i = x.astype(int)
    j = k+i*(i+3-2*n)/2+1
    return i,j

rawDescription: Find all point pairs closer than a given maximum distance


rawDescription: Filter a pandas dataframe using values from a dict


code: instance.otherBaseProperty = "Thingee2"

rawDescription: python: abstract base class' __init__(): initializion or validation?

description: Python: abstract base class' __init__(): initializion or validation


code: conditions_string = ' '.join(["\t\tWHEN %s THEN %s\n" % (x, y) for x, y in logs_age_list])

rawDescription: Python - Generate a multiple row update query


code: {k: sum(d.values()) for k,d in myDict.items()}

rawDescription: Working out certain values from a nested dictionary


code:
picked = [0, 0, 0, 0, 0, 0, 0]

def roll_dice_forever():
    global picked
    while True:
        ra = random.randint(1, 6)
        with lock:
            picked[ra] += 1

rawDescription: How can I show a variable on command that is updating constantly?

description: Show a variable on command that is updating constantly


code: foo[0:4] = [copy.deepcopy(x) for x in baz[0:4]]

rawDescription: Does Python have anything like Java's System.arraycopy?


code:
from selenium import webdriver
from pprint import pprint
driver = webdriver.Firefox()
driver.get('https://stackoverflow.com')

element = driver.find_element_by_xpath('//div[@class="network-items"]/a')
attrs = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)
pprint(attrs)

rawDescription: Selenium webdriver: How do I find ALL of an element's attributes?


rawDescription: Assigning a range to an array in Python

description: Assigning a range to an array in Python


code:
cf_array[cf_array > 4] = 7
cf_array[cf_array <= 1] = 5
cf_array[(1 < cf_array) & (cf_array <= 4)] = 6

rawDescription: Reclassify raster values using python, numpy


code:
costs = {}

for i in range(4):
    item_name = input("What do you want to buy? ")
    costs[item_name] = input('Price? ')

rawDescription: Combine/ "concatenate" two variables, one being a user input


code:
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

rawDescription: Pygame Rect class

description: Pygame Rect class


rawDescription: Merging multiple text files into one and related problems


code:
EMPTY = '-'
FULL = '*'
if cells_copy[coord] == EMPTY:
    if population == 3:
        cells[coord] = FULL
else:
    if population not in set([2,3]):
        cells[coord] = EMPTY

rawDescription: printing out dictionnaires

description: Printing out dictionnaires


rawDescription: Duplicates when extracting data from html table using lxmk.html.xpath()


rawDescription: Non-linear scaling of a colormap to enhance contrast


code:
import sys
import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-b', '--bucket', dest='bucketname', action='store')
    parser.add_argument('-f', '--folder', dest='folder', action='store')
    args = parser.parse_args()
    s3 = get_files()
    s3.foldername = args.folder
    s3.download_files()

rawDescription: implementation of command line arg passing in python, doesn't work

description: Implementation of command line arg passing in python, doesn't work


code:
def read(source):
    had_blank = False
    for char in source:
        if char == ' ':
            had_blank = True
        else:
            if had_blank and not char in '.?!':
                yield ' '
                yield char
                had_blank = False
            else:
                yield char

rawDescription: how do you determine the end of a sentence in a python serial parser?

description: Determine the end of a sentence in a python serial parser


code:
requests.post('http://mypage.com/add', params=params,
              headers = headers, proxies = proxy, timeout = max_timeout)

rawDescription: Python requests post not sending string

description: Python requests post not sending string


code:
a = "I-have-hyphens-yo!"
re.findall('[a-z]+',a)
re.findall('[a-z-]+',a)
re.findall('[a-zA-Z-]+',a)
re.findall('\w+',a)

rawDescription: How do I use rstrip to remove trailing characters?

description: Use rstrip to remove trailing characters


rawDescription: Can the contents of a relationship be filtered when querying parent model?


code: [s.strip().split(': ') for s in data_string.splitlines()]

rawDescription: String split on new line, tab and some number of spaces


code:
df.unstack()
df.unstack().to_dict()

rawDescription: Convert correlation dataframe to dictionary {key = (sample_x,sample_y), value = correlation}


code: print('\t'.join(map(str, x)))

rawDescription: How do I join integers, Decimal() and datetime.datetime() in a list?

description: Join integers, Decimal() and datetime.datetime() in a list


code:
import yaml

d = yaml.load(open('foo.yaml'))

print(d.keys())
print(d.values())

rawDescription: Changing DictMixin.iterkeys to MutableMapping


rawDescription: looping over all member variables of a class in python

description: Looping over all member variables of a class in python


code: from classdef42 import Bigclass

rawDescription: Is there any Python equivalent to partial classes?


code:
import subprocess

COMMAND_LINE = 'echo "Hello World!" ; cat'

process = subprocess.Popen(COMMAND_LINE, shell=True,
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE)

s = process.stdout.readline().strip()
print(s)
s2 = process.communicate(s)[0]
print(s2)

rawDescription: Interactive shell program wrapper in python


rawDescription: Grouping data points into series

description: Grouping data points into series


code:
{film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])]
            for film in j}

rawDescription: Read a dict of dicts in a list

description: Read a dict of dicts in a list


code:
return next(index for index, element in enumerate(array)
            if element["extension"] == ".py")

rawDescription: How to get an object inside an array list by its property value in Python

description: Get an object inside an array list by its property value in Python


code:
class WebmethodBaseClass():
    def post(self, methodName):
        getattr(self, methodName)("kapow")

rawDescription: Use python decorators on class methods and subclass methods


rawDescription: Python - use an operator at runtime

description: Python - use an operator at runtime


rawDescription: Recommended usage of Python dictionary, functions as values


code:
my_car = Car(colour='red')
my_car.get_colour() # should return 'red'

rawDescription: Difference between @classmethod and a method in python


code:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")

from django.core.management import call_command
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
call_command('runserver',  '127.0.0.1:8000')

rawDescription: Django runserver from Python script

description: Django runserver from Python script


code: [x for y in supraList for x in someDict[y]]

rawDescription: List comprehension with some kind of loop interdependence?


code:
import multiprocessing
pool = multiprocessing.Pool()
pool.map(myQueue.get, range(1, 10))

rawDescription: How to remove a lot of elements from a multithread queue without using a for loop

description: Remove a lot of elements from a multithread queue without using a for loop


code: (lambda x: x*2)(3)

rawDescription: accessing lambda value passed to function python

description: Accessing lambda value passed to function python


code: new_metadata = df.apply(lambda x: '{}\b,"timestamp":{}}}'.format(x.metadata,x.timestamp),axis=1)

rawDescription: Mapping pandas DataFrame rows to a pandas Series


code:
for bandNo in range(totalBands):
    contour3d(Eigen[:,:,:, bandNo], contours=[eF1, eF2, eF3], opacity=0.4)

rawDescription: Fermi Surface Plots

description: Fermi Surface Plots


code:
class PushbackWrapper(object):

    def __init__(self, iterator):
        self.__dict__['_iterator'] = iterator
        self.__dict__['_pushed'] = []

    def next(self):
        if len(self._pushed):
            return self._pushed.pop()
        else:
            return self._iterator.next()

    def pushback(self, item):
        self._pushed.append(item)

    def __getattr__(self, attr):
        return getattr(self._iterator, attr)

    def __setattr__(self, attr, value):
        return setattr(self._iterator, attr, value)

rawDescription: Iterator that supports pushback

description: Iterator that supports pushback


code:
c = sorted(a + b)
a = b = []

rawDescription: How do I take 2 sorted lists and add them to another list while removing the elements

description: Take 2 sorted lists and add them to another list while removing the elements


code:
dem_nums = []
for dem in dems:
         dem_num = dem[0:3]
         if dem_num not in dem_nums:
              dem_nums.append(dem_num)

dem_nums

rawDescription: check if a string is in a list, and if not append it to that list

description: Check if a string is in a list, and if not append it to that list


code:
for obj2 in file2:
    if 'name' not in obj2:
        continue
    for obj1 in file1_names.get(obj2['name'], []):
        obj2.update(obj1)

rawDescription: There must be a more optimal way to parse two files


rawDescription: convert a list of x and y coordinates into multistring

description: Convert a list of x and y coordinates into multistring


code:
def foobar(a=0, b=0, c=None):
    return a, b, c

def other_method(x,y,z):
    return  x,y,z

def my_method():
    print('hello')
    foobar('apple', 'pear', 6)
    print('world')
    foobar(1, 2, 3)
    for i in range(10):
        if i > 9:
            s = foobar(4, 5, 6)
            print(s)
    return foobar('a', 'b')

def my_method2():
    foobar('orange', 'tomatoe', 6)
    foobar(10, 20, 30)
    for i in range(10):
        if i > 9:
            foobar(40, 50, 60)
    other_method("foo","bar","foobar")
    return foobar('c', 'd')

rawDescription: Getting method calls and their arguments from method object


code:
p = Product(...)
p.location = l
p.save()

rawDescription: Set parent of model during creation

description: Set parent of model during creation


code:
self.chHead = wx.Choice(self.nbItemPane, -1)
for i in range(len(items)):
    if items[i].GetSlot() == 'Head':
        self.chHead.Append(item=item[i].GetName(), clientData=i)

rawDescription: wxpython: How to create wxChoice contents from a list?

description: Wxpython: How to create wxChoice contents from a list


code:
import requests
session = requests.session()
html = session.get(url).content
soup = BeautifulSoup(html, "html5lib")

rawDescription: What is the practical difference between these two ways of making web connections in Python?


code: from modules import *

rawDescription: Python: Write function in module to import packages


code:
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=TrackingEvent)
def update_latest_tracking_event(sender, instance, created, **kwargs):
    # Is this a new event?
    if created:
        # If yes, then update the Tracking reference
        tracking = instance.tracking
        tracking.last_event = instance
        tracking.save()

rawDescription: Django Admin filter by function / filter only by first object in reverse foreign key lookup


code:
def file_split(f, delim=',', bufsize=1024):
    prev = ''
    while True:
        s = f.read(bufsize)
        if not s:
            break
        split = s.split(delim)
        if len(split) > 1:
            yield prev + split[0]
            prev = split[-1]
            for x in split[1:-1]:
                yield x
        else:
            prev += s
    if prev:
        yield prev

rawDescription: Is there a way to read a file in a loop in python using a separator other than newline


code: mx = lambda x: reduce(lambda xs, ys: xs if xs > ys else ys, x)

rawDescription: Order a list from largest to smallest using insertion sort


rawDescription: How to avoid same variable being used twice in an Orange CN2 rule?

description: Avoid same variable being used twice in an Orange CN2 rule


code: getpixel((x_loc,y_loc),...) #<--wrong

rawDescription: Python Image Processing - Move an Image

description: Python Image Processing - Move an Image


code:
def stretch_to(l, n):
    out = [None] * n
    m = len(l)
    for i, x in enumerate(l):
        out[i*(n-1)//(m-1)] = x

    return out

rawDescription: Stretching a list in Python

description: Stretching a list in Python


code:
letterstring = ''.join(letterlist)
[m.start() for m in re.finditer("CAC", letterstring)]

rawDescription: how to find a pattern of string elements in a list?

description: Find a pattern of string elements in a list


code:
b = np.array([-6 * np.ones(a.shape), -8 * np.ones(a.shape)])
b
np.power(a, b)

rawDescription: ValueError: operands could not be broadcast together with shapes


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

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

#1 colored by value of `z`
ax.scatter(x, y, z, c = plt.cm.jet(z/max(z)))

#2 colored by index (same in this example since z is a linspace too)
N = len(z)
ax.scatter(x, y, z, c = plt.cm.jet(np.linspace(0,1,N)))

plt.show()

rawDescription: Line colour of 3D parametric curve in python's matplotlib.pyplot


code: rfd_header = reader.next()

rawDescription: csvreader.fieldnames not recognized as an attribute of a csv reader object in python

description: Csvreader.fieldnames not recognized as an attribute of a csv reader object in python


rawDescription: z3 const declaration

description: Z3 const declaration