code:
import kivy

from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.lang import Builder

Builder.load_string('''
# a template Butt of type Button
[Butt@Button]
    # ctx.'attribute_name' is used to access the
    # attributes defined in the instance of Butt.
    text: ctx.text
    # below vars are constant for every instance of Butt
    size_hint_x: None
    width: 100

<CalcApp>:
    cols: 3
    row_force_default: True
    row_default_height: 50
    pos_hint: {'center_x':.5}
    size_hint: (None, None)
    # size is updated whenever minimum_size is.
    size: self.minimum_size
    # top is updated whenever height is.
    top: self.height
    Butt:
        text: '1'
    Butt:
        text: '2'
    Butt:
        text: '3'
    Butt:
        text: '4'
    Butt:
        text: '5'
    Butt:
        text: '2'
    Butt:
        text: '6'
    Butt:
        text: '7'
    Butt:
        text: '8'
    Butt:
        text: '9'
    Butt:
        text: '0'
    Butt:
        text: 'Enter'
''')

class CalcApp(App, GridLayout):

    def build(self):
        return self

CalcApp().run()

rawDescription: How can I set the position (x,y coordinates) of a grid layout in kivy?

description: Set the position (x,y coordinates) of a grid layout in kivy


code: prime = {x for x in range(2, 100) if not any(x % y == 0 for y in range(2, x))}

rawDescription: Python generating prime numbers using Set Comprehension


code: from tkinter import ttk

rawDescription: tkinter wrap text if larger than column width

description: Tkinter wrap text if larger than column width


code:
import subprocess
import os

pids = []
for num in range(1,3):
    args = ["ipengine", "--config", os.path.abspath("./profiles/e%d.py" % num), "--file",os.path.abspath( "./profiles/security/ipcontroller-engine.json") ]
    pid = subprocess.Popen(args).pid
    pids.append(pid)

rawDescription: IPython ipengineapp creation with keyword arguments


code:
df = DataFrame(ts)
df.columns=['start','end']

rawDescription: calculating rolling mean pandas with time-weighted values

description: Calculating rolling mean pandas with time-weighted values


code: 'Hello {user[name]}'.format( **{'user': { 'name': 'Markus' } } )

rawDescription: How to use a dot in Python format strings?

description: Use a dot in Python format strings


code: charge = service(x, y, z)

rawDescription: trying to call a string that is assigned within a function

description: Trying to call a string that is assigned within a function


code:
def unquote_url(url):
    """Decodes a URL that was encoded using quote_url.
    Returns a unicode instance.
    """
    return urllib.unquote(url).decode('utf-8')

rawDescription: Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()


code:
for field in sender._meta.local_many:
    values = field.value_from_object(instance).objects.all()
    # Now values is a list of related objects, which you can diff

rawDescription: Diff django model objects with ManyToMany fields


code:
import binascii
import struct

fdata = struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))[0]

rawDescription: How to convert a hex-string into an unpacked IEEE 754 format number:-

description: Convert a hex-string into an unpacked IEEE 754 format number:-


code: words = re.findall('\w+', open(os.path.join(root, file)).read().lower())

rawDescription: Python, loop through files in a folder and do a word count


rawDescription: Locating table with no id or class attributes


code:
x = input('Type the first name: ')
for first, second in list:
    if first == x:
        print(second)
        break

rawDescription: Result the second element of a list in python


code:
def clean_empty(d):
    if not isinstance(d, (dict, list)):
        return d
    if isinstance(d, list):
        return [v for v in (clean_empty(v) for v in d) if v]
    return {k: v for k, v in ((k, clean_empty(v)) for k, v in d.items()) if v}

rawDescription: Python: How to remove all empty fields in a nested dict


code:
import re
with open('file.txt', 'r') as r:
    file = r.read()
    data = re.sub(r'(?s)(?:[^\n]*?Orange[^\n]*\n|\n[^\n]*?Orange[^\n]*$)', r'', file)

with open('file.txt', 'w') as f:
    f.write(data)

rawDescription: How to remove a line in a file with a specific string?

description: Remove a line in a file with a specific string


rawDescription: How to Stem Shakespere/KJV Using nltk.stem.snowball


rawDescription: actual objects and its references in python

description: Actual objects and its references in python


code: [list(combo) for combo in combinations(range(x + 1), y) if 1 in combo]

rawDescription: Combinations Including Select Elements (Python)


code:
import pandas as pd

train_data_contents = """
class_label,distance_from_beginning,distance_from_end,contains_digit,capitalized
B,1,10,1,0
M,10,1,0,1
C,2,3,0,1
S,23,2,0,0
N,12,0,0,1"""

with open('train.csv', 'w') as output:
    output.write(train_data_contents)

train_dataframe = pd.read_csv('train.csv')

rawDescription: Support vector machine in Python using libsvm example of features


code:
def load(self):
    if os.path.exists(CONFIGFILE):
        with open(CONFIGFILE, 'r') as f:
            data = json.load(f)
        title = data['windtitle']
        self.windtitle = wx.StaticText(self.panel, -1, title)
        self.vbox.Add(self.windtitle)
        for checkbox in data['checkboxes']:
            label = checkbox['label']
            cb = wx.CheckBox(
                self.panel, -1, checkbox['label'])
            self.vbox.Add(cb)
            cb.SetValue(checkbox['checked'])
    else:
        self.create_windtitle()
    self.create_buttons()

rawDescription: Python - Saving state of a program between restarts?


code:
{id: (first, last) for id, first, last in name}
{id: job for id, job in occupation}

rawDescription: Join lists by value

description: Join lists by value


code:
# top.pyw file
import main
if __name__ == "__main__":
    import sys
    main.main(*sys.argv[1:])

rawDescription: Compile a .pyw file so it can be run like .pyc without console


code:
hdulists = []
for n in range(1, 23):   # range is exclusive so you get 1-22
    hdulists.append(
        pyfits.open(
            ('/home/ssridhar/mock_test_files/Roncarelli_test'
            '/roncarelli_dist_halo{0}.fits').format(n)
        )
     )

rawDescription: Shortening a Python program

description: Shortening a Python program


rawDescription: Finding the closest point(s) by ranking them


rawDescription: Selecting top N columns for each row in data frame


code: result = a[::blockLengthX, ::blockLengthY]

rawDescription: convert image to value matrix

description: Convert image to value matrix


code: np.allclose(expected, result)

rawDescription: Multiplication of (0,1)-matrix with a (0,1)-vector


rawDescription: How to calculate timedelta until next execution for scheduled events

description: Calculate timedelta until next execution for scheduled events


rawDescription: Adding characters to certain laces in string


code:
new_class_obj = YourMeta.__new__(YourMeta, name, bases, bodydict)
YourMeta.__init__(new_class_obj, name, bases, bodydict)

rawDescription: How to bind a method to class during its metaclass's __init__ method?

description: Bind a method to class during its metaclass's __init__ method


rawDescription: create multiple index for a dataframe in pandas

description: Create multiple index for a dataframe in pandas


code:
import random
import itertools as it
def key_generator():
    characters = [chr(random.randint(65, 90)) for x in range(100)]
    for i in it.count():
            yield ''.join(random.sample(characters, 3))

the_dict = dict((key, random.randint(-500, 500)) for key, _ in zip(key_generator(), range(3000)))
def with_heapq(the_dict):
    items = [(-value, key) for key, value in the_dict.items()]
    smallest = heapq.nsmallest(10, items)
    return [-value for value, key in smallest]

def with_sorted(the_dict):
    return sorted(the_dict.items(), key=(lambda x: x[1]), reverse=True)[:10]

import timeit
timeit.timeit('with_heapq(the_dict)', 'from __main__ import the_dict, with_heapq', number=1000)
timeit.timeit('with_sorted(the_dict)', 'from __main__ import the_dict, with_sorted', number=1000)

rawDescription: How to maintain dictionary in a heap in python?

description: Maintain dictionary in a heap in python


code:
import operator
reduce(operator.add, [1, 23, 456])  # or int.__add__ instead of operator.add

rawDescription: Show all possible groupings of a list, given only the amount of sublists (lengths are variable)


code:
timeit.timeit('s[:-len(s.lstrip())]', 's=" "*2000', number=10000)
timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"\s*");s=" "*2000', number=10000)
timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s=" "*2000', number=10000)

rawDescription: Grab a line's whitespace/indention with Python


code:
class UserProfile(models.Model):
    """Contains user profile fields not provided by User model"""
    user = models.OneToOneField(User)
    # Defined User profile fields like picture, phone, etc

rawDescription: Writing user.get_profile() custom function which should create auth profile if there is not any


code:
with open('output', 'w') as fout:
    fout.writelines(chain.from_iterable(v for k,v in sorted(output.iteritems())))

rawDescription: Sorting csv by number of columns in each row


code:
def average_daily_views(movie_id, customer_id, data):
    daily_values = [data[movie_id][date][customer_id] for date in data[movie_id]]
    return sum(daily_values)/len(daily_values)

rawDescription: most pythonic way to calculate the average

description: Most pythonic way to calculate the average


code:
# after all your code
add_items(self.tree_widget, self.xml)

# select the root item
self.tree_widget.setCurrentItem(self.tree_widget.topLevelItem(0))

rawDescription: QTreeWidget select first item

description: QTreeWidget select first item


code:
nineam = datetime.time(9, 0) #from DB
fivepm = datetime.time(17, 0) #from DB

for t in timerange(nineam, fivepm):
    print(t)

rawDescription: Adjust start and end range for time list in Python


code:
import requests
response = requests.get('http://172.24.48.67:1000', params=...)
print(response.text)

rawDescription: Retrieving a value from an executable/batch file using Python


code:
ip_str = input("Enter a string: ")
ip_str = ip_str.casefold()
count = {}.fromkeys('aeiou',0)
total = 0

for char in ip_str:
   if char in count:
       count[char] += 1
       total += 1

print(count)
print("Number of vowels:", total)

rawDescription: Count the vowels in a string

description: Count the vowels in a string


code:
def enregister(d, obj):
  obj.ds.append(d)
  d[obj.key] = obj

class Item(object):
    def __init__(self, uniq_key, title=None):
        self._key = uniq_key
        self.title = title
        self.ds = []

    def adjust_key(self, newkey):
        newds = [d for d in self.ds if self._key in d]
        for d in newds:
          del d[self._key]
          d[newkey] = self
        self.ds = newds
        self._key = newkey

    def get_key(self):
        return self._key

    key = property(get_key, adjust_key)

rawDescription: Python data structure for a collection of objects with random access based on an attribute


rawDescription: Create numpy array from matrix declared inside .m matlab file


rawDescription: Faster convolution of probability density functions in Python


code:
import MySQLdb
import pandas.io.sql as psql
from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE

conversions[FIELD_TYPE.DECIMAL] = float
conversions[FIELD_TYPE.NEWDECIMAL] = float
conn = MySQLdb.connect(host='',user='',passwd='',db='')
sql = "select * from NUMERICTABLE"
df = psql.read_frame(sql, conn)

rawDescription: Fastest way to load numeric data into python/pandas/numpy array from MySQL


code: len(a) == len(b) and all(x == y for x, y in zip(a,b))

rawDescription: compare ctypes arrays without additional memory

description: Compare ctypes arrays without additional memory


rawDescription: Get Matplotlib legend location?

description: Get Matplotlib legend location


code: from docx import Document

rawDescription: Parse .docx in python 3

description: Parse .docx in python 3


rawDescription: Python - Get the min coordinate element of a 2d numpy array


rawDescription: How to count lines in multi lined strings

description: Count lines in multi lined strings


code:
from datetime import datetime
datetime.strptime('May 5 2016 11:29:32','%b %d %Y %H:%M:%S').timestamp()

rawDescription: Convert string datetime format into integer time in seconds in python


code:
import subprocess

def connect_to_network(name):
    process = subprocess.Popen(
        'netsh wlan connect {0}'.format(name),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()

    # Return `True` if we were able to successfully connect
    return 'Connection request was completed successfully' in stdout

rawDescription: Associating my Windows computer to a wifi AP with Python


code:
def webview(request, url_param):
    context = { "my_url": url_param }
    return render(request, 'myapp/mytemplate.html', context)

rawDescription: How to make Django link jumping game with a web browser inside the app?

description: Make Django link jumping game with a web browser inside the app


code:
import socket
s = socket.socket()
s.connect(('123.123.123.123', 10000))

rawDescription: Can sockets be used to connect multiple computers on different networks in python?


rawDescription: how to convert UTF-8 code to symbol characters in python

description: Convert UTF-8 code to symbol characters in python


rawDescription: Sorting by Date string in pandas - Python 2.7


rawDescription: Python 2.7 -scapy and ARP

description: Python 2.7 -scapy and ARP


code:
from matplotlib import pyplot as plt
from matplotlib import cm
y = [3,7,5,6,4,8,3,4,5,2,9]
z = [0.3,0.4,0.5,0.6,0.7,0.2,0.3,0.4,0.5,0.8,0.9]
for x, (v, c) in enumerate(zip(y,z)):
     plt.plot(x,v,marker='o', color=cm.hot(c))

plt.show()

rawDescription: gnuplot linecolor variable in matplotlib?

description: Gnuplot linecolor variable in matplotlib


code:
data = [{"Type": "A", "Name": "Sam"},{"Type":"A", "Name":"Apple"},{"Type": "B", "Name": "Sam"},{"Type":"C", "Name":"Apple"},{"Type":"C"}]
[d for d in data if d.get('Type') == 'A']

rawDescription: Picking certain set of dictionary

description: Picking certain set of dictionary


code:
class B(object):
    def __getattr__(self, attr):
        if attr == 'a':
            self.a = A()
            return self.a
        raise AttributeError(attr)

rawDescription: Dynamically adding class instance to Python instance à la __setattr__


code:
I, J = np.where(e==n[:,None])
I
J
e[J]
n[I]

rawDescription: Python - Replace data of an array by 2 values of a second array


rawDescription: tuple to string formatting

description: Tuple to string formatting


code: notification.send([to_user], "friends_invite", {"from_user": from_user})

rawDescription: reusable application for django site wide announcements that displays a message only once per user

description: Reusable application for django site wide announcements that displays a message only once per user


code: print('/'.join(item.strip() for item in section.find_all(text=True)))

rawDescription: How to deal with a different format in a specific tag using BeautifulSoup

description: Deal with a different format in a specific tag using BeautifulSoup


code:
avg_lc = np.array([np.average(d[n], weights=e[n], axis=0) for n in range(d.shape[0])])
np.allclose(avg, avg_lc)

rawDescription: Numpy weighted average of 4D array with 2D array of weights without list comprehension


code: global_dict["baz"] = "world"

rawDescription: Using a global dictionary with threads in Python


code:
# DB router for app1

class App1DBRouter(object):
    """
    A router to control app1 db operations
    """
    def db_for_read(self, model, **hints):
        "Point all operations on app1 models to 'db_app1'"
        from django.conf import settings
        if not settings.DATABASES.has_key('app1'):
            return None
        if model._meta.app_label == 'app1':
            return 'db_app1'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on app1 models to 'db_app1'"
        from django.conf import settings
        if not settings.DATABASES.has_key('app1'):
            return None
        if model._meta.app_label == 'app1':
            return 'db_app1'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in app1 is involved"
        from django.conf import settings
        if not settings.DATABASES.has_key('app1'):
            return None
        if obj1._meta.app_label == 'app1' or obj2._meta.app_label == 'app1':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the app1 app only appears on the 'app1' db"
        from django.conf import settings
        if not settings.DATABASES.has_key('app1'):
            return None
        if db == 'db_app1':
            return model._meta.app_label == 'app1'
        elif model._meta.app_label == 'app1':
            return False
        return None

rawDescription: Can i use different databases for different apps in django

description: Use different databases for different apps in django


code:
for x in range(1, 6):
    for y in range(1, 6):
        if x!=y:
            print(x,y)

rawDescription: Looping to calculate False Acceptance Rate (FAR) in python


code:
from functools import wraps

from django.utils.decorators import available_attrs

def protect(func):
    @wraps(func, assigned=available_attrs(func))
    def inner(request, *args, **kwargs):
        if some_condition:
            return render_to_response('protected_template')
        return func(request, *args, **kwargs)
    return inner

rawDescription: Going to another view

description: Going to another view


code:
def contains(X, samples):
    return numpy.vectorize(lambda x: x in samples)(X)

result = X[contains(X[:, 1], set(samples)), :]

rawDescription: Selecting rows from array under many conditions


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

class NewUserModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    new_field_name = models.CharField(max_length=100)

rawDescription: How to Access the custom column from auth_user table in Django?


code: bool(pytz.timezone('America/Los_Angeles').dst(datetime(2015, 2, 1), is_dst=None))

rawDescription: How to determine if a timezone specific date in the past is daylight saving or not in python?

description: Determine if a timezone specific date in the past is daylight saving or not in python


code:
import numpy as np
from bokeh.plotting import figure, curdoc

x = np.random.rand(10)
y = np.random.rand(10)

p = figure()
r2 = p.line(x, y, color="navy", line_width=4)

# define a callback to update the data
def update():
    x = np.random.rand(10)
    y = np.random.rand(10)

    # important to update all data "at once"
    r2.data_source.data = dict(x=x, y=y)

# run the callback to update the data every 2000 ms
curdoc().add_periodic_callback(update, 2000)

rawDescription: Confusion about bokeh 0.11: obtain a user readable session id


code:
from collections import defaultdict

def perms(A, B):
    indexes = defaultdict(set)
    for i, e in enumerate(B):
        indexes[e].add(i)
    def find(perm):
        k = len(perm)
        if k == len(A):
            yield perm
            return
        I = indexes[A[k]]
        for i in list(I):
            I.remove(i)
            yield from find(perm + (i,))
            I.add(i)
    yield from find(())

rawDescription: How to get all orderings of a list such that the list is equal to another list?

description: Get all orderings of a list such that the list is equal to another list


code: function.assert_has_calls([mock.call(1, 2), mock.call(2, 3)])

rawDescription: Checking whether function has been called multiple times with different parameters


code: rdd.zipWithIndex().filter(lambda vi: vi[1] < 163).keys()

rawDescription: Pyspark RDD collect first 163 Rows

description: Pyspark RDD collect first 163 Rows


rawDescription: How to make a canvas (rectangle) in wxpython?

description: Make a canvas (rectangle) in wxpython


code:
import numpy as np
import scipy.ndimage as ndimage

x = np.arange(100, dtype='float')
x[x % 13 == 0] = np.nan
print(x)

N = 2
def blank(window):
    return np.nan if np.any(np.isnan(window)) else window[N]
y = ndimage.generic_filter(x, blank, size=(2*N+1,))
print(y)

rawDescription: an efficient equivalent to numpy isnan or where that looks over a window of N values

description: An efficient equivalent to numpy isnan or where that looks over a window of N values


code:
def total_seconds(timedelta_object):
    return timedelta_object.days * 86400 + timedelta_object.seconds

rawDescription: Manipulating DateTime and TimeDelta objects in python


code:
s = sorted(basket.values(), key=lambda x: x['price'])
s[0] # {'group': 4, 'name': 'Brisket Beef 400G', 'price': 3.5, 'amount': 3, 'promotion': 'get4pay3', 'unit': 'pieces'}

rawDescription: For a dictionary inside another dictionary how do you sort it by the value and compare different items within the dictionary


code:
mydict = {}
for line in f:
    k, v = line.split(None, 1)
    mydict[k] = v

mapp = {}
value_holder = set()

for i in mydict:
    if mydict[i] not in value_holder:
        mapp[i] = mydict[i]
        value_holder.add(mydict[i])

rawDescription: More efficient way to get unique first occurrence from a Python dict


code:
midlen = len(oldstr)/2
newstr = oldstr[:midlen] + oldstr[midlen+1:]

rawDescription: How to delete a character from a string using python?

description: Delete a character from a string using python


code: reduce(np.intersect1d, (a, b, c))

rawDescription: how to get items that belongs to all numpy arrays?

description: Get items that belongs to all numpy arrays


rawDescription: Filtering tuples in a list

description: Filtering tuples in a list


code:
primes = set(primes_to_one_million_however_you_want_to_get_them)

def is_circular(prime, primes=primes):
   prime_str = str(prime)
   # With thanks to Sven Marnach's comments
   return all(int(prime_str[i:]+prime_str[:i]) in primes
              for i in xrange(len(prime_str)))

circular_primes = [p for p in primes if is_circular(p)]

rawDescription: Speeding up string splitting and concatenation


code:
import numpy
lst = ['a', 'a', 'a', 'b', 'b', 'a', 'b']
numpy.array([[1,0] if val =="a" else [0,1]for val in lst])

rawDescription: How to create 2 column binary numpy array from string list?

description: Create 2 column binary numpy array from string list


code:
tree = ast.parse(decistmt(expr), mode='eval')
# walk the tree to validate, make changes, etc.

ast.dump(tree)

rawDescription: Convert ast.Num to decimal.Decimal for precision in python


code:
import psutil

matching = [proc for proc in psutil.process_iter() if proc.username() == 'vinish']
for proc in sorted(matching, key=lambda p: p.pid):
    print(proc)

rawDescription: Any ways to collect process information?

description: Any ways to collect process information


code:
freq = defaultdict(int)
for w in re.findall(r"\w+", text):
    freq[w.lower()] += 1

rawDescription: Python - Number of word occurrences

description: Python - Number of word occurrences


rawDescription: How can I normalize a histogram such that the sum of the heights is equal to 1?

description: Normalize a histogram such that the sum of the heights is equal to 1


code:
def mkrule(ruletxt):
    txt, before, after, phoneme = ruletxt.split('/')
    rule = r""

    if before:
        # use a non-capturing group to match the 'before' text
        rule += r'(?:' + mkregex(before) + ')'

    # create a capturing group for the text in question
    rule += r'(?P<found>' + txt + ')'

    if after:
        # add a lookahead pattern
        rule += r'(?=' + mkregex(after) + ')'

    # return a tuple containing
    #   - the regex created from the rule
    #   - a lower-cased version of the phonemes between dashes
    #   - the original rule (for explaining and debugging)
    return rule, "-%s-" % phoneme.lower(), ruletxt

rawDescription: Python pattern matching of rules to parse text to phonemes


code:
[os.path.split(mypath)[1]
for mypath in L
if mypath.split('.')[-1] in ('v', 'sv', 'vh')]

rawDescription: chaining regular expressing in python

description: Chaining regular expressing in python


code: zip(*[islice(reversed(L),i,None) for i in range(3)])

rawDescription: Assorting elements in a list into a list of lists of specific lengths


code: img = WImage(filename='hat.pdf[1]')

rawDescription: View pdf image in an iPython Notebook

description: View pdf image in an iPython Notebook


code:
def get_file_sizes(parent_dir, files):
    import os
    return sum([os.path.getsize(os.path.join(parent_dir, f)) for f in files])

rawDescription: How to add all the elements inside loop in Python?

description: Add all the elements inside loop in Python


code:
y = linspace(-5, 5, 200)
X = (y + np.random.randn(200)).reshape(-1, 1)
threefold = list(KFold(len(y)))

rawDescription: How is scikit-learn GridSearchCV best_score_ calculated?


code:
class Interner(object):
    def __init__(self):
        self._store = {}
    def canonical_object(self, thing):
        """Returns a canonical object equal to thing.

        Always returns the same result for equal things.

        """

        return self._store.setdefault(thing, thing)

rawDescription: Is there another way to avoid duplication of large hashable objects?


code:
def symmetrize(a):
    return a + a.T - numpy.diag(a.diagonal())

rawDescription: Numpy ‘smart’ symmetric matrix

description: Numpy ‘smart’ symmetric matrix


code:
for letter in one_letter:
    stat_file.writelines("%s: %f%%\n" %(letter, \
        stat.get(letter, 0)/float(total_count)*100))

rawDescription: calculate percentage of strings instead of statistics

description: Calculate percentage of strings instead of statistics


rawDescription: Joining a list of string digits to create an integer Python 3


code: df4.columns = df4.columns.droplevel(0)

rawDescription: Iterate through a dataframe to find number of times a str value appears in an array of tuples


code:
dialog = OpenFileDialog()
dialog.Filter = "All Files|*.*"
if dialog.ShowDialog() == True:
    selectedFile = dialog.FileName

rawDescription: Open file dialog and select a file using WPF controls and Ironpython


rawDescription: pyPdf ignores newlines in PDF file

description: PyPdf ignores newlines in PDF file


code:
#! /usr/bin/python3

def printGrid (it, columns):
    items = ['{} {}'.format (idx, item) for idx, item in enumerate (it) ]
    maxWidths = [max (len (item) for item in items [col::columns] ) for col in range (columns) ]
    padded = [item + ' ' * (4 + maxWidths [idx % columns] - len (item) ) for idx, item in enumerate (items) ]
    while True:
        if not padded: break
        items = padded [:columns]
        padded = padded [columns:]
        print (' '.join (items) )

data = 'Banana,Apple,Orange,Pear,Grape,Coconut,Test1,Test2,Test3,Test4,TestTest5,TestTest6,Test7'.split (',')
printGrid (data, 3)

rawDescription: Fancy String Formating

description: Fancy String Formating


rawDescription: Spark Dataframe distinguish columns with duplicated name


code:
import csv # import the csv module to help us parse the text file

# Create an empty dictionary.
scoreDict = {}

# Open the text file to parse.
with open('sample.csv', newline='') as csvfile:
    # Return an iterable reader object
    reader = csv.reader(csvfile)

    # Now we iterate through the reader object.
    for row in reader:
        if row: # Ignore empty rows
            scoresList = [] # Create an empty list we will be adding scores to.
            # We use the enumerate here to keep track of where we are in the list.
            for index, column in enumerate(row):
                if index != 0: # Ignore the first column as we use it as a key
                    # Turn score into an integer and add it to a list.
                    scoresList.append(int(column))
                    # Add the list of scores to the dictionary.
                    scoreDict[row[0]] = scoresList

print(scoreDict)

rawDescription: How can I put text into a dictionary with keys that have more than one value?

description: Put text into a dictionary with keys that have more than one value


code:
import unicodedata
def compute_ratio(input_str):
    '''
    This function will return the ratio between the number of latin letter and other letters.
    '''
    num_latin = 0
    input_str = "".join(input_str.split()) # Remove whitespaces.
    for char in input_str:
        try:
            if unicodedata.name(unicode(char))[:5] == "LATIN":
                num_latin += 1
            #end if
        except UnicodeDecodeError:
            pass
        #end try
    #end for
    return (num_latin*1.0)/len(input_str)

rawDescription: Python remove non-latin textlines in csv


code:
got = regex.findall(r'[\p{Cf}\p{L}]+', text)
want = [ 'ذوب','خوی','بزاق','آب‌دهان','یم','زهاب','آبرو','حیثیت' ,'شرف']
print(want)
got == want
got[:3]
got[4:]

rawDescription: Tokenizing non English Text in Python

description: Tokenizing non English Text in Python


code:
import numpy as np
from itertools import count

data = [line.split() for line in inputfile.readlines()]
rows = dict(zip(sorted(set(line[0] for line in data)), count()))
cols = dict(zip(sorted(set(line[1] for line in data)), count()))
array = np.zeros((len(rows), len(cols)))

for row, col, val in data:
    index = (rows[row], cols[col])
    array[index] = val

rawDescription: Populate arrays in python (numpy)?

description: Populate arrays in python (numpy)


code: f

rawDescription: Concatenating two series with None value (pandas DataFrame)?


code:
class Test:
    A = []  # a class attribute
    def __init__(self):
        self.a = []  # an instance attribute

rawDescription: Pickle with custom classes

description: Pickle with custom classes


code:
u'Jagiello\u0144ska\n    '
u'\u015br. 06 lip\n        '

rawDescription: problem with deserialization xml to objects - unwanted split by special chars

description: Problem with deserialization xml to objects - unwanted split by special chars


rawDescription: Serve file to browser from python (flask) webservice


code:
def assign_var(tokens):
    # ev = tokens.varvalue.eval()
    # EvalConstant.var_[tokens.varname] = ev
    EvalConstant.var_[tokens.varname] = tokens.varvalue

rawDescription: Evaluating nested variables with pyparsing for a DSL


code: list(enumerate(a))

rawDescription: Create multidimensional list in python through two other lists


code:
from Tkinter import *
from string import ascii_lowercase

class app(Frame):
    def __init__(self, master = None):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.entries = {}
        self.tableheight = 9
        self.tablewidth = 9
        counter = 0
        for row in xrange(self.tableheight):
            for column in xrange(self.tablewidth):
                self.entries[counter] = Entry(self, width=5)
                self.entries[counter].grid(row=row, column=column)
                counter += 1

prog = app()
prog.master.title('Sudoku')
prog.mainloop()

rawDescription: Creating an entry table on TKinter

description: Creating an entry table on TKinter


rawDescription: Python float overflow, what happens when float overflows?


code:
from math import *

def toLatex(powerOf10):
    exponent = int( log10(powerOf10) )
    return "10$^{}$".format(exponent)

nums = [10**-20, 0.01, 0.1, 1, 10, 100, 1000, 10**20]
[(x, toLatex(x)) for x in nums]

rawDescription: How to format an array of floats into a string

description: Format an array of floats into a string


code:
def do_this(page):
    with  open("Output.txt", "a") as f:
        while True:
            url, n = getURL(page)
            page = page[n:]
            if not url:
                break
            f.write("Extracted URL : %s\n" % url)

rawDescription: How To Print Variable To A Text File In Python?


code:
import logging
logging.root.setLevel('INFO')
logging.root.info('Info message')

rawDescription: Project/Multiple Class Verbose Mode Python


code: name = "Fido"

rawDescription: How do I get a formatted list of methods from a given object?

description: Get a formatted list of methods from a given object


rawDescription: Could python split return None while the string has two continuous tab('\t')?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import bivariate_normal
from matplotlib.widgets import Slider, Button, RadioButtons

#Setup figure and data
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
delta = 0.5
t = np.linspace(0.0, 100.0, 256)
x = np.linspace(-4.0, 4.001, 512)
y = np.linspace(-4.0, 4.001, 512)
X, Y = np.meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
XZslice = np.zeros((256,512,512))
for i in range(t.shape[0]):
    XZslice[i,:,:] = (Z1 - Z2) * t[i]/10.
cmap = plt.cm.rainbow
im = ax.pcolormesh(XZslice[128,:,:], cmap=cmap)
fig.colorbar(im)
axcolor = 'lightgoldenrodyellow'
axtime = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
stime = Slider(axtime, 'Time', 0.0, 100.0, valinit=50.0)

#Routines to reset and update sliding bar
def reset(event):
    stime.reset()

def update(val):
    time = int(stime.val/100.* 256)
    im.set_array(XZslice[time,:,:].ravel())
    fig.canvas.draw()

#Bind sliding bar and reset button
stime.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
button.on_clicked(reset)

plt.show()

rawDescription: How to add a time control panel to a FuncAnimation from matplotlib

description: Add a time control panel to a FuncAnimation from matplotlib


code: curOuter.execute('SELECT id FROM myConnections')

rawDescription: Using multiple cursors in a nested loop in sqlite3 from python-2.7


code:
mother = None
for k,v in relation_dict.items():
    if name in v:
        mother = k
        break
return mother

rawDescription: Looping dictionary values

description: Looping dictionary values


code:
import httplib
conn = httplib.HTTPConnection("www.google.nl")
conn.request("HEAD", "/index.html")
res = conn.getresponse()
dir(res)

rawDescription: In Python, what does getresponse() return?


code:
from django.conf.urls.defaults import patterns, include, url
from testsite.views import index

urlpatterns = patterns('',
    url(r'^(\d+)$', index),
)

rawDescription: Django - consume XML - RESTful

description: Django - consume XML - RESTful


code:
vecdget = np.vectorize(lambda x: d.get(tuple(x)))
vecdget(indices)

rawDescription: Conversion: np.array of indices to np.array of corresponding dict entries


code:
from collections import defaultdict

numbered = defaultdict(list)
for i in tup:
    numbered[i[1]].append(i)

rawDescription: Splitting a list of tuples by 2nd element - python


code:
ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2

PRNT1.PORT=9600
PRNT1.BITS=8

rawDescription: Edit configuration file through python

description: Edit configuration file through python


code:
import pandas as pd
data_df = pd.DataFrame({'a': [1,2], 'b': [3,4], 'c': [5,6],
                   'd': [7,8], 'e': [9,10], 'f': [11,12]})
experiment_species = data_df.keys()
species_dct = ['b', 'd', 'e', 'x', 'y', 'z']
good_columns = list(set(experiment_species).intersection(species_dct))
df_filtered = data_df[good_columns]

rawDescription: Collecting data in loop using Pythons Pandas Dataframe


code:
from django.db import models
from django.db.models.fields.related import ManyToManyField

class PrintableModel(models.Model):
    def __repr__(self):
        return str(self.to_dict())

    def to_dict(self):
        opts = self._meta
        data = {}
        for f in opts.concrete_fields + opts.many_to_many:
            if isinstance(f, ManyToManyField):
                if self.pk is None:
                    data[f.name] = []
                else:
                    data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
            else:
                data[f.name] = f.value_from_object(self)
        return data

    class Meta:
        abstract = True

rawDescription: Convert Django Model object to dict with all of the fields intact


code:
with open('inputfilename') as infh:
    lst = list(genoutput(infh))

rawDescription: Extraction of variables from text, with completely different formatting, using Python


code:
def generate_qr_code(data, size=10, border=0):
    qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L,
                       box_size=size, border=border)
    qr.add_data(data)
    qr.make(fit=True)
    return qr.make_image()

rawDescription: How to display a PIL image object in Django view?

description: Display a PIL image object in Django view


rawDescription: How to sort tire sizes in python

description: Sort tire sizes in python


code:
{u'HEADER 1': {u'data_point_1': [u'DATA11', u'DATA21', u'DATA31'],
               u'data_point_2': [u'DATA12', u'DATA22', u'DATA32'],
               u'data_point_3': [u'DATA12', u'DATA23', u'DATA33']},
 u'HEADER 2': {u'data_point_1': [u'DATA11', u'DATA21', u'DATA31'],
               u'data_point_2': [u'DATA12', u'DATA22', u'DATA32'],
               u'data_point_3': [u'DATA13', u'DATA23', u'DATA33']}}

rawDescription: Iterating through a table of rows with beautiful soup in python


code:
c.keys()
c.values()
c.items()

rawDescription: Reducing a list of repeated tuples and counting repeats


code:
import time
while True: time.sleep(0.2)      # 0% CPU
while True: time.sleep(0.02)     # 0% CPU
while True: time.sleep(0.002)    # 0.5% CPU
while True: time.sleep(0.0002)   # 6% CPU
while True: time.sleep(0.00002)  # 18% CPU

rawDescription: Efficient and fast Python While loop while using sleep()


code:
# This is already there
if self._depth and level > self._depth:
    write(rep)
    return

rawDescription: Pretty print and substitute numpy arrays


code: m = re.findall("\\&{0};".format(findVar), value)

rawDescription: Regex for finding variable references in a C file using Python


code:
import json
import sys
from decimal import Decimal

def default(obj):
    if isinstance(obj, Decimal):
        return str(obj)
    else:
        raise TypeError(obj)

# convert during dump
json.dump(data, sys.stdout, indent=2, default=default)

rawDescription: Convert python decimal to string in deeply nested and unpredictable list


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

s = """00 1f 00@ 00c 00e 00N 00> 00E 00O 00F 002 00& 00* 00/
 00) 00 1f 00 1c 00  00  00 17 00\r 00 08 00 03 00 f8 ff ea ff e1 ff e1 ff
e0 ff da ff d2 ff cc ff c9 ff c5 ff c3 ff c3 ff c1 ff ba ff b3 ff b1 ff b2
ff b3 ff b3 ff b6 ff ba ff b7 ff ab ff 9c ff 93 ff 93 ff 9c ff a5 ff aa ff
aa ff a3 ff 9a ff 92 ff 95 ff a3 ff b2 ff b9 ff bd ff cb ff df ff e8 ff dd
ff ca ff c8 ff d9 ff eb ff f1 ff ee ff f0 ff fe ff 10 00 1d 00 1f 00 18 00
0f 00 0e 00 17 00" 00\' 00% 00\' 001 00= 00D 00G 00I 00M 00O 00N 00M 00M 00O
00N 00K 00F 00C 00F 00M 00M 00@ 00. 00$ 00& 00* 00& 00 1d 00 17 00 17 00 17
00 13 00 0f 00 13 00 1f 00* 00/ 00/ 00/ 00/ 00/ 00- 00\' 00 1f 00 18 00 13
00 10 00 0c 00 08 00 03 00 00 00 fd ff f8 ff f3 ff f1 ff ee ff e8 ff e1 ff
e1 ff e9 ff f0 ff f0 ff e9 ff e4 ff e1 ff dd ff da ff d8 ff d9 ff d7 ff d2
ff cc ff c9 ff ca ff ca ff c9 ff c9 ff cd ff d1 ff d3 ff d1 ff d0 ff d1 ff
 d5 ff d9 ff dd ff e1 ff e6 ff e9 ff e9 ff e9 ff ec ff f1 ff f5 ff f8 ff fc
ff 01 00 03 00 00 00 fb ff f9 ff fc ff 00 00 01 00 01 00 00 00 ff ff ff ff
01 00 01 00 ff ff fb ff f9 ff fb ff ff ff 01 00 01 00 00 00 ff ff fe ff 00
00 0b 00 17 00 1c 00 18 00 11 00 0f 00 11 00 10 00 0c 00 08 00 07 00 08 00\t
00 08 00 04 00 00 00 fc ff f8 ff f7 ff f8 ff f9 ff"""

for grp in s.split():
    if len(grp) != 2:
        print(grp[2:])

rawDescription: How to parse this string?

description: Parse this string


code:
import wx #For graphics' interface
import os #For operating system compatibility

class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):

        #SETUP
        wx.Frame.__init__(self, parent, wx.ID_ANY, title = "MyTitle", size = (550,300))
        self.dirname=''

        self.top_panel = wx.Panel(self)
        self.main_sizer = wx.BoxSizer(wx.HORIZONTAL)

        #CREATE
        self.create_status_bar()
        self.create_menu_bar()
        self.create_text_panel()
        self.create_graphics_panel()

        self.SetAutoLayout(True)

        lc = wx.LayoutConstraints()
        lc.top.SameAs(self, wx.Top, 5)
        lc.left.SameAs(self, wx.Left, 5)
        lc.bottom.SameAs(self, wx.Bottom, 5)
        lc.right.PercentOf(self, wx.Right, 40)
        self.panelA.SetConstraints(lc)

        lc = wx.LayoutConstraints()
        lc.top.SameAs(self, wx.Top, 5)
        lc.left.RightOf(self.panelA, 5)
        lc.bottom.SameAs(self, wx.Bottom, 5)
        lc.right.SameAs(self, wx.Right, 5)
        self.panelB.SetConstraints(lc)

        self.top_panel.SetSizer(self.main_sizer)

# FUNCTIONS
# ------------------------------------------------------------------------------
    def create_status_bar(self):
        self.CreateStatusBar() #A Statusbar at the bottom of the window

    def create_menu_bar(self):

    # File Menu
        filemenu= wx.Menu()

        menuOpen = filemenu.Append(wx.ID_OPEN, "&Open", "Open file to edit")
        filemenu.AppendSeparator()
        menuSave = filemenu.Append(wx.ID_SAVE, "&Save", "Save the file")
        menuSaveAs = filemenu.Append(wx.ID_SAVEAS, "Save &As", "Save the file with a new name")
        filemenu.AppendSeparator()
        menuExit = filemenu.Append(wx.ID_EXIT, "E&xit", "Terminate communication and close window")

    #The Menu Bar
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") #Adding the "File" menu to the 'menuBar'
        self.SetMenuBar(menuBar)  #Adding the 'menuBar' to the Frame content

    #Event binding
        self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
        self.Bind(wx.EVT_MENU, self.OnSave, menuSave)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, menuSaveAs)

    def create_text_panel(self):
        self.panelA = wx.Panel(self.top_panel)
        self.panelA.control = wx.TextCtrl(self.panelA, wx.ID_ANY, style = wx.TE_MULTILINE) #Text area with multiline
        self.panelA.SetBackgroundColour(wx.WHITE)

        panelA_sizer = wx.BoxSizer(wx.VERTICAL)
        panelA_sizer.Add(self.panelA.control, 1, wx.EXPAND)
        self.panelA.SetSizer(panelA_sizer)
        self.main_sizer.Add(self.panelA, 1, wx.EXPAND)

    def create_graphics_panel(self):
        self.panelB = wx.Panel(self.top_panel)
        self.panelB.SetBackgroundColour(wx.BLACK)
        self.main_sizer.Add(self.panelB, 1, wx.EXPAND)

# EVENTS
# ------------------------------------------------------------------------------
    def OnExit(self, event):
        self.Close(True) #Close the frame

    def OnOpen(self, event):
        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname, self.filename), 'r')
            self.panelA.control.SetValue(f.read())
            f.close()
        dlg.Destroy()

    def OnSave(self, event):
        f = open(os.path.join(self.dirname, self.filename), 'w')
        f.write(self.panelA.control.GetValue())
        f.close()

    def OnSaveAs(self, event):
        file_choices = "TXT (*.txt)|*.txt"
        dlg = wx.FileDialog(self, message = "Save file as...", defaultDir = os.getcwd(), defaultFile = self.filename, wildcard = file_choices, style = wx.SAVE)

        if dlg.ShowModal() == wx.ID_OK:
            f = open(os.path.join(dlg.GetDirectory(), dlg.GetFilename()), 'w')
            f.write(self.panelA.control.GetValue())
            f.close()

# RUN!
# ------------------------------------------------------------------------------
if __name__ == '__main__':
    app = wx.PySimpleApp(False)
    app.frame = MainWindow(None, wx.ID_ANY, "tSock - Adaptation Technologies")
    app.frame.Show()
    app.MainLoop()

rawDescription: Two panels side by side (one with TextCtrl) - wxPython


code: p["list"]

rawDescription: Extarct particulr part of json string using python regex


code:
mock = unittest.mock.MagicMock()
print(mock.method())
print(mock.attribute.method(10, x=53))
mock.mock_calls

rawDescription: Mock: Tracking all Calls. Shell vs. program inconsistency


rawDescription: associating entries from one pandas data frame to a second one based on time

description: Associating entries from one pandas data frame to a second one based on time


code:
import pandas as pd
from odo import odo
df = pd.DataFrame({'a': [1, 2, 3], 'b': list('abc')})
m = odo(df, 'mongodb://localhost/db::t')
list(m.find())

rawDescription: Insert into MongoDB retuns cannot encode object


code:
def route(self, *rargs, **kargs):
    args = list(rargs)
    if kargs:
        print(kargs['methods'])
    def decorator(f):
        def wrapped(index_args):
            f(args[0])
        return wrapped
    return decorator

rawDescription: Python Decorator Self-firing

description: Python Decorator Self-firing


code:
try:
    tbl = str.maketrans('_ \n', '__')  # Python 3.x
except AttributeError:
    import string
    tbl = string.maketrans('_ \n', '__')  # Python 2.x

def headerfiller(df):
    df.columns = [c.translate(tbl) for c in df.columns]

rawDescription: Remove space and newlines in pandas columns using idiomatic Python?


code:
import re
pattern = re.compile(r"/(\w+)\.mp3$")
for url in urls:
    print(pattern.search(url).group(1))

rawDescription: Find string with regular expression in python


code:
from operator import itemgetter

def minQty(*args):
    return min(args, key=itemgetter('qty'))

rawDescription: Comparing value of same key between multiple dictionaries


code:
cursor.execute("select * from join_table where link1 like '%s'" % (var2))

rows1 = cursor.fetchall()           # <<== fetchall() returns a list of results

for row in rows1:

    listthirditeration.append(row)  # <<== this makes a second copy of the results

rawDescription: Ways to improve searching efficiency

description: Ways to improve searching efficiency


code:
import csv

s='''Device,Serial Number,Realm,Vendor,Model,OS Image
ABBNWX0100,SMG3453ESDN,BlAH BLAH,Cisco,WS-C6509-E,"IOS 12.2(33)SXI9, s72033_rp-ADVENTERPRISEK9_WAN-M"
ABBNWX0101,SDG127343S0,BLAH BLAH,Cisco,WS-C4506-E,"IOS 12.2(53)SG8, cat4500-IPBASEK9-M"
ABBNWX0102,TREFDSFY1KK,BLAH BLAH,Cisco,WS-C3560V2-48PS-S,"IOS 12.2(55)SE5, C3560-IPBASEK9-M"'''

print("\n".join([','.join(row[:5])+","+str(row[5].split(",")[0]) for row in csv.reader(s.split("\n"))]))

rawDescription: Removing text from field in Mongodb with Python


code: [sum(x) for x in zip(list1, list2)]

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


code: soup.select('tr > td.table')

rawDescription: BeautifulSoup4: Find elements with children tags


code:
import re

d = """
<VirtualHost>
  ServerName blah.com
  DocumentRoot /var/www/blah.com
</Virtualhost>
<VirtualHost>
  ServerName blah2.com
  DocumentRoot /var/www/blah2.com
</Virtualhost>
"""

matches = re.findall(r'<VirtualHost>(.*?)</Virtualhost>', d, re.I|re.DOTALL)

#['\n  ServerName blah.com\n  DocumentRoot /var/www/blah.com\n',
# '\n  ServerName blah2.com\n  DocumentRoot /var/www/blah2.com\n']

rawDescription: Pull out content between two strings including strings


code:
# list comprehensions (equivalent)
no_zeroes_lc = [[col for col in row if col != 0.] for row in e]

# no_zeroes_lc:
# [['x', 'x'], [], [], []]

no_zeroes == no_zeroes_lc  # True

rawDescription: Resizing matrix getting rid of 0 entries - Python


code: keys = list(d.keys())

rawDescription: 'Zip' dictionary of lists in Python

description: 'Zip' dictionary of lists in Python


code:
def test_plot_square2():
    f, ax = plt.subplots()
    x, y = [0, 1, 2], [0, 1, 2]
    plot_square(x, y)
    x_plot, y_plot = ax.lines[0].get_xydata().T
    np.testing.assert_array_equal(y_plot, np.square(y))

rawDescription: How can I write unit tests against code that uses matplotlib?

description: Write unit tests against code that uses matplotlib


rawDescription: numpy array multiplication slower than for loop with vector multiplication?

description: Numpy array multiplication slower than for loop with vector multiplication


code:
def EntryMatches(e):
  if use_currency and not (e.currency == currency):
    return False
  if use_category and not (e.category == category):
    return False
  return True

rawDescription: Iterating through large lists with potential conditions in Python


code:
plt.xlim(xl)
plt.ylim(yl)

rawDescription: matplotlib's scatter plot changes the axis of another plot

description: Matplotlib's scatter plot changes the axis of another plot


rawDescription: Vectorize this function in Numpy Python

description: Vectorize this function in Numpy Python


code:
shp = x.shape[:-1]
n_ele = np.prod(shp)
y_out = x.reshape(n_ele,-1)[np.arange(n_ele),m.ravel()].reshape(shp)

rawDescription: indexing in numpy (related to max/argmax)

description: Indexing in numpy (related to max/argmax)


code:
import mydir.mymod
from mydir import mymod
mymod == mydir.mymod

rawDescription: how do python module variables work?

description: How do python module variables work


code:
#!/usr/bin/env python
import itertools, operator

def all_factors(prime_dict):
    series = [[p**e for e in range(maxe+1)] for p, maxe in prime_dict.items()]
    for multipliers in itertools.product(*series):
        yield reduce(operator.mul, multipliers)

rawDescription: All possible pairs of factors

description: All possible pairs of factors


code:
import pickle
serializedString = pickle.dumps({1 : 2, 3 : 4})

rawDescription: Python: Compare dict with a static reference?


code:
echo((foo + bar)*
      baz/(bar+foo))

rawDescription: Find the name of a Python variable that was passed to a function


rawDescription: python regex for grabbing specific parts of a line

description: Python regex for grabbing specific parts of a line


code: dct( X, axis=2)

rawDescription: Iterating over 2d arrays contained in 3d array in Python


code:
a3 = ['First', 'Third', 'Fourth']  # Second novel
b3 = ['First', 'Second', 'Fourth'] # Third novel

rawDescription: Combine two lists of strings

description: Combine two lists of strings


rawDescription: Turning list of lists into objects

description: Turning list of lists into objects


rawDescription: How do I use a python array in a symbolic expression?

description: Use a python array in a symbolic expression


code:
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel
from PyQt5.QtGui import QPixmap
import resources_rc

class Form(QWidget):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        mainLayout = QGridLayout()
        pixmap = QPixmap(':/images/image.png') # resource path starts with ':'
        label = QLabel()
        label.setPixmap(pixmap)
        mainLayout.addWidget(label, 0, 0)

        self.setLayout(mainLayout)
        self.setWindowTitle("Hello Qt")

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    screen = Form()
    screen.show()
    sys.exit(app.exec_())

rawDescription: python 3 how to put pics inside my program

description: Python 3 how to put pics inside my program


code:
myDict = {}
path = ('newEnv','newProj','newComp')
inner = reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
inner.update({'n_thing': 'newThing', 'instances': []})

rawDescription: Creating dictionary using list/tuple elements as key


code: latest_ignit_data.update( updated_time =new_time )

rawDescription: update a specific field in a filter queryset django without creating an instance

description: Update a specific field in a filter queryset django without creating an instance


code: mystring = "iBeacon major:%s minor:%s" % (majorVersion, minorVersion)

rawDescription: Python is there an equivalent of stringWithFormat: from Objective-C?


code:
def func(x0):
    s0, e0 = quad(lambda x: np.sin(x)**2, 0, x0)
    s1, e0 = quad(lambda x: (1 - np.sin(x))**2, x0, 0.5*np.pi)
    return s0 + s1

rawDescription: python curve_fit doesn't work with stiff model

description: Python curve_fit doesn't work with stiff model


code:
if not x == 0 or y == 0:
    somestuff_B

rawDescription: Python Pythonic way to organize/design if statements


code:
with open('org_list.txt') as inputfile, open('gen_list.txt', 'w') as outputfile:
    for line in inputfile:
        try:
            outputfile.write(mapping[line.strip()] + '\n')
        except KeyError:
            pass  # entry not in the mapping

rawDescription: Python program that generate a list from a given list according to a mapping


rawDescription: how to forward fill non-null values in a pandas dataframe based on a set condition

description: Forward fill non-null values in a pandas dataframe based on a set condition


rawDescription: Unpack items and add a new one

description: Unpack items and add a new one


code:
w = np.array((0, 1, 2, 5, 22))
n = len(w)
rang = np.arange(n, 0, -1)
rows = np.repeat(w, rang)
col_idx  = np.arange(n * (n + 1) // 2)
delta = np.repeat(np.concatenate(([0], np.cumsum(rang[1:]))),
                  rang)
col_idx -= delta
cols = np.take(w, col_idx)

rawDescription: How to efficiently select a submatrix with Python?

description: Efficiently select a submatrix with Python


code:
from collections import Counter
c = Counter(dictionary)
c.most_common()

rawDescription: Python Dict more than one Max value

description: Python Dict more than one Max value


code:
a = r"sudo scp -i /home/backup/.ssh/id_rsa /opt/backups/*conf backup@a-hostname.local:/opt/backups/"
b = r"""sudo scp -i /home/backup/.ssh/id_rsa /opt/backups/*conf backup@a-hostname.local:/opt/backups/"""
a == b
b
a

rawDescription: Why is subprocess.call("""scp foo""") broken?


code:
# A simple example
import itertools
lst = [0, 1]
print(list(itertools.product(lst, repeat=2)))
# [(0, 0), (0, 1), (1, 0), (1, 1)]

rawDescription: Create a list with all possible permutations from a know list of objects, but make the final list x in size


code:
@gen.coroutine
def serve_from_cache(self):
  response = yield gen.Task(get_redis)
  if response:
      self.finish(response)
      raise gen.Return(True)
  else:
      raise gen.Return(False)

@gen.coroutine
def get(self):
  if (yield self.serve_from_cache()):
    return
  # do work
  yield self.set_cache(...)

rawDescription: Refactoring a Tornado Request Handler

description: Refactoring a Tornado Request Handler


code: newch = chr( ord(ch) - shift )

rawDescription: How to decode a coded sentence?

description: Decode a coded sentence


code:
import re

def index(longstr, pat):
    rx = re.compile(r'(?P<pre>.*?)({0})'.format(pat))
    match = rx.match(longstr)
    return match and len(match.groupdict()['pre'])

rawDescription: is there a way find substring index through a regular expression in python?

description: Is there a way find substring index through a regular expression in python


code:
from django.contrib.admin.widgets import AdminURLFieldWidget

class CustomAdminURLFieldWidget(AdminURLFieldWidget):
    def render(self, name, value, attrs=None):
        output = []
        output.append(super(CustomAdminURLFieldWidget,
            self).render(name, value, attrs))
        if value:
            output.append('
%s
' %(value, value))
        return mark_safe(u''.join(output))

rawDescription: How can I extend a django admin widget so it's still optional?

description: Extend a django admin widget so it's still optional


code:
score = -75
match = (lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)
grade = lookup['Grade'][match]

rawDescription: Pandas table lookup

description: Pandas table lookup


code:
seen_for = {
    seen.which_reply_id: seen
    for seen in Seen.objects.filter(user=request.user)
}
replies_qs = Reply.objects.filter(whatever)

# you could attach the Seen instance to each Reply
# or just make a paired list e.g.
replies = [
    (reply, seen_for.get(reply.pk))  # None if not found
    for reply in replies_qs
]

rawDescription: How to annotate a related object to queryset, in cases it exists, and None otherwise? (Django)

description: Annotate a related object to queryset, in cases it exists, and None otherwise? (Django)


rawDescription: Write a list to columns

description: Write a list to columns


code: post_dict.update('loginfailed', False)

rawDescription: how to create POST data in django python

description: Create POST data in django python


code:
for fileName in filelist:

    # open in read/write mode
    with open(fileName, 'r+') as data_file:
        data_list = data_file.readlines()

        # list modification
        data_list = [ s.lstrip() for s in data_list ]
        data_list[4] = data_list[4][1:]

        # removes file contents from first character to end
        data_file.truncate(0)

        # puts cursor to the start of the file
        data_file.seek(0)

        # overwriting
        for line in data_list:
            data_file.write(line)

rawDescription: Removing specific characters from multiple lines in a list by indexing


code: /bin/sh -c ls -al

rawDescription: subprocess.call() arguments ignored when using shell=True w/ list

description: Subprocess.call() arguments ignored when using shell=True w/ list


code: b = word in (wordList[:1] + wordList[2:])

rawDescription: python check if word is in certain elements of a list

description: Python check if word is in certain elements of a list


rawDescription: How to keep the weight value to zero in a particular location using theano or lasagne?

description: Keep the weight value to zero in a particular location using theano or lasagne


code:
class Something(Base):
    ...
    _foo = Column('foo', String(123))

    @property
    def foo(self):
        return self._foo

    @foo.setter
    def foo(self, value):
        if len(value) > _foo.type.length:
            raise Exception("Value too long")
        self._foo = value

rawDescription: SQLAlchemy - maximum column length

description: SQLAlchemy - maximum column length


code:
with open('scores.txt', 'r') as infile:
    scores = {}
    for line in infile:
        name, _, score = line.rpartition(' ')
        scores[name] = int(score)

rawDescription: How to create a dictionary based on a text file?

description: Create a dictionary based on a text file


rawDescription: How to copy define function to make 'n' variations of it? (Python)

description: Copy define function to make 'n' variations of it? (Python)


rawDescription: Group values under certain key

description: Group values under certain key


code:
#!/usr/bin/env python
from bokeh.plotting import figure, output_file, show

# output to static HTML file
output_file("circle.html", title="circles")

# create a new plot with a title and axis labels, and axis ranges
p = figure(title="circles!", x_axis_label='x', y_axis_label='y',
           y_range=[-50, 50], x_range=[-50, 50])

# add a circle renderer with color options
p.circle(-25, 25, radius=5, color=(0,0,0), alpha=0.8)
p.circle(-10, 5, radius=5, color=(120, 240, 255))

# show the results
show(p)

rawDescription: Bokeh package in Python: How to use rgb to color option


code:
def function_reader(path):
    line_no = [0]
    with open(path, "r") as myfile:
        def readline():
            line_no[0] += 1
            return myfile.readline()

rawDescription: Scope of nested function declarations

description: Scope of nested function declarations


code:
from pylab import imshow
import numpy as np
import mahotas
wally = mahotas.imread('DepartmentStore.jpg')

wfloat = wally.astype(float)
r,g,b = wfloat.transpose((2,0,1))

rawDescription: How do I find Wally with Python?

description: Find Wally with Python


code:
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

config = {
    'proxy_host': '58.59.21.228',
    'proxy_port': 25,
    'proxy_username': 'yz',
    'proxy_password': 'fangbinxingqusi',
}

tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")

class IndexHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        client.fetch("http://twitter.com/", self.handle_request, **config)

    def handle_request(self, response):
        if response.error:
            print("Error:", response.error)
        else:
            self.write(response.body)
        self.finish()

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)], debug=True)
    httpserver = tornado.httpserver.HTTPServer(app)
    httpserver.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado - How to get response of AsynHTTPClient.fetch()?


code:
import matplotlib.pyplot as plt
from scipy.stats import norm
import numpy as np

xs = np.linspace(-10, 10)
ys = np.linspace(-10, 10)

# Plot integration domain
# Red regions are in the domain of integration, blue
# regions are outside
plt.contourf(xs, ys,
     [ [ 1 if norm.ppf(0.001, x, 3) < y < norm.ppf(0.999, x, 3)
         else 0 for x in xs ] for y in ys ])

rawDescription: efficiently caclulating double integral

description: Efficiently caclulating double integral


code:
pairs = {}
n = 2
word = 'banana'
for i in range(len(word)):
    pair = word[i:i+n]
    pairs[pair] = pairs.get(pair, 0) + 1

pairs

rawDescription: Create a dictionary of all letter transitions from a previous dictionary of words?


code:
model = tsa.arima_model.ARIMA(data, (12,1,0)).fit()
arima_predict = model.predict('2015-01-01','2016-01-01', typ='levels')

rawDescription: Comparison of results from statsmodels ARIMA with original data


code: whens = {'low': 0, 'medium': 1, 'high': 2}

rawDescription: Specify the sort-order for an Enum field type


code:
tags = re.findall(r'#(\w+)', line[0])
# tags = ['foo', 'bar']
tags = re.findall(r'#\w+', line[0])
# tags = ['#foo', '#bar']

rawDescription: Regex to Extract #hashtags from MMD metadata in Python


code:
if line.startswith("Path="):
    return line[5:]

rawDescription: Python - how to remove the left part of a string?


code:
# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)

rawDescription: How do I perform HTML decoding/encoding using Python/Django?

description: Perform HTML decoding/encoding using Python/Django


rawDescription: Capturing input between periods in Python


code:
import threading
import time

def thread_main():
    while True:
        time.sleep(10)
t = threading.Thread(target=thread_main)
t.start()
t.join()

rawDescription: Difference between thread.join and thread.abort in python multithreading


code:
def prepend(element, _list):
    _list.insert(0, element)

_try = [1,2,3]
prepend(0, _try)
print(_try)

rawDescription: Arguments are passed by reference or not in Python


rawDescription: Store and retreive coordinates using python and yaml


code: sum(sum(x) for x in mylist)

rawDescription: Summing a tuple in a list, in python

description: Summing a tuple in a list, in python


code:
def test_google(self):
  s.open('/')
  search_s(self, "hello world")

rawDescription: Selenium, with Python, how to simplify scripts so that I can run them from other python scripts?


code: root.after(1000, mainprgX)

rawDescription: Display a series of interfaces with one click of Run button


code:
# SConstruct
SConscript('SConscript', build_dir='build', src='.')

rawDescription: Why does SCons VariantDir() not put output in the given directory?


code:
UNKNOWN
value
value
UNKNOWN

rawDescription: how to either return string or match empty if node/tag not found in xpath (lxml)

description: Either return string or match empty if node/tag not found in xpath (lxml)


rawDescription: How to pass values to defined template from views.py in Django-python

description: Pass values to defined template from views.py in Django-python


rawDescription: How to initialize NumPy structured array with different default value for each column?

description: Initialize NumPy structured array with different default value for each column


code: df.ix[df.index.quarter == 4]

rawDescription: Pandas select the year end quarters in a DF


code:
import re
import requests
from bs4 import BeautifulSoup

link = 'http://a.vmall.com/topic/list/d6aac030f17e49d990b8a1996e872d53'

r = requests.get(link)
soup = BeautifulSoup(r.text, "html.parser")

for i in soup.find_all('a', {'class': "app-btn-down"}):
    print(re.search('http://.*\.apk', i.get('href')).group(0))

rawDescription: How to automatically download the files that have a download button on a webpage?

description: Automatically download the files that have a download button on a webpage


code: s = df_string.sum(axis=1)

rawDescription: python pandas dataframe to csv exporting a formatted text file with unique formats for each column

description: Python pandas dataframe to csv exporting a formatted text file with unique formats for each column


code: data = np.array([i*np.ones((5,5,3)) for i in range(10)], dtype=np.float64)

rawDescription: Python - read images into image matrix

description: Python - read images into image matrix


rawDescription: In Django, how could I in a single query get total row count based on distinct field values?


code:
class Foo:
    pass

x = Foo()
y = Foo()
id (x)
id (y)

rawDescription: distinguish between instances of class

description: Distinguish between instances of class


code:
def partition(x):
    group1 = []
    group2 = []
    for i in x:
        if i[0] >= "a" and i[0] <= "m":
            group1.append(i)
        else:
            group2.append(i)

    print(group1)
    print(group2)

list1 = ['andy', 'bob', 'marc', 'nick', 'paul', 'zac']

partition(list1)

rawDescription: Why is the second list in this code printing three times?


code: from BeautifulSoup import *

rawDescription: python BeautifulSoup soup.findAll(), how to make search result match

description: Python BeautifulSoup soup.findAll(), how to make search result match


rawDescription: Python, splitting strings on middle characters with overlapping matches using regex


code:
d = {}
with open("myfile.conf", 'r') as f :
    for line in f:
        if not line.strip():
            continue
        key,value = line.split('=')
        d[key.strip()] = value.strip().replace("'","")

rawDescription: Python 3.x - How to get the contents of the variables from the file


code:
from matplotlib.colorbar import ColorbarBase, make_axes_gridspec

# create a new set of axes to put the colorbar in
cax, kw = make_axes_gridspec(ax, shrink=0.6, aspect=15)

# create a new colorbar, using the colormap and norm for the real data
cb = ColorbarBase(cax, cmap=plt.cm.coolwarm, norm=norm)
cb.set_label('Voltage', fontsize='x-large')

rawDescription: Attaching intensity to 3D plot

description: Attaching intensity to 3D plot


code:
with open('index.html', 'w') as f:
    f.write('')

rawDescription: Create an empty HTML file using Python?

description: Create an empty HTML file using Python


code:
(u'Houston', u'Houst')             (u'Alabama', u'Alab')
(u'Florida State', u'FlaSt')       (u'North Carolina State', u'NCSt')
(u'Penn State', u'PnSt')           (u'Iowa', u'Iowa')
(u'Oklahoma', u'Okla')             (u'Texas', u'Texas')
(u'Florida Atlantic', u'FlAtl')    (u'South Florida', u'SFla')
(u'Georgia', u'Geo')               (u'Tennessee', u'Tenn')
(u'San Jose State', u'SJSU')       (u'Idaho', u'UI')
(u'Washington State', u'WshSt')    (u'Arizona State', u'ArzSt')
(u'Fresno State', u'FrsSt')        (u'Nevada', u'Nevad')
(u'Oregon State', u'OSU')          (u'Arizona', u'ARIZ')
(u'Clemson', u'Clem')              (u'Virginia Tech', u'VTech')
(u'Chattanooga', u'UTC')           (u'Arkansas', u'AR')
(u'USC', u'USC')                   (u'Stanford', u'Stanf')
(u'Baylor', u'BU')                 (u'Colorado', u'CU')
(u'North Texas', u'NoTex')         (u'Louisiana-Lafayette', u'LaLaf')
(u'Tulane', u'TLN')                (u'Army', u'ARMY')
(u'Troy', u'TROY')                 (u'Florida International', u'FIU')
(u'Louisiana-Monroe', u'ULM')      (u'Arkansas State', u'ASU')
(u'Texas Tech', u'TT')             (u'Iowa State', u'ISU')
(u'Akron', u'AKRON')               (u'Western Michigan', u'WMU')
(u'Liberty', u'TOLEDO')            (u'Toledo', u'LIBERTY')
(u'Virginia', u'Virg')             (u'Middle Tennessee', u'MTnSt')
(u'Oklahoma State', u'OKSt')       (u'Texas A&M', u'TexAM')
(u'Notre Dame', u'NDame')          (u'UCLA', u'UCLA')
(u'Rutgers', u'Rutgr')             (u'Cincinnati', u'Cincy')
(u'Ohio State', u'OhSt')           (u'Purdue', u'Prdue')
(u'LSU', u'LSU')                   (u'Florida', u'Fla')
(u'Air Force', u'AFA')             (u'UNLV', u'UNLV')
(u'Nebraska', u'Neb')              (u'Missouri', u'Misso')
(u'New Mexico State', u'NMxSt')    (u'Boise State', u'BoiSt')
(u'Pittsburgh', u'Pitt')           (u'Navy', u'Navy')
(u'Wake Forest', u'WFrst')         (u'Florida State', u'FlaSt')
(u'San Jose State', u'SJSt')       (u'Hawaii', u'Hawa')
(u'UCF', u'UCF')                   (u'South Florida', u'SFla')

rawDescription: Pythonic Name Matching

description: Pythonic Name Matching


code:
AtomicCRUD().delete()
# Calling 'delete' with Lock 3075170560
AtomicCRUD().delete()
# Calling 'delete' with Lock 3075170560
AtomicCRUD().create()
# Calling 'create' with Lock 3075170544
AtomicCRUD().create()
# Calling 'create' with Lock 3075170544

rawDescription: How to create a synchronized function across all instances

description: Create a synchronized function across all instances


code:
# Color matrix for Lab
colorMatrix = (
    x1, y1, z1, 0,
    x2, y2, z2, 0,
    x3, y3, z3, 0
)
img1 = img1.convert("RGB", colorMatrix)
img2 = img2.convert("RGB", colorMatrix)

rawDescription: Performing Photoshop's "Luminosity" filter programmatically


code:
from ctypes import (Structure, c_char_p, c_uint, c_int,
    POINTER, CDLL)

class AttrList(Structure): pass
AttrList._fields_ = [
    ('name', c_char_p),
    ('next', POINTER(AttrList)),
    ('op', c_int),
]

(OP1, OP2, OP3) = (2, 3, -1)

enum = CDLL('./libenum.so')
enum.f.argtypes = [POINTER(AttrList)]
enum.f.restype = None

a = AttrList(name=None, next=None, op=OP2)
assert a.op == OP2
enum.f(a)
assert a.op == OP3

rawDescription: Using enums in ctypes.Structure

description: Using enums in ctypes.Structure


code: np.dot(X_test, summed_params)

rawDescription: How to add regression functions in python, or create a new regression function from given coefficients?

description: Add regression functions in python, or create a new regression function from given coefficients


code:
for line in fileinput.input(hostsFileLoc,inplace =1):
    elements = line.split(",")
    first = elements[0].strip()
    if first != hostIP:
        sys.stdout.write(line)

rawDescription: Remove line containing specfic string

description: Remove line containing specfic string


code:
from functools import singledispatch
from collections.abc import Iterable

@singledispatch
def mult(a, b):
    return a * b

@mult.register(Iterable)
def _(it):
    return [mult(a, b) for a, b in it]

rawDescription: can a python decorator make a function able to operate on single objects and collection objects intelligently?

description: Can a python decorator make a function able to operate on single objects and collection objects intelligently


rawDescription: Reset cumsum if over limit (python)

description: Reset cumsum if over limit (python)


code:
def test():
    button_map_set(x, y)
    button_map()

Button(..., command=test)

rawDescription: Button parameter “command” executes when declared, but not when pressed


code:
def callback1(self, event):
    self.start=time.time()*1000.0
    self.pass1.unbind('<Key>') # unbind callback1

rawDescription: Binding multiple events on Tkinter Entry?


code: (datetime.datetime.fromtimestamp(1441151100, tz=pytz.utc) - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()

rawDescription: What's best way to roundtrip an epoch timestamp?


code:
for row in soup.find_all('tr'):
    fragments = row.find_all('span', class_='gw2money-fragment')
    if not fragments:
        continue
    label = row.th or row.td
    print(label.text)
    for fragment in fragments:
        value = fragment.text.split()[0]
        type_ = fragment.i['class'][0].rsplit('-', 1)[-1]
        print('-', value, type_)

rawDescription: beautifulsoup find specific tags

description: Beautifulsoup find specific tags


code:
class SomeTestSuite(unittest.TestSuite):

    # Tests to be tested by test suite
    def makeRemoveAudioSource():
        suite = unittest.TestSuite()
        suite.AddTest(TestSomething("TestSomeClass"))

        return suite

    def suite():
        return unittest.makeSuite(TestSomething)

if __name__ == '__main__':
    unittest.main()

rawDescription: how to add dozen of test cases to a test suite automatically in python

description: Add dozen of test cases to a test suite automatically in python


code:
min=math.sqrt((x - data.X[0])**2 + (y - data.Y[0])**2)
for k in range(0, 10):
    dist = math.sqrt((x - data.X[k])**2 + (y - data.Y[k])**2)
    if dist<min:
        min=dist

rawDescription: Minimum distance using for loop

description: Minimum distance using for loop


code:
class ChatSession(async_chat):
    def __init__(self,server,sock):
        async_chat.__init__(self, sock)
        self.server = server
        self.set_terminator("\r\n")
        self.data = []
        self.sock = sock # <--- add this, so you remember the socket object

rawDescription: socket server - getting a connected user's ip

description: Socket server - getting a connected user's ip


code:
st = "alpha here is my text bravo"
import re
re.findall(r'alpha(.*?)bravo',st)

rawDescription: How to extract information between two unique words in a large text file

description: Extract information between two unique words in a large text file


rawDescription: Return value from button click

description: Return value from button click


code:
import itertools
import functools
@functools.total_ordering
class DryDescriptor(object):
    _order_gen = itertools.count()
    def __init__(self, alias=None):
        self.alias = alias
        self.order = next(self._order_gen)

    def __lt__(self, other):
        return self.order < other.order

rawDescription: OO design: an object that can be exported to a "row", while accessing header names, without repeating myself


code:
import subprocess
subprocess.call(["wget", "www.example.com", "-P", "/dir/to/save"])

rawDescription: How to simulate command prompt in Perl and Python

description: Simulate command prompt in Perl and Python


code:
def inverse_transform(self, X):
    """Transform data back to its original space, i.e.,
    return an input X_original whose transform would be X

    Parameters
    ----------
    X : array-like, shape (n_samples, n_components)
        New data, where n_samples is the number of samples
        and n_components is the number of components.

    Returns
    -------
    X_original array-like, shape (n_samples, n_features)

    Notes
    -----
    If whitening is enabled, inverse_transform does not compute the
    exact inverse operation as transform.
    """
    return np.dot(X, self.components_) + self.mean_

rawDescription: Inversing PCA transform with sklearn (with whiten=True)


rawDescription: I cannot seem to find the correct formatting spec for preceding zeroes in python


code: syscall(39)  # 39 = getpid, but you get the gist

rawDescription: Make syscall in Python

description: Make syscall in Python


code:
# let's add a classmethod to User or its base class:
class User(...):
    ...
    @classmethod
    def find_or_add(cls, session, **kwargs):
        if len(kwargs) > 0:
            obj = session.query(cls).filter_by(**kwargs).first()
            if not obj:
                obj = cls(**kwargs)
                session.add(obj)
        else:
            # Otherwise, let's create an empty one and add it to the session...
            obj = cls()
            session.add(obj)
        return obj
    ...
user = User.find_or_add(session, email="someone@tld.com")

rawDescription: Proxy pattern idiom

description: Proxy pattern idiom


code:
mesh_indices = [0]*len(mesh.shape)
mesh_indices[0] = index0
mesh_indices[index0+1] = slice(0, mesh.shape[index0+1])
mesh_indices[index1+1] = slice(0, mesh.shape[index1+1])

rawDescription: Building a general numpy array index dynamically


code:
"""
Order a new server with RAID configuration.

Important manual pages:
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Hardware_Server
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""

import SoftLayer
import json

# Your SoftLayer API username and key.
USERNAME = 'set me'
API_KEY = 'set me'

quantity = 1
location = 'AMSTERDAM03'
packageId = 265

# Building a skeleton SoftLayer_Hardware_Server object to model the hostname and
# domain we want for our server. If you set quantity greater then 1 then you
# need to define one hostname/domain pair per server you wish to order.
hardware = [
    {
        'hostname': 'test',
        'domain': 'example.org'
    }
]

# Building a skeleton SoftLayer_Product_Item_Price objects. These objects contain
# much more than ids, but SoftLayer's ordering system only needs the price's id
# to know what you want to order.
# Every item in SoftLayer's product catalog is assigned an id. Use these ids
# to tell the SoftLayer API which options you want in your new server. Use
# the getActivePackages() method in the SoftLayer_Account API service to get
# a list of available item and price options per available package.
prices = [
    {'id': 76175},  # Dual Intel Xeon E5-2690 (8 Cores, 2.90 GHz)
    {'id': 74095},  # 16 GB
    {'id': 44988},  # CentOS 7.x (64 bit)
    {'id': 75005},  # RAID
    {'id': 68789},  # 500 GB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 64817},  # 1.00 TB SATA
    {'id': 50357},  # 500 GB Bandwidth
    {'id': 273},  # 100 Mbps Public & Private Network Uplinks
    {'id': 76205},  # Redundant Power Supply
    {'id': 55},  # Host Ping
    {'id': 58},  # Automated Notification
    {'id': 420},  # Unlimited SSL VPN Users & 1 PPTP VPN User per account
    {'id': 418},  # Nessus Vulnerability Assessment & Reporting
    {'id': 21},  # 1 IP Address
    {'id': 57},  # Email and Ticket
    {'id': 906}  # Reboot / KVM over IP
]

# Building a skeleton SoftLayer_Container_Product_Order_Storage_Group object
# Storage groups will only be used if the 'RAID' disk controller price is selected.
# Any other disk controller types will ignore the storage groups set here.
# The first storage group in this array will be considered the primary storage group,
# which is used for the OS. Any other storage groups will act as data storage.
storageGroups = [
    {
         "arraySize": 1998,
         "arrayTypeId": 3,  # RAID_5
         "hardDrives": [
            1,
            2,
            3,
            4
         ],
         "partitionTemplateId": 6
     },
    {
         "arraySize": 500,
         "arrayTypeId": 9,
         "hardDrives": [
             0
         ],
         # The custom partitions only work on other storage groups
         # different from the primary one
         "partitions": [
             {
                 "isGrow": False,
                 "name": "/test",
                 "size": 100
             },
             {
                 "isGrow": True,
                 "name": "/test2",
                 "size": 200
             }
         ]
     },
    {
         "arraySize": 2264,
         "arrayTypeId": 1,  # RAID_0
         "hardDrives": [
             5,
             6,
             7,
             8
         ],
         "partitions": [
             {
                 "isGrow": False,
                 "name": "/rc",
                 "size": 500
             },
             {
                 "isGrow": True,
                 "name": "/tr",
                 "size": 200
             }
         ]
     }
]

# Building a skeleton SoftLayer_Container_Product_Order_Hardware_Server object
# containing the order you wish to place.
orderTemplate = {
    'quantity': quantity,
    'location': location,
    'packageId': packageId,
    'prices': prices,
    'hardware': hardware,
    'storageGroups': storageGroups
}

# Creating a SoftLayer API client object
client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)

try:
    # verifyOrder() will check your order for errors. Replace this with a call
    # to placeOrder() when you're ready to order. Both calls return a receipt
    # object that you can use for your records.
    # Once your order is placed it'll go through SoftLayer's approval and
    # provisioning process. When it's done you'll have a new
    # SoftLayer_Hardware_Server object and server ready to use.
    receipt = client['Product_Order'].verifyOrder(orderTemplate)
    print(json.dumps(receipt, sort_keys=True, indent=2, separators=(',', ': ')))
except SoftLayer.SoftLayerAPIError as e:
    print("Unable to place a server order faultCode=%s, faultString=%s"
          % (e.faultCode, e.faultString))
    exit(1)

rawDescription: Configuring Softlayer Disk Partitions at Order Time


code:
def insert(list1, var, i):
    # An extra temporary without unpacking generalizations, but not ugly
    return list1[:i] + [var] + list1[i:-1]

rawDescription: insert element into list, move pre-existing elements

description: Insert element into list, move pre-existing elements


code: newlist

rawDescription: sorting lists in python 3

description: Sorting lists in python 3


code:
# Mask corresponding to smaller array from where elements are to be taken
select_mask = ~masked_smaller_array.mask

# Use the mask on source (smaller array) to select specific elements from it
# and update sliced and masked (with same mask) places in bigger array
bigger_array[2:4, 2:4][select_mask] = smaller_array[select_mask]

rawDescription: How to replace only part of a numpy array's values with those of another array?

description: Replace only part of a numpy array's values with those of another array


rawDescription: Generate verbose names from CamelCase

description: Generate verbose names from CamelCase


code:
import collections
import string
import random

def random_dict():
    n=random.randint(1,26)
    keys=list(string.letters)
    random.shuffle(keys)
    keys=keys[:n]
    values=[random.randint(1,100) for _ in range(n)]
    return dict(zip(keys,values))

list_dictionaries=[random_dict() for x in xrange(100)]

def f1(list_dictionaries):
    comb_dict = {}
    for dictionary in list_dictionaries:
        for key in dictionary:
            comb_dict.setdefault(key, 0)
            comb_dict[key] += dictionary[key]
    return comb_dict

def f2(list_dictionaries):
    comb_dict = collections.defaultdict(int)
    for dictionary in list_dictionaries:
        for key,value in dictionary.iteritems():
            comb_dict[key] += value
    return comb_dict

def union( dict_list ):
    all_keys = set()
    for d in dict_list:
        for k in d:
            all_keys.add( k )
    for key in all_keys:
        yield key, sum( d.get(key,0) for d in dict_list)

def f3(list_dictionaries):
    return dict(union( list_dictionaries ))

rawDescription: Add elements in a list of dictionaries

description: Add elements in a list of dictionaries


code:
cols = 4
rows = 3
[0] * cols
[[0] * cols] * rows

rawDescription: creating a function that makes a new universum with all elements [0] PYTHON

description: Creating a function that makes a new universum with all elements [0] PYTHON


code:
class Test(object):
    # you are using python 2.x -- make sure your classes inherit from object
    # Secondly, it's very good practice to use CamelCase for your class names.
    # Note how the class name is highlighted in cyan in this code snippet.
    @classmethod
    def set_name(cls, name):
        cls.name = name

Test.set_name("hello")
assert Test().name == "hello"

rawDescription: How to initialise class itself as class Object

description: Initialise class itself as class Object


code:
df = pd.read_clipboard(sep=',', index_col=0)
df

rawDescription: Pandas, to_csv () to a specific format

description: Pandas, to_csv () to a specific format


code:
data = read_csv('foo.csv')
with open('foo.txt') as textwrite:
    for row in data:
        string = '{0} has {1} apples in his Ford {2}.\n'.format(row[0], row[1], row[2])
        textwrite.write(string)
        #if you know the second column is a float:
        manipulate = float(row[1])*3
        textwrite.write(manipulate)

rawDescription: Building on "How to read and write a table / matrix to file with python?"


code:
from functools import partial
from stat import S_ISDIR

def isdir(ftp, path):
    try:
        return S_ISDIR(ftp.stat(path).st_mode)
    except EnvironmentError:
        return None

def makedirs_exists_ok(ftp, path):
    def exists_ok(mkdir, name):
        """Don't raise an error if name is already a directory."""
        try:
            mkdir(name)
        except EnvironmentError:
            if not isdir(ftp, name):
                raise

    # from os.makedirs()
    head, tail = posixpath.split(path)
    if not tail:
        assert path.endswith(posixpath.sep)
        head, tail = posixpath.split(head)

    if head and tail and not isdir(ftp, head):
        exists_ok(partial(makedirs_exists_ok, ftp), head)  # recursive call

    # do create directory
    assert isdir(ftp, head)
    exists_ok(ftp.mkdir, path)

rawDescription: python subprocess communicate freezes

description: Python subprocess communicate freezes


code:
bsizer = wx.BoxSizer()
bsizer.Add(yourTxtCtrl, 1, wx.EXPAND)

rawDescription: wxPython: How to make a TextCtrl fill a Panel

description: WxPython: How to make a TextCtrl fill a Panel


code: from ....common import utils

rawDescription: Python: Import file in grandparent directory


code: b = bytearray.fromhex('deadbeef')

rawDescription: Exploits in Python - manipulating hex strings


code:
app = Flask(__name__)
app.json_encoder = MyJSONEncoder

rawDescription: Flask jsonify a list of objects

description: Flask jsonify a list of objects


code:
import urlparse
pr = urlparse.urlparse(url)
qs = urlparse.parse_qs(pr.query)['q']

rawDescription: How do you parse and match the keyword in search engine url using python re module?

description: Parse and match the keyword in search engine url using python re module


code:
cont = df.isnull().all(1)
cont

rawDescription: Promote certain rows to index in an ordered pandas dataframe


code: 'text/html'

rawDescription: Search in list of tuples

description: Search in list of tuples


rawDescription: What module is PYSIGNAL defined in PyQt4


code:
import dis
def foo(a, b):
    a, b = b, a

dis.dis(foo)

rawDescription: How does swapping of members in the python tuples (a,b)=(b,a) work internally?


rawDescription: Python zipfile library fix

description: Python zipfile library fix


code:
def test_MyClass(self):
    def threaded_test():
        self.assertEqual(mc.get(),6)

    mc = MyClass()
    self.queue.put(1)
    self.queue.put(2)
    self.queue.put(3)
    self.queue.put({'event_name':'call','val':threaded_test})

rawDescription: Python multi-threaded unittesting

description: Python multi-threaded unittesting


code:
[u'S / 34 -- Not Available']
[u'L / 40 -- Not Available']
[u'L / 42']

rawDescription: Scraping dynamic content using python-Scrapy


code:
allindx = set()
for i in indices:
    for j in range(max(0, i-2), min(i+3, len(words))):
        allindx.add(j)

rawDescription: Python: finding the two words following a key word


code:
def check_proc(self):
   if not self.p.is_alive():
       # Process is done. Update the GUI
       self.p.join()
       self.s_button["state"] = 'normal'
       self.p_button["state"] = 'disabled'
       self.update_all()
   else:
       # Not done yet. Check again later.
       self.after(500, self.check_proc)

def on_start(self):
   if self.s_button["text"] == "RESUME":
       self.s_button["text"] = "START"
       self.p_button["text"] = "PAUSE"
       self.ps.resume() #resume command for process
   else:
       str = 'test arg'
       #queue = Queue()
       self.p = multiprocessing.Process(None, test_function)
       self.p.start()
       self.ps = psutil.Process(self.p.pid)

       self.s_button["state"] = 'disabled'
       self.p_button["state"] = 'normal'
       self.update_all()
       self.after(500, self.check_proc)  # Check to see if the process is done in 0.5 seconds

       #p.join() #ending process

rawDescription: Tkinter GUI freezes when using multiprocessing.Process


code:
if form.validate_on_submit():
    meal = form.meal.data
    return tip_calculator(meal)

rawDescription: How do I make this function redirect to a given html page?

description: Make this function redirect to a given html page


code:
for i, var_name in enumerate(data):
    original_class = type(data[var_name])
    new_data[var_name] = original_class(new_data[var_name])

rawDescription: Python string to other classes

description: Python string to other classes


code:
import sys
sys.stdout.write('\a')
sys.stdout.flush()

rawDescription: Python Sound ("Bell")

description: Python Sound ("Bell")


code: pos = np.vstack(positions + positions[:1])

rawDescription: How to remove the previous drawing in matplotlib, Python?

description: Remove the previous drawing in matplotlib, Python


code:
from sys import argv
script, file_name = argv

with open(file_name, 'w') as f:
    f.writelines(line+"\n" for line in iter(raw_input,""))

rawDescription: How to make this code simply which uses argv, raw_input(), f.write() in Python

description: Make this code simply which uses argv, raw_input(), f.write() in Python


code:
import ctypes
from ctypes import wintypes
_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
_GetShortPathNameW.restype = wintypes.DWORD

rawDescription: How to get Windows short file name in python?

description: Get Windows short file name in python


code:
np.nan is np.nan
float('nan') is float('nan')
np.float64('nan') is np.float64('nan')

rawDescription: Reducing pandas series with multiple nan values to a set gives multiple nan values


rawDescription: Delete numbers from dictionary of lists

description: Delete numbers from dictionary of lists


code:
import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

rawDescription: Python 2.7 - Write and read a list from file


code:
# Lets take  1000 rows at the time
batch_size = 1000
while True:
    rows = c.fetchmany(batch_size)
    if not rows: break
    for row in rows:
        print(foo(row))

rawDescription: In python's sqlite3 module, will using cursor.fetchone() as the condition for a while loop fetch a row?


code:
try:
    looknext[char].append(s[index+1])
except KeyError:
    looknext[char] = [s[index+1]]

rawDescription: Python: Get the following letters in a string and use as key value in dictionary


code: df = df.asfreq('H')

rawDescription: Python linear interpolation of values in dataframe


code:
class ClassPropertyDescriptor(object):

    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        return self.fget.__get__(obj, klass)()

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        type_ = type(obj)
        return self.fset.__get__(obj, type_)(value)

    def setter(self, func):
        if not isinstance(func, (classmethod, staticmethod)):
            func = classmethod(func)
        self.fset = func
        return self

def classproperty(func):
    if not isinstance(func, (classmethod, staticmethod)):
        func = classmethod(func)

    return ClassPropertyDescriptor(func)

class Bar(object):

    _bar = 1

    @classproperty
    def bar(cls):
        return cls._bar

    @bar.setter
    def bar(cls, value):
        cls._bar = value

# test instance instantiation
foo = Bar()
assert foo.bar == 1

baz = Bar()
assert baz.bar == 1

# test static variable
baz.bar = 5
assert foo.bar == 5

# test setting variable on the class
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50

rawDescription: How can I make a class property in python

description: Make a class property in python


rawDescription: Pandas: Subtract row mean from each element in row


code:
filtered = (values[index] for index in indices)
next(filtered)
next(filtered)
next(filtered)
next(filtered)

rawDescription: Extract list from given list and given indices


rawDescription: Python: How to split a string of two-digit numbers into an array


code:
res = sqlContext.sql("select id, table, user, changeDate, max(value2) as value2, max(value) as value, max(name) as name \
from (select id, table, user, changeDate, case when trim(deltaCol) == 'value2' then deltaValue else Null end value2,\
case when trim(deltaCol) == 'value' then deltaValue else Null end value,\
case when trim(deltaCol) == 'name' then deltaValue else Null end name from delta) t group by id, table, user, changeDate")

rawDescription: Update a Pyspark DF Column based on an Array in another column


rawDescription: list of indexes of maximum values in ndarray

description: List of indexes of maximum values in ndarray


code:
import matplotlib.pyplot as plt
import numpy as np
xdata = [1, 2, 3, 4, 5]
ydata = [[np.random.randint(0, 6) for i in range(5)],
        [np.random.randint(0, 6) for i in range(5)],
        [np.random.randint(0, 6) for i in range(5)]]
colors = ['r', 'g', 'b']  # can be hex colors as well
legend_names = ['a', 'b', 'c']
for c, y in zip(colors, ydata):
    plt.plot(xdata, y, c=c)
plt.legend(legend_names)
plt.show()

rawDescription: Plotting pandas dataframe with string labels


code:
import numpy as np
def NN(A, start):
    """Nearest neighbor algorithm.
    A is an NxN array indicating distance between N locations
    start is the index of the starting location
    Returns the path and cost of the found solution
    """
    path = [start]
    cost = 0
    N = A.shape[0]
    mask = np.ones(N, dtype=bool)  # boolean values indicating which
                                   # locations have not been visited
    mask[start] = False

    for i in range(N-1):
        last = path[-1]
        next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations
        next_loc = np.arange(N)[mask][next_ind] # convert to original location
        path.append(next_loc)
        mask[next_loc] = False
        cost += A[last, next_loc]

    return path, cost

rawDescription: Nearest Neighbour Algorithm

description: Nearest Neighbour Algorithm


code:
def get_ancestors_recursively(e, b):
    "Finds ancestors of b in the element tree e."
    return _get_ancestors_recursively(e.getroot(), b, [])

def _get_ancestors_recursively(s, b, acc):
    "Recursive variant. acc is the built-up list of ancestors so far."
    if s == b:
        return acc
    else:
        for child in s.getchildren():
            newacc = acc[:]
            newacc.append(s)
            res = _get_ancestors_recursively(child, b, newacc)
            if res is not None:
                return res
        return None

rawDescription: In Python ElementTree how can I get list of all ancestors of an element in tree?


code:
try :
    if(__IPYTHON__) :
        get_ipython().magic(u'cd ~/')
        get_ipython().magic(u'load_ext autosave')
        get_ipython().magic(u'autosave 30')
except NameError :
    pass

rawDescription: Keep cells or magic functions from saving to python script


code: words.extend(w for w in t.with_prefix(string) if len(w) == len(string))

rawDescription: blo python tree

description: Blo python tree


code:
if name not in list_of_allowed_attributes_to_change:
    raise AttributeError('''Can't set attribute "{0}"'''.format(name))

rawDescription: How to make class immutable in python?

description: Make class immutable in python


rawDescription: How to create a sequential combined list in python?

description: Create a sequential combined list in python


rawDescription: Unpickle a data structure Vs. build by calling readlines()


rawDescription: How can I pass a .txt file as a function parameter

description: Pass a .txt file as a function parameter


code: define_words = raw_input("Enter string: ")

rawDescription: Python extracting sentence containing 2 words


rawDescription: Create a bit mask

description: Create a bit mask


code:
one_hour_ago = datetime.now()-timedelta(hours=1)
recent_groups = Group.objects.filter(grouptraffic__time_of_visit>=one_hour_ago)
visitors = recent_groups.annotate(views=Count('grouptraffic__visitor', distinct=True))

rawDescription: How to sort a Django queryset by a conditional aggregation of related items?

description: Sort a Django queryset by a conditional aggregation of related items


rawDescription: open bin file and convert ascii to hex

description: Open bin file and convert ascii to hex


code:
s = slice(1, 2, 3)
s.start
s.stop
s.step

rawDescription: How do I access the elements of a slice object in python

description: Access the elements of a slice object in python


code:
if not getattr(infile, 'read', None):
    print('definitely not a file...')

rawDescription: undefined-variable Warning for python 3.x in pylint

description: Undefined-variable Warning for python 3.x in pylint


code: sampleDateTime = yearStart + datetime.timedelta(0, index * 60 * 60 * 6)

rawDescription: Writing NetCDF time variable from start of year