code:
def ind_3d(lis,val):
    ind=[(j,i,k) for j,x in enumerate(lis) for i,y in enumerate(x) for k,z in enumerate(y) if z==val]
    if len(ind)==0:
        return 'not found'
    else:
        return ind[0]

a=[[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]]]

print(ind_3d(a,11))
print(ind_3d(a,5))
print(ind_3d(a,25))

rawDescription: find an element in a list with 'in' keyword and return that element

description: Find an element in a list with 'in' keyword and return that element


code:
class CubicBSpline(object):
    __slots__ = ("points", )

    def __init__(self, points):
        self.points = [Point(*coords) for coords in points]

rawDescription: Drawing a clamped uniform cubic B-spline using Cairo


code:
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

from check_site.items import YourItem

class StackSpider(CrawlSpider):
    name = 'stack'
    allowed_domains = ['bebizzy.com']
    start_urls = ['http://www.bebizzy.com/the-bebizzy-blog/']

    rules = (
        Rule(LinkExtractor(restrict_css='a.more-link'), callback='parse_item', follow=True),
        Rule(LinkExtractor(restrict_css='div.pagination>div>a'), callback='parse', follow=True),
    )

    def parse_item(self, response):
        self.logger.info(response.url)
        i = YourItem()
        #TODO: fill your item
        #i['title'] = ...
        return i

rawDescription: How to write xPath which has 2 columns

description: Write xPath which has 2 columns


code:
def add_all_attributes_for_base(self, label):
    base = AttributeBase.objects.get(label=label)
    for attribute in base.attributes.all():
        self.attributes.add(attribute)

rawDescription: Embed product-variance logic into Django models


rawDescription: python String interpolation vs another method

description: Python String interpolation vs another method


code:
complex = Filtration()
fill_alpha2D_complex(points, complex)
alphashape = [s for s in complex if s.data[0] <= .5]

rawDescription: How can I find the alpha shape (concave hull) of a 2d point cloud?

description: Find the alpha shape (concave hull) of a 2d point cloud


rawDescription: Python list comprehension to return edge values of a list


code:
a = ["A ", "B ", "C "]
a
a = map(lambda x: x.strip(), a)
a

rawDescription: Convert list of ticker symbols into list in Python


code:
def way5(theList, theDict):
    return list(set(theList).intersection(theDict))

rawDescription: Finding all keys in a dictionary from a given list QUICKLY


code: {TRIGGERS[k]: [ACTIONS(v) for v in vs] for k,vs in d_map.items()}

rawDescription: Python -- elegant dict comp where keys/values comes from sync'd lists?


code:
h1,h2
"this, is, value, 1",value2

rawDescription: How to rename key/header in csv DictReader

description: Rename key/header in csv DictReader


code:
for i in xrange(1,5):
    for j in xrange(1,5):
        for k in xrange(1,5):
            for l in xrange(1,5):
                for m in xrange(1,5):
                    inner_loops(i, j, k, l, m)

def inner_loops(i, j, k, l, m):
    for n in xrange(1,5):
        for o in xrange(1,5):
            for p in xrange(1,5):
                for q in xrange(1,5):
                    pass

rawDescription: Alternative with less indentation for nested loops in Python


code:
fields = [float('nan'),2,3,float('nan'),5]
{"field%d"%i:v for i,v in enumerate(fields) if not math.isnan(v)}

rawDescription: Conditionally add multiple items to dictionary in Python


rawDescription: Parsing hostname and port from string or url


code:
class P(object):
    def __init__(self, lon, lat):
        self.lon = lon
        self.lat = lat

    def __sub__(self, other):
        dist = ((other.lon - self.lon)**2 + (other.lat - self.lat)**2)**0.5
        return dist

rawDescription: How can I create my own datatype in python so that I could overwrite arithmetic operators?

description: Create my own datatype in python so that I could overwrite arithmetic operators


code:
d['pattern'] = d.sid.map(d.groupby('sid')['key'].apply(lambda c: list(c[::2])))
d

rawDescription: Itertools: selecting in pandas based on previous three rows, or previous elements in a list


code:
import numpy as np
x = np.random.randn(100, 3)
y = np.random.randn(100, 3)

rawDescription: Perform a series of outer products using tracedot in scipy


rawDescription: Emailing script - reply to message Gmail conversation


code:
for combo in product(*somedict.values()):
    newdict = dict(zip(somedict.keys(), combo))

rawDescription: Iterating through all combinations across many iterables


code:
import collections
letters = collections.defaultdict(int)
for letter in word:
    letters[letter] += 1

rawDescription: Counting each letter's frequency in a string


code:
def flatten(lst):
    for elem in lst:
        if type(elem) in (tuple, list):
            for i in flatten(elem):
                yield i
        else:
            yield elem

rawDescription: Join a list of lists together into one list in Python


code:
fig, ax = plt.subplots()
ax.scatter(int_dist, int_times, c='orange', s=150)
ax.scatter(ext_dist, ext_times, c='black', s=150)
plt.legend(['INT', 'EXT'], loc=4)
plt.xlabel('Distance')
plt.show()

rawDescription: Python 3.4 reading from CSV formats

description: Python 3.4 reading from CSV formats


code:
Contact.objects.filter(user_1=pk1, user_2=pk2)
Contact.objects.create(user_1=pk1, user_2=pk2) # add logic or db constraints to prevent duplication

rawDescription: Model friends table in Django

description: Model friends table in Django


code:
tonenames = ["a", "b", "c"]
cat = tonenames[-1]
for tname in tonenames:
    print(cat)

rawDescription: CSV download not showing exact values

description: CSV download not showing exact values


code:
class Blub(object):
    def __get__(self, instance, owner):
        print('Blub gets ' + instance._blub)
        return instance._blub

    def __set__(self, instance, value):
        print('Blub becomes ' + value)
        instance._blub = value

class Quish(object):
    blub = Blub()

    def __init__(self, value):
        self.blub = value

rawDescription: Python descriptors __get__ and __set__

description: Python descriptors __get__ and __set__


code: some_json_data = {"companies": {"foo": 1}}

rawDescription: FOR loop in object/array

description: FOR loop in object/array


rawDescription: Matrix Approximation and Predicting Timeseries in Python/R with SVD


code:
class Foo(object):
    def _get_bar(self):
        return self.__bar
    def _set_bar(self, value):
        if not isinstance(value, int):
            raise TypeError("bar must be set to an integer")
        self.__bar = value
    bar = property(_get_bar, _set_bar)

rawDescription: Force python class member variable to be specific type


code:
blinking = False
while True:
    if GPIO.input(16):
        blinking = True

    if blinking:
        blink(11)

    time.sleep(.1)

rawDescription: Continually blink an LED when a button is pressed on a raspberry pi?


code:
myNum = int(raw_input("Enter a number: "))
print(myNum + 1)

rawDescription: How to use inputs in loops

description: Use inputs in loops


rawDescription: How do I group a character followed by a space in a Python regex?

description: Group a character followed by a space in a Python regex


code:
from urlparse import urljoin
# other imports

class MySpider(CrawlSpider):
    handle_httpstatus_list = [416]
    name = 'comparator'
    allowed_domains = ["www.vividseats.com"]
    start_urls = [vs_url]
    tickets_list_xpath = './/*[@itemtype="http://schema.org/Event"]'
    def parse_price(self, response):
        loader = response.meta['loader']
        loader.add_xpath('ticketPrice' , '//*[@class="eventTickets lastChild"]/div/div/@data-origin-price')
        return loader.load_item()

    def parse(self, response):
        selector = HtmlXPathSelector(response)
        # iterate over tickets
        for ticket in selector.select(self.tickets_list_xpath):

            loader = XPathItemLoader(ComparatorItem(), selector=ticket)
            # define loader
            loader.default_input_processor = MapCompose(unicode.strip)
            loader.default_output_processor = Join()
            # iterate over fields and add xpaths to the loader

            loader.add_xpath('eventName' , './/*[@class="productionsEvent"]/text()')
            loader.add_xpath('eventLocation' , './/*[@class = "productionsVenue"]/span[@itemprop  = "name"]/text()')
            loader.add_xpath('ticketsLink' , './/*/td[3]/a/@href')
            loader.add_xpath('eventDate' , './/*[@class = "productionsDate"]/text()')
            loader.add_xpath('eventCity' , './/*[@class = "productionsVenue"]/span[@itemprop  = "address"]/span[@itemprop  = "addressLocality"]/text()')
            loader.add_xpath('eventState' , './/*[@class = "productionsVenue"]/span[@itemprop  = "address"]/span[@itemprop  = "addressRegion"]/text()')
            loader.add_xpath('eventTime' , './/*[@class = "productionsTime"]/text()')

            ticketsURL = "concerts/" + bandname + "-tickets/" + bandname + "-" + loader.get_output_value("ticketsLink")
            ticketsURL = urljoin(response.url, ticketsURL)
            yield scrapy.Request(ticketsURL, meta={'loader': loader}, callback = self.parse_price)

rawDescription: How to use scrapy.Request to load an element from another page into an item

description: Use scrapy.Request to load an element from another page into an item


code:
@classmethod
def get_cars_from(cls, start=0, end=10):
    """ This method get a list of cars from number 1 to 10.
    """
    return_list = []
    for i in range(start, end):
        instance = cls(i)
        return_list.append(instance)
    return return_list

rawDescription: Python: how to get create instance of a class within same class?


code:
import unittest

__private_stuff = 1 # if it would have single underscore, it would bot be a problem.

class ComplexTestCase(unittest.TestCase):
    def test_internal_symbol(self):
        private_stuff = globals()['__private_stuff']
        self.assertEqual(private_stuff, 1)

unittest.main(__name__)

rawDescription: How to test python module privates?

description: Test python module privates


code: new_list = reduce(lambda a, b: a[:-1] + [ a[-1] + [ b ] ] if not element_regex.match(b) or not a[0] else a + [ [ b ] ], test_list, [ [] ])

rawDescription: Splitting a list by matching a regex to an element


code:
parser._positionals.title = 'Positional arguments'
parser._optionals.title = 'Optional arguments'

rawDescription: Customize argparse help message

description: Customize argparse help message


code:
with mock.patch("mymodule.requests.post",
                side_effect=[Mock(status_code=400), Mock(status_code=200)]) as mock_post:
   mymodule.some_function()

rawDescription: Changing the second result of a function call with mock


code:
from fooer import Fooer

y = Fooer.foo(x)

rawDescription: Refactoring: break out class or just function to new file?


rawDescription: python dictionary, make every odd number line to key and even number line to value from a file

description: Python dictionary, make every odd number line to key and even number line to value from a file


rawDescription: Python 2D list slice

description: Python 2D list slice


code:
red = [1, 0, 0]
white = [1, 1, 1]
alpha = 0.5

make_rgb_transparent(red, white, alpha)
# [1.0, 0.5, 0.5]

rawDescription: calculate RGB equivalent of base colors with alpha of 0.5 over white background in matplotlib

description: Calculate RGB equivalent of base colors with alpha of 0.5 over white background in matplotlib


code:
import numpy as np
from numba import autojit

@autojit
def jit_max_grad(y, alpha, grad, B):
    maxgrad = -inf
    maxind = -1
    for ii in xrange(alpha.shape[0]):
        if (y[ii] * alpha[ii] < B[y[ii] + 1]):
            g = -y[ii] * grad[ii]
            if g >= maxgrad:
                maxgrad = g
                maxind = ii
    return maxind, maxgrad

rawDescription: How to vectorize finding max value in numpy array with if statement?

description: Vectorize finding max value in numpy array with if statement


rawDescription: Getting a map() to return a list in Python 3.x


rawDescription: Compare rows then take rows out if neccessary


code:
requires = ['pyramid',
            'WebError',
            'pymongo',
            'mock',
            'formencode']

rawDescription: Python, virtualenv - Is it possible to use a single Pyramid project with multiple virtualenvs on different computers?


code:
def meetup_day(year, month, day_name, week_num):
    year_int = int(year)
    month_int = int(month)
    day_int = list(calendar.day_name).index(day_name)
    relevant_mdays = [i for i in list(zip(*calendar.monthcalendar(year_int, month_int)))[day_int] if i != 0]
    if week_num == 'teenth':
        mday = next((i for i in relevant_mdays if i in range(13, 20)), None)
    else:
        if week_num == 'last':
            week_int = -1
        else:
            week_int = int(week_num[0]) - 1
        mday = relevant_mdays[week_int]
    return datetime.date(year_int, month_int, mday)

rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
opt1 = ["congruent", "incongruent"]
opt2 = ["nocue", "center", "spatial"]
from itertools import product
trials = list(product(opt1, opt2))*36
np.random.shuffle(trials)

rawDescription: Python factor level combinations

description: Python factor level combinations


code:
def nounify(verb_word):
    set_of_related_nouns = set()

    for lemma in wn.lemmas(wn.morphy(verb_word, wn.VERB), pos="v"):
        for related_form in lemma.derivationally_related_forms():
            for synset in wn.synsets(related_form.name(), pos=wn.NOUN):
                if wn.synset('person.n.01') in synset.closure(lambda s:s.hypernyms()):
                    set_of_related_nouns.add(synset)

    return set_of_related_nouns

rawDescription: Get noun from verb Wordnet

description: Get noun from verb Wordnet


code:
edges_recursive = list(edges)
edges_recursive.remove(edge)

rawDescription: Converting a few python lines in pseudocde


code:
@logged
def f(x):
   """does some math"""
   return x + x * x

rawDescription: What does functools.wraps do?

description: What does functools.wraps do


code:
import script
script.merge()

rawDescription: How to run python functions in unix?

description: Run python functions in unix


rawDescription: issue extracting html page's string using bs4

description: Issue extracting html page's string using bs4


rawDescription: Generating new time series index from existing data set in Pandas


code:
arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
ele = numpy.asarray(arr)
'|'.join(map(str,ele[0,]))

rawDescription: Why won't numpy matrix let me print its rows?


key: value

key2: Ohai.

rawDescription: mongodb: insert if not exists

description: Mongodb: insert if not exists


code: numpy.argwhere(H == H.max())

rawDescription: Find peak of 2d histogram

description: Find peak of 2d histogram


code:
from django.utils import formats
formats.get_format('DATE_FORMAT')
formats.get_format('DATE_FORMAT', lang='de')

rawDescription: Get datetime mask for a given locale

description: Get datetime mask for a given locale


code:
dp = [0] * 160
dp[0] = 1
for i in range(1, 100):
    for j in range(i):
        dp[i] += dp[j] * dp[i - j - 1]

rawDescription: Python calculate large number wrong

description: Python calculate large number wrong


code:
from mail_templated import send_mail
send_mail('my_template.tpl', {}, from_email, [user.email])

rawDescription: Django Forms : Make some text sent by form to email appear bold


code: pay_b = interest / 12 * end

rawDescription: Python: smarter way to calculate loan payments


rawDescription: Python all combinations for multiple lists with variable k


rawDescription: how to avoid truncation of numbers- Python

description: Avoid truncation of numbers- Python


code:
def __init__(self, param1, dict_param):
    self.param1 = param1
    default_vals = {
        'key1': 'default 1',
        'key2': 'default 2',
        'etc': 'and so on'
    }

    for key, value in default_vals.iteritems():
        setattr(self, key, dict_param.get(key, value))

rawDescription: Class instantiation with a dictionary parameter and class variables with default values


code:
stats = os.stat(path+name)
stats.st_size

rawDescription: How to search file by its size using Python

description: Search file by its size using Python


code: is_main_thread_active = lambda : any((i.name == "MainThread") and i.is_alive() for i in threading.enumerate())

rawDescription: Check if the Main Thread is still alive from another thread


code:
provided_ips = request.access_route
# First entry in the list is the client's IP

rawDescription: Parse X-Forwarded-For to get ip with werkzeug on Heroku


code:
ax = plt.gca()
ax.xaxis.set_major_locator(plt.MaxNLocator(nbins=3))  # one less tick than 'bin'
tl = ax.xaxis.get_ticklocs()                          # get current tick locations
tl[1:-1] = [neworder[idx] for idx in tl[1:-1]]        # find what the labels should be at those locs
ax.xaxis.set_ticklabels(tl)                           # set the labels
plt.draw()

rawDescription: 're-sort' / adapt ticks of matshow matrix plot


code:
def freqWords(text, k):
    return Counter(text[i:i+k] for i in xrange(len(text) - k))

rawDescription: How to store parts of a string into a dictionary

description: Store parts of a string into a dictionary


code:
class QueryHelper(object):
    def __init__(self, param, text):
        self._param = param
        self._query = self._build_query(text)

    def _build_query(self, text):
        return text + " and ham!"

class RefinedQueryHelper(QueryHelper):
    def _build_query(self, text):
        # no need to know how the query object is going to be used
        q = super(RefinedQueryHelper, self)._build_query()
        return q.replace("ham", "spam")

rawDescription: Should internal class methods returnvalues or just modify instance variables in python?


code:
def run(self):
    while True:
        f, orig_img = self.capture.read()
        #orig_img = cv2.flip(orig_img, 1)

        img = cv2.GaussianBlur(orig_img, (5,5), 0)
        img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2HSV)
        img = cv2.resize(img, (len(orig_img[0]) / self.scale_down, len(orig_img) / self.scale_down))

        boundaries = [([0, 150, 150], [5, 255, 255]),
                        ([40, 80, 10], [255, 255, 255]),
                        ([190, 150, 100], [255, 255, 255])]
        for (lower, upper) in boundaries:
                          lower = np.array(lower,np.uint8)
                          upper = np.array(upper,np.uint8)
                          binary = cv2.inRange(img, lower, upper)
                          dilation = np.ones((15, 15), "uint8")
                          binary = cv2.dilate(binary, dilation)
                          canny = cv2.Canny(binary,100,200)
                          contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

                          max_area = 0
                          largest_contour = None
                          for idx, contour in enumerate(contours):
                              area = cv2.contourArea(contour)
                              if area > max_area:
                                   max_area = area
                                   largest_contour = contour

                          if not largest_contour == None:
                               moment = cv2.moments(largest_contour)
                               if moment["m00"] > 1000 / self.scale_down:
                                    rect = cv2.minAreaRect(largest_contour)
                                    rect = ((rect[0][0] * self.scale_down, rect[0][1] * self.scale_down), (rect[1][0] * self.scale_down, rect[1][1] * self.scale_down), rect[2])
                                    box = cv2.cv.BoxPoints(rect)
                                    box = np.int0(box)
                                    cv2.drawContours(orig_img,[box], 0, (0, 0, 255), 2)

                                    cv2.imshow("ColourTrackerWindow", orig_img)
                                    cv2.imshow("SHAPE", canny)
                                    if cv2.waitKey(20) == 27:
                                        cv2.destroyWindow("ColourTrackerWindow")
                                        self.capture.release()
                                        break

rawDescription: shape and centroid of desired color for following code

description: Shape and centroid of desired color for following code


rawDescription: Python: Start each newline with a specific character


code: pd.core.format.header_style = None

rawDescription: pandas xlsxwriter, format header

description: Pandas xlsxwriter, format header


rawDescription: How to output unicode characters and lines into an image file? -python

description: Output unicode characters and lines into an image file? -python


code:
[{'category': 'Football', 'title': 'Team A'},
 {'category': 'Football', 'title': 'Team B'},
 {'category': 'Baseball', 'title': 'Team C'},
 {'category': 'Baseball', 'title': 'Team D'}]

rawDescription: lxml: split at attribute?

description: Lxml: split at attribute


code:
A_float = A.astype(float)
A_float.dtype

rawDescription: Why doesn't numpy.power act element-wise on arrays when the exponent is negative?


rawDescription: Extracting Directory from Path with Ending Slash


code:
def modify_one(modify, one):
    return modify.unmodified(one)

rawDescription: Python design question (Can/should decorators be used in this case?)


code:
def or_filter_by_conditions(cls, **kwargs):
    return or_(getattr(cls, name) == value for name, value in kwargs.iteritems())

rawDescription: How to make a get_or_create using OR with SQLAlchemy?

description: Make a get_or_create using OR with SQLAlchemy


code:
def reverse(word):
    word_list = []
    for i in word:
        word_list.insert(0, word[i])
    return "".join(word_list)

rawDescription: Reverse String Function in Python (Primitive Steps)


code:
from gps_cacher import GpsCache

def remote_get_gps_data():
    # your function here
    return data

def get_gps_data():
    data = None
    gps_cache = GpsCache()
    current_dt = datetime.datetime.now()
    cached_data = gps_cache.get_cache(current_dt)
    if cached_data:
        data = cached_data
    else:
        data = remote_get_gps_data()
        gps_cache.put_cache(current_dt, data)
    return data

rawDescription: Limit calls to external database with Python CGI


code: [int(round(x)) if x > 0.5 else x for x in lst]

rawDescription: Convert a list of floats to the nearest whole number if greater than x in Python


code:
def mark_slangs(t):
    for w, v in slangs.items():
            s = r'\b' + w + r'\b'
            match = re.search(s,t)
            if match:
                    #print w, "found in:",t, "replacing with",readtable.slangs[w]
                    t = re.sub(w,slangs[w].rstrip(),t)
                    ...

rawDescription: translate by replacing words inside existing text

description: Translate by replacing words inside existing text


code:
def maxdigitsum(number, digits):
    l = list(map(int, str(number)))
    maximum = current = sum(l[:digits])
    for i in range(0, len(l)-digits):
        current = current - l[i] + l[i+digits]
        if current > maximum: maximum = current
    return maximum

rawDescription: Python sum of N consecutive digits of a large number


rawDescription: Recommend way to handle unit conversion

description: Recommend way to handle unit conversion


code:
def category_detail(request, slug):
    obj = NewsCategory.objects.get(slug=slug)
    newsInCat = obj.news_set.all() #for the list of news
    paginator = Paginator(newsInCat, 25) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        news_set = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        news_set = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
            news_set = paginator.page(paginator.num_pages)
    if request.is_ajax():
        context = {
            'news_set':news_set
        }
        return render(request,"news/category_detail_ajax.html",context)
    else:
        bestInCat = obj.news_set.get_bestInCat()
        context = {
          "obj":obj,
          "news_set":news_set,
          "newsInCat":newsInCat,
          "bestInCat":bestInCat,
        }
        return render(request, "news/category_detail.html", context)

rawDescription: load more feature or endless pagination

description: Load more feature or endless pagination


code:
NdocScores[0]
NdocScores[0][u'Car']
sum(NdocScores[1].values())
NdocScores[29]

rawDescription: Accessing values in a list of nested dictionaries


code:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")

rawDescription: Use Python to launch Excel file

description: Use Python to launch Excel file


code:
def random_line(f):
    return random.choice(f.readlines())

rawDescription: How to put random lines from a file into a string in python?

description: Put random lines from a file into a string in python


rawDescription: How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay?

description: Find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay


code:
for v in [custom_validator, EmailValidator()]:
    v(value) # <-----

rawDescription: Python __call__ special method practical example


code:
z = []
excluded = {"Supplementary", "Assignment", "Smith", "Bowen"}
for k, v in b.iteritems():
    if v not in excluded:
        z.append(k)

rawDescription: Python; Dictionary iteration

description: Python; Dictionary iteration


code: df.loc['length (mm)'].values

rawDescription: How to read specific rows from excel file using pandas

description: Read specific rows from excel file using pandas


code:
def remove_image(self, label_id):
    QtCore.QObject.connect(self.deleteButton, QtCore.SIGNAL("clicked()"), label_id.clear)

rawDescription: Remove an Image in QLabel After Button Clicked


code:
from numpy import nanmedian, NaN
nanmedian([1,2,3,NaN,NaN,NaN,NaN,NaN,NaN])

rawDescription: Median of a list with NaN values removed, in python


code: st.rsplit(None, 1)[-1]

rawDescription: Select last chars of string until whitespace in Python


code: res = res*scaling_factor

rawDescription: python - OpenCV mat::convertTo in python

description: Python - OpenCV mat::convertTo in python


code: df.loc[1, 'id'] = 'Lion'

rawDescription: How do I replace the content of an entire Pandas' cell with a string?

description: Replace the content of an entire Pandas' cell with a string


rawDescription: pydoc.render_doc() adds characters - how to avoid that?

description: Pydoc.render_doc() adds characters - how to avoid that


code:
@app.route('/')
def index():
    return 'Index page'

@app.route('/color/<path:template>')
def template_router(template):
    return render_template(template + '.html')

rawDescription: Flask: automatically render templates if request URL matches their name


rawDescription: Defining a function with a loop in Theano


code: reduce(lambda acc, c: acc + c, [i.a for i in B])

rawDescription: Adding up instance variables of a class object


code:
txt1 = self.ui.lineEdit.text #Method reference not Method call
txt2 = self.ui.lineEdit2.text
mySlot = lambda : (instance_b.return_text_username(txt1()), instance_b.return_printtext_password(txt2()))# Passed to lambda method call this time
QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),  mySlot)

rawDescription: How do I call an GUI object or more from main class

description: Call an GUI object or more from main class


code: fields = [item[0] for item in cursor.description]

rawDescription: fetching mysql data as python dictionary

description: Fetching mysql data as python dictionary


code:
def __str__(self):
     return "{0} {1}".format(self.state, (str(i) for i in self.nodelist))

rawDescription: What is the most pyhthonic way of printing instance variables?


code: image = image.convert("RGB")

rawDescription: Pixel Loading and Evaluating with PIL

description: Pixel Loading and Evaluating with PIL


code:
import web
template_globals = {
    "cookies": web.cookies,
}
render = web.template.render('templates/', globals=template_globals, base='layout', cache=False)

rawDescription: how to get cookie in template webpy

description: Get cookie in template webpy


rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


code: from pixie.libs.setup import Setup

rawDescription: how to init system's path variable in python projects

description: Init system's path variable in python projects


code:
async def main():
    asyncio.ensure_future(async_foo())  # fire and forget

    print('Do some actions 1')
    await asyncio.sleep(0.1)
    print('Do some actions 2')

rawDescription: "Fire and forget" python async/await

description: "Fire and forget" python async/await


code:
old_min = min(input)
old_range = max(input) - old_min

rawDescription: How to normalize a list of positive and negative decimal number to a specific range

description: Normalize a list of positive and negative decimal number to a specific range


code: points = [list(map(int, x.split(','))) for x in s]

rawDescription: better way to convert list element into a list like this one

description: Better way to convert list element into a list like this one


code:
seen = set()
add_  = seen.add
next(reader) #skip header
writer.writerows([row[-1]] for row in reader if row[-1] not in seen
                                                        and not add_(row[-1]))

rawDescription: Extract a list without duplicates from a CSV file


code: cats = i.tolist() + i.sym_diff(df2['A'].astype('category').cat.categories).tolist()

rawDescription: pandas and category replacement

description: Pandas and category replacement


code:
class TestFrame(wx.Frame):
    def __init__(self, parent):
        super(TestFrame, self).__init__(parent, title='test', size=(1280, 950))
        self.matricesPanel = MatricesPanel(self)

        sizer = wx.BoxSizer()
        sizer.Add(self.matricesPanel, flag=wx.EXPAND)
        self.SetSizer(sizer)

        self.Centre()
        self.Show()
        self.matricesPanel.initResize()

        wx.EVT_IDLE(wx.GetApp(),  wx.WakeUpIdle())

rawDescription: Placing two wx Grids side by side

description: Placing two wx Grids side by side


code:
# setup.py file
import sys
import os
import shutil

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

# clean previous build
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        if (name.startswith("myext") and not(name.endswith(".pyx") or name.endswith(".pxd"))):
            os.remove(os.path.join(root, name))
    for name in dirs:
        if (name == "build"):
            shutil.rmtree(name)

# build "myext.so" python extension to be added to "PYTHONPATH" afterwards...
setup(
    cmdclass = {'build_ext': build_ext},
    ext_modules = [
        Extension("myext",
                  sources=["myext.pyx",
                           "SomeAdditionalCppClass1.cpp",
                           "SomeAdditionalCppClass2.cpp"
                       ],
                  libraries=["externlib"],          # refers to "libexternlib.so"
                  language="c++",                   # remove this if C and not C++
                  extra_compile_args=["-fopenmp", "-O3"],
                  extra_link_args=["-DSOME_DEFINE_OPT",
                                   "-L./some/extra/dependency/dir/"]
             )
        ]
)

rawDescription: Using Cython To Link Python To A Shared Library


code: d

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


code:
changed = False
added = len(tuple1) != len(tuple2)
for e1, e2 in zip(tuple1, tuple2):
    if e1 != e2:
        changed = True
return changed, added, a==b

rawDescription: Python compare 2 lists filled with 3-tuples


code:
u'the' in u'they'
u' the ' in u' they '

rawDescription: How to select the finest granularity of string items in a list

description: Select the finest granularity of string items in a list


rawDescription: Split list python

description: Split list python


code: (f < min_freq) | (f > max_freq)

rawDescription: How to convert complex numbers back into "normal" numbers after performing FFT

description: Convert complex numbers back into "normal" numbers after performing FFT


code:
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
    if not (item % 2):
        items[index] = None

rawDescription: Replace values in list using Python

description: Replace values in list using Python


code:
from contextlib import contextmanager

@contextmanager
def replace_stdout(f):
    old_stdout = sys.stdout
    try:
        sys.stdout = PrintAndLog(f)
        yield
    finally:
        sys.stdout = old_stdout

rawDescription: Can I write to terminal and a given file with one command in Python?

description: Write to terminal and a given file with one command in Python


rawDescription: Remove rotation effect when drawing a square grid of MxM nodes in networkx using grid_2d_graph


code:
import pandas as pd
import matplotlib.pyplot as plt

result = [{0: 21, 1: 7, 2: 67, 3: 12, 4: 15, 5: 7, 6: 54, 7: 49, 8: 50, 9: 31,
           10: 6, 11: 2, 12: 8, 13: 2, 14: 2, 15: 1, 16: 35, 17: 2, 18: 1, 19:
           4, 20: 2, 21: 4, 22: 3, 23: 1, 24: 1, 25: 1, 26: 1, 27: 1, 28: 1,
           29: 1},
          {0: 2, 1: 5, 2: 2, 3: 3, 4: 1, 5: 2, 6: 3, 7: 2, 8: 1, 9: 1, 10: 1,
           11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1}]

df = pd.DataFrame([(level,val) for level, dct in enumerate(result)
                   for val in dct.values()],
                  columns=['level', 'size'])
size_count = df.groupby(['level'])['size'].apply(lambda x: x.value_counts())
size_count = size_count.reset_index()
size_count.columns = ['level', 'community size', 'number of communities']
cmap = plt.get_cmap('jet')
size_count.plot(kind='scatter', x='community size', y='number of communities',
                s=100, c='level', cmap=cmap)
plt.show()

rawDescription: How to dynamically update a plot in a loop?

description: Dynamically update a plot in a loop


code:
assert 123

if __debug__:
    do_something()

rawDescription: How can I unit test that something behaves differently when Python is in optimised mode?

description: Unit test that something behaves differently when Python is in optimised mode


rawDescription: Factor sympy expression to matrix coefficients?


code:
import cv2
help(cv2.findContours)

rawDescription: How does one look at imported OpenCV code? (specifically python's cv2)

description: Look at imported OpenCV code? (specifically python's cv2)


rawDescription: Saving a file with the date and time using shell


code:
for i, x in enumerate(train_station, 1):
    print("Current station is: "+x)
    print("Stations to go: ")

    for y in train_station[i:]:
        print(y)

rawDescription: Tracking counter in nested for loop

description: Tracking counter in nested for loop


code:
from PIL import Image
import numpy as np

im = np.array(Image.open('pic.jpg'))

rawDescription: How to use Pillow instead cv2?

description: Use Pillow instead cv2


code:
d = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
from nltk import trigrams
tri = trigrams(d.split(' '))
counter = Counter(tri)
import random
random.sample(counter, 5)

rawDescription: Can't Import Bigrams From NLTK Library

description: Can't Import Bigrams From NLTK Library


rawDescription: Need to add space between SubPlots for X axis label, maybe remove labelling of axis notches


code: out = np.einsum('ijk,ki->ji', R, v)

rawDescription: Producing slices of dot output without intermediates


code: np.where((A < thresh).all(0),-1,(A >= thresh).argmax(0))

rawDescription: Find the lowest non-masked point with numpy efficiently


code:
import ast
import sys

ser.write(ast.literal_eval("'{0}'".format(sys.argv[1])))

rawDescription: Encoding passed argument for serial.write python


code:
import timeit

s = """\
import re

s = \"\"\"1,' unchanged 1' " unchanged  2 "   2.009,-2e15 35  "  fad!" '   dfgsdfg ' ,   'asdfasdf'  " fasf ,  , asfa" "2 fs", .085     .835\"\"\"
rgex = re.compile(r\"\"\"(?<=["'])\s+(?=["'])|(?<=["'])\s+(?=\d)|(?<=\d)\s+(?=\d|\.\d)|(?<=(?<=\w|\d)\d)\s+(?=["'])|(?<=["'\d])\s*,\s*\"\"\")

re.sub(rgex, ",", s)

"""

print("1k iterations: ", timeit.timeit(stmt=s, number=1000))
print("10k iterations: ", timeit.timeit(stmt=s, number=10000))
print("100k iterations: ", timeit.timeit(stmt=s, number=100000))
print("200k iterations: ", timeit.timeit(stmt=s, number=200000))
print("300k iterations: ", timeit.timeit(stmt=s, number=300000))

rawDescription: python regex to split by comma or space (but leave strings as it is)

description: Python regex to split by comma or space (but leave strings as it is)


code:
from spectrum import *

data = data_cosine(N=2048, A=0.1, sampling=1024, freq=200)
# If you already have the DPSS windows
[tapers, eigen] = dpss(2048, 2.5, 4)
res = pmtm(data, e=tapers, v=eigen, show=False)
# You do not need to compute the DPSS before end
res = pmtm(data, NW=2.5, show=False)
res = pmtm(data, NW=2.5, k=4, show=True)

rawDescription: Multitaper function in Python?

description: Multitaper function in Python


code:
country = 'CANADA'
'*'.join(country)

rawDescription: How to do slicing when using sys.stdout.write()

description: Do slicing when using sys.stdout.write()


code: links = soup.find_all('a', {'id': re.compile('^c\d+')})

rawDescription: Find specific link text with bs4

description: Find specific link text with bs4


code:
word = 'alexgao'
split=3
[word[start:start+split] for start in range(0, len(word)-2)]
from nltk.util import ngrams
["".join(ng) for ng in ngrams(word,3)]

rawDescription: Creating a feature dictionary for Python machine learning (naive bayes) algorithm


code:
import re

p = re.compile(r'(?P<prefix>(?:\bu8|\b[LuU])?)(?:"(?P<dbl>[^"\\]*(?:\\.[^"\\]*)*)"|\'(?P<sngl>[^\'\\]*(?:\\.[^\'\\]*)*)\')|R"([^"(]*)\((?P<raw>.*?)\)\4"')
s = "\"text'\\\"here\"\nL'text\\'\"here'\nu8\"text'\\\"here\"\nu'text\\'\"here'\nU\"text'\\\"here\"\nR\"delimiter(text\"'\"here)delimiter\""
print(s)
print('--------- Regex works below ---------')
for x in p.finditer(s):
    if x.group("dbl"):
        print(x.group("dbl"))
    elif x.group("sngl"):
        print(x.group("sngl"))
    else:
        print(x.group("raw"))

rawDescription: Match C++ Strings and String Literals using regex in Python


code: patches = [mpl.patches.Rectangle(xy[i], dx[i], dy[i]) for i in range(mesh.shape[0])]

rawDescription: Log Scale Matplotlib PatchCollection Colors


code:
from datetime import datetime
datetime.strptime(" ".join(datetuple), "%b %d, %Y")

rawDescription: How do I strptime from a pattern like this?

description: Strptime from a pattern like this


code: grand_Matrix = np.vstack(m[None,...] for m in matrices)

rawDescription: Inserting one matrix as an element of another matrix using Numpy


rawDescription: Zip lists of tuples

description: Zip lists of tuples


rawDescription: Verifying counter falls in particular range or not in a packet capture


code:
import pyscreenshot as ImageGrab
# fullscreen
im=ImageGrab.grab()
im.show()

# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()

# to file
ImageGrab.grab_to_file('im.png')

rawDescription: Taking Screen shots of specific size

description: Taking Screen shots of specific size


code:
class FrmMainForm (QtGui.QWidget):
    def __init__(self):
        ...
        self._child_window = None

    def handleNewWindow(self):
       if self._child_window is None:
           self._child_window = Main(self)
       self._child_window.show()

class Main(QtGui.QWidget):
    ...
    def __init__(self, parent):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

rawDescription: Main form and child form

description: Main form and child form


code:
target_set = ['2', '3', '4']
any([l for l in result_matrix if target_set == l[1:-1]])
target_set = ['1', '2', '3']
any([l for l in result_matrix if target_set == l[1:-1]])

rawDescription: python slice set in list

description: Python slice set in list


code:
def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v  is  dictionary)
    reasons = {}
    for i in range(counter):
        reasons["reason{}".format(i)] = "{}[{}]".format(d_name, entry)
    return reasons

rawDescription: How to pass the name of a dictionary

description: Pass the name of a dictionary


rawDescription: Pandas comparison with variable number of columns


code:
[{'red': {'S': {'leather': {'available': True, 'cost': 100}}}},
 {'red': {'S': {'linen': {'available': True, 'cost': 100}}}},
 {'red': {'M': {'leather': {'available': True, 'cost': 100}}}},
 {'red': {'M': {'linen': {'available': True, 'cost': 100}}}},
 {'red': {'L': {'leather': {'available': True, 'cost': 100}}}},
 {'red': {'L': {'linen': {'available': True, 'cost': 100}}}},
 {'green': {'S': {'leather': {'available': True, 'cost': 100}}}},
 {'green': {'S': {'linen': {'available': True, 'cost': 100}}}},
 {'green': {'M': {'leather': {'available': True, 'cost': 100}}}},
 {'green': {'M': {'linen': {'available': True, 'cost': 100}}}},
 {'green': {'L': {'leather': {'available': True, 'cost': 100}}}},
 {'green': {'L': {'linen': {'available': True, 'cost': 100}}}},
 {'yellow': {'S': {'leather': {'available': True, 'cost': 100}}}},
 {'yellow': {'S': {'linen': {'available': True, 'cost': 100}}}},
 {'yellow': {'M': {'leather': {'available': True, 'cost': 100}}}},
 {'yellow': {'M': {'linen': {'available': True, 'cost': 100}}}},
 {'yellow': {'L': {'leather': {'available': True, 'cost': 100}}}},
 {'yellow': {'L': {'linen': {'available': True, 'cost': 100}}}}]

rawDescription: combine multidementional array into key based dictionary object

description: Combine multidementional array into key based dictionary object


code:
def gmm_kl(gmm_p, gmm_q, n_samples=10**5):
    X = gmm_p.sample(n_samples)
    log_p_X, _ = gmm_p.score_samples(X)
    log_q_X, _ = gmm_q.score_samples(X)
    return log_p_X.mean() - log_q_X.mean()

rawDescription: KL-Divergence of two GMMs

description: KL-Divergence of two GMMs


code:
Explanation
# regular expression to match line with a single value identified
# by having two commas at the end of the line.
# This grabs nike and adidas.
# It also grabs all lines after that until the next single valued line.
m = re.findall(r'(.*,,\n(.*([^,]|,[^,])\n)*)', text)

# place holder for list of sub dataframes
dfs = range(len(m))
# place holder for list of keys.  In this example this will be nike and adidas
keys = range(len(m))

# Loop through each regex match.  This example will only have 2.
for i, f in enumerate(m):
    # split on new line so I can grab and fix stuff
    lines = f[0].split('\n')
    # Fix that header row only has 2 columns and data has 3
    lines[1] += ','
    # Grab nike or adidas or other single value
    keys[i] = lines[0].split(',')[0]
    # Create dataframe by reading in rest of lines
    dfs[i] = pd.read_csv(StringIO('\n'.join(lines[1:])))

# Concat dataframes with appropriate keys and pivot stuff
df = pd.concat(dfs, keys=keys)
df = df.set_index(['USER_ID', 'USER_NAME'], append=True).unstack(0)

df.index = df.index.droplevel(0)
df.columns = df.columns.droplevel(0)

df = df.stack().unstack()

rawDescription: process data with header in rows in python csv

description: Process data with header in rows in python csv


rawDescription: Dealing with floating points: With numpy python in particular


code:
# Here we split the string into two lists, one containing adjacent tokens (nonwords)
# and the other containing the words
# The idea is to split / recombine the source string with quotes around all our words

w = re.compile(r'\W+')
nw = re.compile(r'\w+')

words = w.split(y)[1:-1] # ignore the end elements which are empty.
nonwords = nw.split(y) # list elements are contiguous non-word characters, i.e not a-Z_0-9
struct = '"{}"'.join(nonwords) # format structure of final output with quotes around the word's placeholder.
almost_there = struct.format(*words) # insert words into the string

rawDescription: Custom format to JSON

description: Custom format to JSON


code:
def this_takes_really_long():
    for _ in range(10000):
        do_some_more_work()
        while gtk.events_pending():
            gtk.main_iteration()

rawDescription: python GTK: Dialog with information that app is closing

description: Python GTK: Dialog with information that app is closing


code:
AfterHoursChangeRealtime
AnnualizedGain
Ask
AskRealtime
AverageDailyVolume
Bid
BidRealtime
BookValue
Change
Change_PercentChange
ChangeFromFiftydayMovingAverage
ChangeFromTwoHundreddayMovingAverage
ChangeFromYearHigh
ChangeFromYearLow
ChangeinPercent
ChangePercentRealtime
ChangeRealtime
Commission
Currency
DaysHigh
DaysLow
DaysRange
DaysRangeRealtime
DaysValueChange
DaysValueChangeRealtime
DividendPayDate
DividendShare
DividendYield
EarningsShare
EBITDA
EPSEstimateCurrentYear
EPSEstimateNextQuarter
EPSEstimateNextYear
ErrorIndicationreturnedforsymbolchangedinvalid
ExDividendDate
FiftydayMovingAverage
HighLimit
HoldingsGain
HoldingsGainPercent
HoldingsGainPercentRealtime
HoldingsGainRealtime
HoldingsValue
HoldingsValueRealtime
LastTradeDate
LastTradePriceOnly
LastTradeRealtimeWithTime
LastTradeTime
LastTradeWithTime
LowLimit
MarketCapitalization
MarketCapRealtime
MoreInfo
Name
Notes
OneyrTargetPrice
Open
OrderBookRealtime
PEGRatio
PERatio
PERatioRealtime
PercebtChangeFromYearHigh
PercentChange
PercentChangeFromFiftydayMovingAverage
PercentChangeFromTwoHundreddayMovingAverage
PercentChangeFromYearLow
PreviousClose
PriceBook
PriceEPSEstimateCurrentYear
PriceEPSEstimateNextYear
PricePaid
PriceSales
SharesOwned
ShortRatio
StockExchange
symbol
Symbol
TickerTrend
TradeDate
TwoHundreddayMovingAverage
Volume
YearHigh
YearLow
YearRange

rawDescription: Scraping for text between nondescript tags


code:
movie_actor =  (actor_movie.map(swap)
    .partitionBy(actor_movie.getNumPartitions())
    .cache())

rawDescription: PySpark - create pair RDD with two keys that share the same value


rawDescription: Python: sorting multilevel dictionary by part of key


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

register = create_template_register()

@register.filter
def replace_underscores(strng):
    return strng.replace('_', ' ')

rawDescription: Google appengine string replacement in template file


rawDescription: Python string formatting - old `%` vs new `str.format`


rawDescription: Summing up every alternate 4 elements in list


code: print('\n'.join(['%s %s'%(i,x) for i,j in zip(ul,ll) for x in j]))

rawDescription: How to Transpose Column Values to Row Values in Python


code: re.findall(r"Test([\d.]*\d+)", text)

rawDescription: Python regex findall numbers and dots

description: Python regex findall numbers and dots


code:
import time, pytz
utc = pytz.timezone('UTC')
utc_dt = utc.normalize(dt.astimezone(utc))
time.mktime(utc_dt.timetuple())

rawDescription: Convert datetime object in a particular timezone to epoch seconds in that timezone


rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code: GTK_ICONS = os.path.join("share", "icons")

rawDescription: Bundling GTK resources with py2exe

description: Bundling GTK resources with py2exe


rawDescription: Django - Following ForeignKey relationships "backward" for entire QuerySet


code:
from time import sleep
import threading
import uwsgidecorators

i = 0

@uwsgidecorators.postfork
@uwsgidecorators.thread
def daemon():
  global i
  while True:
    i += 1
    print(i)
    sleep(3)

def application(environ, start_response):
  start_response('200 OK', [('Content-Type','text/html')])
  return [str(i).encode()]

rawDescription: Python3 threading with uWSGI

description: Python3 threading with uWSGI


code:
val
'-'.join(str(x) for x in [val[6],val[5],val[4],val[2],val[1],val[0]])

rawDescription: Python 2.7 formatting data for writing as csv


rawDescription: Printing the values of a dictionary when its key is equal to the value of a list element


rawDescription: create dictionary from list same values

description: Create dictionary from list same values


code:
country_codes = {country: code for code, country in pytz.country_names.items()}
{c: pytz.country_timezones[country_codes[c]]
 for c in "Italy Egypt China India Singapore".split()}

rawDescription: Time Zones in python for program

description: Time Zones in python for program


code:
class CommentForm(ModelForm):
        class Meta:
               model = Comment
               exclude = ('user',)
               widgets = {'review': forms.HiddenInput()}

rawDescription: Django: posting a template value to a view


code: x[[1, random.randint(2, 4)]]

rawDescription: Select a specific column in a DF and a random column (python3, pandas)


code:
#set columns home and away to one columns for cumsum
df2 = df[['date', 'home', 'away', 'one']].set_index(['date', 'one'])
df2 = df2.stack().reset_index(name="both")
df2['new'] =  df2.groupby(['both'])['one'].cumsum() - 1
#print df2

#get back to original index
df1 = pd.pivot_table(df2, index=['date'], columns=['level_2'], values='new').reset_index()
#print df1

#merge with original df
df1 = pd.merge(df, df1, on=['date'], suffixes=('', '_new'))

#rename and casr float columns to integers columns
df1 = df1.rename(columns={'away_new':'aag', 'home_new':'hag',})
df1['aag'] = df1['aag'].astype(int)
df1['hag'] = df1['hag'].astype(int)

#count aaag and hahg
df1['aaag'] =  df1.groupby(['away'])['one'].cumsum() - 1
df1['hahg'] =  df1.groupby(['home'])['one'].cumsum() - 1

#drop helper column one and set index
df1 = df1.drop(['one'], axis=1 ).set_index('date')
#reorder columns
df1 = df1[['league', 'home', 'away', 'hscore', 'ascore', 'hag', 'aag', 'hahg', 'aaag']]

rawDescription: How to iteratively count in Pandas Dataframe

description: Iteratively count in Pandas Dataframe


code:
from operator import add
map(add, list1, list2)

rawDescription: Element-wise Addition of 2 Lists in Python?


code:
# Each x is a tuple (some-b-value, iterator-over-dicts-with-b-equal-some-b-value)
newdictList = [ next(x[1]) for x in tmp2 ]

rawDescription: Removing dictionaries from a list on the basis of duplicate value of key


code:
arr = df.unstack(['id']).values
# array([[ True, False,  True],
#        [ True,  True,  True]], dtype=bool)

rawDescription: pandas count true values in multi-index frame

description: Pandas count true values in multi-index frame


code:
from dateutil.parser import parse
data.sort(key=lambda x: parse(x[6]))

rawDescription: Sorting a list of different values by a specific field


code:
@app.route('/delete-bot/', methods=['post'])
def delete_bot():
    form = BotFormDelete()
    if form.validate():
        delete_bot(id=form.botid.data)
    flash('Bot is GONE')
    return redirect(url_for('index'))

rawDescription: flask wtforms, what input is pressed

description: Flask wtforms, what input is pressed


code: Panes = []

rawDescription: why is my code still displaying the old panes?

description: Why is my code still displaying the old panes


code:
def generate(r, maxs):
    m = np.zeros((r + 1, r + 1), dtype = np.int32)
    rows = [0]*(r+1) # We avoid recomputing row/col sums on each cell.
    cols = [0]*(r+1)
    rows[0] = cols[0] = m[0, 0] = maxs

    def go(i, j):
        if (i, j) == (r, r):
            yield m[1:, 1:].copy()
            return

        (i2, j2) = (i + 1, 1) if j == r else (i, j + 1)

        max_val = min(rows[i-1] - rows[i], cols[j-1] - cols[j])

        if i == j:
            max_val = min(max_val, m[i-1, j-1])
        if (i, j) != (1, 1):
            max_val = min(max_val, m[1, 1])

        for n in xrange(max_val, -1, -1):
            m[i, j] = n
            rows[i] += n
            cols[j] += n
            for matrix in go(i2, j2):
                yield matrix
            rows[i] -= n
            cols[j] -= n

    return go(1, 1)

rawDescription: Enumeration all possible matrices with constraints


code:
for book, author in bookdict.items():
    print(book.ljust(bookwidth) + ' ' + author.rjust(authorwidth))

rawDescription: Equally separating words in Python

description: Equally separating words in Python


code:
def __getattr__(self, name):
    def set_fn(self, value):
        return self.set({name:value})
    return set_fn

rawDescription: Mapping obj.method({argument:value}) to obj.argument(value)


code:
def add_data(node, name, value):
    # We're at a parent node (ex: paragraph-0), so we need to drill down until
    # we find a leaf node
    if '-' in name:
        key = name[:name.index('-')]
        node_index = int(name[len(key) + 1:name.index('.')])

        # Initialize the parent node if needed by giving it a dict to store it's
        # information nodes
        node.setdefault(key, [])
        if node_index >= len(node[key]):
            node[key].append({})

        # Drill down the tree by calling this function again, making this
        # parent node the root
        add_data(node[key][node_index],
                 name[name.index('.') + 1:],
                 value)

    # We're at a leaf node, so just add it to the parent node's information
    # ex:  The first formdata item would make the root_node dict look like
    # { 'name': 'Roel Kramer' }
    else:
        node[name] = value

rawDescription: HTML form data to recursive json dict

description: HTML form data to recursive json dict


rawDescription: Binary string in Python issues

description: Binary string in Python issues


code:
length_dict = {key: len(value) for key, value in d.items()}
length_key = length_dict['key']  # length of the list stored at `'key'` ...

rawDescription: How to find length of dictionary values

description: Find length of dictionary values


code:
def _show_value(*pargs):
    print(*pargs)
    print(root.globalgetvar(pargs[0]))

rawDescription: How to get Entry value using PY_VAR0 or PY_VAR1?

description: Get Entry value using PY_VAR0 or PY_VAR1


code:
driver = ogr.GetDriverByName("ESRI Shapefile")
shapeData = driver.CreateDataSource(args.output_folder) #so there we will store our data

for featidx, features in featmap.iteritems():
    featname = catnames[featidx]
    layer = shapeData.CreateLayer(featname, spatialReference, ogr.wkbPolygon)
for feature in features:
    layer.CreateFeature(feature)

shapeData.Destroy() #lets close the shapefile

rawDescription: Convert grc file to shp file using category names


code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 1234))
s.listen(1)
conn, addr = s.accept()
b = b''
while 1:
    tmp = conn.recv(1024)
    b += tmp
d = json.loads(b.decode('utf-8'))
print(d)

rawDescription: How to send the content of a dictionary properly over sockets in python3x?

description: Send the content of a dictionary properly over sockets in python3x


code:
df =  sc.parallelize([
    (1, "2016-01-06 00:04:21"),
    (2, "2016-05-01 12:20:00"),
    (3, "2016-08-06 00:04:21")
]).toDF(["id", "ts_"])

now = lit("2016-06-01 00:00:00").cast("timestamp")
five_months_ago = now - expr("INTERVAL 5 MONTHS")

(df
    # Cast string to timestamp
    # For Spark 1.5 use cast("double").cast("timestamp")
    .withColumn("ts", unix_timestamp("ts_").cast("timestamp"))
    # Find all events in the last five months
    .where(col("ts").between(five_months_ago, now))
    # Find first Sunday after the event
    .withColumn("next_sunday", next_day(col("ts"), "Sun"))
    # Compute difference in days
    .withColumn("diff", datediff(col("ts"), col("next_sunday"))))

rawDescription: PySpark add a column to a DataFrame from a TimeStampType column


code:
application = webapp.WSGIApplication([
        ...
        ('/i/(\d+)\.jpg', DownloadImage),
        ...
    ], debug=True)

rawDescription: Python app engine: how to save a image?

description: Python app engine: how to save a image


code:
for i in range(len(new_list)):
    cursor.executemany(query, new_list[i])
cnxn.commit()
cnxn.close()

rawDescription: how to transform pandas dataframe for insertion via executemany() statement?

description: Transform pandas dataframe for insertion via executemany() statement


code:
import itertools as IT
import numpy as np
import scipy.stats as stats

sample = np.array(list(IT.product(np.arange(5)-0.5,
                                  np.arange(5)*10-5,
                                  np.arange(5)*100-50)))
bins = [np.arange(4),
        np.arange(4)*10,
        np.arange(4)*100]

statistic, bin_edges, binnumber = stats.binned_statistic_dd(
    sample=sample, values=sample, statistic='count',
    bins=bins,
    range=[(0,100)]*3)

bin_edges = [np.r_[-np.inf, edge, np.inf] for edge in bin_edges]
edge_index = np.unravel_index(binnumber, [len(edge)-1 for edge in bin_edges])

for samp, idx in zip(sample, zip(*edge_index)):
    vert = [edge[i] for i, edge in zip(idx, bin_edges)]
    print('{} goes in bin with left-most corner: {}'.format(samp, vert))

rawDescription: How to find bin edges of given bin number returned by scipy.stats.binned_statistic_dd()?

description: Find bin edges of given bin number returned by scipy.stats.binned_statistic_dd()


rawDescription: Assign unique id to columns pandas data frame


code:
df2 = df.drop('bar') ## drops both 'bar one' and 'bar two'
df2 = df.drop(('baz', 'two')) ## drops only 'baz two'

rawDescription: Filter out rows/columns with zero values in MultiIndex dataframe


code:
first, _, _ = s.partition('\r')
k = len(first)

rawDescription: How do I get the length of the first line in a multi line string?

description: Get the length of the first line in a multi line string


code:
from django.conf.urls.defaults import patterns, url
from models import Model1, Model2, Model3

urlconf = ['', ]

for obj in (Model1, Model2, Model3):
    name = obj.__class__.__name__
    ResourceClass = type('%sResource' % name, (obj,), {
        'model': obj,
    })
    urlconf.append(url(r'^%s/$' % name, ListOrCreateModelView.as_view(resource=ResourceClass)))
    urlconf.append(url(r'^%s/(?P<pk>[^/]+)/$' % name, ListOrCreateModelView.as_view(resource=ResourceClass)))
urlpatterns = patterns(urlconf)

rawDescription: Django Rest Framework using the url to load specified models


rawDescription: Using BeautifulSoup to search html for string


code:
str_age = input("What is your present age ?\n")
present = int(str_age)
future = present + 5
future

rawDescription: How do I take output after giving the input in python?

description: Take output after giving the input in python


code:
removeNumerics('21st amendment')
removeNumerics('durham 28x23')

rawDescription: Removing numbers from strings

description: Removing numbers from strings


code:
result = pd.DataFrame({'X': g.count(),
                       'Y': g.apply(lambda x: x.str.startswith('u').sum())})

rawDescription: Plot bar graph using multiple groupby count in panda


code:
from Crypto.PublicKey import RSA
from base64 import b64decode

key64 = b'MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k\
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+znJDEbNHOD\
ZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE='

keyDER = b64decode(key64)
keyPub = RSA.importKey(keyDER)

rawDescription: How to read a RSA public key in PEM + PKCS#1 format

description: Read a RSA public key in PEM + PKCS#1 format


code:
filepath = 'C:\\Users\\Josh\\Documents\\Programming\\'
infile = filepath + 'data.txt'
infile = open(infile,"r")

rawDescription: Accelerometer Data write to file then graph Matplotlib (3 subplots [x, y, z])


code:
def sum(lst):
    s = 0
    for e in lst:
        s += e
    return s

def reverse(lst):
    l = []
    for e in lst:
        l = [e] + l
    return l

rawDescription: How simple list functions could be implemented in Python


code:
from bs4 import BeautifulSoup
import requests
import re

while True:
    symbol = input("Enter symbol: ")

    if symbol == 'stop':
        break

    url = 'http://finance.yahoo.com/q?s={}'.format(symbol)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, "html.parser")

    try:
        data = soup.find('span', attrs= {'id' : re.compile(r'yfs_.*?_{}'.format(symbol.lower()))})
        print('{} = {}'.format(symbol, data.text))
    except AttributeError:
        print("Unknown symbol: {}".format(symbol))

rawDescription: Python scraping stock prices

description: Python scraping stock prices


rawDescription: How to group a list into inclusive sequential n-tuples

description: Group a list into inclusive sequential n-tuples


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

for i in range(3):
    plt.plot(np.arange(10) + i)

plt.gca().set_color_cycle(None)

for i in range(3):
    plt.plot(np.arange(10, 1, -1) + i)

plt.show()

rawDescription: Reset color cycle in Matplotlib

description: Reset color cycle in Matplotlib


code:
def find_by_val(col, k, fle, delim=","):
    with open(fle) as f:
        names = next(f).rstrip().split(delim)
        if col not in names:
            print("Column does not exist.")
            return
        r, found = csv.DictReader(f, fieldnames=names), False
        for d in r:
            if un_id == d[col]:
                if not found:
                    print(",".join(names))
                    print(",".join([d[n] for n in names]))
                    found = True
                else:
                    print(",".join([d[n] for n in names]))
        if not found:
            print("No matching value for {} found".format(k))

rawDescription: Python2.7 - Passing argument to command line to filter CSV according to parameter


code: count = property(Get_count, Set_count)

rawDescription: How can I write a class that behaves exactly like another dynamically determined class? (Python)

description: Write a class that behaves exactly like another dynamically determined class? (Python)


code:
args.a
args.x
etc

rawDescription: Neatly pass positional arguments as args and optional arguments as kwargs from argpase to a function


code:
aList = [olditem, olditem, newitem, newitem]
                                  # ^ aList[0]

rawDescription: creating a dict iterating through two nested loops and a JSON output

description: Creating a dict iterating through two nested loops and a JSON output


code: [SeqRecord(seq=Seq('GAGATCGTCCGGGACCTGGGT', SingleLetterAlphabet()), id='chr1:1154147-1154167', name='chr1:1154147-1154167', description='chr1:1154147-1154167', dbxrefs=[]), SeqRecord(seq=Seq('GTCCGCTTGCGGGACCTGGGG', SingleLetterAlphabet()), id='chr1:983001-983021', name='chr1:983001-983021', description='chr1:983001-983021', dbxrefs=[])]

rawDescription: How to randomly extract FASTA sequences using Python?

description: Randomly extract FASTA sequences using Python


code:
result = []
for line in content:
    result.append(line.replace("\n",""))

rawDescription: for line in f: why is there a difference when replacing in lists?

description: For line in f: why is there a difference when replacing in lists


code: all_b_2s = [t for t in list_of_named_tuples if t.b == 2]

rawDescription: get all with same name and value in tuple using named tuple

description: Get all with same name and value in tuple using named tuple


code:
l=[sum([v for (k,v) in Transitions.iteritems() if k[1] == i]) for i in range(1,4,1)]
l

rawDescription: Sum values of a dictionary

description: Sum values of a dictionary


code:
s, t = 'acegikmoqsuwy', 'bdfhjlnprtvxz'
print(''.join(a + b for a, b in zip(s, t)))

rawDescription: How you can unite-merge parts of a sliced string?


code:
"""
print(table[0][0].rjust(colWidths[0]), table[1][0].rjust(colWidths[1]), table[2][0].rjust(colWidths[2]))
print(table[0][1].rjust(colWidths[0]), table[1][1].rjust(colWidths[1]), table[2][1].rjust(colWidths[2]))
print(table[0][2].rjust(colWidths[0]), table[1][2].rjust(colWidths[1]), table[2][2].rjust(colWidths[2]))
print(table[0][3].rjust(colWidths[0]), table[1][3].rjust(colWidths[1]), table[2][3].rjust(colWidths[2]))
"""

rawDescription: Automate the Boring Stuff, Chapter 6 Table Printer


code:
def test_once_more():
    return "123456789"

rawDescription: AttributeError: 'function' object has no attribute 'replace'


code:
def my_function(argument1, argument2):
    if some_obvious_error_condition:
        return "ERR"

    # 100 lines of complex code

    return other_thing

rawDescription: Reducing the amount of return statements


code:
df = pd.DataFrame([[1, 2], [1, 3], [5, 6]], columns=['A', 'B'])
df
g = df.groupby('A')  #  GROUP BY A
g.filter(lambda x: len(x) > 1)  #  HAVING COUNT(*) > 1

rawDescription: pandas: what is the equivalent of SQL group by having?

description: Pandas: what is the equivalent of SQL group by having


rawDescription: How should I take the max of 2 columns in a dataframe and make it another column?


rawDescription: Title case for a paragraph

description: Title case for a paragraph


code:
def pairwise_distance2(s):
    # we need this because we're gonna divide by zero
    old_settings = np.seterr(all="ignore")

    N = N_segments # just shorter, could also use len(s)

    # we repeat p0 and p1 along all columns
    p0 = np.repeat(s[:,0:3].reshape((N, 1, 3)), N, axis=1)
    p1 = np.repeat(s[:,3:6].reshape((N, 1, 3)), N, axis=1)
    # and q0, q1 along all rows
    q0 = np.repeat(s[:,0:3].reshape((1, N, 3)), N, axis=0)
    q1 = np.repeat(s[:,3:6].reshape((1, N, 3)), N, axis=0)

    # element-wise dot product over the last dimension,
    # while keeping the number of dimensions at 3
    # (so we can use them together with the p* and q*)
    a = np.sum((p1 - p0) * (p1 - p0), axis=-1).reshape((N, N, 1))
    b = np.sum((p1 - p0) * (q1 - q0), axis=-1).reshape((N, N, 1))
    c = np.sum((q1 - q0) * (q1 - q0), axis=-1).reshape((N, N, 1))
    d = np.sum((p1 - p0) * (p0 - q0), axis=-1).reshape((N, N, 1))
    e = np.sum((q1 - q0) * (p0 - q0), axis=-1).reshape((N, N, 1))

    # same as above
    s = (b*e-c*d)/(a*c-b*b)
    t = (a*e-b*d)/(a*c-b*b)

    # almost same as above
    pairwise = np.sqrt(np.sum( (p0 + (p1 - p0) * s - ( q0 + (q1 - q0) * t))**2, axis=-1))

    # turn the error reporting back on
    np.seterr(**old_settings)

    # set everything at or below the diagonal to 0
    pairwise[np.tril_indices(N)] = 0.0

    return pairwise

rawDescription: Python, Pairwise 'distance', need a fast way to do it


code:
all_mentions = all_mentions.stack()
all_mentions

rawDescription: Split a Pandas 'findall' result list into multiple items, to group by uniques


code: bInds = [ indices[c] for c in a ]

rawDescription: large array searching with numpy

description: Large array searching with numpy


code:
def getCordInImage(self, x, y, t):
    return [x - t.x, y - t.y]

rawDescription: Python pygame Detect if mouse is over non transparent part of surface


code:
def shift_hue(arr, hout):
    r, g, b, a = np.rollaxis(arr, axis=-1)
    h, s, v = rgb_to_hsv(r, g, b)
    h = hout
    r, g, b = hsv_to_rgb(h, s, v)
    arr = np.dstack((r, g, b, a))
    return arr

rawDescription: Changing the color of an image based on RGB value


code:
import numpy as np
import pylab as plt

xs = [1, 2, 1, 4, 3, 2]
ys = [1, 3, 2, 2, 3, 1]
labels = [1, 1, 0, 2, 1, 3]

xs = np.array(xs)
ys = np.array(ys)
labels = np.array(labels)

labels_masks =( (x,(labels == x)) for x in set(labels))
data_dict = dict( (lbl,(xs[mask],ys[mask])) for lbl,mask in labels_masks )

label_dict = {0: 'r', 1: 'k', 2: 'b', 3: 'g'}
legend_dict = {0: 'foo', 1: 'bar', 2: 'baz', 3: 'biff'}

for label,data in data_dict.items():
    x,y = data
    plt.scatter(x,y,c=label_dict.get(label),label=legend_dict.get(label))

plt.legend()
plt.show()

rawDescription: Depict legend without repeats

description: Depict legend without repeats


code:
def final_result(r):
    if isinstance(r.result, celery.result.AsyncResult):
         return final_result(r.result)
    else:
        return r.result

rawDescription: celery issuing tasks from subtasks

description: Celery issuing tasks from subtasks


code:
iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_frame(iframe)

rawDescription: How to find xpath of an element in a window that's inside another "frame window"

description: Find xpath of an element in a window that's inside another "frame window"


code:
name, ext = os.path.splitext(path)
ext = ext[1:]

rawDescription: Is there another better way to get file ext from a given path in python


code:
high
jive
life
shah
facie
hutch

rawDescription: Find words from a sequence of random letters?


code:
def dict_to_csv(my_dict, txtFileName, destination_file):

    with open(destination_file, 'wb') as f:
        writer = csv.DictWriter(f, my_dict.keys())
        writer.writeheader()
        for key, row in my_dict.iteritems():
            writer.writerow(dict(row, **{'': key})) #this is the row where I'm getting the error message
    f.closed()

rawDescription: writing a nested dictionary to csv file

description: Writing a nested dictionary to csv file


code: import urllib.request

rawDescription: Python can't find installed modules

description: Python can't find installed modules


code:
import requests
r = requests.get('http://nppes.viva-it.com/NPI_Files.html')
import re
re.findall('http.*NPPES.*\.zip', r.text)

rawDescription: Python Downloading Data File from Web-Scraped URL


rawDescription: find tangent vector at a point for discrete data points

description: Find tangent vector at a point for discrete data points


code: yield key, [v for v in value if v not in seen]

rawDescription: Dictionary with sorted unique values

description: Dictionary with sorted unique values


code:
import xlrd
book = xlrd.open_workbooks('Book1')
sheet = book.sheet_by_name('Sheet1')
sheel.col(1)

rawDescription: Querying an Excel spreadsheet and returning results? But which program?


code:
#XXX: WRONG (for any timezone with a non-fixed utc offset), DON'T DO IT
datetime(2011,2,11,20,0,0,0,pacific).astimezone(utc).strftime("%s")

rawDescription: Python - Setting a datetime in a specific timezone (without UTC conversions)


code:
Abstract()
class StillAbstract(Abstract):
    pass

StillAbstract()
class Concrete(Abstract):
    def foo(self):
        print('Hello, World')

Concrete()

rawDescription: Is it possible to make abstract classes in python?


rawDescription: Cross-list comprehension in Python

description: Cross-list comprehension in Python


code: lines = [line.strip('<>,\n').split(',') for line in f]

rawDescription: Splitting Lists elements further

description: Splitting Lists elements further


code:
def CalcOrPass(func):
    @wraps(func)
    def result(self, *args, **kwargs):
        res = self.stats[func.__name__]
        if not res:
            res = func(self, *args, **kwargs)
            self.stats[func.__name__] = res
        return res
    return result

rawDescription: Accessing self from outside of a class

description: Accessing self from outside of a class


code:
def GetIntegerSlice(i, n, m):
  # return nth to mth digit of i (as int)
  l = math.floor(math.log10(i)) + 1
  return i / int(pow(10, l - m)) % int(pow(10, m - n + 1))

rawDescription: Get part of an integer in Python

description: Get part of an integer in Python


code:
def content_text(text):
    stopwords = set(nltk.corpus.stopwords.words('english'))
    with_stp = Counter()
    without_stp  = Counter()
    for word in text:
        # update count off all words in the line that are in stopwords
        word = word.lower()
        if word in stopwords:
             with_stp.update([word])
        else:
           # update count off all words in the line that are not in stopwords
            without_stp.update([word])
    # return a list with top ten most common words from each
    return [k for k,_ in with_stp.most_common(10)],[y for y,_ in without_stp.most_common(10)]

print(content_text(nltk.corpus.inaugural.words('2009-Obama.txt')))

rawDescription: Print 10 most frequently occurring words of a text that including and excluding stopwords


rawDescription: Can somebody explain a money regex that just checks if the value matches some pattern?


code: np.broadcast_arrays(arr, [1,3,9])

rawDescription: comparing ndarray with values in 1D array to get a mask

description: Comparing ndarray with values in 1D array to get a mask


code:
import time, datetime

def now_milliseconds():
   return int(time.time() * 1000)

# reference time.time
# Return the current time in seconds since the Epoch.
# Fractions of a second may be present if the system clock provides them.
# Note: if your system clock provides fractions of a second you can end up
# with results like: 1405821684785.2
# our conversion to an int prevents this

def date_time_milliseconds(date_time_obj):
   return int(time.mktime(date_time_obj.timetuple()) * 1000)

# reference: time.mktime() will
# Convert a time tuple in local time to seconds since the Epoch.

mstimeone = now_milliseconds()

mstimetwo = date_time_milliseconds(datetime.datetime.utcnow())

# value of mstimeone
# 1405821684785
# value of mstimetwo
# 1405839684000

rawDescription: python function to return javascript date.getTime()

description: Python function to return javascript date.getTime()


code: exre = r'decadal[0-9]{4}'

rawDescription: Create list using regex inputs

description: Create list using regex inputs


code:
from matplotlib import interactive
interactive(True)
from matplotlib import pyplot as plt
plt.plot([1,2,3,4])

rawDescription: Interactive matplotlib under windows

description: Interactive matplotlib under windows


code: collection.update({ "_id" : ObjectId("4f1c567d60de7d0908000000")}, { '$pushAll' : { 'pricing' : newpricingdata } }, false, false);

rawDescription: python/mongodb Updating and Structure in subtrees

description: Python/mongodb Updating and Structure in subtrees


code: df_scen['% change'] = 100 * df_scen[('scenario', 2)] / df_scen[('scenario', 1)] - 100

rawDescription: How to df.groupby.sum only one column

description: Df.groupby.sum only one column


John Doe

address: myAdress

rawDescription: Parsing a file that looks like JSON to a JSON


code:
import pandas as pd
import numpy as np

np.random.seed(5)
strings=list('ABC')
events=[strings[i] for i in np.random.randint(0,3,20)]
groups=[1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2]
index=pd.date_range('2/2/2012',periods=20,freq='T')
dfm=pd.DataFrame(data={'event':events,'group':groups},index=index)
for i in range(1,4):
    dfm['event_t%i'%i]=dfm.event.groupby(dfm.group).shift(-i)

rawDescription: Estimating transition probabilities (pandas)


code:
class FakeHandleFactory():
    _hl = threading.Lock()
    _next = 0
    @staticmethod
    def next():
        FakeHandleFactory._hl.acquire()
        ret = FakeHandleFactory._next
        FakeHandleFactory._next += 1
        FakeHandleFactory._hl.release()
        return ret

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code:
def aggregate(documents, base_document=None, unique=True):
    # use unique=False to keep all values in the lists, even if repeated
    # like [100, 100, 200, 300], leave it True otherwise
    for doc in documents:
        if isinstance(doc, list):
            if base_document is None: base_document = []
            for d in doc:
                base_document.append(d)
            if unique==True: base_document = set(base_document)
            base_document = sorted(base_document)
        else:
            if base_document is None: base_document = {}
            for d in doc:
                b = base_document[d] if d in base_document \
                    else [] if isinstance(doc[d], list) else {}
                base_document[d] = aggregate([doc[d]], base_document=b)
    return base_document

rawDescription: Combining nested collection in mongodb with documents written from parallel nodes


code:
class File(Model):
    node # foreign key to Node
    name # name of file
    file # django models.FileField

rawDescription: How can i make the tree like menus from python list

description: Make the tree like menus from python list


code:
new_list = []
for i in items:
    new_list.append(i["name"])

return ','.join(new_list)

rawDescription: Taking a list of items and displaying a value from each item as a string


code:
import tkinter as tk

root = tk.Tk()

global num
num = 0

def create():
    global entry
    global num
    if num == 0:
        num = 1
        entry = tk.Entry()
        entry.pack()

def destroy():
    global entry
    global num
    if num == 1:
        num = 0
        entry.destroy()

button1 = tk.Button(text = 'create entry', command = create)
button1.pack()

button2 = tk.Button(text = 'destroy entry', command = destroy)
button2.pack()

root.mainloop()

rawDescription: Python: Using Tkinter radio-buttons to add/remove fields from GUI


code: lookup = {entry['name']: entry['id'] for entry in stop_list}

rawDescription: How to get a value from a list of dictionary Python?

description: Get a value from a list of dictionary Python


code:
class MoveFileCommand(object):
    def __init__(self, src, dest):
        self.src = src
        self.dest = dest
        os.rename(self.src, self.dest)
    def undo(self):
        os.rename(self.dest, self.src)

undo_stack = []
undo_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))
undo_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))
# foo.txt is now renamed to baz.txt
undo_stack.pop().undo() # Now it's bar.txt
undo_stack.pop().undo() # and back to foo.txt

rawDescription: General Command pattern and Command Dispatch pattern in Python


code:
from Tkinter import *
framelist=[]
frames=1
def add_frame():
    global frames
    framelist.append(Frame(root))
    framelist[-1].grid()
    frames+=1

root=Tk()
for i in range(20):
    add_frame()
    Label(framelist[i], text="Frame %i" % (i)).grid()
framelist[6].destroy()
root.mainloop()

rawDescription: How to delete a specific row of label widgets in tkinter app

description: Delete a specific row of label widgets in tkinter app


code:
res_best_times = [result.best * 1e9 for result in res]
# "* 1e9" to get the result in nanoseconds
print(res_best_times)
# [61.2, 61.3, 61.5]

rawDescription: %timeit equivalent in code

description: %timeit equivalent in code


code:
import json
# Make sure output is the list object not a string representing the object
json_string = json.dumps(output)
jason = json.loads(output)
jason[0]['entities']['hashtags']

rawDescription: Python Json loads() returning string instead of dictionary?


code:
from scipy.interpolate import griddata
import numpy as np

# Create some test data, 3D gaussian, 200 points
dx, pts = 2, 100j

N = 500
R = np.random.random((N,3))*2*dx - dx
V = np.exp(-( (R**2).sum(axis=1)) )

# Create the grid to interpolate on
X,Y,Z = np.mgrid[-dx:dx:pts, -dx:dx:pts, -dx:dx:pts]

# Interpolate the data
F = griddata(R, V, (X,Y,Z))

rawDescription: 3D Contour plot from data using Mayavi / Python


code:
primes=[]
for x in range(2,50):
  if x not in noprimes:
    primes.append(x)

rawDescription: No Primes list Comprehension

description: No Primes list Comprehension


code:
class CategoryAdmin(admin.ModelAdmin):

    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}

        if request.user.is_superuser:
            self.list_filter = ['department','name']
        else:
            self.list_filter = (UserCategoryListFilter,)

rawDescription: django1.8 filter list_filter based on login

description: Django1.8 filter list_filter based on login


code:
url(r'(?P<category>[a-z]+)$', 'display', name='dyn_display')
reverse('dyn_display', kwargs={'category': 'first'})

rawDescription: pass kwargs for the view in reverse; django 1.5

description: Pass kwargs for the view in reverse; django 1.5


code:
@property
def responseoperationcode(self):
    return self.innerobject.operationcode

@responseoperationcode.setter
def responseoperationcode(self, value):
    self.innerobject.operationcode = value

rawDescription: Getter and Setter for member variable in Python


rawDescription: Multi-index slicing of dataframe with list


code: numpy.minimum(A, B, out=A)

rawDescription: Python replacing max values in array

description: Python replacing max values in array


code:
def p_dynamics(p):
    'DYNAMICS BLOCK END DYNAMICS'

rawDescription: Identifying keyword pairs in lex

description: Identifying keyword pairs in lex


code:
def set_viewport_size(driver, width, height):
    window_size = driver.execute_script("""
        return [window.outerWidth - window.innerWidth + arguments[0],
          window.outerHeight - window.innerHeight + arguments[1]];
        """, width, height)
    driver.set_window_size(*window_size)

rawDescription: How to set browser viewport size

description: Set browser viewport size


code:
tags = soup.find_all(None)
for tag in tags:
   if tag.child is None:
       tag.child.contents[0].replace('\n ', '')
   else:
       tag.contents[0].replace('\n ', '')

rawDescription: How do I remove linebreaks ONLY if they occur inside html tags?

description: Remove linebreaks ONLY if they occur inside html tags


code:
for i in range (x):
    newDict[data[i]] = data[i+x::x]

print (newDict)

rawDescription: How can I create a nested list from an existing one where the first x items are the outer items?

description: Create a nested list from an existing one where the first x items are the outer items


code:
myList = ['', '', 'foo', '', 'bar', '', '', 'fizz', '', 'buzz']

from itertools import groupby, chain

def consec(l):
    for k, v in groupby(l):
        lst = list(v)
        if len(lst) > 1 or lst[0]:
            yield lst

myList[:] = chain.from_iterable(consec(myList))
print(myList)

rawDescription: How to remove blank element in between non-blank elements in list?

description: Remove blank element in between non-blank elements in list


code:
if right_best is None:
    return bst.val

rawDescription: How can I make the following function into a tail-recursive function?

description: Make the following function into a tail-recursive function


rawDescription: How to use reverse() in django on included URLs?

description: Use reverse() in django on included URLs


rawDescription: Pandas: Dealing with Boolean in Pivot Table


code:
with open('jag.txt') as f:
    lines = [ line for line in csv.reader(f, delimiter='\t') ]

rawDescription: python text files

description: Python text files


rawDescription: Looped vs Bulk arithmetic

description: Looped vs Bulk arithmetic


code:
new_key = db.Key.from_path(*old_key.to_path(),
                           _app='new-app-id',
                           parent=old_key.parent(),
                           namespace=old_key.namespace())

rawDescription: programmatically convert a string of datastore key for a new app ID? (Master/slave -> HRD migration)

description: Programmatically convert a string of datastore key for a new app ID? (Master/slave -> HRD migration)


code:
def twolines(file):
    cur = None
    for i in file:
        if cur is None:
            cur = i
        else:
            yield (cur, i)
            cur = None

rawDescription: Manually read lines in python

description: Manually read lines in python


code:
characterslist=[]
f=open('putyourtextfilenamehere','r')
while 1:
    x=f.readline().strip()
    if x=='':
        f.close()
        break
    x=[x[i] for i in range(len(x))]
    for j in x:
        characterslist.append(j)

rawDescription: Python. Import specific characters from a .txt file


rawDescription: convert string to date type python

description: Convert string to date type python


code:
class A(object):
    _COUNTER = 0

    @increment_counter
    def do_something_1(self):
        ...

    @increment_counter
    def do_something_2(self):
        ...

    @increment_counter
    def do_something_N(self):
        ...

rawDescription: How can I increase counter properties of class when a instance is called?

description: Increase counter properties of class when a instance is called


code:
len(teamid)
teamid[0].keys()

rawDescription: Parsing json element

description: Parsing json element


code:
class Parameters(object):
    def __init__(self):
        self.__dict__['paramOrder'] = []

    # etc.

rawDescription: How to handle call to __setattr__ from __init__?

description: Handle call to __setattr__ from __init__


code:
timer = QTimer()
timer.timeout.connect(self.update_game)
timer.start(100)  # Update rate

@QtCore.pyqtSlot()
def update_game(self):
    if Qt.Key_Space in pressed_keys:
        ...
    if Qt.Key_Up in pressed_keys:
        ...

rawDescription: How to process short keypress in the same time long keypress is performed?

description: Process short keypress in the same time long keypress is performed


code: grid_widget.Scroll(row, column)

rawDescription: How to make auto scrolling wx.grid table?

description: Make auto scrolling wx.grid table


code:
from itertools import groupby
from operator import itemgetter
lst = [[1, 1, 1], [2, 1, 2], [2, 2, 1], [3, 4, 1], [3, 4, 5], [3, 1, 0]]
[[k] + [sum(col) for col in zip(*g)[1:]] for k, g in groupby(lst, itemgetter(0))]

rawDescription: Python: Add lists together

description: Python: Add lists together


rawDescription: Guessing a number, true or false? Python


rawDescription: Creating a list using csv.reader()

description: Creating a list using csv.reader()


code:
a = [[2,4],[3,1]]
sweep_non_sym(a, 0)
sweep_non_sym(sweep_non_sym(a, 0), 1)
np.dot(a, sweep_non_sym(sweep_non_sym(a, 0), 1))

rawDescription: Python implementation of statistical Sweep operator


rawDescription: savetxt two columns in python,numpy

description: Savetxt two columns in python,numpy


rawDescription: Python pandas to partially collapse 2d matrix


code:
# This code assumes Python 3.x
from itertools import count, zip_longest

def file_data_lines(fname, comment_start="* "):
    """
    Return lines of data from file
     (strip out blank lines and comment lines)
    """
    with open(fname) as inf:
        for line in inf:
            line = line.rstrip()
            if line and not line.startswith(comment_start):
                yield line

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=fillvalue, *args)

def city_data(fname):
    data = file_data_lines(fname)

    # city 0 has no distances line
    city_line = next(data)
    city, lat, lon, pop = get_city(city_line)
    yield city, (lat, lon), pop, []

    # all remaining cities
    for city_line, dist_line in grouper(data, 2, ''):
        city, lat, lon, pop = get_city(city_line)
        dists = get_distances(dist_line)
        yield city, (lat, lon), pop, dists

rawDescription: Regular Expressions in data parsing Python


code:
def createImageDb(directory):
    d = {}
    # do something to fill in the dict
    return d

rawDescription: Subclassing dict: should dict.__init__() be called?


code:
from django.db import connections

class DBRouter(object):
    """A router to control all database operations on models in
    the contrib.auth application"""

    def db_for_read(self, model, **hints):
        if hasattr(model,'connection_name'):
            return model.connection_name
        return None

    def db_for_write(self, model, **hints):
        if hasattr(model,'connection_name'):
            return model.connection_name
        return None

    def allow_syncdb(self, db, model):
        if hasattr(model,'connection_name'):
            return model.connection_name
        return None

rawDescription: Multiple Database Config in Django 1.2

description: Multiple Database Config in Django 1.2


code:
n = 2
listo = [1, 2, 3, 4, 5, 6, 7, 8, 9]
split_list = [listo[i:i+n] for i in range(0, len(listo), n)]
split_list
listo = '123456789'
split_list = [listo[i:i+n] for i in range(0, len(listo), n)]
split_list

rawDescription: how to parse a list or string into chunks of fixed length

description: Parse a list or string into chunks of fixed length


code:
x=0
if isinstance(a,(dict,list,tuple)):
    x=sum(similarity(i,j) for i in a for j in b)

rawDescription: Python, best way to write a sum of two for loops


code:
class Parent(Base):
    __tablename__ = 'parent'
    parent_id = Column(String, primary_key=True)
    name = Column(String, nullable=False)

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    parent = relationship(
        Parent,
        primaryjoin=("A" + cast(id, String) == Parent.parent_id),
        foreign_keys=id,
        remote_side=Parent.parent_id,
        backref="children",
        # uselist=False,  # use in case of one-to-one relationship
    )

rawDescription: relationship with a sliced and casted value of the column in SQLAlchemy

description: Relationship with a sliced and casted value of the column in SQLAlchemy


rawDescription: Python: Function returning highest value in list without max()?


rawDescription: Please explain (python): example_list[a < b]


code:
class Article(Base):
    # ...

    segments = relationship(Segment)

    visible_segments = relationship(Segment,
            primaryjoin="and_(Segment.article_id == Article.id, Segment.visible == True)")

    @property
    def visible_items(self):
        return [item for segment in self.visible_segments
                     for item in segment.visible_items]

class Segment(Base):
    # ...

    items = relationship(Item)
    visible_items = relationship(Item,
               primaryjoin="and_(Item.segment_id == Segment.id, Item.visible==True)")

rawDescription: SQLAlchemy - Filtering children in One-To-Many relationships


code:
for an_id in a_long_list_of_ids:
   cursor.execute("SELECT * FROM my_table WHERE id=%s", (an_id,))
   do_something(cursor.fetchall())

rawDescription: difference between SELECT queries embedded in for loop vs WHERE id IN syntax

description: Difference between SELECT queries embedded in for loop vs WHERE id IN syntax


code:
nums = arange(2003, 2010)
xticks(nums, (str(n) for n in nums))

rawDescription: How do I force matplotlib to write out the full form of the x-axis label, avoiding scientific notation?

description: Force matplotlib to write out the full form of the x-axis label, avoiding scientific notation


code:
class Address(models.Model):
    blah

class MemberData(models.Model):
    user = models.ForeignKey(User)
    addresses = models.ManyToManyField(Address,through='MemberAddress')

class MemberAddress(models.Model):
    member = models.ForeignKey(MemberData)
    address = models.ForeignKey(Address)

rawDescription: Enabling Django Admin Filters on Many-to-Many Fields


rawDescription: Python enumerate downwards or with a custom step


code:
import json
with open('myfile', 'w') as f:
    f.write(json.dumps(data))

rawDescription: Overwrite flags in a file python

description: Overwrite flags in a file python


code: assert all([i==j for i,j in zip(tuple1,tuple2)])

rawDescription: pytest: assert almost equal

description: Pytest: assert almost equal


code:
import lxml.etree as etree

file_content = '''<tes:variable xmlns:tes="http://www.tidalsoftware.com/client/tesservlet" xmlns="http://purl.org/atom/ns#">
  <tes:ownername>OWNER</tes:ownername>
  <tes:productiondate>2015-08-23T00:00:00-0400</tes:productiondate>
  <tes:readonly>N</tes:readonly>
  <tes:publish>N</tes:publish>
  <tes:description>JIRA-88</tes:description>
  <tes:startcalendar>0</tes:startcalendar>
  <tes:ownerid>88</tes:ownerid>
  <tes:type>2</tes:type>
  <tes:innervalue>4</tes:innervalue>
  <tes:calc>N</tes:calc>
  <tes:name>test_number3</tes:name>
  <tes:startdate>1899-12-30T00:00:00-0500</tes:startdate>
  <tes:pub>Y</tes:pub>
  <tes:lastvalue>0</tes:lastvalue>
  <tes:id>2078</tes:id>
  <tes:startdateasstring>18991230000000</tes:startdateasstring>
</tes:variable>'''

template = '''<?xml version="1.0" encoding="UTF-8" ?>
<entry xmlns="http://purl.org/atom/ns#">
    <tes:Variable.update xmlns:tes="http://www.tidalsoftware.com/client/tesservlet">
        <object></object>
    </tes:Variable.update>
</entry>'''

tree = etree.fromstring(template)
container = tree.xpath('//d:object', namespaces={'d':'http://purl.org/atom/ns#'})[0]
parent = container.getparent()

content_tree = etree.fromstring(file_content)

parent.replace(container, content_tree)

print(etree.tostring(tree))

rawDescription: python lxml insert xml file into xml string

description: Python lxml insert xml file into xml string


code:
from itertools import cycle, islice

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

rawDescription: Merge 2 lists at every x position

description: Merge 2 lists at every x position


code: newstring = "".join(s1[i:i+1] for i in lst)

rawDescription: How to construct a string by joining characters efficiently?

description: Construct a string by joining characters efficiently


code: df.groupby(lambda x: x/2).mean().groupby(lambda y: y/2, axis=1).mean()

rawDescription: How to downsample a pandas dataframe

description: Downsample a pandas dataframe


code: locations = filter(None, [self.room, self.floor, self.building])

rawDescription: Python: a better way to write a if-then block with join?


code:
def minmax(val_list):
    min_val = min(val_list)
    max_val = ma(val_list)

    return (min_val, max_val)

rawDescription: Getting the range of data from a list in Python


code: {{ text|linebreaks }}

rawDescription: How to output a paragraph with line breaks in django and mysql?

description: Output a paragraph with line breaks in django and mysql


rawDescription: Calculation and construction of two dimensional array with nested loop


code:
list_of_dicts = [{'ParentGuardianID': 'PG001'}, {'ParentGuardianID': 'PG002'}, {'ParentGuardianID': 'PG003'}, {'ParentGuardianID': 'PG004'}]
list_of_dicts[0]  # returns one of the dictionaries
list_of_dicts[0]['ParentGuardianID']  # get the value from the dict
[d['ParentGuardianID'] for d in list_of_dicts]

rawDescription: Obtaining a value from a list of dictionaries


code:
self.name = name
self.poketype = poketype

rawDescription: Error with a simple program, printing error (python)


code:
mat = np.arange(16).reshape(4, 4)
n = 4
idx = np.arange(n)
idx[:, None] + idx
idx[:, None] + idx < n - 1
mat[idx[:, None] + idx < n  -1] = 0
mat

rawDescription: How do i access all elements of numpy array which indexes satisfy some condition?

description: Access all elements of numpy array which indexes satisfy some condition


code:
# a.py
from pymc import *

count = [10, 10] # perhaps good to put this stuff in data.py
prob_distribution = [[.5, .5], [.1, .2, .7]]
data = [[2, 8], [2, 3, 5]]

def model(training_pool):
    x = Uniform('x', lower = 0, upper = 1)
    rv = [ Multinomial("rv"+str(i), count[i], prob_distribution[i], value = data[i], observed=True) for i in training_pool ]

    return locals()

rawDescription: import a module with parameter in python

description: Import a module with parameter in python


true

false

false

rawDescription: Query mysql from json came from angularjs - Python


code:
...
plt.savefig(...)
plt.close()

rawDescription: Numpy and matplotlib garbage collection

description: Numpy and matplotlib garbage collection


code:
from csv import reader, writer

data = list(reader(open("filename.csv", "r"), delimiter=" "))

out = writer(open("output.csv", "w"), delimiter=" ")

for row in reader(open("index.csv", "r"), delimiter=" "):
    out.writerow(row + data[int(row[3])])

rawDescription: Python: How to write values to a csv file from another csv file


rawDescription: How do I change an element in a list, and keep a copy of the original list?

description: Change an element in a list, and keep a copy of the original list


code:
import re
with open('C:\\Users\\Me\\file.bin', 'rb') as f:
    data = f.read()

re.findall("\d+\.\d+", data)

rawDescription: How to find floating point numbers in binary file with Python?

description: Find floating point numbers in binary file with Python


code:
from itertools import permutations, product, chain
def my_prod(lst):
    return product(*map(permutations, lst))

list(chain(*map(my_prod, permutations(lst))))

rawDescription: Python itertools get permutations and combinations of a list of lists


code:
first = True
for i in range(10):
    if first:
        first = False
        # Do whatever you need to do for the first time
        continue
    # Do something...

rawDescription: Making for loop ignore something first time through


code:
def qt_connections(self):
    self.increasebutton.clicked.connect(self.on_increasebutton_clicked)
    self.decreasebutton.clicked.connect(self.on_decreasebutton_clicked)

rawDescription: How to update a realtime plot and use buttons to interact in pyqtgraph?

description: Update a realtime plot and use buttons to interact in pyqtgraph


code:
if request.method == 'POST' and request.POST['action'] == 'start_manifest':
    call_function1()
if request.method == 'POST' and request.POST['action'] == 'close_manifest':
    call_function2()

rawDescription: how to pass multiple ajax calls in a single django view

description: Pass multiple ajax calls in a single django view


rawDescription: Class attribute overriding: keep parent class changes


code:
counts = {}
for p in paths:
   parts = p.split('/')
   branch = counts
   for part in parts[1:-1]:
      branch = branch.setdefault(part, {})
   branch[parts[-1]] = 1 + branch.get(parts[-1], 0)

rawDescription: Python: recursively create dictionary from paths


code:
def read_all(self,count=-1):
    """return an iterable of all packets in the pcap file
    """
    while count != 0:
        count -= 1
        p = self.read_packet()
        if p is None:
            break
        yield p
    return

rawDescription: How to read .cap files other than Pyshark that is faster than Scapy's rdpcap ()?

description: Read .cap files other than Pyshark that is faster than Scapy's rdpcap ()