code:
import json

d = dict({'2':'two', '11':'eleven'})
json.dumps({int(x):d[x] for x in d.keys()}, sort_keys=True)

rawDescription: How to print JSON with keys in numeric order (i.e. as if the string keys were integers)

description: Print JSON with keys in numeric order (i.e. as if the string keys were integers)


code:
details = site.select('//*[@id="detailFacts"]/div[1]/div[2]//text()|//*[@id="detailFacts"]/div[2]/div[2]//text()').extract()
item['details'] = next(s for s in details if s)  # getting first not-empty item from the list

rawDescription: Scrapy xpath how to

description: Scrapy xpath how to


code:
range(3, 6)             # normal call with separate arguments
args = [3, 6]
range(*args)            # call with arguments unpacked from a list

rawDescription: Can I convert a tuple to a parameter list 'inline'?

description: Convert a tuple to a parameter list 'inline'


code:
import numpy as np

np.random.seed(323)

keys = ["foo"] * 50 + ["bar"] * 50
values = (
    np.vstack([np.repeat(-10, 500), np.repeat(10, 500)]).reshape(100, -1) +
    np.random.rand(100, 10)
)

rdd = sc.parallelize(zip(keys, values))

rawDescription: Is it possible to scale data by group in Spark?


rawDescription: Python's equivalent to C# Hash (#) in a format string


code:
df = pd.DataFrame({"t": pd.date_range('2014-01-01', periods=5, freq='H')})
df
pd.DatetimeIndex(df.t).normalize()
df['date'] = pd.DatetimeIndex(df.t).normalize()
df

rawDescription: Dropping time from datetime <[M8] in Pandas


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

np.random.seed(2015)
N = 10**5
val1 = np.random.normal(loc=10, scale=2,size=N)
val2 = np.random.normal(loc=0, scale=1, size=N)

fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True)
cmap = plt.get_cmap('jet')
norm = mcolors.LogNorm()

num_samples = 10**4
idx = np.random.choice(np.arange(len(val1)), num_samples)
ax[0].scatter(val1[idx], val2[idx])
ax[0].set_title('subsample')

im = ax[1].hexbin(val1, val2, gridsize=50, cmap=cmap, norm=norm)
ax[1].set_title('hexbin heatmap')

plt.tight_layout()
fig.colorbar(im, ax=ax.ravel().tolist())

plt.show()

rawDescription: Python - Randomly subsamble a range of points to plot


code:
from nltk.corpus import names
names[:5]
names.words()[:5]

rawDescription: TypeError: 'WordListCorpusReader' object has no attribute '__getitem__' while using nltk.classify.apply_features


rawDescription: Sum float values at each index point in nested lists


code:
rows = 15

s = [''] + list('YWE17N0AZX')
df = pd.DataFrame(np.random.choice(s, size=(rows, 7)), columns=list('abc') + ['dxpoa1', 'dxpoa2', 'dxpoa3', 'dxpoa4'])

cols = df.filter(like='dxpoa').columns

rawDescription: Filter pandas dataframe based on values in multiple columns


code:
thing = myclass()
thing['x,y'] = 3,6
x,y = thing['x,y']
thing['x,y,z'] = 1,2,3

rawDescription: A member tuple (as opposed to member variable) of a class?


code:
import skimage.io
import skimage.segmentation
import numpy as np
import matplotlib.pyplot as plt

# Read in the image
# Note - intensities are floating point from [0,1]
im = skimage.io.imread('balls.jpg', True)

# Threshold the image first then clear the border
im_clear = skimage.segmentation.clear_border(im > (200.0/255.0))

# Determine where to split up the image
split_point = int(im.shape[1]/5)

# Show image in figure and hold to place dots in
plt.figure()
plt.imshow(np.dstack([im,im,im]))

# For each image...
for idx in range(5):

  # Extract sub image
  img = im_clear[:,idx*split_point:(idx+1)*split_point]

  # Find coordinates of thresholded image
  y,x = np.nonzero(img)

  # Find average
  xmean = x.mean()
  ymean = y.mean()

  # Plot on figure
  plt.plot(xmean + idx*split_point, ymean, 'r.', markersize=14)

# Show image and make sure axis is removed
plt.axis('off')
plt.show()

rawDescription: how to locate the center of a bright spot in an image?

description: Locate the center of a bright spot in an image


rawDescription: Remove matched tags in html files?

description: Remove matched tags in html files


code:
def rec_split(s):
    rest, tail = os.path.split(s)
    if rest in ('', os.path.sep):
        return tail,
    return rec_split(rest) + (tail,)

rawDescription: Python Split path recursively

description: Python Split path recursively


code:
basicfile = open('membersofcongress.txt', 'r')
outfile = open('memberswcomma.txt','w')

for line in basicfile:
   partyst = line.find('(')
   partyend = line.find(')')
   party = line[partyst:partyend+1]
   name = line[+0:partyst-1]
   outp = name + "," + party + "\n"
   outfile.write(outp)

outfile.close()
basicfile.close()

rawDescription: Making a loop to write new lines to a txt file using python


code:
def __eq__(self, other):
    return self.lwh == other.lwh

rawDescription: Naming coordinates in python

description: Naming coordinates in python


code:
def get_structure_for_node(structure, find_node=1):
    return list(flat_list(structure))[find_node][1]

rawDescription: How can I find the index for a list of nested lists which I am recursing over?

description: Find the index for a list of nested lists which I am recursing over


rawDescription: Aparrent looping issue: Why am I appending the same thing to my list over and over again?


code:
content = 'I opened my mouth, "Good morning!" I said cheerfully'
content = re.sub(r'".*"', '""', content)
print(content)

rawDescription: Python regex replace text in quotes except quotes themselves


code:
nums = [1, 2, 3, 4]
[(x, tuple(y for y in nums if y != x)) for x in nums]

rawDescription: Python list combination

description: Python list combination


code:
g = open("outfile.txt", "w")
for (i,x) in stops:
    g.write("Stop codon " + x + " found at position " + str(i) + "\n")
g.close()

rawDescription: Getting Python to read a text file in chunks of 3 (codons) and give me an output


code:
import difflib
def merge (l, r):
    m = difflib.SequenceMatcher(None, l, r)
    for o, i1, i2, j1, j2 in m.get_opcodes():
        if o == 'equal':
            yield l[i1:i2]
        elif o == 'delete':
            yield l[i1:i2]
        elif o == 'insert':
            yield r[j1:j2]
        elif o == 'replace':
            yield l[i1:i2]
            yield r[j1:j2]

rawDescription: How to find union of two strings and maintain the order

description: Find union of two strings and maintain the order


code: CELERY_ROUTES = {'project.tasks.ex_task': {'queue': 'multiprocessing_queue'}}

rawDescription: Celery worker hangs on ZEO database access (race condition?)


code: df2.loc[:, to_shift].shift(1)

rawDescription: For any rows with a NaN in a Pandas DataFrame, shift by 1


code:
dis.dis(lambda x: str(x))
dis.dis(lambda x: '%s' % x)

rawDescription: str performance in python

description: Str performance in python


rawDescription: how to parse a boolean argument in a script?

description: Parse a boolean argument in a script


code: database[data]=[value]

rawDescription: changing values of a dictionary to a list

description: Changing values of a dictionary to a list


code: pd.read_csv("h.csv", names=["Number", "Line", "Code"], index_col=0)

rawDescription: Python: Not able to read first row of csv file correctly using read_csv


code: any('b' in s for s in input_list)

rawDescription: Checking if a str is in a list of str?

description: Checking if a str is in a list of str


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

class Category(models.Model):
    pass

class Video(models.Model):
    category = models.ManyToManyField('Category')

@receiver(m2m_changed, sender=Video.category.through)
def video_category_changed(sender, **kwargs):
    action = kwargs.pop('action', None)
    pk_set = kwargs.pop('pk_set', None)
    if action == "pre_add":
        if 1 not in pk_set:
            pk_set.update([1])

rawDescription: Using Django's m2m_changed to modify what is being saved pre_add


code:
class BigTilePlugin(CMSPluginBase):
    ...
    def render(self, context, instance, placeholder):
        context['tile'] = instance.tile
        return context

rawDescription: Django-CMS Custom plugin and placeholders


code:
c = None
a[2:c]

rawDescription: List Range Refinement

description: List Range Refinement


code:
import codecs
import csv
import os

path_to_folder = '/insert/path/'

with open('hasfares.txt', 'w') as hf:
    for root, subFolders, files in os.walk(path_to_folder):
        if 'fare_rules.csv' in files:
            hf.write('%s\n' % root)

        if 'routes.csv' in files:
            routes_path = os.path.join(root, 'routes.csv')
            bus_route_ids_path = os.path.join(root, 'bus_route_ids.csv')
            appending_to_existing_file = os.path.exists(bus_route_ids_path)
            with codecs.open(routes_path, 'r', 'utf-8-sig') as inf, \
                    open(os.path.join(root, "bus_route_ids.csv"), "a") as output:
                reader = csv.DictReader(inf, quotechar='"')
                headers = ['route_id']
                writer_bus_routes = csv.DictWriter(output, headers,
                                                   extrasaction='ignore')
                if not appending_to_existing_file:
                    writer_bus_routes.writeheader()
                for row in reader:
                    if row['route_type'] == '3':
                        writer_bus_routes.writerow(row)

rawDescription: Python: csv.DictWriter returning blank strings if value is alphanumeric


rawDescription: getting median of particular rows of array based on index

description: Getting median of particular rows of array based on index


code: event = pygame.event.poll()

rawDescription: How do I add key commands to sprite?

description: Add key commands to sprite


code:
def unionAll(*dfs):
    first, *rest = dfs  # Python 3.x, for 2.x you'll have to unpack manually
    return first.sql_ctx.createDataFrame(
        first.sql_ctx._sc.union([df.rdd for df in dfs]),
        first.schema
    )

rawDescription: Spark union of multiple RDDs

description: Spark union of multiple RDDs


code:
root = lxml.etree.fromstring(xml)
a = root.find('.//a')
parent = lxml.etree.Element('new_parent')
parent.extend(a)
a.append(parent)

rawDescription: Change parent in xml by Python (lxml)

description: Change parent in xml by Python (lxml)


code:
mapper = data_frame_mapper(binarizers=['gender'],
    encoders=['gradelevel', 'subject', 'districtid'],
    scalars=['sbmRate', 'pRate', 'assn1', 'assn2', 'assn3', 'assn4', 'assn5', 'attd1', 'attd2', 'attd3', 'attd4', 'attd5', 'sbm1', 'sbm2', 'sbm3', 'sbm4', 'sbm5'])

rawDescription: how to apply preprocessing methods on several columns at one time in sklearn

description: Apply preprocessing methods on several columns at one time in sklearn


rawDescription: List of zeros in python

description: List of zeros in python


rawDescription: Celery tasks immediately autodiscover

description: Celery tasks immediately autodiscover


code: ips.append(match.group()) #append to list

rawDescription: set() not removing duplicates

description: Set() not removing duplicates


code: print('I want to say:', stringA, stringB)

rawDescription: Simple adding spaces between variables in python3


code:
storage = messages.get_messages(request)
for message in storage:
    do_something_with(message)

rawDescription: Modifying the warning message when deleting an object in django admin?


code:
print( [data] )
# or
print( repr(data) )

rawDescription: How can I identify invisible characters in python strings?

description: Identify invisible characters in python strings


rawDescription: Checking if elements exist in list using python


code:
x
x[:,None,:] - x

rawDescription: How do I calculate all pairs of vector differences in numpy?

description: Calculate all pairs of vector differences in numpy


code:
stocks = [('rsi1', 'macd1','capratio1','other1'),
         ('rsi2','macd2','capratio2','other2'),
         ('rsi3', 'macd3','capratio3','other3')]

S = Statistician()
S.read_stocks(stocks)

#define a closure function
def statisticCollector(statistician, key):
    def collect():
        return statistician.stock_stats(key)
    return collect

#instanciate the closed function
collectRSI = statisticCollector(S, 'RSI')
collectMACD= statisticCollector(S, 'MACD')

if __name__ == "__main__":
    print(collectRSI())
    print(collectMACD())

rawDescription: multiple call to a function to return a list of accumulated result

description: Multiple call to a function to return a list of accumulated result


code:
df
df['num'] = df.subject.map({'math':0,'literature':1,'science':2})
df

rawDescription: Process string-valued columns from a CSV file with Pandas


code:
items = ['a','b','c']
print(items[0])

rawDescription: How to assign variable to listed items in python?

description: Assign variable to listed items in python


code:
first
Done
second

rawDescription: Does PyQT4 signal.connect keep objects live?


code:
import numpy as NP
from matplotlib import pyplot as PLT

A = NP.random.random_integers(0, 10, 100).reshape(10, 10)
fig = PLT.figure()
ax1 = fig.add_subplot(111)

cax = ax1.imshow(A, interpolation="nearest")

# set the tickmarks *if* you want cutom (ie, arbitrary) tick labels:
cbar = fig.colorbar(cax, ticks=[0, 5, 10])

# note: 'ax' is not the same as the 'axis' instance created by calling 'add_subplot'
# the latter instance i bound to the variable 'ax1' to avoid confusing the two
cbar.ax.set_yticklabels(["lo", "med", "hi"])

PLT.show()

rawDescription: How do I set a matplotlib colorbar extents?

description: Set a matplotlib colorbar extents


code:
def config_meta(classname, parents, attrs):
    defaults = {}
    groups = {}
    newattrs = {'defaults':defaults, 'groups':groups}
    for name, value in attrs.items():
        if name.startswith('__'):
            newattrs[name] = value
        elif isinstance(value, type):
            groups[name] = value
        else:
            defaults[name] = value
    def init(self):
        for name, value in defaults.items():
            self.__dict__[name] = value
        for name, value in groups.items():
            group = value()
            group.config = self
            self.__dict__[name] = group
    newattrs['__init__'] = init
    return type(classname, parents, newattrs)

class Config2(object):
    __metaclass__ = config_meta
    a = 10
    b = 2
    class group(object):
        c = 5
        @property
        def d(self):
            return self.c * self.config.a

rawDescription: Python: Idiomatic properties for structured data?


code:
"""
The ``obvious`` module
======================

Use it to import very obvious functions.

:Example:

>>> from obvious import add
>>> add(1, 1)
2

This is a subtitle
-------------------

You can say so many things here ! You can say so many things here !
You can say so many things here ! You can say so many things here !
You can say so many things here ! You can say so many things here !
You can say so many things here ! You can say so many things here !

This is another subtitle
------------------------

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

"""

def add(a, b):
    """
    Adds two numbers and returns the result.

    This add two real numbers and return a real result. You will want to
    use this function in any place you would usually use the ``+`` operator
    but requires a functional equivalent.

    :param a: The first number to add
    :param b: The second number to add
    :type a: int
    :type b: int
    :return: The result of the addition
    :rtype: int

    :Example:

    >>> add(1, 1)
    2
    >>> add(2.1, 3.4)  # all int compatible types work
    5.5

    .. seealso:: sub(), div(), mul()
    .. warnings:: This is a completly useless function. Use it only in a
              tutorial unless you want to look like a fool.
    .. note:: You may want to use a lambda function instead of this.
    .. todo:: Delete this function. Then masturbate with olive oil.
    """
    return a + b

rawDescription: How to comment parameters for pydoc

description: Comment parameters for pydoc


code:
import sys

def main(src, dest):
    with open(dest, 'w') as output:
        with open(src) as source:
            for line in source:
                try:
                    start, end, sound = line.split()
                except ValueError:
                    continue
                if sound == 'ay':
                    start = int(start)
                    end = int(end)
                    offset = (end - start) // 2
                    output.write('%s %s ao\n' % (start, start + offset))
                    output.write('%s %s ih\n' % (start + offset, end))
                else:
                    output.write(line)

if __name__ == "__main__":

    main(*sys.argv[1:])

rawDescription: changing the contents of a file applying different conditions

description: Changing the contents of a file applying different conditions


code:
from werkzeug.formparser import parse_form_data
from werkzeug.wsgi import get_input_stream
from io import BytesIO

class MethodMiddleware(object):
    """Don't actually do this. The disadvantages are not worth it."""
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        if environ['REQUEST_METHOD'].upper() == 'POST':
            environ['wsgi.input'] = stream = \
                BytesIO(get_input_stream(environ).read())
            formdata = parse_form_data(environ)[1]
            stream.seek(0)

            method = formdata.get('_method', '').upper()
            if method in ('GET', 'POST', 'PUT', 'DELETE'):
                environ['REQUEST_METHOD'] = method

        return self.app(environ, start_response)

rawDescription: Changing request method using hidden field _method in Flask


rawDescription: SQLAlchemy - Using Relationships to filter by class of row type


code: {k: sum(1 for val in v.itervalues() if val == 'available') for k, v in seats.iteritems()}

rawDescription: counting the number of key value pairs in a dictionary

description: Counting the number of key value pairs in a dictionary


code:
waiting = True
while waiting:
    # see if Parent is at home
    if os.getppid() != self.parentPID:
        # woe is me! My Parent has died!
        sys.exit() # or whatever you want to do to quit the Worker process
    try:
        # I picked the timeout randomly; use what works
        data = self.queue.get(block=False, timeout=0.1)
        waiting = False
    except queue.Queue.Empty:
        continue # try again
# now do stuff with data

rawDescription: Python-daemon doesn't kill its kids

description: Python-daemon doesn't kill its kids


code:
isbn = [int(input("ISBN character {0}: ".format(i)))
        for i in range(1, 11)] # or 'format(i+1)' and 'range(10)'

rawDescription: Getting type error in python when using for loop


rawDescription: Most efficient way of keeping only the unique items in a list in Python


rawDescription: How to run an operation on a collection in Python and collect the results?

description: Run an operation on a collection in Python and collect the results


code: re.split(r'{|}', str)

rawDescription: Using re.split() for two { } in python

description: Using re.split() for two { } in python


rawDescription: Rolling mean with customized window with Pandas


rawDescription: Build a color palette from image URL

description: Build a color palette from image URL


code:
data=[]
ss=((0,19),(20,41),(42,80))
with open('/tmp/p.txt','r') as f:
    for n,line in enumerate(f):
        fields={}
        for i,j in ss:
            field=line[i:j]
            t=field.split(':')
            fields[t[0].strip()]=t[1].strip()
        data.append(fields)

rawDescription: Parsing string sections

description: Parsing string sections


rawDescription: Django 1.5 url redirect with regex?

description: Django 1.5 url redirect with regex


code:
def parse_signed_request(signed_request, secret):
    """
    Parse signed_request given by Facebook (usually via POST),
    decrypt with app secret.

    Arguments:
    signed_request -- Facebook's signed request given through POST
    secret -- Application's app_secret required to decrpyt signed_request
    """

    if '.' in signed_request:
        (esig, payload) = signed_request.split('.')
    else:
        return {}

    sig = urlsafe_b64decode(str(esig))
    data = _parse_json(urlsafe_b64decode(str(payload)))

    if not isinstance(data, dict):
        raise SignedRequestError('Pyload is not a json string!')
        return {}

    if data['algorithm'].upper() == 'HMAC-SHA256':
        if hmac.new(secret, payload, hashlib.sha256).digest() == sig:
            return data
    else:

        raise SignedRequestError('Not HMAC-SHA256 encrypted!')

    return {}

def get_user_from_cookie(cookies, app_id, app_secret):
    """Parses the cookie set by the official Facebook JavaScript SDK.

    cookies should be a dictionary-like object mapping cookie names to
    cookie values.

    If the user is logged in via Facebook, we return a dictionary with the
    keys "uid" and "access_token". The former is the user's Facebook ID,
    and the latter can be used to make authenticated requests to the Graph API.
    If the user is not logged in, we return None.

    Download the official Facebook JavaScript SDK at
    http://github.com/facebook/connect-js/. Read more about Facebook
    authentication at http://developers.facebook.com/docs/authentication/.
    """
    cookie = cookies.get('fbsr_' + app_id, '')
    if not cookie:
        return None
    response = parse_signed_request(cookie, app_secret)
    if not response:
        return None

    args = dict(code=response['code'], client_id=app_id,
                client_secret=app_secret, redirect_uri='')

    file = \
        urllib.urlopen('https://graph.facebook.com/oauth/access_token?'
                       + urllib.urlencode(args))
    try:
        token_response = file.read()
    finally:
        file.close()

    access_token = cgi.parse_qs(token_response)['access_token'][-1]
    logging.debug('returning cookie')
    return dict(uid=response['user_id'], access_token=access_token)

rawDescription: Understanding "runwithfriends" facebook-app sample code


code:
range(0,3)
list(range(0,3))

rawDescription: What is the difference between "range(0,2)" and "list(range(0,2))"?


code:
from itertools import islice

# Dummy data
with open("/tmp/foo", "w") as fw:
    fw.writelines(["foo", "1.0", "2.0", "3.0"])

def process_part(i, iter):
    if i == 0:
        # We could use enumerate as well
        for x in islice(iter, 1):
            yield x
    for x in iter:
        yield float(x)

(sc.textFile("foo.txt")
    .mapPartitionsWithIndex(process_part)
    .collect())
## ['"foo"', 1.0, 2.0, 3.0, 4.0]

rawDescription: RDD transformation map, Python

description: RDD transformation map, Python


code: cats = [categories_mapping[key] for key in categories_mapping if any(label.lower() in key.lower() for label in labels)]

rawDescription: Pythonic way to check if element in a list contains in key dictionary


rawDescription: Summing elements in a list

description: Summing elements in a list


code:
import itertools as it
[sum(r) for r in it.izip_longest(l[::2], l[1::2], fillvalue=0)]

rawDescription: adding two consecutive numbers in a list

description: Adding two consecutive numbers in a list


code: b = list(map(sum,zip(*a)))

rawDescription: In Python, how to sum nested lists: [[1,0], [1,1], [1,0]] → [3,1]


code:
fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)

rawDescription: Pandas: plotting two histograms on the same plot


code: separated

rawDescription: Separating strings (list elements) with many spliters without loosing spliter from list


code:
def Select4(M, I):
  return Concat(Select(M, I + 3), Select(M, I + 2), Select(M, I+1), Select(M, I))

rawDescription: Z3: How to select 4 bytes from array of 8-bits?


code:
import sys
from HTMLParser import HTMLParser
from xml.etree import cElementTree as etree

class LinksParser(HTMLParser):
  def __init__(self):
      HTMLParser.__init__(self)
      self.tb = etree.TreeBuilder()

  def handle_starttag(self, tag, attributes):
      self.tb.start(tag, dict(attributes))

  def handle_endtag(self, tag):
      self.tb.end(tag)

  def handle_data(self, data):
      self.tb.data(data)

  def close(self):
      HTMLParser.close(self)
      return self.tb.close()

parser = LinksParser()
parser.feed(sys.stdin.read())
root = parser.close()
span = root.find(".//span[@itemprop='description']")
etree.ElementTree(span).write(sys.stdout)

rawDescription: Get the html under a tag using htmlparser python


code:
from proj import tasks
tasks.my_task.delay('hi', 'hello')

rawDescription: User defined celery task class : init is getting called during import


code:
def removeRow(dct, col, val):
    '''remove a "row" from a table-like dictionary containing lists,
       where the value of that row in a given column is equal to some
       value'''
    idx = dct[col].index(val)
    for key in dct:
        dct[key].pop(idx)

rawDescription: Python 2.7.9 dictionary find and delete

description: Python 2.7.9 dictionary find and delete


code:
class MyClass:
    x = 1
    results = list(i+x for i in range(10))

rawDescription: How to reference a static attribute from within a class in Python?

description: Reference a static attribute from within a class in Python


code:
if mc.objExists ('L_ShoulderOrient_NODE'): mc.delete ('L_ShoulderOrient_NODE')
mc.shadingNode ('transform', au=1, n='L_ShoulderOrient_NODE')
mc.addAttr ('L_ShoulderOrient_NODE', ln='jointOrient', at='enum', en='yup', k=1)

rawDescription: How can I query a joints sao (secondary axis world orientation)? Maya Python

description: Query a joints sao (secondary axis world orientation)? Maya Python


code: re.findall(r'\w+\b', s)

rawDescription: Confusing Behaviour of regex in Python

description: Confusing Behaviour of regex in Python


code:
sc = set(chars_to_remove)
''.join([c for c in subj if c not in sc])

rawDescription: Removing a list of characters in string

description: Removing a list of characters in string


code:
A[index] += W
A += np.bincount(index, W, minlenght=len(A))

rawDescription: Numpy loop using an index

description: Numpy loop using an index


code:
lines_are_equal = all(a == b for a, b in
                      itertools.zip_longest(lines1, lines2, fillvalue=object()))

rawDescription: How to detect that two Python iterators yield the same items?

description: Detect that two Python iterators yield the same items


rawDescription: Most efficient way to list all oriented cycles given n elements in Python


code:
for label in self.labels:
    label.some_method()
    do_something(label)
    ...

rawDescription: Iterating over a list to make widgets

description: Iterating over a list to make widgets


code:
def on_resize(self, widget, event):
    if Gdk.ModifierType.BUTTON1_MASK & event.get_state() != 0:
        mouse_y = event.device.get_position()[2]
        new_height = mouse_y - self.get_position()[1]
        if new_height > 0:
            self.resize(self.get_allocation().width, new_height)
            self.show()

rawDescription: resize borderless window with vpaned in python+gtk3

description: Resize borderless window with vpaned in python+gtk3


code:
contacts = {'Aname':{'name': name,
                     'phone': phone,
                     'email': email
                     },
            'Bname':{'name': name,
                     'phone': phone,
                     'email': email
                    }
           }

rawDescription: How to delete dictionary from list of dictionaries in JSON

description: Delete dictionary from list of dictionaries in JSON


code:
"""One of many builders.  This changes all the time to fit
specific needs and situations.  The goal is to keep this
short and to-the-point so that it has the mapping and nothing
but the mapping.
"""

import model

class MyTargetBuilder( object ):
    def makeFromXML( self, element ):
        result= model.MyTargetObject()
        result.someAttr= element.findtext( "Some" )
        result.anotherAttr= element.findtext( "Another" )
        result.this= int( element.findtext( "This" ) )
        result.that= float( element.findtext( "that" ) )
        return result

rawDescription: Which language is easiest and fastest to work with XML content?


code:
import pandas as pd
from io import StringIO

data = """
id tweet
12  "this is the first tweet"
34  "this is the second tweet"
48  "this is the third tweet"
59  "finally the fourth tweet"
"""

df = pd.read_csv(StringIO(data), delimiter='\s+')

rawDescription: How to access a specific row in a DataFrame

description: Access a specific row in a DataFrame


code: dict((char,i) for i,char in enumerate(ascii_lowercase, 1))

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


code: [ a for a in alphagen(10)]

rawDescription: Is there a way to subclass a generator in Python 3?


code: ["{:06d}".format(item) for item in data]

rawDescription: add leading zeros to a list of numbers in Python

description: Add leading zeros to a list of numbers in Python


rawDescription: Comparison between adjacent elements in sequences


code:
a = numpy.arange(9).reshape(3, 3)
numpy.broadcast_arrays(a, 1)[1]

rawDescription: Is there a better way to broadcast arrays?


code:
out = []

while len(li):
    tmp = li.pop(0)
    i = 0
    while i < len(li):
        item = li[i]
        if tmp[0] == item[0] and tmp[2] == item[2] and tmp[3] == item[3]:
            tmp[1] = 'Sum'
            tmp[4] = '{:.3f}'.format((float(tmp[4]) + float(item[4])))
            tmp[6] = '{:.1f}\n'.format(float(tmp[6]) + float(item[6]))
            li.pop(i)
        else:
            i += 1
    out.append(tmp)

rawDescription: How to add objects from different rows of a Python list?

description: Add objects from different rows of a Python list


code:
import os, itertools
test = ['abc_1_2', 'abc_2_2', 'hij_1_1', 'xyz_1_2', 'xyz_2_2']
[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]

rawDescription: How to group similar items in a list?

description: Group similar items in a list


code: subprocess.check_output("cat fable.txt | grep %s" %variable, shell=True)

rawDescription: Variable in subprocess

description: Variable in subprocess


code: [c['type'].python_type for c in query.column_descriptions]

rawDescription: how to know the type of sql query result before it is executed in sqlalchemy

description: Know the type of sql query result before it is executed in sqlalchemy


code:
import xmlrpclib
import base64
device = xmlrpclib.ServerProxy("http://localhost:1234/RPC2")
device.output(base64.b64encode(".\n."+chr(2)))

rawDescription: How can I transfer binary data over xmlrpc (python)?

description: Transfer binary data over xmlrpc (python)


code:
from films.models.genre import Genre
from films.models.actor import Actor
from films.models.title import Title
from films.models.actorrole import ActorRole

rawDescription: When to split sub-apps into new apps

description: When to split sub-apps into new apps


rawDescription: Calculate a point along a line segment one unit from a end of the seg


List of strings in ints ['123 121','42 23','23 23']


code:
from scapy.all import *
import sys
sr(IP(dst=sys.argv[1])/ICMP())

rawDescription: Scapy In A Script

description: Scapy In A Script


code:
if not (0 <= x <= 78 and 0 <= y <= 28):
    level.remove_obj(theobj)

rawDescription: Checking if a tuple is in range

description: Checking if a tuple is in range


code:
from __future__ import print_function
from itertools import groupby

decode = {'2': 'ABC', '3': 'DEF', '4': 'GHI', '5': 'JKL',
    '6': 'MNO', '7': 'PQRT', '8': 'TUV', '9': 'WXYZ'}

def dial_up(digits):
    #return ''.join([decode[key][len(list(value)) - 1]
    result = []
    for key, value in groupby(digits):
        if key == ' ':
            continue
        i = len(list(value)) - 1
        s = decode[key]
        result.append(s[i % len(s)])
    return ''.join(result)

# Test

data = (
    '999 666 88',
    '33 99 8',
    '222 2 22',
    '22 22',
    '2222',
    '444 43',
)

for s in data:
    print(s, dial_up(s))

rawDescription: Trying to write a function that simulates a cellphone dial up


code:
wx.lib.colourdb.updateColourDB()  #adds ALOT more named colours to wx.TheColourDatabase
c1 = wx.NamedColour("light coral")
c2 = wx.NamedColour("peachpuff2")

rawDescription: How to use named colors in wxpython?

description: Use named colors in wxpython


code:
import PIL
import Image
import numpy as np

i = 0
im = Image.open('%*s.bmp' % (1, i)).convert('RGB')
n_test = np.asarray(im)
r, g, b = np.rollaxis(n_test, axis=-1)
ni_test = np.empty(n_test.shape[:2], dtype=np.uint8)
ni_test.fill(255)

mask = (r >= 5) & (r <= 10) & (g >= 5) & (g <= 10) & (b >= 5) & (b <= 10)
ni_test[mask] = 0
im_test = Image.fromarray(ni_test, '1')
im_test.save('test_%*s.bmp' % (1, i))

rawDescription: finding colors in Image and redraw on second image(using numpy)

description: Finding colors in Image and redraw on second image(using numpy)


code:
curve = plotItem.plot(data)
curve.setPos(x, 0)  # Move the curve

rawDescription: Live Data Monitor: PyQtGraph

description: Live Data Monitor: PyQtGraph


code: import myapplication.myviews.view

rawDescription: How to share the global app object in flask?

description: Share the global app object in flask


code: static, dynamic = line.split(';', 1)

rawDescription: very specific substring retrieval and split

description: Very specific substring retrieval and split


rawDescription: Python sort list of lists / ascending and then decending


rawDescription: Determine number of row in matrix

description: Determine number of row in matrix


code:
highscores.append(wins)
# Print sorted highscores print to file
file = open('highscore.txt', 'w') #write to file
file.write('Highscores (number of wins out of 10 games):')
for line in highscores:
     file.write(line)
file.close() #close file

rawDescription: Python: Write array values into file

description: Python: Write array values into file


code:
def func(alist):
    return zip(alist, alist[1:])

rawDescription: Get Pairs of List Python

description: Get Pairs of List Python


code:
from functools import partial

def outer(**kwargs):
    def inner(**kwargs):
        return(kwargs)
    return partial(inner, **kwargs)

rawDescription: How to pass kwargs to another kwargs in python?

description: Pass kwargs to another kwargs in python


code:
def my_plotter(ax, t, z, est_z):
    ln1 = ax.plot(t, z, 'bo-', label='sample data')
    ln2 = ax.plot(t, est_z, 'go-', label='estimated sample data')
    ax.xlabel('time')
    ax.ylabel('data value')
    ax.grid(True)
    ax.legend()
    return ln1 + ln2

for i in xrange(2):
    # get the data
    t = a[i+1:(i+1)*60, 2]
    z = a[i+1:(i+1)*60, 3]
    est_z = a[i+1:(i+1)*60, 6]
    # make the figure
    fig, ax = plt.subplots()
    # do the plot
    my_plotter(ax, t, z, est_Z)
    # save
    fig.savefig('test_{}.png'.format(i))

rawDescription: matplotlib for loop to show, save and redraw all plots

description: Matplotlib for loop to show, save and redraw all plots


code:
import os, fnmatch

#
# This wrapper for os.walk is based on Python Cookbook, 2.16.
# Added the exclude_dirs named parameter so that we can skip svn folders.
# Added the yield_files named parameter so that we can return only folders.
#

def walk_file_system (root, patterns='*', single_level=False, yield_folders=False, yield_files=True, exclude_dirs='.svn'):
    # Expand patterns from semicolon-separated string to list
    patterns = patterns.split (';')
    exclude_dirs = exclude_dirs.split (';')
    for path, subdirs, files in os.walk (root):
        for exclude_dir in exclude_dirs:
            for dir in subdirs:
                if fnmatch.fnmatch (dir, exclude_dir):
                    subdirs.remove(dir)
        fsnodes = []
        if yield_folders:
            fsnodes.extend(subdirs)
        if yield_files:
            fsnodes.extend(files)
        fsnodes.sort ( )
        for name in fsnodes:
            for pattern in patterns:
                if fnmatch.fnmatch (name, pattern):
                    yield os.path.join (path, name)
                    break
        if single_level:
            break

rawDescription: Os.walk wont work with directory matched with regex


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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4)

elements = (len(xedges) - 1) * (len(yedges) - 1)
xpos, ypos = np.meshgrid(xedges[:-1]+0.25, yedges[:-1]+0.25)

xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

#Define colormap and get values for barcolors from it
cmap = plt.cm.RdYlBu_r
norm = mpl.colors.Normalize(vmin=dz.min(), vmax=dz.max())
barcolors = plt.cm.ScalarMappable(norm, cmap)

#Plot bar3d
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=barcolors.to_rgba(dz),alpha=0.4,linewidth=0.5, zsort='average')

#Add colorbar
fig.subplots_adjust(bottom=0.25)
ax1 = fig.add_axes([0.05, 0.10, 0.9, 0.1])
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap,
                                   norm=norm,
                                   orientation='horizontal')
plt.show()

rawDescription: generating custom colorbar: match data with color scheme

description: Generating custom colorbar: match data with color scheme


rawDescription: Extend numpy array in a way compatible with builtin arrays


rawDescription: indexing/slicing in numpy array to modify it

description: Indexing/slicing in numpy array to modify it


code:
from datetime import datetime
datetime.utcfromtimestamp(129893678626216000/1e8)

rawDescription: Python date format?

description: Python date format


rawDescription: How to find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)

description: Find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)


code:
import sys
class ListStream:
    def __init__(self):
        self.data = []
    def write(self, s):
        self.data.append(s)

sys.stdout = x = ListStream()

for i in range(2):
    print ('i = ', i)

sys.stdout = sys.__stdout__
print(x.data)

rawDescription: Redirect print to string list?

description: Redirect print to string list


rawDescription: How to make filename/path from Gtk+ (Python 3.4) FileChooserDialog accessible globally

description: Make filename/path from Gtk+ (Python 3.4) FileChooserDialog accessible globally


code:
a = np.array(xrange(5 * 3))
a.shape = (5, 3)

rawDescription: selecting rows in numpy ndarray based on the value of two columns

description: Selecting rows in numpy ndarray based on the value of two columns


code:
class Purchase(models.Model):
    price = models.DecimalField("Price", max_digits=18, decimal_places=2)
    user = models.ForeignKey('auth.User', related_name='purchase_set')

rawDescription: Find what customer has spent the most money across multiple payments


code:
x = '["List", "with", "strings", "including", "snowman", "\u2603"]'
ast.literal_eval(x)
json.loads(x)
x = "(1, 2, 3, 'a tuple is Python syntax, not JSON')"
ast.literal_eval(x)
json.loads(x)

rawDescription: Convert Python string to list

description: Convert Python string to list


code:
s = set()
result = []
for tup in lst:
    for el in tup:
        if el not in s:
            s.add(el)
            result.append(el)

rawDescription: How to flatten a list of tuples and remove the duplicates?

description: Flatten a list of tuples and remove the duplicates


code:
def do_something(request):
    # read the params first
    enterprise = request.GET['enterprise']
    ...
    # do something with those values

rawDescription: Several query params URL in DRF

description: Several query params URL in DRF


code: documents = " ".join(documents)

rawDescription: How to stem words in python list?

description: Stem words in python list


code:
class EncodingConverter:
    def __init__(self, fobj, encoding):
        self._iter_fobj = iter(fobj)
        self._encoding = encoding
    def __iter__(self):
        return self
    def __next__(self):
        return next(self._iter_fobj).decode(self._encoding)

rawDescription: Python/Linux - unzip file while reading it


rawDescription: Sort a list of lists with two index

description: Sort a list of lists with two index


rawDescription: Vectorize a 2-dimensional function in python


rawDescription: How to find how many powers double 'n' is raised to to get to double 'n' in Java. Equivalent of Math.log in Python

description: Find how many powers double 'n' is raised to to get to double 'n' in Java. Equivalent of Math.log in Python


code:
from django.utils import timezone
tznow = timezone.now()
'{:%d-%m-%Y:%H:%M:%S}.{:03d}'.format(tznow, tznow.microsecond // 1000)

rawDescription: Python/Django timestamp including milliseconds


code: url(r'^$', MyView.as_view(),  name='myview'),

rawDescription: How do you use django-datatable-view

description: Use django-datatable-view


rawDescription: How to round a number to significant figures in Python

description: Round a number to significant figures in Python


code:
@login_required
@transaction.commit_manually
def submission_set_rank(request):
    keys = {'rank1': 5, 'rank2': 4, 'rank3': 3, 'rank4': 2, 'rank5': 1}
    ranks = [request.GET.get(key,'') for key in keys]
    for ballot in BallotStats.objects.filter(object_id__in=ranks):
        ballot.score += keys[ballot.object_id]
        ballot.save()
    transaction.commit()

    return HttpResponseRedirect('/submissions/results/film/')

rawDescription: How can I write this with less redundancy/copy-paste?

description: Write this with less redundancy/copy-paste


code:
def test_read(self):
    self.mock.inWaiting.return_value = 4
    self.mock.read.return_value = 'lulu'
    self.assertEqual(self.mc.read(), 'lulu')
    self.mock.read.assert_called_with(1)

rawDescription: Python Unit testing with mock and patch a foreign modul


code: from filename import variablename

rawDescription: Variable in other python file, how to load in?


code:
import traceback

def get_caller_info():
    filename, _, function_name, _ = traceback.extract_stack(limit=2)[1]
    return filename, function_name

rawDescription: Calling C functions. Who is calling

description: Calling C functions. Who is calling


rawDescription: Read sparse matrix in python

description: Read sparse matrix in python


code:
data = np.zeros([rows, cols], dtype='uint8')
for chunk_start in xrange(0, rows, rows/10):
    data[chunk_start: chunk_start+rows/10] = (
            np.random.randint(0, 100, (rows/10, cols)))
return data

rawDescription: python.exe crushed while creating numpy array

description: Python.exe crushed while creating numpy array


code:
from collections import Counter

s = "CTAACAAC"

def chunk_string(s, n):
    return [s[i:i+n] for i in range(len(s)-n+1)]

counter = Counter(chunk_string(s, 3))
# Counter({'AAC': 2, 'ACA': 1, 'CAA': 1, 'CTA': 1, 'TAA': 1})

rawDescription: Counting multiple letter groups in a string (python)


code:
from collections import deque

activities = deque(maxlen=5)
# if len(activities) == 5 then the leftmost item will be removed before the push
activities.push(activity)

rawDescription: Most efficient way to add an item and at the same time remove one from a list with a fixed length


code:
list(changetwo('cow'))
for x in changetwo('1234'):
    x

rawDescription: Python String Permutations Up To 2 Letter Changes Per Permutation


code:
import numpy as np

def make_data(N=100):
    X = np.random.randint(1, 20, (N, 36))
    connections = np.random.randint(2, 5, N)
    nbrs = {i: list(np.random.choice(N, c))
            for i, c in enumerate(connections)}
    return X, nbrs

def original_solution(X, nbrs):
    output = np.zeros(shape=X.shape)
    for k, v in nbrs.items():
        output[k] = np.sum(X[v], axis=0)
    return output

def vectorized_solution(X, nbrs):
    # Make neighbors all the same length, filling with -1
    new_nbrs = np.full((X.shape[0], max(map(len, nbrs.values()))), -1, dtype=int)
    for i, v in nbrs.items():
        new_nbrs[i, :len(v)] = v

    # add a row of zeros to X
    new_X = np.vstack([X, 0 * X[0]])

    # compute the sums
    return new_X.take(new_nbrs, 0).sum(1)

rawDescription: Code optimization - number of function calls in Python


rawDescription: Get dictionaries in a list where the key:value pairs are in another list of dictionaries


code:
import timeit
from matplotlib import pyplot as plt

setup = \
"""
import numpy
import random

number_of_members = 20
values = range(50)
"""

number_of_repetitions = 20
array_sizes = (10, 200)

python_random_times = [timeit.timeit(stmt = "[random.sample(values, number_of_members) for index in xrange({0})]".format(array_size),
                                     setup = setup,
                                     number = number_of_repetitions)
                                        for array_size in xrange(*array_sizes)]

numpy_permutation_times = [timeit.timeit(stmt = "[numpy.random.permutation(values)[:number_of_members] for index in xrange({0})]".format(array_size),
                               setup = setup,
                               number = number_of_repetitions)
                                    for array_size in xrange(*array_sizes)]

numpy_shuffle_times = [timeit.timeit(stmt = \
                                """
                                random_arrays = []
                                for index in xrange({0}):
                                    numpy.random.shuffle(values)
                                    random_arrays.append(values[:number_of_members])
                                """.format(array_size),
                                setup = setup,
                                number = number_of_repetitions)
                                     for array_size in xrange(*array_sizes)]

numpy_sample_times = [timeit.timeit(stmt = \
                                    """
                                    values = numpy.asarray(values)
                                    random_arrays = [values[indices][:number_of_members]
                                                for indices in (numpy.random.sample(({0}, len(values))) * len(values)).astype(int)]
                                    """.format(array_size),
                                    setup = setup,
                                    number = number_of_repetitions)
                                         for array_size in xrange(*array_sizes)]

line_0 = plt.plot(xrange(*array_sizes),
                             python_random_times,
                             color = 'black',
                             label = 'random.sample')

line_1 = plt.plot(xrange(*array_sizes),
         numpy_permutation_times,
         color = 'red',
         label = 'numpy.random.permutations'
         )

line_2 = plt.plot(xrange(*array_sizes),
                    numpy_shuffle_times,
                    color = 'yellow',
                    label = 'numpy.shuffle')

line_3 = plt.plot(xrange(*array_sizes),
                    numpy_sample_times,
                    color = 'green',
                    label = 'numpy.random.sample')

plt.xlabel('Number of Arrays')
plt.ylabel('Time in (s) for %i rep' % number_of_repetitions)
plt.title('Different ways to sample.')
plt.legend()

plt.show()

rawDescription: Create numpy array with random elements from list


code:
if __name__ == "__main__":
    main(sys.argv[1:])

rawDescription: give parameters to function and load the function the right way

description: Give parameters to function and load the function the right way


code:
class Foo(unittest.TestCase):

      def shortDescription(self):
          doc = self.__str__() +": "+self._testMethodDoc
          return doc or None

      def test_bar_1(self):
          """ this is docstring 1"""
          pass

      def test_bar_2(self):
          """ this is docstring 2"""
          self.fail()

rawDescription: How to add Test name and module to Test docstring in result?

description: Add Test name and module to Test docstring in result


code:
t=Tkinter.Text(r)
t.pack()
t.insert('1.0','aaa')
t.delete('1.0','end') # clear text widget
t.insert('1.0','bbb')

rawDescription: Window is losing keyboard focus after recreation


code:
def get_pos():
    with open("CONTCAR", "r") as finp:
        for line in finp:
            for _ in range(6):
                sdata = finp.readline()
                tpos.append(sdata.split())

    # print(tpos)
    return tpos

rawDescription: assign list to python object

description: Assign list to python object


code: Word(''.join(c for c in printables if c != ':'))

rawDescription: python pyparsing word excludeChars

description: Python pyparsing word excludeChars


rawDescription: Python: Automatically initialize instance variables?


rawDescription: Python convert table to dictionary

description: Python convert table to dictionary


code:
things_to_add = [(1, 1), (2, 1)]
for idx, amount in things_to_add:
    L[idx] += amount

L

rawDescription: Add to integers in a list

description: Add to integers in a list


rawDescription: Flask, python dictionary to highcharts JS figure


code:
a = raw_input("Enter Path:")
a

rawDescription: Sanitizing user input path names

description: Sanitizing user input path names


code:
try:
    # Python 3
    from collections.abc import MutableSet
except ImportError:
    # Python 2
    from collections import MutableSet

class SortingSet(MutableSet):
    def __init__(self, values):
        self._values = set()
        for v in values:
            self.add(v)

    def __repr__(self):
        return '<{}({}) at {:x}>'.format(
            type(self).__name__, list(self._values), id(self))

    def __contains__(self, value):
        return tuple(sorted(value)) in self._values

    def __iter__(self):
        return iter(self._values)

    def __len__(self):
        return len(self._values)

    def add(self, value):
        self._values.add(tuple(sorted(value)))

    def discard(self, value):
        self._values.discard(tuple(sorted(value)))

rawDescription: Set of string tuples in python

description: Set of string tuples in python


rawDescription: Computer Vision: Masking a human hand

description: Computer Vision: Masking a human hand


code:
q = (select([fruit.type, func.min(fruit.price).label("min_price")]).
    group_by(fruit.type)).alias("subq")
s = (session.query(fruit).
        join(q, and_(fruit.type==q.c.type, fruit.price == q.c.min_price))
    )
res = s.all()

rawDescription: How do I express this query in sqlalchemy?

description: Express this query in sqlalchemy


code:
somefloat=0.0123456789
precision = 5
print("{0:.{1}f}".format(somefloat, precision))
# 0.01235

rawDescription: Limiting floats to a varying number (decided by the end-user) of decimal points in Python


code:
from collections import Counter

counterA = Counter(listA)
counterB = Counter(listB)

rawDescription: Compute the similarity between two lists


code:
import numpy as np

# some example data
acc = np.zeros((4, 3))
legit_indices = np.array([[0, 1],
                          [0, 1],
                          [1, 2],
                          [1, 0],
                          [1, 0],
                          [1, 0]])

# convert the index array into a set of indices into acc.flat
flat_idx = np.ravel_multi_index(legit_indices.T, acc.shape)

# get the set of unique indices and their corresponding counts
uidx, ucounts = np.unique(flat_idx, return_counts=True)

# assign the count value to each unique index in acc.flat
acc.flat[uidx] = ucounts

# confirm that this matches the result of your for loop
acc2 = np.zeros_like(acc)
for ii, jj in legit_indices:
    acc2[ii, jj] += 1

assert np.array_equal(acc, acc2)

rawDescription: numpy: ravel_multi_index increment different results from iterating over indices loop

description: Numpy: ravel_multi_index increment different results from iterating over indices loop


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Circle

#Set axes aspect to equal as orbits are almost circular; hence square is needed
ax = plt.figure(0).add_subplot(111, aspect='equal')

#Setting the title, axis labels, axis values and introducing a grid underlay
#Variable used so title can indicate user inputed date
plt.title('Inner Planetary Orbits at[user input date]')
plt.ylabel('x10^6 km')
plt.xlabel('x10^6 km')
ax.set_xlim(-300, 300)
ax.set_ylim(-300, 300)
plt.grid()

#Creating the point to represent the sun at the origin (not to scale),
ax.scatter(0,0,s=200,color='y')
plt.annotate('Sun', xy=(0,-30))

#Implementing ellipse equations to generate the values needed to plot an ellipse
#Using only the planet's min (m) and max (M) distances from the sun
#Equations return '2a' (the ellipses width) and '2b' (the ellipses height)
def OrbitLength(M, m):
    a=(M+m)/2
    c=a-m
    e=c/a
    b=a*(1-e**2)**0.5
    print(a)
    print(b)
    return 2*a, 2*b

#This function uses the returned 2a and 2b for the ellipse function's variables
#Also generating the orbit offset (putting the sun at a focal point) using M and m
def PlanetOrbit(Name, M, m):
    w, h = OrbitLength(M, m)
    Xoffset= ((M+m)/2)-m
    Name = Ellipse(xy=((Xoffset),0), width=w, height=h, angle=0, linewidth=1, fill=False)
    ax.add_artist(Name)

from math import *

EPSILON = 1e-12
def solve_bisection(fn, xmin,xmax,epsilon = EPSILON):
  while True:
      xmid = (xmin + xmax) * 0.5
      if (xmax-xmin < epsilon):
        return xmid
      fn_mid = fn(xmid)
      fn_min = fn(xmin)
      if fn_min*fn_mid < 0:
          xmax = xmid
      else:
          xmin = xmid

'''
Found something similar at this gamedev question:
http://gamedev.stackexchange.com/questions/11116/kepler-orbit-get-position-on-the-orbit-over-time?newreg=e895c2a71651407d8e18915c38024d50

Equations taken from:
https://en.wikipedia.org/wiki/Kepler%27s_laws_of_planetary_motion#Position_as_a_function_of_time
'''
def SolveOrbit(rmax, rmin, t):
  # calculation precision
  epsilon = EPSILON
  # mass of the sun [kg]
  Msun = 1.9891e30
  # Newton's gravitational constant [N*m**2/kg**2]
  G = 6.6740831e-11
  # standard gravitational parameter
  mu = G*Msun
  # eccentricity
  eps = (rmax - rmin) / (rmax + rmin)
  # semi-latus rectum
  p = rmin * (1 + eps)
  # semi/half major axis
  a = p / (1 - eps**2)
  # period
  P = sqrt(a**3 / mu)
  # mean anomaly
  M = (t / P) % (2*pi)
  # eccentric anomaly
  def fn_E(E):
    return M - (E-eps*sin(E))
  E = solve_bisection(fn_E, 0, 2*pi)
  # true anomaly
  # TODO: what if E == pi?
  def fn_theta(theta):
    return (1-eps)*tan(theta/2)**2 - ((1+eps)*tan(E/2)**2)
  theta = solve_bisection(fn_theta, 0, pi)
  # if we are at the second half of the orbit
  if (E > pi):
    theta = 2*pi - theta
  # heliocentric distance
  r = a * (1 - eps * cos(E))
  return theta, r

def DrawPlanet(name, rmax, rmin, t):
  SCALE = 1e9
  theta, r = SolveOrbit(rmax * SCALE, rmin * SCALE, t)
  x = -r * cos(theta) / SCALE
  y = r * sin(theta) / SCALE
  planet = Circle((x, y), 8)
  ax.add_artist(planet)

#These are the arguments taken from hyperphysics.phy-astr.gsu.edu/hbase/solar/soldata2.html
#They are the planet names, max and min distances, and their longitudinal angle
#Also included is Halley's Comet, used to show different scale  and eccentricity
PlanetOrbit('Mercury', 69.8, 46.0)
PlanetOrbit('Venus', 108.9, 107.5)
PlanetOrbit('Earth', 152.1, 147.1)
PlanetOrbit('Mars', 249.1, 206.7)
PlanetOrbit("Halley's Comet",45900,88)
for i in range(0, 52):
  DrawPlanet('Earth', 152.1, 147.1, i/52 * 365.25 *60*60*24)
for i in range(-2, 3):
  DrawPlanet("Halley's Comet",45900,88, 7*i *60*60*24)
print(60*60*24*365)

plt.show()

rawDescription: How do I plot a planet's orbit as a function of time on an already plotted ellipse?

description: Plot a planet's orbit as a function of time on an already plotted ellipse


rawDescription: Python - How can I return a list for each xml node I am iterating through using xml.etree.ElementTree?


code:
from collections import defaultdict

def check():
    d = defaultdict(list)
    with open('logfile.py', 'rU') as datafile:
        for line in datafile:
            data = line.split(',')
            d[data[1].strip()].append(data[0].strip())
    return d
res = check()

for k, v in res.items():
    print("{} : {}".format(k, ', '.join(v)))

rawDescription: Parsing the file in Python

description: Parsing the file in Python


code:
timeit('len(list(islice(xrange(1000), 2)))', 'from itertools import islice')
timeit('sum(1 for _ in islice(xrange(1000), 2))', 'from itertools import islice')

rawDescription: How to know a generated sequence is at most a certain length

description: Know a generated sequence is at most a certain length


code:
from oauth2client.appengine import CredentialsModel
from oauth2client.appengine import StorageByKeyName
credentials = StorageByKeyName(
     CredentialsModel, user_id, 'credentials').get()

rawDescription: How to make 'access_type=offline' / server-only OAuth2 operations on GAE/Python?

description: Make 'access_type=offline' / server-only OAuth2 operations on GAE/Python


code:
result_dict = {'type_0' : {'file_name' : 'abc', 'count' : 0},
               'type_1' : {'file_name' : 'xyz', 'count' : 50}}
t = Template('''
{% for key, value in result_dict.items %}
    {{ value }}
{% endfor %}
''')
print(t.render(Context({'result_dict': result_dict})))

rawDescription: Django template in nested dictionary

description: Django template in nested dictionary


code: img.repeat(2, axis=0).repeat(2, axis=1)

rawDescription: Python function to expand image

description: Python function to expand image


code: matches = re.findall('\s{3}(.*)', contents)

rawDescription: Regular Expression for multiple lines

description: Regular Expression for multiple lines


code:
import pytest

@pytest.mark.parametrize(
    ("value", "expected"),
    [
        (True, True),
        (False, False),
    ]
)
def test_identical(value, expected):
    assert value is expected

rawDescription: A pythonic way to code self writing test methods


code: new_dict = {key:value for key, value in dict2.items() if key not in dict1}

rawDescription: python3 + Set function: how to get key and values from dictionary performing set operation

description: Python3 + Set function: how to get key and values from dictionary performing set operation


code:
data
sort_idx = np.argsort(data,axis=1)
data

rawDescription: Set duplicate elements as zeros

description: Set duplicate elements as zeros


code:
class DepartmentPeopleInline(admin.TabularInline):
    model = DepartmentPeople
    extra = 1

class DepartmentAdmin(admin.ModelAdmin):
    inlines = (DepartmentPeopleInline,)

admin.site.register(Person, PersonAdmin)
admin.site.register(Department, DepartmentAdmin)

rawDescription: Define an order for ManyToManyField with django


code: sorted(c, key=sum)[:k]

rawDescription: Find k smallest pairs in two lists

description: Find k smallest pairs in two lists


code:
for fv in range(1870, 1875, 1):
    sols = sp.solve(eq.subs({FV:fv}), check=False)
    print("{}: {}".format(fv, sols))

rawDescription: Sympy seems to break down with higher numbers


code: exec(c, {"secret": secret, "public": public})

rawDescription: Creating a simple scripting language in Python


code:
# power_reading is the data type corresponding to one set of power readings
# (it could be a simple float, or a tuple, or a class if you want; just make
# sure that you can add them together)
hourly_readings = collections.defaultdict(power_reading)
minutely_readings = { ... };  # dict of time.struct_time ==> power_reading

for timestamp, reading in minutely_readings.iteritems():
    hour = datetime.datetime(timestamp.tm_year, timestamp.tm_mon,
                             timestamp.tm_mday, timestamp.tm_hour);
    hourly_readings[hour] += reading

rawDescription: How do I easily manipulate a timestamp key in a Python dictionary?

description: Easily manipulate a timestamp key in a Python dictionary


code:
lineBoxSizer.Add(self.scroll, 1, wx.EXPAND)
boxSizer.Add(lineBoxSizer, 1, wx.EXPAND)

rawDescription: wxPython ScrolledWindow too small

description: WxPython ScrolledWindow too small


code:
import re
s = 'adsgasdlkgasYasdgjaUUalsdkjgaZsdalkjgalsdkjTlaksdjfgasdkgj'
''.join(re.findall(r'[A-Z][^A-Z]*', s)[3:])

rawDescription: Parse 4th capital letter of line in Python?


code:
def example():
    example.has_been_called = True
    pass
example.has_been_called = False

example()

#Actual Code!:
if example.has_been_called:
   print("foo bar")

rawDescription: Find Out If a Function has been Called

description: Find Out If a Function has been Called


rawDescription: Python regex split but put end part of regex match back into string?


code:
import subprocess
label = subprocess.check_output(["git", "describe"])

rawDescription: Get the current git hash in a python script


rawDescription: Save Json data to csv file

description: Save Json data to csv file


code: dict(zip(a, b))

rawDescription: mapping in SD in python

description: Mapping in SD in python


code:
def main():

    class MyParser(optparse.OptionParser):
        def format_epilog(self, formatter):
            return self.epilog

    parser =MyParser(epilog=
"""Examples:

check_dell -c all
check_dell -c fans memory voltage
check_dell -s
""")
...

rawDescription: python optparse, how to include additional info in usage output?

description: Python optparse, how to include additional info in usage output


rawDescription: opencv python copy mask region (black or white pixels) onto a BGR image region

description: Opencv python copy mask region (black or white pixels) onto a BGR image region


code:
TEMP = dict.fromkeys('''FHDosed FHControl FNHDosed FNHControl FTDosed FTControl MHDosed
                      MHControl MNHDosed MNHControl MTDosed MTControl'''.split(), 0)
TRI_1, TRI_2, TRV_1, TRV_2, TRV_3, TRV_4 = [TEMP.copy() for i in range(6)]

dmap = {
    ('G', 'A'): TRI_1,
    ('C', 'T'): TRI_1,
    ('A', 'G'): TRI_2,
    ('T', 'C'): TRI_2,
    ('G', 'C'): TRV_1,
    ('C', 'G'): TRV_1,
    ('A', 'T'): TRV_1,
    ('T', 'A'): TRV_1,
    }

for row in lst:
    key, q, s = row
    dmap[q, s][key] += 1

rawDescription: How to bin many category combinations (72 variables) in python lists

description: Bin many category combinations (72 variables) in python lists


code: posts_list = sorted(posts_list, key=lambda post: (Vote.objects.get_score(post)['score'], post.datetime))

rawDescription: Is it possible to sort using sorted() with attributes from two different models?


code:
pd.read_csv("h.csv", header=0, index_col=0)
pd.read_csv("h.csv", header=None, index_col=0)

rawDescription: Python: Not able to read first row of csv file correctly using read_csv


code: RESULT = sparse.coo_matrix((V,(I,J)),shape=(N, N))

rawDescription: Which is the best way to multiply a large and sparse matrix with its transpose?


code:
while True:
    data = queue.get() # This call will block, and won't use CPU while doing so
    # process data

rawDescription: efficient python raw_input and serial port polling

description: Efficient python raw_input and serial port polling


code: grouped = df.groupby('No.')

rawDescription: Ho to convert a pd data frame to matrix structure in python


code:
from urllib.parse import urlparse
from urllib.request import urlopen

resource = input('Enter a URL or relative file path: ')
if urlparse(resource).scheme == '':
    # assume that it is a file, use "file:" scheme
    resource = 'file:{}'.format(resource)
data = urlopen(resource).read()

rawDescription: Get arbitrary resources content in Python 3


code: out = A*M.reshape(A.shape)

rawDescription: How to find all elements in a numpy 2-dimensional array that match a certain list?

description: Find all elements in a numpy 2-dimensional array that match a certain list


code:
intersection = list_of_sets[0]
for s in list_of_sets[1:]:
    intersection.intersection_update(s)

rawDescription: Why are methods so slow?

description: Why are methods so slow


code:
def select(lst, *indices):
    return (lst[i] for i in indices)

rawDescription: Accessing non-consecutive elements of a list or string in python


code:
@app.route('/timeline.html', methods=['POST','GET'])
def timeline(request):
    checked = request.form.getlist('channel')

    # do something with checked array

    return render_template('timeline.html')

rawDescription: Passing parameters from webpage to server (Flask)


code:
# now do the real calculations for the covariogram
#    sort by h and give clear names
i = argsort(m[:,0])  # h sorting
h = m[i,0]
zh = m[i,1]
zsh = m[i,2]
zz = zh*zsh

hvals = linspace(0,S,1000)  # the values of h to use (S should be in the units of distance, here I just used ints)
ihvals = searchsorted(h, hvals)
result = []
for i, ihval in enumerate(ihvals[1:]):
    start, stop = ihvals[i-1], ihval
    N = stop-start
    if N>0:
        mnh = sum(zh[start:stop])/N
        mph = sum(zsh[start:stop])/N
        szz = sum(zz[start:stop])/N
        C = szz-mnh*mph
        result.append([h[ihval], C])
result = array(result)
plt.plot(result[:,0], result[:,1])
plt.grid()
plt.show()

rawDescription: Fast, elegant way to calculate empirical/sample covariogram


rawDescription: Pythonic way of applying changes on closing a dialog window


code: title = pattern.sub(words[0], title)

rawDescription: Pattern matching and compiling

description: Pattern matching and compiling


rawDescription: Python Regex: Mixed format string duration to seconds


rawDescription: Extracting just a string element from a pandas dataframe


code:
float1 = re.findall(r'\d+\.\d+', string1)
float2 = re.findall(r'\d+\.\d+', string2)

rawDescription: Regex Findall Hang in Linux

description: Regex Findall Hang in Linux


code:
import itertools
def string_splosion(string):
    return ''.join(itertools.accumulate(string))

rawDescription: python3 string "abcd" print: aababcabcd?

description: Python3 string "abcd" print: aababcabcd


code: s == 'True'

rawDescription: Converting from a string to boolean in Python?


code:
import pandas as pd

df = pd.DataFrame({'user_data':user_data, 'label_user':label_user})
print(df.groupby('user_data').label_user.unique())
# user_data
# User0        [0]
# User1        [1]
# User2        [1]
# User3        [0]
# User4        [0]
# Name: label_user, dtype: object

rawDescription: Attach label information when averaging predictions across users


code:
class YourModel(models.Model):
    # here your fields

    def as_dict(self):
        context = {
            'pk': self.id,
            'name': self.name,
            # ...
        }

        return context

rawDescription: How to return table data as different format types via views in Django

description: Return table data as different format types via views in Django


code:
d = {k: v.drop("Category", axis=1) for k,v in list(df.groupby("Category"))}
pprint.pprint(d)

rawDescription: Group by category in pandas DataFrame object output to dictionary object


code:
df = pd.DataFrame(np.random.rand(15, 5), index=[0]*15)
df[0] = range(15)
df

rawDescription: How to iterate over consecutive chunks of Pandas dataframe efficiently

description: Iterate over consecutive chunks of Pandas dataframe efficiently


code: new_dict = {(2 * x + 1, 2 * y + 1): v for (x, y), v in d.items()}

rawDescription: Making a grid with curses from a dictionary of flat tuples


code:
import re

string = ''.join(lst)
results = []

for match in re.finditer('\w\(', string):
    parens = 0
    substring = string[match.start():]
    results.append([substring[0]])
    for ii, ch in enumerate(substring):
        if ch == '(':
            parens += 1
            if parens == 1:
                results[-1].append(substring[ii+1])
        elif ch == ')':
            parens -= 1
            if parens < 0:
                break

rawDescription: How to iterate over a list of strings and do pattern matching?

description: Iterate over a list of strings and do pattern matching


code: 'Block. CertNot Valid.\nQuery with me'

rawDescription: Remove line break inside line row from CSV with regular expression


rawDescription: Common xlabel/ylabel for matplotlib subplots


rawDescription: Sort dictionary values and discard those which do not have a value


code:
query = si.query()

for word in words:
    query |= si.Q(word)

rawDescription: Creating a dynamic sized OR query using Sunburnt+Solr


code:
import mycustomsessionbackend as myengine

class MyCustomSessionMiddleware(object):
    def process_request(self, request):
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = myengine.SessionStore(session_key, request)

...

# mycustomsessionbackend.py
class SessionStore(SessionBase):
    def __init__(self, session_key=None, request=None):
        super(SessionStore, self).__init__(session_key)
        self.request = request

rawDescription: Django: How to extend SessionBase to have access to the Request Object


code:
district = driver.find_element_by_css_selector("input[label=District]")
print(district.get_attribute("value"))

rawDescription: How to check if form filled in python selenium

description: Check if form filled in python selenium


code:
#Create test data:
data = np.random.random_sample((25, 25))
#Create a diagonal mask:
mask = np.diag(np.ones(25))
#Apply mask to data:
masked_data = ma.masked_array(data, mask)
#Set mask color to white:
cm.jet.set_bad(color='white', alpha=None)
#for this to work we use pcolormesh instead of pcolor:
pcolormesh(masked_data, cmap=cm.jet)
colorbar()
show()

rawDescription: Make reverse diagonals white in heatmap

description: Make reverse diagonals white in heatmap


rawDescription: Looking for algorithm to merge tuples containing duplicate fields, within list of tuples


rawDescription: floating number string formatting in python

description: Floating number string formatting in python


code:
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import normalize # Added this new line

# This is how I normalized the vector. "ydata" looked like this:
# original_ ydata = [ 1, 3, 8, 14, 12, 27, 33, 36, 87, 136, 77, 57, 32, 31, 28, 24, 12, 2 ]
# The curve was NOT fitting using this values, so I found a function in
# scikit-learn that normalizes (multidim) arrays: [normalize][2]

# m = []
# m.append(original_ydata)
# ydata = normalize(m, norm='l2') * 10

# Why 10? This function is converting my original values in a range
# going from [0.00014, ..., 0.002 ] or something similar. So "curve_fit"
# couldn't find anything but a horizontal line crossing y = 1.
# I tried multiplying by 5, 6, ..., 12, and I realized that 10 is
# the maximum value that lets the maximum value of my array below 1.00, like 0.97599.

# Length of both arrays is 209
# Y-axis data has been normalized BUT then multiplied by 10
ydata = array([  5.09124776e-04,   1.01824955e-03, ... , 9.75992196e-01])
xdata = array(range(0,len(ydata),1))

def sigmoid(x, x0, k):
    y = 1 / (1+ np.exp(-k*(x-x0)))
    return y

popt, pcov = curve_fit(sigmoid, xdata, ydata)

x = np.linspace(0, 250, 250)
y = sigmoid(x, *popt)

plt.plot(xdata, ydata, 'o', label='data')
plt.plot(x,y, linewidth=3.0, label='fit')
plt.ylim(0, 1.25)
plt.legend(loc='best')

# This (m, b, C) parameters not sure on where they are... popt, pcov?
# y = C * sigmoid(m*x + b)

rawDescription: Parameters of a sigmoid regression in Python + scipy


code:
import sympy

def definition_to_function(s):
    lhs, rhs = s.split("=", 1)
    rhs = rhs.rstrip('; ')
    args = sympy.sympify(lhs).args
    f = sympy.sympify(rhs)
    def f_func(*passed_args):
        argdict = dict(zip(args, passed_args))
        result = f.subs(argdict)
        return float(result)
    return f_func

rawDescription: Python: How to evaluate a function which is string?


code:
def f():
    g.db = connect_db()

app.before_request(f)

rawDescription: '@' python decorator used to do something similar to method overriding in java?


code:
setup(
    # ...
    namespace_packages  = ["rewind"]
)

rawDescription: Can two distributions deliver the same package?


code:
blog = Blog.objects.db_manager('sqlite').create(
    name='This is a blog post', tagline='python django')

rawDescription: How to use other than default database

description: Use other than default database


code:
foo = Queue.mkQueue()
foo.stack1
foo.stack2
foo.stack1 is foo.stack2

rawDescription: Queue, stack python

description: Queue, stack python


code:
import random

x = random.randrange(1,1000)
counter = 0

while True:
    guess = int(input("I have a number between 1 and 1000. Can you guess my number?\nPlease type your first guess."))
    if guess == x:
        print ("Excellent! You guessed the number in", counter,"tries.")
        play_again = input("Type Y if you'd like to play again, or N if not")
        if play_again == 'N':
            break
    else:
        if guess > x:
            print("high")
        else:
            print("low")
        counter += 1

rawDescription: Python: Looping issue or indentation

description: Python: Looping issue or indentation


rawDescription: Counting data points within limits, and applying buffer to isolated points [data analysis]


code: ['foo', 'bar', 'baz', 'qux', 'foo bar', 'bar baz', 'baz qux', 'foo bar baz', 'bar baz qux', 'foo bar baz qux']

rawDescription: Break string into words and phrases

description: Break string into words and phrases


rawDescription: Building a histogram from MongoDB with Pymongo


code:
time
flux
time2 = time[~np.isnan(flux)]
flux2 = flux[~np.isnan(flux)]
time2
flux2

rawDescription: Removing Corresponding Entries from Two Numpy Arrays


code:
مافظة_البدائع
أوريويلا
Battle_of_Nicopolis
Qingdao

rawDescription: python unicode issues in both python2 and python3

description: Python unicode issues in both python2 and python3


code:
if __name__=='__main__':
    p = Person()
    print(rgetattr(p, 'pet.favorite.color', 'calico'))
    # 'calico'

    try:
        # Without a default argument, `rgetattr`, like `getattr`, raises
        # AttributeError when the dotted attribute is missing
        print(rgetattr(p, 'pet.favorite.color'))
    except AttributeError as err:
        print(err)
        # 'Pet' object has no attribute 'favorite'

    rsetattr(p, 'pet.name', 'Sparky')
    rsetattr(p, 'residence.type', 'Apartment')
    print(p.__dict__)
    print(p.pet.name)
    # Sparky
    print(p.residence.type)
    # Apartment

rawDescription: getattr and setattr on nested objects?

description: Getattr and setattr on nested objects


code:
path = "path/"
name = "fileName"

xmlRoot = Element("root")#create a root element for the xml structure
xmlSub = SubElement(xmlRoot,"sub")
subName = SubElement(xmlCard,"name")
subName.text = "element text"

saveName = path + name + ".xml" #constructs location of xml file (path/fileName.xml)
tree = ElementTree(xmlRoot) #compiles the tree
tree.append(saveName) #appends to specified file

rawDescription: How can I force ElementTree to write to disk every change?

description: Force ElementTree to write to disk every change


code: L = L[:subscript] + L[subscript:]

rawDescription: Removing Negative Elements in a List - Python


code: mydict = {"Pepsi": {"respondent": 3, "rating": 8}, "Coke": {"respondent": 3, "rating":10}}

rawDescription: What is the best Python data structure for named 2D array


code:
import inspect

def inheritdocstring(cls):
    for base in inspect.getmro(cls):
        if base.__doc__ is not None:
            cls.__doc__ = base.__doc__
            break
    return cls

rawDescription: Inherit a parent class docstring as __doc__ attribute


code:
import datetime
userdateString = '2013-2-1'
datetime.datetime.strptime(userdateString, '%Y-%m-%d')

rawDescription: How to allow users to pick dates using Python

description: Allow users to pick dates using Python


rawDescription: Python PIL: IOError: cannot identify image file


code: data2 = np.asarray(data2, dtype=np.int16)

rawDescription: Writing wav file in Python with wavfile.write from SciPy


rawDescription: Merging two dictionaries while keeping the original


code:
{'word','word 1','word 2'}.issubset(['desk','chair','lamp'])
{'word','word 1','word 2'}.issubset(['cow','word','horse','word 2','word 1'])

rawDescription: How to print a sublist that contains all of the strings in another list?

description: Print a sublist that contains all of the strings in another list


code:
bb.view()
plt.show()

rawDescription: Can't get menpo to display images in Pycharm


code: struct.unpack('2q', x)

rawDescription: How to unpack a struct in Python?

description: Unpack a struct in Python


rawDescription: Using Python's PIL, how do I enhance the contrast/saturation of an image?


code:
import pandas as pd

df = pd.read_table('data', sep='\s+')
previous_15 = df['SMA_15'].shift(1)
previous_45 = df['SMA_45'].shift(1)
crossing = (((df['SMA_15'] <= df['SMA_45']) & (previous_15 >= previous_45))
            | ((df['SMA_15'] >= df['SMA_45']) & (previous_15 <= previous_45)))
crossing_dates = df.loc[crossing, 'Date']
print(crossing_dates)

rawDescription: Python and Pandas - Moving Average Crossover


code:
k = [j[0] for j in a]
[i for i in b if i[0] not in k]

rawDescription: Remove arrays from nested arrays based on first element of each array


code: myArray = np.zeros((6,6))

rawDescription: How to set first column to a constant value of an empty np.zeros numPy matrix?

description: Set first column to a constant value of an empty np.zeros numPy matrix


rawDescription: Numpy genfromtxt Column Names

description: Numpy genfromtxt Column Names


code:
from bs4 import BeautifulSoup

import urllib2
import re

def get_players(team_id, year):
    link = "http://espn.go.com/nba/team/stats/_/name/{}/year/{}/".format(team_id, year)
    source = urllib2.urlopen(link)
    html = source.read()
    source.close();
    soup = BeautifulSoup(html, "html.parser")

    players_table = soup.find_all("tr",{"class" : re.compile(r"\d+$")})
    player_names = []
    for table in players_table:
        for a in table.find_all('a'):
            player_names.append(a.get_text())

    return player_names

rawDescription: Getting names from HTML file via python

description: Getting names from HTML file via python


rawDescription: Is this possible using regular expression


code:
var1 = f(var2, var3)
var4 = f(var5, var6)

rawDescription: How can you output a varying argument in Python?

description: Output a varying argument in Python


code: sorted(lst, key=str.lower)

rawDescription: Python data structure sort list alphabetically


code:
val1, val2 = 0.5, 1
a[a<-1]= val1
a[a>1] = val2
ax.imshow(a, interpolation='nearest')

rawDescription: Displaying multiple masks in different colours in pylab


code:
class TessBaseAPI(_object):
    __swig_setmethods__ = {}
    __setattr__ = lambda self, name, value: _swig_setattr(self, TessBaseAPI, name, value)
    __swig_getmethods__ = {}
    __getattr__ = lambda self, name: _swig_getattr(self, TessBaseAPI, name)
    __repr__ = _swig_repr
    def __init__(self):
        this = _tesseract.new_TessBaseAPI()
        try: self.this.append(this)
        except: self.this = this
    __swig_destroy__ = _tesseract.delete_TessBaseAPI
    __del__ = lambda self : None;
    __swig_getmethods__["Version"] = lambda x: _tesseract.TessBaseAPI_Version
    if _newclass:Version = staticmethod(_tesseract.TessBaseAPI_Version)
    __swig_getmethods__["getOpenCLDevice"] = lambda x: _tesseract.TessBaseAPI_getOpenCLDevice
    if _newclass:getOpenCLDevice = staticmethod(_tesseract.TessBaseAPI_getOpenCLDevice)
    __swig_getmethods__["CatchSignals"] = lambda x: _tesseract.TessBaseAPI_CatchSignals
    if _newclass:CatchSignals = staticmethod(_tesseract.TessBaseAPI_CatchSignals)
    def SetInputName(self, *args): return _tesseract.TessBaseAPI_SetInputName(self, *args)
    def GetInputName(self): return _tesseract.TessBaseAPI_GetInputName(self)
    ...
    def ClearAdaptiveClassifier(self): return _tesseract.TessBaseAPI_ClearAdaptiveClassifier(self)
    def SetImage(self, *args): return _tesseract.TessBaseAPI_SetImage(self, *args)

rawDescription: python tesseract "AttributeError: setImage"

description: Python tesseract "AttributeError: setImage"


code: ''.join(s.split(' - second - '))

rawDescription: Python 3 String Method?

description: Python 3 String Method


code:
profile = webdriver.FirefoxProfile()
profile.set_preference ('media.navigator.permission.disabled', True)
profile.update_preferences()

rawDescription: Using Selenium/WebDriver and Python, how do I suppress the prompt to share my camera and microphone?


code:
class MyClass(object):
    varx = Desc('varx')

rawDescription: python descriptors sharing values across classes

description: Python descriptors sharing values across classes


code:
def foo():
    def bar():
        print(spam)

    spam = 'ham'
    bar()
    spam = 'eggs'
    bar()
    return bar

b = foo()
b()

rawDescription: What exactly is contained within a obj.__closure__?


code:
source = urllib2.urlopen("http://someUrl.com/somePage.html").read()
open("/path/to/someFile", "wb").write(source)

rawDescription: How to download a file using Python

description: Download a file using Python


code: map(str.strip, s.split('-'))

rawDescription: Python Regular Expressions re.findall -- split a string into two


code:
num = .2 + .1
'Float: %f. Repr: %r Str: %s' % (num, num, num)

rawDescription: Why would I ever use anything else than %r in Python string formatting?


code:
weights = getWeights_function_handler()
list = [weights[i] for i in xrange(ARRAY_SIZE_I_KNOW_IN_ADVANCE)]

rawDescription: Python Ctypes: Convert returned C array to python list, WITHOUT numpy


code:
import re
reg = re.compile(r'(?:\").*?(\")')

rawDescription: Python regex to find only second quotes of paired quotes


code:
import numpy as np

TIME = np.array([0.,   10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90.])
FLOW = np.array([100., 75.,  60.,  20.0, 60.0, 50.0, 20.0, 30.0, 20.0, 10.0])
TEMP = np.array([300., 310., 305., 300., 310., 305., 310., 305., 300., 295.0])

last_high_flow_index = np.flatnonzero(FLOW > 50)[-1]
low_flow_indices = np.flatnonzero(FLOW < 30)
acceptable_low_flow_indices = low_flow_indices[low_flow_indices > last_high_flow_index]
apply_after_index = acceptable_low_flow_indices[0]

rawDescription: Numpy time based vector operations where state of preceding elements matters - are for loops appropriate?


code: df

rawDescription: Time series normalization by event

description: Time series normalization by event


rawDescription: In python curly braces with numbers from range() inside


code:
posts = user.posts_set.all() #or Posts.objects.filter(user=user)
comments = Comments.objects.filter(post_id__user=user)

import itertools
qs = itertools.chain.from_iterable([posts, comments])

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


code:
ax1.get_xlim()
ax2.get_xlim()

rawDescription: matplotlib - Second X axis has an offset (wrt 1st X axis) I can't pin down

description: Matplotlib - Second X axis has an offset (wrt 1st X axis) I can't pin down


rawDescription: Format string to make MySQL query using .format in Python way


rawDescription: Decode High Level Python to easier code

description: Decode High Level Python to easier code


code:
import getopt
import msvcrt

opts, args = getopt.getopt(sys.argv[1:], '...', ['pause', ...])
for opt, arg in opts:
    if opt == "--pause":
        promptForKeypress = True
    ...
...
if promptForKeypress:
    msvcrt.getch()      # note: Windows-only
# End of Script

rawDescription: Run python.exe and pause after the script has executed


code:
import re
just = 'Standard Price:20000'
price = re.findall("\d+", just)[0]

rawDescription: Get only numbers from string in python

description: Get only numbers from string in python


code:
print(re.split(r'\s+(?=")', line.strip())) #split on white space only if followed by a quote.
#['<abc<hd <>', '"abc"d" ef"']

rawDescription: How to ignore quotes while splitting strings python

description: Ignore quotes while splitting strings python


rawDescription: Get a 3D or 4D array as input and reshape it to 2D array in a function from external script


code:
d = {1: [1, 2], 3: [2,4], 4:[3,3], 2:[4,1], 0:[5,0]} # dict to remove items from

sorted_list=sorted(d.items(), key=lambda x: x[1][1])
sorted_keys = [key[1] for key in sorted_list]

n=2 # number of items to remove
for key in sorted_keys[0:n]:
    d = dict([(k,v) for k,v in d.items() if v != key ])

rawDescription: Python: Remove top 'n' keys from a dictionary


code:
import os
help(os)

rawDescription: How to disable Python shell spawning less with "help"

description: Disable Python shell spawning less with "help"


code:
class Cart(models.Model):
    user = models.OneToOneField(User, related_name='cart')
    date_added = models.DateTimeField(auto_now_add=True, help_text="Date when cart is added.")
    date_modified = models.DateTimeField(auto_now=True, help_text="Date when cart is modified.")

class CartDetail(models.Model):
    cart = models.ForeignKey(Cart, related_name='cart_details')
    flower = models.ForeignKey(Flower)
    quantity = models.PositiveSmallIntegerField(help_text='Quantity to be purchased.')
    date_added = models.DateTimeField(auto_now_add=True,
                                      help_text="Date when this item is added.")
    date_modified = models.DateTimeField(auto_now=True, help_text="Date when this item is modified.")

rawDescription: Python/Django: RelatedObjectDoesNotExist: Cart has no user


rawDescription: strange output when using flags in python

description: Strange output when using flags in python


code: r.set('key', val)

rawDescription: Store SQL query result into Redis using Python?


code:
import lxml.etree, os, urlparse
root = lxml.etree.HTML(html)
for img in root.iter("img"):
    src = img.get("src", None)
    if src is not None:
        if urlparse.urlparse(src).scheme in ("http", "https"):
            src_path = urlparse.urlparse(src).path
            src_path_base = os.path.basename(src)
            src = "id:" + os.path.basename(src)
            img.set("src", src)
html = lxml.etree.tostring(root)

rawDescription: Python regex: search for HTML tags and modify them


code: file_location= '/temp/foobar'

rawDescription: Writing and reading variables in a file in Python


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

pi = np.pi
sin = np.sin
cos = np.cos

def mvee(points, tol = 0.001):
    """
    Finds the ellipse equation in "center form"
    (x-c).T * A * (x-c) = 1
    """
    N, d = points.shape
    Q = np.column_stack((points, np.ones(N))).T
    err = tol+1.0
    u = np.ones(N)/N
    while err > tol:
        # assert u.sum() == 1 # invariant
        X = np.dot(np.dot(Q, np.diag(u)), Q.T)
        M = np.diag(np.dot(np.dot(Q.T, la.inv(X)), Q))
        jdx = np.argmax(M)
        step_size = (M[jdx]-d-1.0)/((d+1)*(M[jdx]-1.0))
        new_u = (1-step_size)*u
        new_u[jdx] += step_size
        err = la.norm(new_u-u)
        u = new_u
    c = np.dot(u,points)
    A = la.inv(np.dot(np.dot(points.T, np.diag(u)), points)
               - np.multiply.outer(c,c))/d
    return A, c

#some random points
points = np.array([[ 0.53135758, -0.25818091, -0.32382715],
                   [ 0.58368177, -0.3286576,  -0.23854156,],
                   [ 0.18741533,  0.03066228, -0.94294771],
                   [ 0.65685862, -0.09220681, -0.60347573],
                   [ 0.63137604, -0.22978685, -0.27479238],
                   [ 0.59683195, -0.15111101, -0.40536606],
                   [ 0.68646128,  0.0046802,  -0.68407367],
                   [ 0.62311759,  0.0101013,  -0.75863324]])

# Singular matrix error!
# points = np.eye(3)

A, centroid = mvee(points)
U, D, V = la.svd(A)
rx, ry, rz = 1./np.sqrt(D)
u, v = np.mgrid[0:2*pi:20j, -pi/2:pi/2:10j]

def ellipse(u,v):
    x = rx*cos(u)*cos(v)
    y = ry*sin(u)*cos(v)
    z = rz*sin(v)
    return x,y,z

E = np.dstack(ellipse(u,v))
E = np.dot(E,V) + centroid
x, y, z = np.rollaxis(E, axis = -1)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(x, y, z, cstride = 1, rstride = 1, alpha = 0.05)
ax.scatter(points[:,0],points[:,1],points[:,2])

plt.show()

rawDescription: Port MATLAB bounding ellipsoid code to Python


rawDescription: Change text value with lxml

description: Change text value with lxml


code:
import numpy

def print_matrix(M):
    print (M)

def transform_matrix(M, L):
    for x in L:
        M = M*x
    return M

rawDescription: Passing a List and numpy.matrix to a python function from a C++ application


code: inetnums=[(int(x) for x in line.rstrip('\n').split('\t')) for line in fin]

rawDescription: How to quicky create array from  big file?

description: Quicky create array from  big file


code:
struct.pack('!Bhh', 1, 1, 13)
struct.pack('!Bhh', 1, 1, 9)
struct.pack('!Bhh', 1, 1, 65)

rawDescription: Python struct.pack dropping a byte.

description: Python struct.pack dropping a byte.


code:
import abc
abc.__file__

rawDescription: How to know the location of the library that I load in Python?

description: Know the location of the library that I load in Python


code:
from operator import add
rdd = sc.parallelize([(1038, u'XYZ'), ...])
(rdd.filter(lambda x: "XYZ" == x[1])
 .map(lambda x: (x[1], x[0]))
 .reduceByKey(add).collect())

rawDescription: Summing integers across records in Spark


rawDescription: semantics of generating symmetric matrices in numpy

description: Semantics of generating symmetric matrices in numpy


code:
@contextmanager
def cbreak():
    old_attrs = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin)
    try:
        yield
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attrs)

rawDescription: Python, "filtered" line editing, read stdin by char with no echo


code:
def stringMatch(L, char):
    counts = (char in word for word in L)  # compute the counts of `char` in each list item
    for word, count in zip(L, counts):
        if not count: continue
        print(word, count)

rawDescription: Print only the list items that contain a certain character


code:
rev = lis[::-1]
rev

rawDescription: How does this code snippet rotating a matrix work?


code:
class Bar(models.Model):
    name = models.CharField(max_length=20)

class Foo(models.Model):
    bar = models.OneToOneField(Bar)

rawDescription: when does django run the query for a OneToOneField?

description: When does django run the query for a OneToOneField


code:
def test(list_of_lists):
    final = []
    for L in list_of_lists:
        final += L
    return final

rawDescription: Iterate function changing parameter after each run


code:
from django.test.testcases import TestCase

def create_user(data='testuser'):
    email = '%s@%s.com' % (data, data)
    user = G(User, username=data, email=email, is_active=True)
    user.set_password(data)
    user.save()
    return user

class UsernameCaseInsensitiveTests(TestCase):

    def test_user_create(self):
        testuser = 'testuser'
        user = create_user(testuser)
        # Lowercase
        self.assertEqual(testuser, user.username)
        # Uppercase
        user.username = testuser.upper()
        user.save()
        self.assertEqual(testuser, user.username)

def test_username_eq(self):
    testuser = 'testuser'
    user = create_user(testuser)
    self.assertTrue(isinstance(user.username, iunicode))
    self.assertEqual(user.username, testuser)
    self.assertEqual(user.username, testuser.upper())
    self.assertTrue(user.username == testuser.upper())
    self.assertTrue(testuser.upper() == user.username)
    self.assertTrue(user.username == iunicode(testuser.upper()))

rawDescription: Django : Case insensitive matching of username from auth user?


code:
a = ['cat','dog', 'cat12', 'catcat']
print([x for x in a if 'cat' in x])

rawDescription: How do I find a specific word in elements in a list (python)

description: Find a specific word in elements in a list (python)


code: plt.contourf(X, Y, Z) # filled contour

rawDescription: Smooth contour plot in matplotlib from 3 lists of different size


code: [u'Birthday:', u'Education', u'Job:', u'Child Sex:']

rawDescription: Dictionary As Table In Django Template

description: Dictionary As Table In Django Template


code: np.intersect1d(A, B)

rawDescription: Efficient way to compute intersecting values between two numpy arrays


code: check_output('''curl -d '{"data": [{"content": "blabla"}]}' http://service.location.com''', shell=True)

rawDescription: Passing string as argument adds escape characters


rawDescription: Python - Why doesn't this instance method need parentheses when called inside another instance method?


rawDescription: How to get a list of dates from a week number in python

description: Get a list of dates from a week number in python


rawDescription: adding string in others

description: Adding string in others


code:
D2 = (xf[:,None] - xg[None,:])**2 + (yf[:,None] - yg[None,:])**2 + (zf[:,None] - zg[None,:])**2
near = D2 < 20**2
a1 = np.array([G.epsilon[near_row].mean() for near_row in near])

rawDescription: Code works but too slow

description: Code works but too slow


code:
# don't step on the `join` built-in
from django.template.defaultfilters import join as join_filter

class Project(models.Model):

    @property
    def leaders(self):
        return join_filter(self.objects.values_list('some_field', flat=True), ', ')

rawDescription: django concat string with comma in template

description: Django concat string with comma in template


code:
@post_blueprint.route('/posts/')
def get_all_posts():
    models = database_call_of_some_kind # This is assuming you use some kind of model
    posts = []
    for model in models:
        posts.append(dict(year=model.year, month=model.month, title=model.title))
    return render_template('p.html', posts=posts)

rawDescription: Creating link to an url of Flask app in jinja2 template


code: my_list = my_list[:8] + new_array

rawDescription: Python - insert into list

description: Python - insert into list


code:
res = df1.merge(df2, on=['store_id', 'phone'], how='outer')
res

rawDescription: Conditional merge for CSV files using python (pandas)


code:
from itertools import combinations
lol = [[1,2],[1,3],[3,4]]
k = len(lol[0])
pair_sets = (set().union(*x) for x in combinations(lol,2))
keep = [sorted(x) for x in pair_sets if len(x) == k+1]
keep

rawDescription: Generate Joined Lists of Given Size in python


code:
renamed = []
for h in name_from_hash1:
    if h in name_from_hash2 and name_from_hash1[h] != name_from_hash2[h]:
        renamed.append(name_from_hash2[h])

rawDescription: Comparing 2 dicts, if values are the same, but key is different, add key to a new list in python


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

fig, axes = plt.subplots(nrows=2, ncols=2, sharey=True, sharex=True)
for i, ax in enumerate(axes.flat, start=1):
    ax.set(aspect=1, adjustable='box-forced', xticks=range(i))
    ax.plot(np.arange(0, i * 4, i))

plt.show()

rawDescription: matplotlib: aspect ratio in subplots with various y-axes

description: Matplotlib: aspect ratio in subplots with various y-axes


code:
from model import Foo
Foo()

rawDescription: How can I split a module into multiple files, without breaking a backwards compatibly?

description: Split a module into multiple files, without breaking a backwards compatibly


code: set(map(tuple, items))

rawDescription: How do I remove duplicate arrays in a list in Python

description: Remove duplicate arrays in a list in Python


code:
encoded_data = base64.b64encode(open(file_name, 'rb').read())
strg = ''
for i in xrange((len(encoded_data)/40)+1):
    strg += encoded_data[i*40:(i+1)*40]
# strg then contains data required

rawDescription: Python Create Byte Array for Web Service Expecting Byte[]


code:
Y = np.zeros((M, M), dtype=float)
for j in xrange(N):
    Y += X[:,np.newaxis,j] * X.T[j,np.newaxis,:]

rawDescription: Multipy matrix by its transpose in constant memory


code:
class FullscreenToggler(object):

    def __init__(self, window, keysym=gtk.keysyms.F11):
        self.window = window
        self.keysym = keysym
        self.window_is_fullscreen = False
        self.window.connect_object('window-state-event',
                                   FullscreenToggler.on_window_state_change,
                                   self)

    def on_window_state_change(self, event):
        self.window_is_fullscreen = bool(
            gtk.gdk.WINDOW_STATE_FULLSCREEN & event.new_window_state)

    def toggle(self, event):
        if event.keyval == self.keysym:
            if self.window_is_fullscreen:
                self.window.unfullscreen()
            else:
                self.window.fullscreen()

rawDescription: Simple way to toggle fullscreen with F11 in PyGTK


code: guessleg = int(input('Guess the number of legs: '))

rawDescription: Returning to menu after command? Python

description: Returning to menu after command? Python


code:
import threading
import time
import Tkinter

root = Tkinter.Tk()

def autosave():
    while True:
        # do something you want
        time.sleep(60 * 5)

saver = threading.Thread(target=autosave)
saver.start()
root.mainloop()

rawDescription: Auto-save function implementation with Python and Tkinter


code:
def corr2_coeff(A,B):
    # Rowwise mean of input arrays & subtract from input arrays themeselves
    A_mA = A - A.mean(1)[:,None]
    B_mB = B - B.mean(1)[:,None]

    # Sum of squares across rows
    ssA = (A_mA**2).sum(1);
    ssB = (B_mB**2).sum(1);

    # Finally get corr coeff
    return np.dot(A_mA,B_mB.T)/np.sqrt(np.dot(ssA[:,None],ssB[None]))

rawDescription: Computing the correlation coefficient between two multi-dimensional arrays


code: matches = []

rawDescription: Extracting Data From Multiple Dictionaries


code: dict_generator = grabber3(a_file)

rawDescription: Returning elements from a loop, one at a time


code: stats = subclassed_dict()

rawDescription: How do I initialize values in a dictionary?

description: Initialize values in a dictionary


rawDescription: How to fill a button with image in python gtk

description: Fill a button with image in python gtk


code:
Comment2
Comment3
Comment1

rawDescription: Dynamic order in django-mptt

description: Dynamic order in django-mptt