rawDescription: How to format a floating number to fixed width with forced sign in Python

description: Format a floating number to fixed width with forced sign in Python


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

v1 = -1+2*np.random.rand(50,150)
v1a = masked_array(v1,v1<0)
v1b = masked_array(v1,v1>=0)
fig,ax = plt.subplots()
pa = ax.imshow(v1a,interpolation='nearest',cmap=cm.Reds)
cba = plt.colorbar(pa,shrink=0.25)
pb = ax.imshow(v1b,interpolation='nearest',cmap=cm.winter)
cbb = plt.colorbar(pb,shrink=0.25)
plt.xlabel('Day')
plt.ylabel('Depth')
cba.set_label('positive')
cbb.set_label('negative')
plt.show()

rawDescription: Two different color colormaps in the same imshow matplotlib


code:
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i+n]

rawDescription: How do you split a list into evenly sized chunks in Python?

description: Split a list into evenly sized chunks in Python


code:
unicode_snowman = '\xe2\x98\x83'.decode('utf8')
unicode_snowman = unichr(0x2603)

rawDescription: Python unicode string literals in module declared as utf-8


code:
from django.shortcuts import render
def myrender(request, template, dictionary):
    dictionary.update({'template_name': template})
    return render(request, template, dictionary)

rawDescription: Get template name in template tag ( Django )


code: [list(g) for _, g in groupby(bool_array)]

rawDescription: How do I identify sequences of values in a boolean array?

description: Identify sequences of values in a boolean array


code:
import random
random.choice(map.spawn_locations)
random.choice(map.spawn_locations)

rawDescription: Storing and then accessing a pair of coordinates


code:
from django.contrib.auth.decorators import login_required

@login_require
def my_func(request):
    print(user.id) #the user is loggedin

rawDescription: login sessions for django

description: Login sessions for django


code:
df = DataFrame(table, columns=headers)
df

rawDescription: Getting list of lists into pandas DataFrame


code:
for key, value in format_mapping.items():
    df[key] = df[key].apply(value.format)

rawDescription: Python Pandas Apply Formatting to Each Column in Dataframe Using a Dict Mapping


rawDescription: Check if number is made of both 0 and 1 using regex


rawDescription: Running two methods (with arguments) simultaneously?


code:
@task
def provision():
    # ... do some stuff on each host here, e.g. install mongodb
    execute(stuff_to_do_on_all_hosts)

    # build list of mongo primaries
    primaries = [host for host, result in execute(is_primary, roles=('mongo',)).iteritems() if result]

    # run task only on those hosts
    execute(stuff_to_do_on_mongo_primaries, hosts=primaries)

@task
def stuff_to_do_on_all_hosts():
    do_stuff()

@task
def stuff_to_do_on_mongo_primaries():
    add_user()
    do_other_stuff()

rawDescription: Can a fabric task execute other tasks and respect decorators such as runs_once?


rawDescription: How do I convert Python's itertools.product library from a list comprehension to normal for loops?

description: Convert Python's itertools.product library from a list comprehension to normal for loops


code:
import numpy as np
import numpy.linalg as linalg

def solve(n):
    # upper left block
    n_to_M = -2. * np.eye(n-1)

    # lower left block
    n_to_N = (n * np.eye(n-1)) - np.diag(np.arange(n-2, 0, -1), 1)

    # upper right block
    m_to_M = n_to_N.copy()
    m_to_M[1:, 0] = -np.arange(1, n-1)

    # lower right block
    m_to_N = np.zeros((n-1, n-1))
    m_to_N[:,0] = -np.arange(1,n)

    # build A, combine all blocks
    coeff_mat = np.hstack(
                          (np.vstack((n_to_M, n_to_N)),
                           np.vstack((m_to_M, m_to_N))))

    # const vector, right side of eq.
    const = n * np.ones((2 * (n-1),1))

    return linalg.solve(coeff_mat, const)

rawDescription: How to set up and solve simultaneous equations in python

description: Set up and solve simultaneous equations in python


rawDescription: Timer Python 3,3

description: Timer Python 3,3


code:
from nltk.corpus import wordnet as wn
x = [i.strip() for i in """corporal, dog, cat, distingus, Company, phone, authority, vhicule, seats, lightweight, rules, resident, expertise""".lower().split(",")]
x
[i for i in x if wn.synsets(i)]

rawDescription: How to use NLTK WordNet to check for incomplete words in Python?

description: Use NLTK WordNet to check for incomplete words in Python


code:
for lst in d.values():
    if 'b' in lst:
        key = let
        break

rawDescription: How to access a list containing specific item in a dictionary?

description: Access a list containing specific item in a dictionary


code:
import webapp2
from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request

        self.session_store = sessions.get_store(request = self.request)

        try:
            webapp2.RequestHandler.dispatch(self)
        finally:
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key
        return self.session_store.get_session()

rawDescription: Stuck retrieving parameters in sessions - GAE webapp2


rawDescription: How reverse query OnetoOne Django

description: How reverse query OnetoOne Django


code:
my_list = [1,2,3,4,5,6,7]
length=len(my_list)
index=2
length-(index+1)  #remaining elements are [4,5,6,7]
index=4
length-(index+1)  #remaining elements are [6,7]

rawDescription: Calculating the number of remaining items in a list from a given index


code:
# 1 Section
## 1.1 Subsection
## 1.2 Subsection
# 2 Section
## 2.1 Subsection
### 2.1.1 Subsubsection
### 2.1.2 Subsubsection
## 2.2 Subsection
### 2.2.1 Subsubsection
### 2.2.2 Subsubsection
#### 2.2.2.1 Sub4section
#### 2.2.2.2 Sub4section
#### 2.2.2.3 Sub4section
#### 2.2.2.4 Sub4section
##### 2.2.2.4.1 Sub5section
#### 2.2.2.5 Sub4section
##### 2.2.2.5.1 Sub5section
##### 2.2.2.5.2 Sub5section
### 2.2.3 Subsubsection
### 2.2.4 Subsubsection
#### 2.2.4.1 Sub4section
#### 2.2.4.2 Sub4section
## 2.3 Subsection
### 2.3.1 Subsubsection
### 2.3.2 Subsubsection
### 2.3.3 Subsubsection
#### 2.3.3.1 Sub4section
##### 2.3.3.1.1 Sub5section
##### 2.3.3.1.2 Sub5section
### 2.3.4 Subsubsection
#### 2.3.4.1 Sub4section
## 2.4 Subsection
### 2.4.1 Subsubsection
### 2.4.2 Subsubsection
# 3 Section
## 3.1 Subsection
## 3.2 Subsection
# 4 Section
## 4.1 Subsection
### 4.1.1 Subsubsection
#### 4.1.1.1 Sub4section
#### 4.1.1.2 Sub4section
#### 4.1.1.3 Sub4section
##### 4.1.1.3.1 Sub5section
#### 4.1.1.4 Sub4section
### 4.1.2 Subsubsection
## 4.2 Subsection
### 4.2.1 Subsubsection
# 5 Section
## 5.1 Subsection

rawDescription: "Counting" with multiple regular expressions matches in Python


rawDescription: Python - Split a List into 2 by even or odd index?


code:
csv_file = 'file.csv'
with open(csv_file, 'wb') as fd:
    writer = csv.DictWriter(
        fd, sorted(dictionary), delimiter=',')
    # write formatted headers
    writer.writerow({k: ' {} '.format(k) for k in dicitonary})

    csv_data = itertools.izip_longest(*dictionary.values(), fillvalue='     ')
    writer.writerows(dict(zip(dictionary, row)) for row in csv_data)

rawDescription: How to sort uneven dictionary by key and create CSV

description: Sort uneven dictionary by key and create CSV


rawDescription: how can I flatten an 2d numpy array, which has different length in the second axis?

description: Flatten an 2d numpy array, which has different length in the second axis


code:
root.tk_setPalette(background='#40E0D0', foreground='black',
               activeBackground='black', activeForeground=mycolor2)
Tkinter.Button(root, text="Press me!").pack()

rawDescription: Default window colour Tkinter and hex colour codes


code:
def with_dok(x, y):
    for k in y.keys():  # no has_key in py3
        if k in x:
           x[k] += y[k]
        else:
           x[k] = y[k]
    return x

def with_update(x,y):
    x.update((k, v+x.get(k)) for k, v in y.items())
    return x

rawDescription: Adding two `csc` sparse matrices of different shapes in python


code:
a = [1,2,3,4,5]
b = [[x, True if x == 4 else False] for x in a]
b

rawDescription: list comprehension to create list of list

description: List comprehension to create list of list


code:
from collections import OrderedDict
from queue import Queue

sample_dict = {8: [9], 3: [6, 8], 4: [2, 1], 5: [4, 3], 6: [0, 7]}

rawDescription: How can I arrange a dictionary?

description: Arrange a dictionary


code:
from itertools import groupby
[' '.join(w.split()[1] for w in words)
       for key, words in groupby(raw, key=lambda e: e.split()[0])]

rawDescription: Merge some part of the list together using python


code:
import requests
from bs4 import BeautifulSoup
import re

#Gets chapter links
def get_chapter_links(index_url):
    r = requests.get(index_url)
    soup = BeautifulSoup(r.content, 'lxml')
    links = soup.find_all('a')
    url_list = []
    for url in links:
        url_list.append((url.get('href')))
    match = [] # Create a list and append to it the matched links
    for link in url_list: # Iterates through every line and looks for a match:
        if link: # I have added this to see in there are value in link.
            match += re.findall(r"https://bluesilvertranslations\.wordpress\.com/\d{4}/\d{2}/\d{2}/douluo-dalu-\d{1,3}-.*/", link) # I have changed the regex a bit since your did not match
    return match

links = 'https://bluesilvertranslations.wordpress.com/chapter-list/'

print(get_chapter_links(links))

rawDescription: "TypeError: expected string or buffer" when filtering list with regex


code:
import urlparse
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import Selector
from TOSpider.items import TOSpiderItem

class MySpider(BaseSpider):
    name = "TOSpider"
    allowed_domains = ["http://nowtoronto.com/"]
    start_urls = ["http://www.nowtoronto.com/music/listings/"]

    def parse(self, response):
        selector = Selector(response)
        listings = selector.css("div.listing-item0, div.listing-item1")

        for listing in listings:
            item = NowTorontoItem()
            for body in listing.css('span.listing-body > div.List-Body'):
                item ["eventArtist"] = body.css("span.List-Name::text").extract()
                item ["eventTitle"] = body.css("span.List-Body-Emphasis::text").extract()
                item ["eventHolder"] = body.css("span.List-Body-Strong::text").extract()
                item ["eventDetails"] = body.css("::text").extract()

            # instead of returning all items at the end,
            # you can use yield with an item in each iteration
            yield item

            # and you can also yield a Request()
            # so that scrapy enqueues a new page to fetch
            detail_url = listing.css("div.listing-readmore > a::attr(href)")
            if detail_url:
                yield Request(urlparse.urljoin(response.url,
                                               detail_url.extract()[0]),
                              callback=self.parse_details)

    def parse_details(self, response):
        selector = Selector(response)
        # and here you parse
        # ,
        # ,
        # ,
        # ,
        # ,
        # ,
        #  and  ...
        #
        # and return a item

rawDescription: Increasing the functionality of my Scrapy spider - Following internal links


code: ASCII = ''.join(chr(x) for x in range(128))

rawDescription: Is there a variable in python that holds all ASCII characters?


rawDescription: Python List of Lists vs numpy

description: Python List of Lists vs numpy


code: lesk(sent, 'be', 'v').name()

rawDescription: I am having problems doing Word Sense Disambiguation in Python using Lesk algorithm


code: hsls = np.zeros((H, W, 3), dtype=float)

rawDescription: Draw NxMx3 ndarray as image using matplotlib imshow


code:
if self.color_array is None:
     self.color_array = numpy.empty((len(activity), 4))
diff_activity = (activity - self.min) / abs_diff
self.color_array[:, :3] = (start_colors +
                           diff_activity[:, numpy.newaxis] +
                           end_colors)
self.color_array[:, 3] = 1

rawDescription: fastest way to iterate in python

description: Fastest way to iterate in python


code:
ranks = [
    {'url': 'example.com', 'rank': '11,279'},
    {'url': 'facebook.com', 'rank': '2'},
    {'url': 'google.com', 'rank': '1'}
]
from pprint import pprint
pprint(sorted(ranks, key=lambda x: int(x["rank"].replace(",", ""))))

rawDescription: How to convert dictionary values to int in Python?

description: Convert dictionary values to int in Python


rawDescription: Selective Numpy array manipulation (dependent on value)


code:
indices = np.unique(np.concatenate((indices1, indices2, indices3, indices4)))
result = tab[indices]

rawDescription: Fast duplicates removal in numpy and python


code:
# contents of outfile.txt
Sardes_xxR_SL1344_4567
Modex_polA_SGR222_3950
MOdex_uui_gytI

rawDescription: search contents of one file with contents of a second file using python

description: Search contents of one file with contents of a second file using python


code:
a = np.arange(9).reshape(3,3)
a
index = np.array([0,1,2])
b = a[index, index]
b

rawDescription: puzzled on how to slice a numpy array

description: Puzzled on how to slice a numpy array


code:
from collections import OrderedDict

def category(s):

    catdict = OrderedDict([(income, 'income'),
                          (expense, 'expense'),
                          (transfer, 'transfer'),
                          ])
    for ptn, name in catdict.iteritems():
        if ptn.search(s):
            return name
    return 'RECONCILE'

rawDescription: Create column of categories from a column of transactions using regular expressions within a dictionary


code:
from __future__ import unicode_literals

import io

import pandas as pd
from pandas.compat import string_types

def iter_fields(buf):
    for l in buf:
        yield l.rstrip('\n\r').split(':', 1)

def iter_messages(buf):
    it = iter_fields(buf)
    k, v = next(it)
    while True:
        n = int(v)
        _, v = next(it)
        date = pd.Timestamp(v)
        _, v = next(it)
        from_add, from_name, from_comp = v.split('|')[:-1]
        k, v = next(it)
        to = []
        while k == 'To':
            to_add, to_name, to_comp = v.split('|')[:-1]
            yield (n, date, from_add[1:], from_name[1:-1], from_comp,
                   to_add[1:], to_name[1:-1], to_comp)
            k, v = next(it)

    if not hasattr(filepath_or_buffer, read):
        filepath_or_buffer

def _read_email_headers(buf):
    columns=['email_message#', 'email_message_sent',
             'from_address', 'from_name', 'from_company',
             'to_address', 'to_name', 'to_company']
    return pd.DataFrame(iter_messages(buf), columns=columns)

def read_email_headers(path_or_buf):
    close_buf = False
    if isinstance(path_or_buf, string_types):
        path_or_buf = io.open(path_or_buf)
        close_buf = True
    try:
        return _read_email_headers(path_or_buf)
    finally:
        if close_buf:
            path_or_buf.close

rawDescription: Read data from text format into Python Pandas dataframe


code:
a = 0.01
df[(df['USRECQ NEXT'] == 1) & (df['GDP'] > a) & (pd.notnull(df['GDP']))]

rawDescription: Boolean Check in a Pandas DataFrame based on Criteria at different Index values


code:
@classmethod
def related_set(cls, wip):
  classes = cls.__subclasses__()
  return sum([c.objects.filter(wip=wip).all() for c in classes], [])

rawDescription: Iterating through all foreign key related children of an abstract django model


code:
import shutil
import os
screenshotsDir = "absolute-path-to-a-folder"
img = capture(some_region)
shutil.move(img, os.path.join(screenshotsDir, "some-name.png"))

rawDescription: Using Sikuli to take automated screenshots of a window?


code: {p:sum(map(lambda x:x[p],vals))/len(vals) for p in ['a','b','c']}

rawDescription: Averaging a list of dicts in Python

description: Averaging a list of dicts in Python


code:
ax = plot_rect(data)
ax.set_xlabel('Whatever')
for rect in ax.patches:
    rect.set(facecolor=(0.9,0.9,0.2,1.0), # a tuple, RGBA
          edgecolor=(0.6,0.2,0.3,1.0),
          linewidth=3.0)
plt.show()

rawDescription: Proper plot to use in matplotlib for this type of bar graph?


code: q2 = sess.query(table1, table2, table3.string_column).select_entity_from(q)

rawDescription: selecting whole entities from SQLAlchemy subqueries

description: Selecting whole entities from SQLAlchemy subqueries


code:
class Contacts:
    all_contacts = []

    def __init__(self, name, email):
       self.name = name
       self.email = email
       Contacts.all_contacts.append(self)

    def __str__(self):
       return '%s, <%s>' % (self.name, self.email)

    def __repr__(self):
        return str(self)

contact1 = Contacts("Grace1", "something1@hotmail.com")
contact2 = Contacts("Grace2", "something2@hotmail.com")
contact3 = Contacts("Grace3", "something3@hotmail.com")
print(Contacts.all_contacts)

rawDescription: How do I print this class variable?

description: Print this class variable


code:
fkeys = ['dma_targets', 'ids']
fvals = [5678, None]
d = {'profile': {k:v for (k,v) in zip(fkeys, fvals) if v is not None}}

rawDescription: Python Best Way to construct Dictionary from Inputs


rawDescription: QTableWidget how to have a cell selected for editing from code and/or with single click


code: cursor.execute("UPDATE Writers SET Name = %s WHERE Id = %s", ("Leo Tolstoy", "1"))

rawDescription: Best way of gluing strings in Python to compose SQL query


code:
import threading
iid = 1
iid_lock = threading.Lock()

def next_id():
    global iid
    with iid_lock:
        result = iid
        iid += 1
    return result

rawDescription: Python - Global counter

description: Python - Global counter


code:
class Tile:
    def __init__(self, val):
        # here paste the code making Tile object out of other objects,
        # possibly checking their types in the process
        pass

rawDescription: Type casting with non standard types in python


code:
re = []
for ml in key:
    value = myDict.get(ml, "not found")
    re.append(value)
return '-'.join(re)

rawDescription: python - return and print does not give same result

description: Python - return and print does not give same result


code: decrypt = open("crypt.txt").read()

rawDescription: stripping away code in python using "re.sub"

description: Stripping away code in python using "re.sub"


code: tempBoard = genBoard

rawDescription: Generate list of possible moves Python Tic-Tac-Toe


code:
out = np.zeros_like(x)
sum_function(A, x, n, out)
out

rawDescription: How can I efficiently use numpy to carry out iterated summation

description: Efficiently use numpy to carry out iterated summation


rawDescription: How to return a single row for rows that have duplicate values in Pandas

description: Return a single row for rows that have duplicate values in Pandas


code: df = df.reset_index()

rawDescription: Pandas: transforming the DataFrameGroupBy object to desired format


code:
class Base(object):
    def __init__(self, *args, **kw):
        for k,v in zip(self.__slots__, args):
            setattr(self, k, v)

        for k,v in kw.items():
            setattr(self, k, v)

class ChildA(Base):
    __slots__ = 'a', 'b', 'c'

class ChildB(Base):
    __slots__ = 'x', 'y', 'z'

rawDescription: A Common constructor in Python

description: A Common constructor in Python


code: r.config.store_json_result = True

rawDescription: PRAW: serializing Comment and Submission objects as JSON


code:
import re

test_string = '44MB\n12b\n6GB\n12pb'

regex = re.compile(r'(\d+)\s*([kmgtp]?b)', re.IGNORECASE)

order = ['b', 'kb', 'mb', 'gb', 'tb', 'pb']

for value, unit in regex.findall(test_string):
    print(int(value) * (1024**order.index(unit.lower())))

rawDescription: Extract Numbers and Size Information (KB, MB, etc) from a String in Python


code: global count

rawDescription: Passing list (stack) in backtracing in python


code: arduino.write('%d' % 5)

rawDescription: PySerial communication with variables

description: PySerial communication with variables


code:
if condition1:
    statement
elif condition2:
    statement
elif condition2:
    statement
else:
    statement

rawDescription: Conditional Statement in python

description: Conditional Statement in python


rawDescription: pandas looking at next row and swapping values

description: Pandas looking at next row and swapping values


code:
def my_decorator(a):
    def wrapper(f):
        def wrapped_function():
            return f() + a
        return wrapped_function
    return wrapper

rawDescription: Why are Python decorators with arguments syntactically different from those without?


code: dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }

rawDescription: Filter dict to contain only certain keys?


rawDescription: Count of specific case per row in matrix


code:
class Note(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value
class Item(object):
    def __init__(self, name, description=''):
        self.name = name
        self.description = description
    notes = association_proxy('_notesdict', 'value', creator=Note)

rawDescription: SQLAlchemy - Dictionary of tags

description: SQLAlchemy - Dictionary of tags


rawDescription: Using Python List Comprehension to match values that exist in a 2d array and simple list


code:
import itertools
for k, grp in itertools.groupby(tempsorted, key=lambda x: x.oscis):
    summedodmcas = 0
    summedodmnj = 0
    for li in grp:
        summedodmcas += li.odmcas
        summedodmnj += li.odmnj
    print(li.oscis, li.cicin, li.zapl, li.odmdr, summedodmcas, summedodmnj, li.odmzak)

rawDescription: Sum array objects by array object key

description: Sum array objects by array object key


code:
import datetime
b = B([datetime.date(2012, 1, 1), datetime.date(2012, 2, 2), datetime.date(2012, 3, 3)])
list(b.month)

rawDescription: Get attribute of all items in container python


code:
import re
ref = re.compile(u'<ref.*?ref>', re.DOTALL)

ref.sub(u'', yourtext)

rawDescription: How can I remove a substring, given a start and end token, in python?

description: Remove a substring, given a start and end token, in python


code:
ref_dict = {'field1': 'a', 'field2': 'b', 'field3': 'c'}
def update(field, value):
    globals()[ref_dict[field]] = value

rawDescription: python reference to a float, int, etc

description: Python reference to a float, int, etc


code: tableau = [extract(data) for data in data_list]

rawDescription: How to use "While()" in python

description: Use "While()" in python


code: [''.join(x) for x in zip(*[iter(a)]*3)]

rawDescription: Python - How to add space on each 3 characters?


code:
numpy.dot(A,B)
51

rawDescription: multiplying two nparray together python

description: Multiplying two nparray together python


code:
class LineFactory:
    class Line:
        def __init__(self, a, b, noSlope):
            self.a = a
            self.b = b
            self.noSlope = noSlope

    @staticmethod
    def fromPoints(point1, point2):
        deltaX = point2[0] - point1[0]
        deltaY = point2[1] - point1[1]
        if deltaX == 0:
            return LineFactory.Line(point1[0], 0, True)
        else:
            a = deltaY / deltaX
            b = point1[1] - a * point1[0]
            return LineFactory.Line(a, b, False)

    @staticmethod
    def fromVector(vector, point):
        if vector[0] == 0:
            return LineFactory.Line(point1[0], 0, True)
        else:
            a = vector[1] / vector[0]
            b = point1[1] - a * point1[0]
            return LineFactory.Line(a, b, False)

# Create line
line = LineFactory.fromPoints((0,0), (1,1))

rawDescription: Best practice to implement multiple contructors in python


code:
def update_slug(mapper, connection, target):
    target.slug = slugify(target.name)
    if target.name_en:
        target.slug_en = slugify(target.name_en)

event.listen(Post, 'before_insert', update_slug_with_date)
event.listen(Post, 'before_update', update_slug_with_date)

rawDescription: How to bind event on create of object in SqlAlchemy?

description: Bind event on create of object in SqlAlchemy


code:
def dosomething(event):
    """
    on enter, capture the value from the Listbox
    and assign the value captured to value via the get method form the selected value
    """
    try:
        selection = listnotes.curselection()
        value = listnotes.get(selection[0])

    except Exception as select:
        print("Nothing selected")
        pass

rawDescription: selecting an item from listbox and using the name of the item later

description: Selecting an item from listbox and using the name of the item later


code:
data=[{'title': 'title_text #49', 'x':0},
      {'title':'title_text #5', 'x':10},
      {'title': 'title_text #50','x':20}]

data.sort(key=lambda x: alphanum_key(x['title']))
# [{'x': 10, 'title': 'title_text #5'}, {'x': 0, 'title': 'title_text #49'}, {'x': 20, 'title': 'title_text #50'}]

rawDescription: Sorting dicts (contained in lists) alphanumerically in Python


code:
import datetime
now = datetime.datetime.now()
now.microsecond

rawDescription: time series in python up to microseconds

description: Time series in python up to microseconds


rawDescription: Values Not Adding Up

description: Values Not Adding Up


code:
from tokenize import NAME, INDENT, DEDENT, ENDMARKER, NEWLINE, generate_tokens
from xml.etree import ElementTree as etree

def parse(file, TreeBuilder=etree.TreeBuilder):
    tb = TreeBuilder()
    tb.start('ul', {})
    for type_, text, start, end, line in generate_tokens(file.readline):
        if type_ == NAME: # convert name to <li> item
            tb.start('li', {})
            tb.data(text)
            tb.end('li')
        elif type_ == NEWLINE:
            continue
        elif type_ == INDENT: # start <ul>
            tb.start('ul', {})
        elif type_ == DEDENT: # end </ul>
            tb.end('ul')
        elif type_ == ENDMARKER: # done
            tb.end('ul') # end parent list
            break
        else: # unexpected token
            assert 0, (type_, text, start, end, line)
    return tb.close() # return root element

rawDescription: Convert tabbed text to html unordered list?


rawDescription: Subsetting DataFrame using ix in Python

description: Subsetting DataFrame using ix in Python


rawDescription: Adding a Method to an Existing Object Instance


code: [''.join(t) for t in list_of_tuples]

rawDescription: Extract a 2-element tuple and convert it to String


code:
import A

var = A.something().foo

rawDescription: Python within python

description: Python within python


code:
a = MyClass().method()
someFunc(a)

rawDescription: Any method to denote object assignment?

description: Any method to denote object assignment


rawDescription: Generate list of numbers in specific format


code:
from math import sin, cos, acos, radians, degrees
from unittest import assertAlmostEqual

def assertAlmostEqualAngles(x, y, **kwargs):
    x,y = radians(x),radians(y)
    c2 = (sin(x)-sin(y))**2 + (cos(x)-cos(y))**2
    angle_diff = degrees(acos((2.0 - c2)/2.0))
    assertAlmostEqual(angle_diff, 0.0, **kwargs)

rawDescription: Python unittesting: Test whether two angles are almost equal


code:
import csv
import random

def select_n_random(n):
    fin = open('emails.csv', 'r+')
    reader = csv.reader(fin)
    email_list = list(reader)[0]
    output_list = []
    for i in range(n):
        idx = random.randint(0, len(email_list)-1)
        output_list.append(email_list.pop(idx))

    fout = open('email_output.csv', 'wb')
    writer = csv.writer(fout, quoting=csv.QUOTE_NONE)
    writer.writerow(output_list)

    fout.close()
    fin.close()

    # reopen original file and remove the randomly selected emails
    fin = open('emails.csv', 'w')
    writer = csv.writer(fin, quoting=csv.QUOTE_NONE)
    writer.writerow(email_list)
    fin.close()

select_n_random(10)

rawDescription: Random Email Picker of Size n

description: Random Email Picker of Size n


code:
subj = 'abc123 bbb22 cc'
rgx = re.compile(r'[a-z]+(\d+)?')
result = [i for i in re.findall(rgx, subj) if i]
for match in result:
    print (match)

rawDescription: Testing not-empty Group captures

description: Testing not-empty Group captures


code:
class States(object):
    ALABAMA = "AL"
    FLORIDA = "FL"

    @classmethod
    def is_state(cls, to_find):
        print(vars(cls))
        states = [val for key, val in vars(cls).items()
                  if not key.startswith("__")
                  and isinstance(val, str)]
        return to_find in states

States.is_state("AL") # True
States.is_state("FL") # True
States.is_state("is_state") # False
States.is_state("__module__") # False

rawDescription: Checking if a variable belongs to a class in python


rawDescription: How do I specify "%-*s" in new-style .format()?

description: Specify "%-*s" in new-style .format()


code: word_list = words_str.split(" ")

rawDescription: Map reduce problem in python

description: Map reduce problem in python


code:
import wx
class MyFrame(wx.Frame):
    def __init__(self,items):
        wx.Frame.__init__(self,None,-1,"Demo")
        self.start_y = 25
        self.my_items,self.my_prices = [],[]
        for i,(iName,iPrice) in enumerate(items):
            self.my_items.append(wx.StaticText(self,-1,iName,pos=(50,self.start_y+50*i)))
            self.my_prices.append(wx.StaticText(self,-1,str(iPrice),pos=(90,self.start_y+50*i)))
        btn = wx.Button(self,-1,"Next Items")
        btn.Bind(wx.EVT_BUTTON,self.OnNext)

    def OnNext(self,evt):
        for t1,t2 in zip(self.my_items,self.my_prices):
            t1.Destroy()
            t2.Destroy()
        self.my_items,self.my_prices = [],[]
        items = itemSets.pop(0)
        for i,(iName,iPrice) in enumerate(items):
            self.my_items.append(wx.StaticText(self,-1,iName,pos=(50,self.start_y+50*i)))
            self.my_prices.append(wx.StaticText(self,-1,str(iPrice),pos=(90,self.start_y+50*i)))
        itemSets.append(items)

itemSets = [
    [("item1",25),("item2",35),("item3",55)],
    [("item3",44),("item4",65),("item5",75)],
    [("item5",66),("item6",78),("item7",93)],
]
a = wx.App(redirect=None)
f = MyFrame([("ItemA",33),("ItemB",44),("ItemC",66)])
f.Show()
a.MainLoop()

rawDescription: How to update wxStatic Text in wxpython?

description: Update wxStatic Text in wxpython


code:
from ctypes import *
windll.kernel32.GetModuleHandleW(0)

rawDescription: Python import dll

description: Python import dll


rawDescription: Python, neighbors on a regular grid

description: Python, neighbors on a regular grid


rawDescription: print a tensor variable

description: Print a tensor variable


code:
def myindex(lst, target):
    for index, item in enumerate(lst):
        if item == target:
            return [index]
        if isinstance(item, str): # or 'basestring' in 2.x
            return []
        try:
            path = myindex(item, target)
        except TypeError:
            pass
        else:
            if path:
                return [index] + path
    return []

rawDescription: Find index of nested item in python

description: Find index of nested item in python


code:
from sqlalchemy.ext.hybrid import hybrid_property

_missing = object()   # sentinel object for missing values

class cached_hybrid_property(hybrid_property):
    def __get__(self, instance, owner):
        if instance is None:
            # getting the property for the class
            return self.expr(owner)
        else:
            # getting the property for an instance
            name = self.fget.__name__
            value = instance.__dict__.get(name, _missing)
            if value is _missing:
                value = self.fget(instance)
                instance.__dict__[name] = value
            return value

class Example(object):
    @cached_hybrid_property
    def foo(self):
        return "expensive calculations"

rawDescription: How to combine SQLAlchemy's @hybrid_property decorator with Werkzeug's cached_property decorator?

description: Combine SQLAlchemy's @hybrid_property decorator with Werkzeug's cached_property decorator


code: Value1 if Condition else Value2

rawDescription: Conditional calculation in python

description: Conditional calculation in python


rawDescription: Prevent a file from being opened

description: Prevent a file from being opened


code:
docs=[]
with open("data1.txt") as f:
    lines=f.read().split("<NEW DOCUMENT>")[1:]
    for x in lines:
        docs.append(x.strip())
    print (docs)
search = input("Enter search words: ")
for x in docs:
    if search in x:
        print ("{} found in:\t {}".format(search,x))

rawDescription: document search and retrieval from external file in python

description: Document search and retrieval from external file in python


code:
list = ['a','b','c','d','e', 'a', 'd', 'e', 'c']
wanted = ['a', 'c', 'e' ]
[x for x in list if x in wanted]

rawDescription: Keeping some of the elements in a list

description: Keeping some of the elements in a list


code: from time import time

rawDescription: Python: Generate a date time string that I can use in for MySQL


rawDescription: Create a Tuple from text file

description: Create a Tuple from text file


code: x = list(someiter)

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


code:
with open('newfoo.py', 'wb') as f:
    for name, value in foo.__dict__.items():
        if ast.literal_eval(repr(value)) != value:
            raise ValueError('Tried to save {}'.format(value))
        f.write('{} = {!r}\n'.format(name, value))

rawDescription: Exporting a python module (to string or py file)


rawDescription: Python string.replace() not replacing characters


code: results + get_nodes(items=item.children, ages=ages, results=results)

rawDescription: python - return flat list of objects from recursive function

description: Python - return flat list of objects from recursive function


code: ('filmgroup', 'John Smith')

rawDescription: xmlns namespace breaking lxml

description: Xmlns namespace breaking lxml


code:
import copy
d2 = copy.deepcopy(docsite)

rawDescription: Python Dictionary in Dictionary

description: Python Dictionary in Dictionary


code:
for client in filter(shouldrecieve, all_clients):
    client.send(data)

rawDescription: How can i send a packet to some users in python?

description: Send a packet to some users in python


code: (item.pk, item.__unicode__())

rawDescription: Use method other than __unicode__ in ModelChoiceField Django


code:
A = tf.constant([[1, 1], [2, 2], [3, 3]])
r = tf.reduce_sum(A*A, 1)

# turn r into column vector
r = tf.reshape(r, [-1, 1])
D = r - 2*tf.matmul(A, tf.transpose(A)) + tf.transpose(r)
sess = tf.Session()
sess.run(D)

rawDescription: Compute pairwise distance in a batch without replicating tensor in Tensorflow?


rawDescription: Adding an attribute to a list

description: Adding an attribute to a list


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

driver = webdriver.Chrome()  # or webdriver.Firefox()
driver.get('http://www.starwoodhotels.com/sheraton/property/reviews/index.html?propertyID=115&language=en_US')

# wait for the reviews to load
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "span.BVRRReviewText")))

# get reviews
for review_div in driver.find_elements_by_css_selector("span.BVRRReviewText"):
    print(review_div.text)
    print("---")

driver.close()

rawDescription: Unable to get actual Markup from a page with BeautifulSoup


code:
from collections import defaultdict
import re

myarch = 'C:/code/test5.txt'   #this is your archive
mydict = defaultdict(int)

with open(myarch) as f:
    for line in f:
        codes = re.findall("\'(\S*)\'", line)
        for key in codes:
            mydict[key] +=1

out = []
for key, value in mydict.iteritems():
    if value > 1:
        text = "['%s'], %s" % (key, value)
        out.append(text)

#save to a file
with open('C:/code/fileout.txt', 'w') as fo:
    fo.write('\n'.join(out))

rawDescription: Lists in text file

description: Lists in text file


code:
class RedirectText(object):
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

rawDescription: Read a command prompt output in a separate window in python


code: min(list,key=func)

rawDescription: max() function: how to get the item being iterated and pass to key=func()

description: Max() function: how to get the item being iterated and pass to key=func()


code:
df
df.dtypes
df.sort_values(["ID", "time"])

rawDescription: Sort grouped dataframe based on the time variable colum


code:
if (data > 0).all():
    renormed += 1

renormed.mean(), renormed.std()

rawDescription: How should the values of a list be scaled such that they meet standard deviation and mean requirements?


code:
class myWidget(QWidget):

    def __init__(self):
        super().__init__()

        self.myLay = QVBoxLayout()
        self.setLayout(self.myLay)

        # Notice self is being passed in to set the parent
        self.mySlider = QSlider(Qt.Horizontal, self)

        # You need to add widgets to a layout to position them properly
        self.myLay.addWidget(self.mySlider)

rawDescription: PyQt5 add custom QWidget to QLayout

description: PyQt5 add custom QWidget to QLayout


code:
import numpy as np

x = range(10)
y = range(10)

ticks = [ctime(1), ctime(2), ctime(3)]
xtickpos = np.linspace(min(x), max(x), 3)

plt.plot(x,y)
plt.xticks(xtickpos, ticks)

rawDescription: My xticks are pushed to the left

description: My xticks are pushed to the left


code:
class NestedTuples:
    def __init__(self, num):
        self.tuple = tuple((x, []) for x in range(num))
t = NestedTuples(4)
t.tuple

rawDescription: Initializes a class with n-nested tuples


code:
import numpy as np
fd = open('flight0000.raw', 'rb')
rows = 480
cols = 640
f = np.fromfile(fd, dtype=np.uint8,count=rows*cols)
im = f.reshape((rows, cols)) #notice row, column format
fd.close()

rawDescription: Opencv Python display raw image

description: Opencv Python display raw image


code:
from haystack.constants import DEFAULT_ALIAS
from haystack import connections
class TokenSearchForm(SearchForm):
    def prepare_tokens(self):
        try:
            query = self.cleaned_data.get('q')
        except:
            return {}
        opts = connections[DEFAULT_ALIAS].get_unified_index().fields.keys()
        kwargs = {}
        query_text = []
        for word in query.split(" "):
            if ":" in word:
                opt,arg = word.split(":",1)
                if opt in opts:
                    kwargs[str(opt)]=arg
            else:
                query_text.append(word)
        self.query_text = " ".join(query_text)
        self.kwargs = kwargs
        return kwargs

    def search(self):
        self.query_text = None
        kwargs = self.prepare_tokens()
        if not self.is_valid():
            return self.no_query_found()

        if not self.cleaned_data.get('q'):
            return self.no_query_found()

        sqs = self.searchqueryset.auto_query(self.query_text)

        if kwargs:
            sqs = sqs.filter(**kwargs)

        if self.load_all:
            sqs = sqs.load_all()

        return sqs

rawDescription: Using "google-like" colon-search operator with Haystack


code:
results == {'Contact': ' Angha Mitra',
            'Purpose': ' Economics and Finance, Micro-enterprises',
            'Email': ' a.mitra1@lse.ac.uk'}

rawDescription: Extract data from a site using python

description: Extract data from a site using python


code:
line = s[i]
idx = line.find(pattern)
if idx >= 0:
    end = idx+len(pattern)
    selection.append(line[end:end+5])

rawDescription: Selecting item in a string from a starting point retrieved via regex (Python)


code:
a = np.arange(6).reshape(2, 3)
b = np.zeros((3, 2, 3))
a
b

rawDescription: copy numpy array efficiently

description: Copy numpy array efficiently


code:
class defaultdict(dict):
    # default_factory is a function which supplies the default value when a key is not found
    def __init__(self, default_factory):
        self.default_factory = default_factory

    def __getitem__(self, key):
        if key in self:
            # the super() call works here because we are
            # subclassing dict, which supports __getitem__
            return super().__getitem__(key)
        if self.default_factory is not None:
            val = self.default_factory(key)
            self[key] = val
            return val
        raise KeyError(key)

rawDescription: proper way to subclass object for __getitem__() in python if emulating a dict

description: Proper way to subclass object for __getitem__() in python if emulating a dict


code:
path = os.path.dirname(getBundlePath())
directory = os.listdir(path)
for file in directory:
    print(file)

rawDescription: Return the file path of the file, not the current directory


rawDescription: Mix two arrays. Simple. Python

description: Mix two arrays. Simple. Python


rawDescription: Pandas select and write rows that contain certain text


code:
from delayed import delayed
del_list = delayed(lambda: [1,2,3,4,5])
# At this point the lambda function has not been called
print(del_list[0])
# Now that we have used the variable, the lambda has been called

rawDescription: Delay load/calculate values in Python

description: Delay load/calculate values in Python


code:
def print_with_context (diff, context = 3):
    buf = []
    print_more = 0

    for line in diff:
        if line.startswith('-') or line.startswith('+'):
            if len(buf) > context:
                print('...')
            print('\n'.join(buf[-context:]))
            buf = []
            print_more = context
            print(line)
        elif print_more:
            print(line)
            print_more -= 1
            if print_more == 0:
                print('...')
        else:
            buf.append(line)

rawDescription: How to display the List diff with out the common lines in python?

description: Display the List diff with out the common lines in python


code:
import inspect
foo = lambda x, y, z: x + y + z
inspect.signature(foo).parameters

rawDescription: Determining the number of parameters in a lambda


code: re.findall(r'ABC\s*(\d+)', 'Some text with ABC 98765. There is some other text too, with ABC 55555<!')

rawDescription: Finding first non-digit character with .find in Python


code:
import json, gzip
s = b"""\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00\xabVJ\xceOIU\xb2\xaaV*K\xcc)\x052\x94\xcc\x95t\x94\xe2\xf3\x12sA\xec\x10\x7foW?\xa5Z\x1d\xa5\x94\xc4\x92D\x90\xa2\x82\xc4"\xa0LIjQ\xb1\x92U^iN\x8e\x8eRI~vj\x1eP\xa9\xae\x99\xb1\xa1\xa1\xa9\xb9\x85\x91\xa5\x89\x99\xb9\x81\x99\xb9\x99\x89\xa5)\xd0\xa4\xd2\xa2\x1c\x88J\xa0!\xb9\xa9\xc5\xc5\x89\xe9\xa90\x9dP.\xd4\xa4Z\x00\x94\x8a\xf6\xe1\x8a\x00\x00\x00"""
with gzip.GzipFile(fileobj=io.BytesIO(s)) as gz:
    json.loads(gz.read().decode('utf-8'))

rawDescription: Unknown response encoding: gathered by urequest.urlopen()


code:
from flask import Flask, send_from_directory
import os

BASE_URL = os.path.abspath(os.path.dirname(__file__))
CLIENT_APP_FOLDER = os.path.join(BASE_URL, "ClientApp")

# This is required by zone.js as it need to access the
# "main.js" file in the "ClientApp\app" folder which it
# does by accessing "<your-site-path>/app/main.js"
@app.route('/app/<path:filename>')
def client_app_app_folder(filename):
    return send_from_directory(os.path.join(CLIENT_APP_FOLDER, "app"), filename)

# Custom static data
@app.route('/client-app/<path:filename>')
def client_app_folder(filename):
    return send_from_directory(CLIENT_APP_FOLDER, filename)

rawDescription: how to combine angular2 with jinja2 templates and flask

description: Combine angular2 with jinja2 templates and flask


rawDescription: Efficiently grouping the rows of a Pandas DataFrame by the value of a column?


code:
for test_string in ["doc", "pdf", "xls", "jpg"]:
    if test_string in text:
        break
else:
    filtered.append(text)

rawDescription: Python Logic in searching String

description: Python Logic in searching String


rawDescription: How can I save output tho the same file that I have got the data from, in Python 3

description: Save output tho the same file that I have got the data from, in Python 3


code: from mymodule import Popen

rawDescription: extending subprocess.Popen through inheritence

description: Extending subprocess.Popen through inheritence


code:
import os
os.unlink("infile")
os.rename("infile.2", "infile")

rawDescription: adding string at the end of the file python

description: Adding string at the end of the file python


code:
if int(vsdir[-4:]) < 2010:
    print("yeh, less tha 2010")
else:
    print("greater than 2010")

rawDescription: convert char to int using regular expression

description: Convert char to int using regular expression


code:
# create new post
@app.route('/admin/post', methods=['GET', 'POST'])
@login_required  # required for Flask-Security
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data, pub_date=form.pub_date.data,
                    body=form.body.data, category=form.category.data)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been published.')
        return redirect(url_for('admin'))
    posts = Post.query.all()
    return render_template('create_post.html', form=form, posts=posts)

rawDescription: A Complete Many-to-One Example Using Flask, WTForm, SQLAlchemy, and Jinja2


rawDescription: Logical OR on a subset of columns in a DataFrame


code:
import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

rawDescription: Find a file in python

description: Find a file in python


code: [n.split()[3] for n in lines]

rawDescription: How to generate an array/list from an output using .split() in Python 2.6

description: Generate an array/list from an output using .split() in Python 2.6


code:
for w in issuer:
    print(w)
    df.loc[df.issuer.str.contains(w).fillna(False), "website"] = issuer[w]

rawDescription: Key to Value to Key in Python Dictionary


code:
print(ud.name(combined_astr))
# LATIN SMALL LETTER E WITH ACUTE

rawDescription: Precompose Unicode Character Sequences in Python


code: rewards = Reward.objects.all()

rawDescription: Using dehydrate in Tastypie to return all objects


rawDescription: Python: creating customer sort method & loop stops before list sorted


rawDescription: insert dictionaries to a dictionary in Python

description: Insert dictionaries to a dictionary in Python


rawDescription: Using AJAX to execute Python Django Script


rawDescription: How to operate on list of data frame in one instruction

description: Operate on list of data frame in one instruction


code: next_line = string.readline(+2)

rawDescription: Chunk long string into 513 character chunks | Python 3.3


rawDescription: Mercurial's showconfig with the proper encoding?


code:
def most_ambiguous_words(words, n):
  # wordsUniqeTags holds a list of uniqe tags that have been observed for a given word
  wordsUniqeTags = {}
  for (w,t) in words:
    wordsUniqeTags.setdefault(w, set()).add(t)
  # Starting to count
  return [(word,tags) for word,tags in wordsUniqeTags.iteritems() if len(tags) >= n]

rawDescription: Is that a tag list or something else?

description: Is that a tag list or something else


rawDescription: Adding '-' into string in dataframe

description: Adding '-' into string in dataframe


rawDescription: How do you set the column width on a QTreeView?

description: Set the column width on a QTreeView


rawDescription: Count Number of Rows Between Two Dates BY ID in a Pandas GroupBy Dataframe


code:
while c:
    c = f.read(1)
    if c.isdigit():
        myList.append(c)

rawDescription: Checking if characters in a file can be integers


code:
from itertools import izip_longest
[x + y for x, y in grouper(2,q)]

rawDescription: List comprehension with multiple variables


code:
label.grid( row=0, column=0, sticky="ne")
label2.grid(row=1, column=0, sticky="ne")
label3.grid(row=2, column=0, sticky="ne")

nameentry.grid(   row=0, column=1, sticky="nsew")
addressentry.grid(row=1, column=1, sticky="nsew")
numberentry.grid( row=2, column=1, sticky="nsew")

rawDescription: Python using Tkinter moving Labels and Entry boxes


code:
class Deck(object):

    def __init__(self, suits='CSHD', ranks='23456789TJQKA'):
        self.cards = [''.join(card) for card in itertools.product(ranks, suits)]

    def shuffle(self):
        random.shuffle(self.cards)

    def deal_cards(self, hand, count=1):
        for _ in range(count):
            hand.append(self.cards.pop())

    def return_cards(self, hand):
        self.cards.extend(hand)

rawDescription: Deck of cards, dealing alternately

description: Deck of cards, dealing alternately


code:
for r in records:
    d[r[0]] = d.get(r[0], 0) + r[1]

rawDescription: How to update the values in a dict cleanly?

description: Update the values in a dict cleanly


code:
def download_and_save_the_file(some_url):
    thestring = requests.get(some_url).content
    #Make sure you create unique names
    something = unique_filename(some_url)
    file_ref = open(something)
    fileref.write(the_string)
    fileref.close()

rawDescription: Threading or Multiprocessing

description: Threading or Multiprocessing


rawDescription: How do I remove hex values in a python string with regular expressions?

description: Remove hex values in a python string with regular expressions


code:
import random
words = ["Please", "Help", "Me", "Merry", "Christmas"]
random.sample(words, len(words))

rawDescription: Print a list of words in random order - Python


code:
@app.route('/login', methods=['POST'])
def login():
    error = None
    if request.method == 'POST':
        # post data: cGFzc3dvcmQ9ZGVmYXVsdCZlbWFpbD10ZXN0JTQwZXhhbXBsZS5jb20=
        data = b64decode(request.data)
        # decoded data: password=default&email=test%40example.com
        if not data:
            data = b64decode(request.form.keys()[0])
        special_mimetype = request.mimetype
        return(special_mimetype + '\n' + data)

rawDescription: Force Content-Type or expose request.data in Flask for known content-type


rawDescription: Python Iterate over range starting with variable (i,20)


code:
ARRAY_MACHINE= ['machine1', 'machine2', 'machine3']
print('The machines are {}'.format(', '.join(ARRAY_MACHINE)))
ARRAY_MACHINE= ['machine1', 'machine2']
print('The machines are {}'.format(', '.join(ARRAY_MACHINE)))

rawDescription: print out the pattern in an array in python

description: Print out the pattern in an array in python


code:
from itertools import permutations
x = ['0', '1']
y = 2
set(permutations(x * 2))

rawDescription: Python permutations of x unique characters repeated y times each


code:
import csv
large = [('5501', [(4, 5, 8), (6, -4, -6)]), ('2222', [(2, -4, 5), (1, 15, -4)])]

with open("out1.csv", "wb") as fp: # open the file, call it fp, and autoclose it
    writer = csv.writer(fp, delimiter=",")
    for entry in large:
        writer.writerow([entry[0]]) # one-element list
        for line in entry[1]: # loop over each tuple in the second element
            writer.writerow(line)
        writer.writerow([]) # write an empty row

rawDescription: Exporting a non-ideal list format to Excel


code:
import types

isinstance(getattr(klass, methodName), types.MethodType)

rawDescription: How to know if a member of a class is a method?

description: Know if a member of a class is a method


rawDescription: How can i get a log system similar with appengine(GAE) in django?

description: Get a log system similar with appengine(GAE) in django


code: game(zoomin, greedy, board)

rawDescription: Python 3 Passing a Function into Another Function


rawDescription: DJANGO: how to create a web query form?

description: DJANGO: how to create a web query form


rawDescription: Python match raw HTTP POST data

description: Python match raw HTTP POST data


code:
from subprocess import check_output

def merge(inputs, output, grid='2x2'):
    return check_output(['pdfjam'] + inputs + ['--nup', grid, '--outfile', output])

files = ['1.pdf', '2.pdf', '3.pdf', '4.pdf', '1.pdf', '2.pdf', '3.pdf', '4.pdf']
merge(files, 'top.pdf', '4x2')

files = ['1.pdf', '2.pdf', '3.pdf', '4.pdf', '5.pdf', '6.pdf', '1.pdf', '2.pdf',
    '3.pdf', '4.pdf', '5.pdf', '6.pdf']
merge(files, 'bottom.pdf', '2x6')

merge(['top.pdf', 'bottom.pdf'], 'final.pdf', '1x2')

rawDescription: PyPdf Merge error

description: PyPdf Merge error


code:
res = iter(self.results)  # get an iterator for the list values
next(res)  # iterate once to throw away first value
for number in res:
    # same code you already have goes here
    ...

rawDescription: What's causing the 135k/sec page faults in this python code? (trial-division prime sieve)


code:
sp_mat[:,1].getnnz()
# 1

rawDescription: Check Density of a Scipy Sparse Matrix

description: Check Density of a Scipy Sparse Matrix


code:
from collections import defaultdict
d = defaultdict(dict)
'foo' in d
d['foo']
'foo' in d

rawDescription: Python's collections.defaultdict returns default value correctly unless the key isn't referenced first


code:
import os
import urllib.parse as urlparse
from redis import Redis
from rq import Worker, Queue, Connection

listen = ['high', 'default', 'low']

redis_url = os.getenv('REDISTOGO_URL')
if not redis_url:
    raise RuntimeError('Set up Redis To Go first.')

urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)

with Connection(conn):
    worker = Worker(map(Queue, listen))
    worker.work()

rawDescription: How to execute function after returning Flask response (hosted on Heroku)?

description: Execute function after returning Flask response (hosted on Heroku)


code:
s = pd.Series([False, False, True, False, False, False, True, True])
s
s | s.shift(-1)
s.index[s | s.shift(-1)]

rawDescription: Finding False-True and True-True row indices


code:
def fetch_connected_nodes(G, node, seen = None):
    if seen == None:
        seen = set([node])
    for neighbor in G.neighbors(node):
        print(neighbor)
        if neighbor not in seen:
            seen.add(neighbor)
            fetch_connected_nodes(G, neighbor, seen)
    return seen

rawDescription: Fetch connected nodes in a NetworkX graph


code:
from collections import namedtuple

foo = namedtuple('foo', ('bar', 'baz'))

rawDescription: How to protect class attributes in Python?

description: Protect class attributes in Python


rawDescription: How to add two list up in alternate positions? - python

description: Add two list up in alternate positions? - python


value: three

value: two

value: one

rawDescription: How do I compare multiple key values from a list of dictionaries?

description: Compare multiple key values from a list of dictionaries


code:
import math
def distance(p1, p2):
    return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)

rawDescription: Shortest distance between one point and a group of others?


code:
from PySide import QtGui, QtCore
app = QtGui.QApplication([])

buttonBox = QtGui.QDialogButtonBox()
buttonBox.setOrientation(QtCore.Qt.Horizontal)
buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel)
buttonBox.layout().setDirection(QtGui.QBoxLayout.RightToLeft) # with this line the order of the buttons swap

buttonBox.show()
app.exec_()

rawDescription: PyQt4: Reorder Ok and Cancel buttons in the QDialogButtonBox


code:
def test():
    output = False
    exec('output=True')
    print(output)

test()
test()

rawDescription: One-liner to set a variable value with signal handler function in response to a signal from GUI?


code:
def main(sc):
    sc.nodelay(1)

    while True:
        sc.addstr(1, 1, time.strftime("%H:%M:%S"))
        sc.refresh()

        if sc.getch() == ord('q'):
            break

        #time.sleep(1) <------

rawDescription: Python3 + Curses: How to press "q" for ending program immediately?


code:
def random_insert_seq(lst, seq):
    insert_locations = sample(xrange(len(lst) + len(seq)), len(seq))
    inserts = dict(zip(insert_locations, seq))
    input = iter(lst)
    lst[:] = [inserts[pos] if pos in inserts else next(input)
        for pos in xrange(len(lst) + len(seq))]

rawDescription: Python | How to append elements to a list randomly


code:
from collections.abc import Iterator

class SequenceIterator(Iterator):

    def __init__(self, seq):
        self.seq = seq
        self.idx = 0

    def __next__(self):
        try:
            ret = self.seq[self.idx]
        except IndexError:
            raise StopIteration
        else:
            self.idx += 1
            return ret

    def seek(self, offset):
        self.idx += offset

rawDescription: Readable, controllable iterators?

description: Readable, controllable iterators


rawDescription: Regarding ascii and python packing

description: Regarding ascii and python packing


code:
class TypeAwareManager(models.Manager):
    def __init__(self, type, *args, **kwargs):
        super(TypeAwareManager, self).__init__(*args, **kwargs)
        self.type = type

    def get_query_set(self):
        return super(TypeAwareManager, self).get_query_set().filter(
              type = self.type)

class Dog(Animal):
    objects = TypeAwareManager('dog')
    ...

class Cat(Animal):
    objects = TypeAwareManager('cat')
    ...

rawDescription: using django, how do i construct a proxy object instance from a superclass object instance?

description: Using django, how do i construct a proxy object instance from a superclass object instance


code:
def with_loop2(l):
    x_max = float('+inf')
    x_min = float('-inf')
    for el in l:
        x_min = min(x_min, el)
        x_max = max(x_max, el)
    return x_min, x_max
timeit.timeit('with_loop2(range(6000000))', 'from __main__ import with_loop2', number=5)

rawDescription: List Comprehensions in Python to compute minimum and maximum values of a list


code:
from cStringIO import StringIO
import csv
f = StringIO()
writer = csv.writer(f, delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')
writer.writerow(['{"user.CustomAttribute.ISOLanguageCode": "en"}'])
f.getvalue()

rawDescription: python csv writer is adding quotes when not needed

description: Python csv writer is adding quotes when not needed


code: from module1 import A

rawDescription: How to import part of a module in python?

description: Import part of a module in python


code:
from itertools import groupby
a = [1,2,2,3]
[k for k, v in groupby(a)]

rawDescription: How to have adjacent elements reduced to a single element

description: Have adjacent elements reduced to a single element


rawDescription: Why there is a "array" in the result of split? (Python)


code:
common_columns = df1.columns.union(df2.columns)

df1 = df1.reindex(columns=common_columns, fill_value='W4L')
df2 = df2.reindex(columns=common_columns, fill_value='W4L')

pd.concat([df1, df2])

rawDescription: when combining pandas dataframe (concat or append) can I set the default value?

description: When combining pandas dataframe (concat or append) can I set the default value


code:
import itertools

def strong_connect(vertex):
    global edges, indices, lowlinks, connected_components, index, stack
    indices[vertex] = index
    lowlinks[vertex] = index
    index += 1
    stack.append(vertex)

    for v, w in (e for e in edges if e[0] == vertex):
        if indices[w] < 0:
            strong_connect(w)
            lowlinks[v] = min(lowlinks[v], lowlinks[w])
        elif w in stack:
            lowlinks[v] = min(lowlinks[v], indices[w])

    if indices[vertex] == lowlinks[vertex]:
        connected_components.append([])
        while stack[-1] != vertex:
            connected_components[-1].append(stack.pop())
        connected_components[-1].append(stack.pop())

edges = [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'),
         ('E', 'A'), ('A', 'E'), ('C', 'A'), ('C', 'E'),
         ('D', 'F'), ('F', 'B'), ('E', 'F')]
vertices = set(v for v in itertools.chain(*edges))
indices = dict((v, -1) for v in vertices)
lowlinks = indices.copy()
connected_components = []

index = 0
stack = []
for v in vertices:
    if indices[v] < 0:
        strong_connect(v)

print(connected_components)

rawDescription: Tarjan's strongly connected components algorithm in python not working


code:
def create_matrix(m, n, initial=0):
    return [[initial] * n for _ in xrange(m)]

rawDescription: How do I initialize a one-dimensional array of two-dimensional elements in Python?

description: Initialize a one-dimensional array of two-dimensional elements in Python


rawDescription: Attributes/information contained in DataFrame column names


code:
class Bunch(object): pass
widgets = Bunch()

rawDescription: Specifying TkInter Callbacks In Dictionary For Display Launcher Function


code:
class PrintMacro(Macro):
  syntax = 'print', OneOrMore(Var(), name='vars')
  ...

rawDescription: Pythonic macro syntax

description: Pythonic macro syntax


code: Unlock

rawDescription: Can I 'wrap' an USB stick with Python?

description: 'wrap' an USB stick with Python


code:
def f(values):
    print(multiprocessing.current_process())
    time.sleep(1)
    return values

rawDescription: Python Multiprocessing - number of process


code:
# List View
url_for('user.index_view')

# Create View (redirect back to index_view)
url_for('user.create_view', url=url_for('user.index_view'))

# Edit View for record #1 (redirect back to index_view)
url_for('user.edit_view', id=1, url=url_for('user.index_view'))

rawDescription: url_for for class-based views in Flask-Admin

description: Url_for for class-based views in Flask-Admin


code:
a = np.mgrid[0:4, 0:4, 0:11]     # All points in a 3D grid within the given ranges
a = np.rollaxis(a, 0, 4)         # Make the 0th axis into the last axis
a = a.reshape((4 * 4 * 11, 3))   # Now you can safely reshape while preserving order

rawDescription: Numpy: efficient way to generate combinations from given ranges


code:
list1 = list(range(1, 11, 2))
list2 = list(range(2, 11, 2))

rawDescription: Adding elements to a list in Python 3.3 by extracting consecutive elements from two other lists


code: np.where(lbl == 2)

rawDescription: How to group elements of a numpy array with the same value in separate numpy arrays

description: Group elements of a numpy array with the same value in separate numpy arrays


rawDescription: Identify a string by searching for 2 or more RE's in python


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

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

THETA, PHI = np.ogrid[0:2*np.pi:40j, 0:np.pi:30j]

X = 10 * np.cos(THETA) * np.sin(PHI)
Y = 10 * np.sin(THETA) * np.sin(PHI)
Z = 10 * np.ones_like(THETA) * np.cos(PHI)

def func(THETA, PHI):
    mask = (THETA < np.pi/2) & (np.pi/3 < PHI) & (PHI < 2 * np.pi/3)
    return np.where(mask, 1, 0.5)

C = func(THETA, PHI)
jet = plt.cm.jet
ax.plot_surface(X, Y, Z, rstride=2, cstride=2, facecolors=jet(C))
ax.set_aspect('equal')
plt.show()

rawDescription: Matplotlib boolean coloring

description: Matplotlib boolean coloring


code:
class RandomForestClassifierWithCoef(RandomForestClassifier):
    def fit(self, *args, **kwargs):
        super(RandomForestClassifierWithCoef, self).fit(*args, **kwargs)
        self.coef_ = self.feature_importances_

rawDescription: How to get attribute list from fitted model in Scikit-learn?

description: Get attribute list from fitted model in Scikit-learn


code:
import filecmp
filecmp.cmp('undoc.rst', 'undoc.rst')
filecmp.cmp('undoc.rst', 'index.rst')

rawDescription: check files for equality

description: Check files for equality


rawDescription: Average time for datetime list

description: Average time for datetime list


code:
import re
def removeNonAscii(s):
    return re.sub(r'\\u\w{4}','',s)

rawDescription: Removing non-ASCII characters from file text


code:
from io import BytesIO
import matplotlib.pyplot as plt
from IPython.display import display, Image, HTML
import base64

def plotdesc(fig, text, iwidth=None):
    bio = BytesIO()
    # save fig as png to bytes IO instead to disk
    fig.savefig(bio, format='png')
    plt.close(fig)
    iwidth = ' width={0} '.format(iwidth) if iwidth is not None else ''
    img_tag = "".format(iwidth)
    datatable = '

{0}	{1}

'.format(img_tag, text)
    display(HTML(datatable))

rawDescription: How to display a text paragraph next to figure in jupyter/ipython notebook

description: Display a text paragraph next to figure in jupyter/ipython notebook


code:
def a(): 'docstring works'

a.__doc__
def b(): "formatted docstring doesn't work %s" % ':-('

b.__doc__

rawDescription: How to put a variable into Python docstring

description: Put a variable into Python docstring


code: array([array([], dtype=int32), array([1]), array([2, 3]), array([3, 4, 5])], dtype=object)

rawDescription: Simpler code to combine multiple lists into one array? I actually wish "lists" are still "lists" in that array


code:
query = "{0} <= x & x <= {1}".format(xnew.min()*0.9, xnew.max()*1.1)

with tb.open_file('myfile.h5', 'r') as f:
    data = f.root.mytable.read_where(query)

f = scipy.interpolate.interp1d(data['x'], data['y'])
ynew = f(xnew)

rawDescription: How to Interpolate Over Data in Pytables Efficiently


rawDescription: numpy reverse multidimensional array

description: Numpy reverse multidimensional array


code:
a = 'apple'
o = 'orange'
'%s and %s' % (a,o)
'{} and {}'.format(a,o)

rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


code: game_state_loaded = load('save.txt')

rawDescription: name 'newList' is not defined

description: Name 'newList' is not defined


rawDescription: How to replace values in a dataFrame by checking for a condition?

description: Replace values in a dataFrame by checking for a condition


code:
b = B()
A.f(b)  # unbound A.f(), passing in an instance of `B`

rawDescription: How can I decide to call an overrided method in child class from either parent or child class?

description: Decide to call an overrided method in child class from either parent or child class


code:
original = '\xAD\xDE\xDE\xC0'
''.join([c for t in zip(original[1::2], original[::2]) for c in t])

rawDescription: byte reverse AB CD to CD AB with python

description: Byte reverse AB CD to CD AB with python


code:
import os
import logging
import settings   # alternativly from whereever import settings

class Logger(object):

    def __init__(self, name):
        name = name.replace('.log','')
        logger = logging.getLogger('log_namespace.%s' % name)    # log_namespace can be replaced with your namespace
        logger.setLevel(logging.DEBUG)
        if not logger.handlers:
            file_name = os.path.join(settings.LOGGING_DIR, '%s.log' % name)    # usually I keep the LOGGING_DIR defined in some global settings file
            handler = logging.FileHandler(file_name)
            formatter = logging.Formatter('%(asctime)s %(levelname)s:%(name)s %(message)s')
            handler.setFormatter(formatter)
            handler.setLevel(logging.DEBUG)
            logger.addHandler(handler)
        self._logger = logger

    def get(self):
        return self._logger

rawDescription: How to configure Logging in Python

description: Configure Logging in Python


code:
# Now we'll create a classifier, note we wrap it up in the
# FaceRecognizerModel we have defined in this file. This is
# done, so we can use it in the awesome scikit-learn library:
estimator = FaceRecognizerModel()
# And getting the precision_scores is then as easy as writing:
precision_scores = cval.cross_val_score(estimator, X, y, score_func=precision_score, cv=cv)

rawDescription: Face recognition in OpenCV Python FAR/FRR


code:
from django.contrib.auth.models import User
class Trial(models.Model):
    title = models.CharField(max_length=800)
    publication_date = models.DateField()
    assessors = models.ManyToManyField(User,related_name="trials")

rawDescription: Django: Including standard User table as foreign key in my models?


code:
uniques_dict = {}
for record in base:
    key, values = record[1], record[2:]
    for unique in set(values):
        uniques_dict.setdefault(unique, set()).append(key)

uniques_dict
list(uniques_dict)

rawDescription: Dictionary from associations found in list of lists (performance issue)


code: df[bf]

rawDescription: How to get the filtered dataframe for calculations while retaining the original one in pandas?

description: Get the filtered dataframe for calculations while retaining the original one in pandas


code:
with open("./testStage1.txt", 'r') as osrc:
    osrc.seek(291)
    lines = list(osrc)
    #Do whatever you need with your line list

rawDescription: readline function returning empty string

description: Readline function returning empty string


rawDescription: How to set a range of values in numpy to nan?

description: Set a range of values in numpy to nan


code: verbose=False

rawDescription: How can I suppress "Sent $X packet" output in Scapy?

description: Suppress "Sent $X packet" output in Scapy


code:
import apsw
import StringIO as io
output=io.StringIO()
conn = apsw.Connection('dbTest.dat')
shell=apsw.Shell(stdout=output, db=conn)
# How to execute a dot command
shell.process_command(".mode html")
# continue

rawDescription: HTML output using Python 3/sqlite3

description: HTML output using Python 3/sqlite3


code:
status = True
page_id = ""

# META INFORMATION
meta_keywords = ""
meta_description = ""
page_title = ""
favicon = ""

# RESOURCES
javascript_resources = []
javascript_files = []
style_sheets = []

def __init__(self, page_id = "home"):
    self.page_id = page_id.lower()
    self.get_status()
    self.get_meta()
    self.get_javascript()
    self.get_style_sheets()

def get_status(self):
    status = settings.SITE_STATUS

    if(status != "live"):
        self.status = False
    else:
        self.status = True

def get_meta(self):
    current = Meta.objects.get(page_id = self.page_id)
    self.meta_keywords = current.meta_keywords
    self.meta_description = current.meta_description
    self.page_title = current.page_title
    self.favicon = current.favicon

# this function will set all of the proper javascript lists and validate all files!
def get_javascript(self):

    javascript_list = Javascript.objects.filter(Q(page_id = "all") | Q(page_id = self.page_id)).filter(status = self.status)
    javascript_resources_list = Javascript_resources.objects.filter(Q(page_id = "all") | Q(page_id = self.page_id)).filter(status = self.status)

    #now evaulate the javascript
    if len(javascript_list) > 0:
        for resource in javascript_list:
            file_name = resource.url

            if self.exists(file_name):
                self.javascript_files.append(file_name)

    if len(javascript_resources_list) > 0:
        for resource in javascript_resources_list:
            file_name = resource.url

            if self.exists(file_name):
                self.javascript_resources.append(file_name)

def get_style_sheets(self):

    style_sheet_list = Style_sheets.objects.filter(Q(page_id = "all") | Q(page_id = self.page_id)).filter(status = self.status)

    if len(style_sheet_list) > 0:
        for resource in style_sheet_list:
            file_name = resource.url
            file_type = resource.file_type

            if self.exists(file_name):
                style_sheet = []
                style_sheet.append(file_type)
                style_sheet.append(file_name)

                self.style_sheets.append(style_sheet)

def exists(self, file_name):

    url = settings.STATIC_URL + file_name

    status = False

    if  path.exists(url):
        status = True

    return status

rawDescription: Django Model With Multiple Classes

description: Django Model With Multiple Classes


code:
import collections
import operator
import itertools as IT

Mapping = collections.namedtuple('Mapping', ['DispName', 'MachID'])

objectList = [Mapping('map 2 (MT1)', 'MT1'),
          Mapping('theoretical (MT1)', 'MT1'),
          Mapping('map 3 (MT2)', 'MT2'),
          Mapping('theoretical (MT2)', 'MT2'),
          Mapping('map 1 (MT1)', 'MT1'),
          Mapping('map 2 (MT2)', 'MT2')]

sortedMappingList = sorted(objectList,
             key=lambda mapping:
                            (mapping.MachID,
                             not mapping.DispName.startswith('theoretical'),
                             mapping.DispName))

for key, group in IT.groupby(sortedMappingList, key=operator.attrgetter('MachID')):
    for g in group:
        print(g.DispName)

rawDescription: Sorting grouped objects

description: Sorting grouped objects


code: "\n".join(["FILE{} blabla{}".format(x, x*2) for x in xrange(1, 10)])

rawDescription: How to create a string with loop in python and save it in file

description: Create a string with loop in python and save it in file


code:
s="""out.test
WS12345678
something here
pineapple joe"""
import re
re.search(r'WS\d{8}',s).group(0)

rawDescription: How do I set a variable to a regex string in Python Script for notepad++?

description: Set a variable to a regex string in Python Script for notepad++


code: import java.lang.Math as Math

rawDescription: Instantiating object in Python same as Java using jython


code:
import json

# ...
data = json.loads(req.content)
return int(data['statistics']['dataCount'])

rawDescription: How to get the json data from the url using Python script apart from requests library?

description: Get the json data from the url using Python script apart from requests library


code:
strformat = '\n'.join(
    ',  '.join('{:>5.1f}' for item in row)
    for row in chunks(data, 3))
print(strformat.format(*data))

rawDescription: Write to list to rows with specific number of columns


code:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

rawDescription: Django: does ImageField need a filepath or an actual image object?


code:
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(DictVectorizer(), LogisticRegressionCV())
pipe.fit(input_data, y_input)
y_new = pipe.predict(new_data)

rawDescription: How to transform new input data using dictVectorize and using the model?

description: Transform new input data using dictVectorize and using the model


code: non_vowels = bytearray(set(range(0x100)) - set(b'aeiou'))

rawDescription: Deleting consonants from a string in Python


code: np.insert(A.ravel(), np.ravel_multi_index((range(A.shape[0]), C), A.shape) + 1, B[range(B.shape[0]), C]).reshape(A.shape[0], A.shape[1]+1)

rawDescription: Efficent insertion of not aligned elements in a numpy array


code:
from Crypto import Random
from Crypto.Cipher import AES

BS = 16
def pad(data):
    padding = BS - len(data) % BS
    return data + padding * chr(padding)

def unpad(data):
    return data[0:-ord(data[-1])]

def decrypt_node(hex_data, key='0'*32, iv='0'*16):
    data = ''.join(map(chr, bytearray.fromhex(hex_data)))
    aes = AES.new(key, AES.MODE_CBC, iv)
    return unpad(aes.decrypt(data))

def encrypt_node(data, key='0'*32, iv='0'*16):
    aes = AES.new(key, AES.MODE_CBC, iv)
    return aes.encrypt(pad(data)).encode('hex')

print(encrypt_node('this-needs-to-be-encrypted'))
print(decrypt_node('b88e5f69c7bd5cd67c9c12b9ad73e8c1ca948ab26da01e6dad0e7f95448e79f4'))

rawDescription: encrypt using node.js crypto aes256 and decrypt using python2.7 PyCrypto

description: Encrypt using node.js crypto aes256 and decrypt using python2.7 PyCrypto


code:
myset = ['flower', 'bird']
df[((df.CAT1 == 'animal') & (df.CAT2.isin(myset))) | ((df.CAT2 == 'animal') & (df.CAT1.isin(myset)))]

rawDescription: pandas: applying multiple filters

description: Pandas: applying multiple filters


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

x = np.linspace(1, 10)

def f(x):
    return np.sin(x) + np.random.normal(scale=0.1, size=len(x))

pl.plot(x, f(x))

rawDescription: Produce random wavefunction

description: Produce random wavefunction


code: listt

rawDescription: How to assign "empty" to a list position (python)

description: Assign "empty" to a list position (python)


code:
def get_season(month):
    seasons = {
    'Autumn': ['September', 'October', 'November', 'December', 'January'],
    'Spring': ['January', 'February', 'March', 'April'],
    'Summer': ['Apirl', 'May', 'June', 'July']
    }

    for season in seasons:
        if month in seasons[season]:
            return season
    return 'Invalid input month'

rawDescription: How to check what month it is? Python

description: Check what month it is? Python


code:
result = generator_func()
isinstance(result, (collections.Sequence, collections.Iterator))
result = [1,2,3,4,5]
isinstance(result, (collections.Sequence, collections.Iterator))
result = (1,2,3,4,5)
isinstance(result, (collections.Sequence, collections.Iterator))
result = {1,2,3,4,5}
isinstance(result, (collections.Sequence, collections.Iterator))
result = {1:1,2:2,3:3,4:4,5:5}
isinstance(result, (collections.Sequence, collections.Iterator))

rawDescription: How can I tell if a structure in Python has order?

description: Tell if a structure in Python has order


code: sortedItems = sorted(currentItems, key=lambda x: x.getTimestamp())

rawDescription: How can I merge and sort two sorted lists of QTreeWidgetItems?

description: Merge and sort two sorted lists of QTreeWidgetItems


code:
def mykey(s):
    parts = s.split("_",1)
    importantPart = splits[0]
    number = int(importantPart[1:])  # remove the "S"
    return number

rawDescription: Python Sort List, Skipping a Character

description: Python Sort List, Skipping a Character


code: destMatches = [i for i,destEntry in enumerate(destList) if destEntry[0] == sourceMatch]

rawDescription: finding first item in a list whose first item in a tuple is matched

description: Finding first item in a list whose first item in a tuple is matched


code: iterate(seed, num, lambda x: 3*x*(4-x))

rawDescription: How to pass a function as function parameter in Python

description: Pass a function as function parameter in Python


code:
fig2, ax2 = plt.subplots(1, 1)
data2 = np.linspace(-1, 1, 9).reshape(3, 3)
m2 = plot_corr_ellipses(data2, ax=ax2, cmap='seismic', clim=[-1, 1])
cb2 = fig2.colorbar(m2)
ax2.margins(0.3)

rawDescription: How can I plot a correlation matrix as a set of ellipses, similar to the R open-air package?

description: Plot a correlation matrix as a set of ellipses, similar to the R open-air package


rawDescription: Selecting objects

description: Selecting objects


code:
# Convert each bit of input string to numerals
str2num = (np.fromstring(A, dtype=np.uint8)-48).reshape(-1,4)

# Setup conversion array for binary number to decimal equivalent
de2bi_convarr = 2**np.arange(3,-1,-1)

# Use matrix multiplication for reducing each row of str2num to a single decimal
out = str2num.dot(de2bi_convarr)

rawDescription: fastest way to convert bitstring numpy array to integer base 2

description: Fastest way to convert bitstring numpy array to integer base 2


code:
df = DataFrame(np.random.randn(10,1),index=date_range('20130101 23:55:00',periods=10,freq='T'))
df['Active'] = False
df
df['Active'] = False

rawDescription: Selecting DataFrame slices by date string


code:
#from lxml import html
from bs4 import BeautifulSoup
from bs4.element import NavigableString

...

def traverse(parent, graph, labels):
    labels[hash(parent)] = parent.name
    for node in parent.children:
        if isinstance(node, NavigableString):
            continue
        graph.add_edge(hash(parent), hash(node))
        traverse(node, graph, labels)

...

#html_tag = html.document_fromstring(raw)
soup = BeautifulSoup(raw)
html_tag = next(soup.children)

...

rawDescription: HTML Parse tree using Python 2.7

description: HTML Parse tree using Python 2.7


rawDescription: What is the best way to store and use information between two objects in python?


code:
import io

with io.open(filename) as f:
    lines = sum(1 for line in f)

rawDescription: Why Python does not see all the rows in a file?


rawDescription: How can I create a new column and assign values to it based off of critieria?

description: Create a new column and assign values to it based off of critieria


code:
def super(cls, obj):
    mro = type(obj).__mro__
    parent = mro[mro.index(cls) + 1]
    class proxy(object):
        def __getattribute__(self, name):
            return getattr(parent, name).__get__(obj)
    return proxy()

rawDescription: One-Many-One Inheritance in Python

description: One-Many-One Inheritance in Python


code:
from celery import shared_task

@shared_task
def my_add_task(a, b):
    return a + b

rawDescription: Django Celery Directory Structure and Layout


code:
def show_frame(self, page_name):
    '''Show a frame for the given page name'''
    frame = self.frames[page_name]

    # tries to find and call an update method on the frame
    update_method =  getattr(frame, 'update', None)
    if callable(update_method):
        update_method()

    frame.tkraise()

rawDescription: Python & Tkinter Structure Issue

description: Python & Tkinter Structure Issue


code:
for ima in images:
    plt.figure()
    plt.imshow(ima)

rawDescription: Display multiple images in one IPython Notebook cell?


rawDescription: Concatenating Pandas data frame without removing row names


code:
col_mapping = {'Central M': ['CM', 'CM % of LSA'],
               'Lower BH': ['LBH % of LSA', 'LBH'],
                'Summary': ['Total Area', 'Total Area % of LSA']}

rawDescription: Grouping Python Panda table with additional heading


code: buttons_dict[COORDS_LIST[-1]]["command"] = lambda x=c, y=r: fire_here(x, y)

rawDescription: tkinter >> how to get button references?

description: Tkinter >> how to get button references


rawDescription: Change color of 3D scatterplot each iteration


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

    def dosomething(self, y):
        _dosomething(self.x, y)

@numba.jit(nopython=True)
def _dosomething(x, y):
    for i in range(len(x)):
        x[i] += y[i]

rawDescription: Design heuristics for writing Python classes that interact with `scipy.integrate.odeint`?


rawDescription: python: find and replace numbers < 1 in text file

description: Python: find and replace numbers < 1 in text file


code: label_im, nb_labels = ndimage.label(mask)

rawDescription: Blob ID tagging for OpenCV python

description: Blob ID tagging for OpenCV python


code:
import turtle
import numpy as np

tlist = list()
colorlist = ["red", "green", "black", "blue", "brown"]
for i in xrange(5):
    tlist.append(turtle.Turtle(shape="turtle"))
    tlist[i].color(colorlist[i])
    tlist[i].speed(1)
screen = turtle.getscreen()
for i in xrange(100):
    screen.tracer(1000)
    for t in tlist:
        t.right((np.random.rand(1) - .5) * 180)
        t.forward(int((np.random.rand(1) - .5) * 100))
    screen.update()

rawDescription: Running turtles simultaneously with turtle graphics


code:
import re

pat = re.compile(r'
\s*(.*?)\s*
')
pat.findall(src) # src is your last codeblock from above
## OUTPUT:
['This account is run by Organizing for Action staff. Tweets from the President are signed -bo.']

rawDescription: Why is this RegEx not finding any data?

description: Why is this RegEx not finding any data


code:
class MyMetaClass(type):
    @property
    def my_data(cls):
        if getattr(cls, '_MY_DATA', None) is None:
            my_data = ...  # costly database call
            cls._MY_DATA = my_data
        return cls._MY_DATA

class MyClass(object):
    __metaclass__ = MyMetaClass

rawDescription: Python class member lazy initialization

description: Python class member lazy initialization


rawDescription: What is the best way to append lists inside a dict?


rawDescription: Comparing and discarding two consecutive elements not complying certain condition in a list using Python


code:
import re

text = "Hello, this is a test. Let's tag @[William Maness], and then tag @[Another name], along with @[More Name]."

def replace(match):
    text = match.group(1)  # Extract the first capturing group

    return '{1}'.format(  # Format it into a link
        text.lower().replace(' ', '-'),
        text
    )

re.sub(r'@\[(.*?)\]', replace, text)

rawDescription: Python / Regular Expression Token conversion with parameter capture


code: df = df[start_timestamp:end_timestamp]

rawDescription: Python pandas, how to truncate DatetimeIndex and fill missing data only in certain interval


code:
if raw_input('Enter a word: ')[-1:] == 's': # Or you can use [-1]
    do_stuff()

rawDescription: Python: Last character of user input

description: Python: Last character of user input


code: fig, ax = plt.subplots()

rawDescription: Python Pandas Pivot tables to pie chart

description: Python Pandas Pivot tables to pie chart


code:
class Image(models.Model):
    width = ...  # Width in pixels
    height = ... # Height in pixels

rawDescription: When should I use a custom Manager versus a custom QuerySet in Django?


code: collections.deque(map(lambda x: x.pop(which_column), triangle), maxlen=0)

rawDescription: Python - Delete column from a matrix without numPy


code:
from tkinter import *
from tkinter import ttk

rootwin = Tk()

roomtext = Text(rootwin)
roomtext.grid(column=0, row=0)

rtas = ttk.Scrollbar(rootwin, orient = "vertical", command = roomtext.yview)

def show_scrollbar():
    if roomtext.cget('height') < int(roomtext.index('end-1c').split('.')[0]):
        rtas.grid(column=1, row=0, sticky=N+S)
        roomtext.config(yscrollcommand = rtas.set)
        rootwin.after(100, hide_scrollbar)
    else:
        rootwin.after(100, show_scrollbar)

def hide_scrollbar():
    if roomtext.cget('height') >= int(roomtext.index('end-1c').split('.')[0]):
        rtas.grid_forget()
        roomtext.config(yscrollcommand = None)
        rootwin.after(100, show_scrollbar)
    else:
        rootwin.after(100, hide_scrollbar)

show_scrollbar()
rootwin.mainloop()

rawDescription: Create scrollbar only when text length greater than text area


code:
sys.stdout = os.fdopen(1, 'w', 0)    # from first part of your script
...
sys.stdout = os.fdopen(new, 'w', 0)  # from second part of your script

rawDescription: dup, dup2, tmpfile and stdout in python

description: Dup, dup2, tmpfile and stdout in python


code:
query = """ SELECT BO_INDEX FROM GeoTest.dbo.Tabelle_Bohrung
    WHERE BO_BEMERKUNG LIKE '%ab%'
     OR O_BEMERKUNG LIKE '%cd%'
     OR O_BEMERKUNG LIKE '%ef%' """

query = """ SELECT BO_INDEX FROM GeoTest.dbo.Tabelle_Bohrung
    WHERE {params}""".format(
        params=" OR ".join("BO_BEMERKUNG LIKE '%%%s%%' \n" % w for w in wortliste)
    )
print(query)

rawDescription: Give a list of strings to a sql-query [Python]


code:
import pandas as np
import numpy as np

df = pd.DataFrame(np.random.randint(0, high=9, size=(100,2)),
         columns = ['A', 'B'])

threshold = 10 # Anything that occurs less than this will be removed.
for col in df.columns:
    value_counts = df[col].value_counts() # Specific column
    to_remove = value_counts[value_counts <= threshold].index
    df[col].replace(to_remove, np.nan, inplace=True)

rawDescription: Remove low frequency values from pandas.dataframe


rawDescription: function initialize and object initialization (multiprocessing)

description: Function initialize and object initialization (multiprocessing)


code:
from needle.cases import NeedleTestCase

class Tests(NeedleTestCase):
    def setUp(self):
        self.driver = webdriver.Chrome(chromedriver)
        self.accept_next_alert = True
        self.driver.set_window_size(1100, 800)
        self.base_url = "http://someurl"

    def test_anchor(self):
        driver = self.driver
        driver.get(self.base_url)
        driver.implicitly_wait(1)

        driver.find_element_by_partial_link_text("anchor_text").click()

        self.assertScreenshot('#my_element_id', 'screenshot-file-name')

rawDescription: Selenium - Get location after clicking on an anchor


code:
stats.sort(key=lambda x: (x['A'], x['Z']))
stats.sort(key=lambda x: (x['K'], x['B']), reverse=True)

rawDescription: Sort list of dictionaries by multiple keys with different ordering


code:
from itertools import permutations
list(permutations(range(1, 5), 4))

rawDescription: Go through every possible combination of an array python


rawDescription: How to reset some function variables in Python in a loop

description: Reset some function variables in Python in a loop


rawDescription: How to merge item in list

description: Merge item in list


code:
keys = ['Orange','Blue','Green']
colors={key:[] for key in keys}
colors

rawDescription: What is the Pythonic way to use (elements of) a list as keys in a dictionary?


code:
rmask1=sparse.coo_matrix(mask1)
rmask1.row
rmask1.col
sparse.coo_matrix((res1, (rmask1.row, rmask1.col)),rmask1.shape).A

rawDescription: How can I create a sparse matrix instead of a dense one in this program?

description: Create a sparse matrix instead of a dense one in this program


code:
import numpy
from scipy import sparse

A = numpy.array([0, 0, 1, 2, 1])
k = 3
B = sparse.coo_matrix((numpy.full(len(A), 1, dtype=int), (numpy.arange(len(A)), A)), shape=(len(A), k))

rawDescription: Numpy: efficient array of indices to "bump" array


rawDescription: When saving pylab figure plot, cant change the name from figure_1.png. Also label problems


rawDescription: Python Variable

description: Python Variable


code:
sort_idx = A.argsort()
out = sort_idx[np.searchsorted(A,B,sorter = sort_idx)]

rawDescription: Finding indices of matches of one array in another array


code:
for age in range(20, 70, 5):
    print(age, end=" ") #end is space
    for percentage in range(4, 12, 2):
        result = calc_final_balance(age, amount_saved, percentage)
        print("\t $" + format(result, '.2f').rjust(10), end=" ")
    print()

rawDescription: Python - Erase the first word in a line in a nested loop


code:
unq_val, unq_idx = np.unique(B.ravel(), return_inverse=True)
unq_count = np.bincount(unq_idx)
unq_tally = np.bincount(unq_idx, weights=A.ravel())
unq_freq = unq_tally / unq_count

rawDescription: Plotting Histogram using data from 2 numpy matrices


code:
a1
b2
c3
d4
e5

rawDescription: Print two presorted lists into one output file in python


code:
def my_view(request):
    ...
    return redirect('/some/url/')

rawDescription: Django - dictionary passed in redirect is not showing in template


code:
now = datetime.now().date()
ts = '2015-03-01T17:09:00.000+0000'
ts = ts[:10]
f = '%Y-%m-%d'
date_from_sql = datetime.strptime(ts, f).date()
print(date_from_sql - now).days

rawDescription: Subtracting Dates of Different Formats and converting to Int


code:
inDict={
"httpXYZ_ACTION1": [10, 0],
"http123_ITEM1": [0.055, 0.0875],
"http456_ACTION1": [0.01824, 0.066667],
"httpABC_ITEM2": [1214.666667, 1244.195833],
"http999_ACTION2": [None, 213],
}
outDictKeys=set('_'+x.split('_')[1] for x in inDict)
outDict={}
for outKey in outDictKeys:
    total=0
    for inKey in inDict:
        if inKey.endswith(outKey):
            total=total+sum([x for x in inDict[inKey] if x is not None])
    outDict[outKey]=total
print (outDict)

rawDescription: python sum dict keys AND sum dict values

description: Python sum dict keys AND sum dict values


code:
from bs4 import BeautifulSoup
import re

a = """<meta property="tall"/>
<meta property="wide" content="spiral"/>
<meta name="red"/>
<meta name="tall"/>"""

soup = BeautifulSoup(a)

rawDescription: Beautifulsoup extracting

description: Beautifulsoup extracting


code:
import copy
l1 = [['a2', 1], ['a2', 2], ['a2', 3], ['a2', 4], ['a2', 5]]
membership = [0, 1, 1, 2, 3]
l2=copy.deepcopy(l1)
[item.append(membership[i]) for i, item in enumerate(l2)]
l1
l2

rawDescription: Why does this code change both lists (id is not the same)?


code: max((equation(v), k) for k, v in d.items())

rawDescription: How do I get values from a dictionary run them through an equation and return the key with the greatest value

description: Get values from a dictionary run them through an equation and return the key with the greatest value


code:
m = np.array([[0,0,1],[1,1,0],[1,1,1]])
np.apply_along_axis(np.bincount, 1, m)
[np.bincount(m[i]) for i in range(m.shape[1])]

rawDescription: Can numpy bincount work with 2D arrays?

description: Can numpy bincount work with 2D arrays


code: encoded = [[s.encode('utf8') for s in t] for t in resultsList]

rawDescription: How to convert a unicode list of tuples into utf-8 with python

description: Convert a unicode list of tuples into utf-8 with python


code: new_L = [e + ' ' * (max_length - len(e)) for e in L]

rawDescription: I have been trying to write a program python


code:
@set_properties
class Item01Object(object):
    properties = ["a","c"]
    ATTR = None

@set_properties
class Item02Object(object):
    properties = ["b","c"]
    ATTR = None

rawDescription: Python: Copy properties with it's functions (fget, fset, fdel) from one class to another


code:
#!/usr/bin/env python
from socket import socket, AF_PACKET, SOCK_RAW
s = socket(AF_PACKET, SOCK_RAW)
s.bind(("eth1", 0))

# We're putting together an ethernet frame here,
# but you could have anything you want instead
# Have a look at the 'struct' module for more
# flexible packing/unpacking of binary data
# and 'binascii' for 32 bit CRC
src_addr = "\x01\x02\x03\x04\x05\x06"
dst_addr = "\x01\x02\x03\x04\x05\x06"
payload = ("["*30)+"PAYLOAD"+("]"*30)
checksum = "\x1a\x2b\x3c\x4d"
ethertype = "\x08\x01"

s.send(dst_addr+src_addr+ethertype+payload+checksum)

rawDescription: How Do I Use Raw Socket in Python?

description: How Do I Use Raw Socket in Python


code:
...
logOutput.moveCursor(QTextCursor.End)
logOutput.setCurrentFont(font)
logOutput.setTextColor(color)

logOutput.insertPlainText(text)

sb = logOutput.verticalScrollBar()
sb.setValue(sb.maximum())
...

rawDescription: pyqt - how to make a textarea to write messages to - kinda like printing to a console

description: Pyqt - how to make a textarea to write messages to - kinda like printing to a console


code:
import re

ex_1 = "03/09     03/09      ACH CREDIT BALANCE REF     47AJ    1234    250.00"
ex_2 = "          03/10      ACH CREDIT BALANCE REF             1234    98.00"
ex_3 = "03/09     03/09      ACH CREDIT BALANCE REF             1234    50.00"
lines = [ex_1, ex_2, ex_3]

data = []
regex = r"(\d\d/\d\d)?\s+(\d\d/\d\d)\s+([A-Z]+(?:\s[A-Z]+)*)\s+([0-9A-Za-z]{1,5})?\s+(\d{1,5})\s+(-?[\d,]+\.\d\d)"
for line in lines:
    match = re.search(regex, line)
    if match:
        elems = match.groups()
        data.append(elems)

rawDescription: How to force a regex to be as conservative as possible when some elements are optional?

description: Force a regex to be as conservative as possible when some elements are optional


rawDescription: Open file with pyQt

description: Open file with pyQt


code:
def pad_to_square(a, pad_value=np.nan):
    m = a.reshape((a.shape[0], -1))
    padded = pad_value * np.ones(2 * [max(m.shape)], dtype=m.dtype)
    padded[0:m.shape[0], 0:m.shape[1]] = m
    return padded

g = np.isnan(grid)
grid = pad_to_square(grid[:, ~np.all(g, axis=0)][~np.all(g, axis=1)])

rawDescription: Crop nan rows and columns of a matrix, but keep it square


code:
new_volume = 50
with open("/home/administrator/files/mplayer-control.pipe","w") as fp:
    fp.write("set_property volume %d\n" % (new_volume,))

rawDescription: Write to a FIFO from a Python program

description: Write to a FIFO from a Python program


code:
class TranslatedSlugInline(TranslatedTabularInline):
    model = TranslatedCharField
    _relation_field_filter = "slug_event_portal"
    verbose_name = "Slug"
    verbose_name_plural = "Slug"

class TranslatedSlugInline(TranslatedTabularInline):
    model = TranslatedCharField
    _relation_field_filter = "slug2_event_portal"
    verbose_name = "Slug2"
    verbose_name_plural = "Slug2"

rawDescription: Django Multiple GenericRelation related_name in admin


rawDescription: Does Python IO allow opened file to be deleted/renamed on Windows?


rawDescription: Test for list without duplicated elements


code:
re.search(r'/\d{0,3}$', 'Titile Something/17').group()
re.search(r'/\d{0,3}$', 'Titile Something/1').group()

rawDescription: How to extract number from end of the string

description: Extract number from end of the string


code:
def __init__(self, user, id):
    self.user = user.upper()
    self.id = id

rawDescription: Retrieve data from MongoDB/Flask and display it in an HTML page using Jinja2


rawDescription: Average of a numpy array returns NaN

description: Average of a numpy array returns NaN


code:
def __eq__(self, other):
    for key, v in other.__dict__.iteritems(): # .items() in Python 3
        if isinstance(v, np.array) and sorted(v) != sorted(self.__dict__[key]):
                return False
        elif self.__dict__[key] != v:
            return False
    return True

rawDescription: Sort both elements of a tuple, ignoring case, within a list, so that the keys of a dictionary line up correctly


rawDescription: How can I find all indices of a value in a multidimensional array?

description: Find all indices of a value in a multidimensional array


code: date_time_milis = time.mktime(datetimeobj.timetuple()) * 1000 + datetimeobj.microsecond / 1000

rawDescription: Returning millisecond representation of datetime in python


code:
def buildRex(self, lst):
    '''Build a regular expression mathing substrings from the lst.'''

    # Build a list of escaped unique substrings from the input list.
    # The order is not important now as it must be corrected later.
    lst2 = [re.escape(s) for s in set(lst)]

    # Join the escaped substrings to form the regular expression
    # pattern, build the regular expression, and return it. There could
    # be longer paterns that contain shorter patterns. The longer patterns
    # should be matched first. This way, the lst2 must be reverse sorted
    # by the length of the patterns.
    pat = '|'.join(sorted(lst2, key=len, reverse=True))
    rex = re.compile(pat)
    return rex

rawDescription: Synchronizing markdown automatically in the translated text (ProGit book, sources available)


code: globals()[var]()

rawDescription: Use class as string

description: Use class as string


code: dictionary = {k: tuple(v) for k,v in dictionary.iteritems()}

rawDescription: Convert dictionary of lists to dictionary of tuples


rawDescription: python multiprocessing peculiar memory management

description: Python multiprocessing peculiar memory management