code:
import cProfile

cProfile.run('get_worker_stats(worker_id)')

rawDescription: Proper way to debug statement-level performance


code: Verb("make", "make", "makes", "make", "make", "make")

rawDescription: Represent a table as object

description: Represent a table as object


code:
class Base(object):

    def load(self):
        print('do logic A')
        print('do logic B')

class Child(Base):

    def load(self):
        super().load()
        print('do logic C')

c = Child()
c.load()

rawDescription: Extending the behavior of an inherited function in Python


rawDescription: Represent a hash string to binary in Python


code:
for i in xrange(0,5):
    for j in xrange(0,5):
        text(i, j,
             "{0:5.2f}".format(a[i][j]),
             horizontalalignment="center",
             verticalalignment="center")

rawDescription: Creating an Infographic In Python

description: Creating an Infographic In Python


code:
chunks = []
for chunk in start_stop:
    chunks.append(format2[chunk])

rawDescription: Writing python chunking loops with reference to another txt


code:
with open('a.txt', 'r') as infile:
    for line in infile:
        line = line.split()
        new_line = '{0} "yyy" {1} "xxx"'.format(line[0], line[3])
        print(new_line)

rawDescription: python program - modify columns in text file

description: Python program - modify columns in text file


code:
binary = WindowsFirefoxBinary()
browser = webdriver.Firefox(firefox_binary=binary)

rawDescription: How to run Selenium Webdriver with pythonw?

description: Run Selenium Webdriver with pythonw


code:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class SmartBool(QObject):

    valueChanged = pyqtSignal(bool)         # Signal to be emitted when value changes.

    def __init__(self, value=False):
        super(SmartBool, self).__init__()   # Call QObject contructor.
        self.__value = value                # False initialized by default.

    @property
    def value(self):
        return self.__value

    @value.setter
    def value(self, value):
        if self.__value != value:
            self.valueChanged.emit(value)   # If value change emit signal.
            self.__value = value

class SelectionWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ILCheck = SmartBool()          # Your steroides bool variable.
        ILCheckbox = QCheckBox(self)
        self.connect(self.ILCheck, SIGNAL("valueChanged(bool)"), ILCheckbox, SLOT("setChecked(bool)"))
        ILCheckbox.setCheckState(Qt.Unchecked)
        ILCheckbox.stateChanged.connect(self.ILCheckbox_changed)
        MainLayout = QGridLayout()
        MainLayout.addWidget(ILCheckbox, 0, 0, 1, 1)
        self.setLayout(MainLayout)

    def ILCheckbox_changed(self, state):
        self.ILCheck = (state == Qt.Checked)
        print(self.ILCheck)

if __name__ == '__main__':
  app = QApplication(sys.argv)
  window = SelectionWindow()
  window.show()
  window.ILCheck.value = True
  sys.exit(app.exec_())

rawDescription: Python2 PyQt4 Connect a bool Variable to a QCheckBox item


code:
keys = [k for d in dict_x for k in d]
{k: sum(d.get(k, 0) for d in dict_x) for k in keys}

rawDescription: How to merge a list of dicts, summing values for repeated keys

description: Merge a list of dicts, summing values for repeated keys


code:
re.search(r'(?<=//)([^/]+)(/.*)?(?= \" target)',
          'http://example.com/path/to/whatever " target').groups()

rawDescription: Regex to return all characters until "/" searching backwards


code:
import csv
import sys
import datetime
import pprint

all_data_points = {}
all_dates = []
expected = ''
format = "%Y%m%d %H:%M"

with open('datafile', 'rt') as f:
    reader = csv.reader(f)
    for row in reader:
        if row and 'Datetime' not in row:
            day_str = row[0]
            rain_str = row[1]
            if not expected:
                all_data_points[day_str] = rain_str
                all_dates.append(day_str)
                d = datetime.datetime.strptime(day_str, format)
                expected = d + datetime.timedelta(days=1)
            else:
                d = datetime.datetime.strptime(day_str, format)
                gap_in_days = d - expected
                start_day = expected
                if gap_in_days.days > 1:
                    for i in xrange(gap_in_days.days):
                        next_day = start_day + datetime.timedelta(days=1+i)
                        day_str = next_day.strftime(format)
                        all_data_points[day_str] = 'M'
                        all_dates.append(day_str)
                all_data_points[day_str] = rain_str
                expected = d

    pprint.pprint(all_data_points)

rawDescription: parse using dateutil

description: Parse using dateutil


code: sortedData = sorted(rowData, key = lambda x:(x[1]+x[2]))

rawDescription: Is this a bad way to sort a list based on another list's sorted permutation?


code: ['bananas-10', '10-bananas']

rawDescription: Checking if string contains a word that is subset of a word in a list


rawDescription: 3x1 Matrix Multiplication with lists[UPDATED]


code:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        self.wfile.write('Hello world!\n')

HTTPServer(('', 8000), MyHandler).serve_forever()

rawDescription: Differences between BaseHttpServer and wsgiref.simple_server


code:
nans_in_grid = np.isnan(grid)
nan_rows = np.all(nans_in_grid, axis=0)
nan_cols = np.all(nans_in_grid, axis=1)

indicies_to_remove = zip(np.nonzero(nan_rows)[0], np.nonzero(nan_cols)[0])
y_indice_to_remove, x_indice_to_remove = zip(*indicies_to_remove)

tmp = grid[[x for x in range(grid.shape[0]) if x not in x_indice_to_remove], :]
grid = tmp[:, [y for y in range(grid.shape[1]) if y not in y_indice_to_remove]]

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


rawDescription: Replace a blank space followed by text with a blank space using string replace


code:
randlist = [r + (end - start + 1) * (r >= start) for r in
            random.sample(range(total - end + start), 100)]

rawDescription: Python random unique values from two non overlapping ranges


rawDescription: python Binary string to binary data

description: Python Binary string to binary data


code:
s = Spam()
spams = []
spams.append(s)
spams.append(s)

rawDescription: Wrapping an std::vector using boost::python vector_indexing_suite


code: arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|>', color='k', shrinkA=0, shrinkB=0)

rawDescription: Arrows in matplotlib using mplot3d

description: Arrows in matplotlib using mplot3d


rawDescription: Representing rings of algebraic integers


code:
def func_1():
    global a
    global b
    global c
    # Function body

rawDescription: Python: variables not cumulative passing through functions


code:
import re
from operator import itemgetter
mystr='Version 1.15.6\n'
m = re.match('Version (?P<_0>.+)\.(?P<_1>.+)\.(?P<_2>.+)', mystr)
map(itemgetter(1), sorted(m.groupdict().items()))

rawDescription: Convert string to variables (like format(), but in reverse) in Python


code:
some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
value_to_remove = "You say yes"
some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
some_dict
some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
some_dict

rawDescription: Best way to remove an item from a Python dictionary?

description: Remove an item from a Python dictionary


rawDescription: Python regex multiline replacement

description: Python regex multiline replacement


code:
# Knuth-Morris-Pratt string matching
# David Eppstein, UC Irvine, 1 Mar 2002

def KnuthMorrisPratt(text, pattern):

    '''Yields all starting positions of copies of the pattern in the text.
Calling conventions are similar to string.find, but its arguments can be
lists or iterators, not just strings, it returns all matches, not just
the first one, and it does not need the whole text in memory at once.
Whenever it yields, it will have read the text exactly up to and including
the match that caused the yield.'''

    # allow indexing into pattern and protect against change during yield
    pattern = list(pattern)

    # build table of shift amounts
    shifts = [1] * (len(pattern) + 1)
    shift = 1
    for pos in range(len(pattern)):
        while shift <= pos and pattern[pos] != pattern[pos-shift]:
            shift += shifts[pos-shift]
        shifts[pos+1] = shift

    # do the actual search
    startPos = 0
    matchLen = 0
    for c in text:
        while matchLen == len(pattern) or \
              matchLen >= 0 and pattern[matchLen] != c:
            startPos += shifts[matchLen]
            matchLen -= shifts[matchLen]
        matchLen += 1
        if matchLen == len(pattern):
            yield startPos

rawDescription: Detect whether sequence is a multiple of a subsequence in Python


code: g.filter(lambda x: len(x) >= 10)

rawDescription: Replace rarely occurring values in a pandas dataframe


code:
import ast
help(ast)

rawDescription: Recommended Compiler Parse Tree Data Structure


code:
def my_range(start=0, stop=None, step=1):
    if stop == None:
        start, stop = 0, start
    while start < stop:
        yield start
        start += step

rawDescription: How do Python methods handle arbitrary parameters?


code:
lienyears = tax_allyears.loc[tax_allyears['type'] == 'Lien','tax_year'].unique().tolist()
lienendorsementyears = tax_allyears.loc[tax_allyears['type'] == 'Lien Endorsement','tax_year'].unique().tolist()

by_year_lien_interest = tax_allyears[(tax_allyears['type'] == 'Lien Interest') & tax_allyears['tax_year'].isin(lienyears)].groupby('tax_year')['amount'].sum()
by_year_lien_endorsement_interest = tax_allyears[(tax_allyears['type'] == 'Lien Interest') & tax_allyears['tax_year'].isin(lienendorsementyears)].groupby('tax_year')['amount'].sum()

rawDescription: Pandas groupby sum if value in group

description: Pandas groupby sum if value in group


code:
#!python2
import json

# here you read your new user and his password
user = raw_input("User: ")
display = raw_input("Display name: ")
pwd = raw_input("Pass: ")

with open('text.json') as data_file:
    data = json.load(data_file)
    data['users'][user] = {'display':display,'pass':pwd}

with open('text.json','w') as data_file:
    json.dump(data, data_file, indent=4)

rawDescription: How to add to a json file in python

description: Add to a json file in python


code: def f(L = []): pass

rawDescription: Why this local variable can keep its value in the function


code:
fd = os.open('test.txt', os.O_RDONLY)
file1 = FileIO(fd, 'r', closefd=False)
file2 = FileIO(fd, 'r', closefd=False)

file1.read(100)
assert file1.tell() == 100
file2.read(100)
assert file1.tell() == 200

rawDescription: prevent BufferedReader from closing the file for a list of files

description: Prevent BufferedReader from closing the file for a list of files


code: client.propget( "svn:externals", base_checkout_path, recurse=True)

rawDescription: Script/utility to rewrite all svn:externals in repository trunk


code:
from io import StringIO
# from StringIO import StringIO -- python 2.x
import sys
my_out = StringIO()
sys.stdout = my_out
print("hello") # now stored in my_out

rawDescription: Storing Python output in a string

description: Storing Python output in a string


code:
from django.db import models
import choices

class SomeModel(models.Model):
    somefield = models.IntegerField('field', choices=choices.as_list())

rawDescription: How to store python classes into a database with Django?

description: Store python classes into a database with Django


code:
mask = df3['City_x'] < df3['City_y']
df3 = df3.loc[mask]; df3

rawDescription: Count by combination

description: Count by combination


code: b = np.zeros((7,))

rawDescription: Fastest way to replace values in a numpy array with a list


code:
result = collection.aggregate([
    # Matchn the documents possible
    { "$match": { "date": { "$gte": startdate } } },

    # Group the documents and "count" via $sum on the values
    { "$group": {
        "_id": {
            "scan_status": "$scan_status",
            "date": "$date"
        },
        "count": { "$sum": 1 }
    }}
])

rawDescription: PyMongo group by multiple keys

description: PyMongo group by multiple keys


rawDescription: Plot topics with bokeh or matplotlib

description: Plot topics with bokeh or matplotlib


code:
def traverseTree(tree):
  if not isinstance(tree, nltk.Tree): return []
  h = []
  for subtree in tree:
    if type(subtree) == nltk.tree.Tree:
      t = traverseTree(subtree)
      #RIGHT HERE!! need to extend by t or the other found nodes are thrown out
      h.extend(t)

      if subtree.label() == 'NP' and len(t) == 0:
          h.append(subtree)

  return h

rawDescription: Retrieve Graph Lowest Height Node with Filter


code: assert len(self.soup.find_all('html')) == 1

rawDescription: Checking for duplicate tags using Beautifulsoup


code:
match = np.logical_and(C1 == C2, D1 == D2)
match
A[match]
B[match]

rawDescription: Getting values OF a set in Python

description: Getting values OF a set in Python


rawDescription: Build slice objetcs from subscript notation


rawDescription: Python Regex challenge indentation

description: Python Regex challenge indentation


rawDescription: Output of Python interpreter?

description: Output of Python interpreter


code:
import pyparsing as pyp

pyp.delimitedList(pyp.quotedString | pyp.SkipTo(',' | pyp.LineEnd()), ',') \
    .parseWithTabs().parseString(s)

rawDescription: Python delimited line split problems

description: Python delimited line split problems


code:
values = [200, -140, 400, -260]
values = [max(x, 0) for x in values]

rawDescription: Check if multple variables greater than zero in python


code:
def choice(self, seq):
    return seq[int(self.random() * len(seq))]

rawDescription: Performance of choice vs randint

description: Performance of choice vs randint


code:
if minorallelefreq[x] > 0.4 and minorallelefreq[x] <= 0.4:  # never True
    minprop4 = minprop4 + 1                                 # indentation??

rawDescription: Why does the following loop keep returning me results of 0?


code:
for sublist in list:
    if movie in sublist and code in sublist:
         return True
return False

rawDescription: How to check whether a value is in a list

description: Check whether a value is in a list


rawDescription: How to sort through keys in a dictionary, adding the values and returning a list of keys if combined values equal a certain number

description: Sort through keys in a dictionary, adding the values and returning a list of keys if combined values equal a certain number


code:
import numpy as np
from scipy.interpolate import UnivariateSpline, splev, splrep
from scipy.optimize import minimize

def guess(x, y, k, s, w=None):
    """Do an ordinary spline fit to provide knots"""
    return splrep(x, y, w, k=k, s=s)

def err(c, x, y, t, k, w=None):
    """The error function to minimize"""
    diff = y - splev(x, (t, c, k))
    if w is None:
        diff = np.einsum('...i,...i', diff, diff)
    else:
        diff = np.dot(diff*diff, w)
    return np.abs(diff)

def spline_neumann(x, y, k=3, s=0, w=None):
    t, c0, k = guess(x, y, k, s, w=w)
    x0 = x[0] # point at which zero slope is required
    con = {'type': 'eq',
           'fun': lambda c: splev(x0, (t, c, k), der=1),
           #'jac': lambda c: splev(x0, (t, c, k), der=2) # doesn't help, dunno why
           }
    opt = minimize(err, c0, (x, y, t, k, w), constraints=con)
    copt = opt.x
    return UnivariateSpline._from_tck((t, copt, k))

rawDescription: Spline with constraints at border

description: Spline with constraints at border


code: list1 = list2 = list3 = list()

rawDescription: Python: Appending items to lists by iterating through list of lists


code:
for tr in soup.find_all('tr', align='center'):
    stack = []
    for td in tr.findAll('td'):
        stack.append(td.text.replace('\n', '').replace('\t', '').strip())

    acct.write(", ".join(stack) + '\n')

rawDescription: Cleaning Up HTML Parse in Python

description: Cleaning Up HTML Parse in Python


code:
from flask import Flask, render_template

app = Flask(__name__)

app.route('/',methods=['GET','POST'])
def print_form():
    if request.method == 'POST':
        return render_template('form.html',result=request.form['fooput'])
    if request.method == 'GET':
        return render_template('form.html')

if __name__ == '__main__':
    app.run()

rawDescription: How to get the text input given by a user for an HTML page through python?

description: Get the text input given by a user for an HTML page through python


code:
df
df[~df.isin(allowed_vals)] = "None"
df

rawDescription: How to replace all values in a Pandas Dataframe not in a list?

description: Replace all values in a Pandas Dataframe not in a list


code:
for line in file:
    left,right = line.split('(',1)
    hexvalues = right.split(')')[0]
    hex1,hex2 = hexvalues.split(',')

rawDescription: Convert a string containing hex (along with other characters) to binary in Python


code: print('; '.join(map(str, range(50, 150))))

rawDescription: How to delete a character off a string with variables and functions in Python?

description: Delete a character off a string with variables and functions in Python


code:
lettersGuessed = ['a', 'b', 'c']
'wedqwdasdasccdshjasdcas'.translate(None, ''.join(lettersGuessed))

rawDescription: Removing a char from String, what's a more efficient way to do this?


rawDescription: Python - Find top largest numbers in array


rawDescription: Return rows only if all items of category are True


code:
find_word("xylon")
find_word("bad")

rawDescription: Python: Find a word in a matrix of characters


code:
def dic_gen(exc):
    param_errors = {re.sub(r'(sss_)|(ttt_)',
        lambda mo: 'aaa_' if mo.group(0) == 'sss_' else 'bbb_', err.name):
        err.address for err in exc.errors}
    param_errors["status"] = "ERROR"
    return param_errors

rawDescription: replace string if regex matched and replace with something else it matches some other regex

description: Replace string if regex matched and replace with something else it matches some other regex


code:
a = { 'name': 'mary', 'age': 56, 'gender': 'female' }
b1 = { 'name': 'mary', 'age': 56 }

all(a[k]==v for k,v in b1.iteritems())
b2 = { 'name': 'elizabeth', 'age': 56 }
all(a[k]==v for k,v in b2.iteritems())

rawDescription: is there a built-in feature to say a dict A contains another dict B?

description: Is there a built-in feature to say a dict A contains another dict B


code:
import htql
page="""

      word

          another_word

   """

query = """

{
      c1 = 1 &tx;
      c2 = 2 &tx &trim;
   }
   """

a=htql.query(page, query)
print(dict(a))

rawDescription: Parsing html elements using BeautifulSoup


code:
def compile_theano_uniq(x):
    diffs = x[1:] - x[:-1]
    diffs = tt.concatenate([tt.ones_like([x[0]], dtype=diffs.dtype), diffs])
    y = diffs.nonzero_values()
    return theano.function(inputs=[x], outputs=y)

theano_uniq = compile_theano_uniq(tt.vector(dtype='int32'))

rawDescription: `uniq` for 2D Theano tensor

description: `uniq` for 2D Theano tensor


code: {{ myvariable|safe }}

rawDescription: Django, automatic HTML "sanitizing" when putting HTML to template, how to stop it?


code:
def original(data):
    data = json.loads(data)
    lis = [row['text'] for row in data['City']['values'] if row['text'].startswith("A")]
    lis = sorted(lis)
    return lis[:5]

rawDescription: Python beginner: how to reduce execution time of this small program?


code:
for project in projects:
    project.extend([orig_project[1] for orig_project in Projects_with_owner if
                    orig_project[1] is not None and
                    orig_project[0] == project[0]])

rawDescription: best way to do list comprehension matching when there are multiple matches

description: Do list comprehension matching when there are multiple matches


code: roottree = tree.find('root')

rawDescription: Get part of XML document in Python

description: Get part of XML document in Python


code:
import dis
dis.dis(compile('divmod(n, d)', '', 'exec'))
dis.dis(compile('(n // d, n % d)', '', 'exec'))

rawDescription: Is divmod() faster than using the % and // operators?


code: ipfirewall

rawDescription: Matching IP addresses to a list of subnets and then returning the firewall


code:
from math import pi

def leibniz():
    from itertools import count
    s, x = 1.0, 0.0
    for i in count(1, 2):
        x += 4.0*s/i
        s = -s
        yield x

def avg(seq):
    a = next(seq)
    while True:
        b = next(seq)
        yield (a + b) / 2.0
        a = b

base = leibniz()
d1 = avg(base)
d2 = avg(d1)
d3 = avg(d2)

for i in range(20):
    x = next(d3)
    print("{:.6f} {:8.4%}".format(x, (x - pi)/pi))

rawDescription: Pi calculation in python

description: Pi calculation in python


code: pandas.DataFrame([convert(c) for c in l] for l in df.values)\

rawDescription: numerical sort a column containing numbers and strings (pandas/python)

description: Numerical sort a column containing numbers and strings (pandas/python)


code:
items = {item[4] for item in main_list}
for child in xml_data:
    value = child.get('value')
    if value in items:
        print(value)

rawDescription: Compare two lists in python and print the output


code:
from proj.celery import app
app.control.purge()

rawDescription: How do I permanently remove a celery task from rabbitMQ?

description: Permanently remove a celery task from rabbitMQ


code: Counter(tuple(e) for e in li)

rawDescription: How to count number of unique lists within list?

description: Count number of unique lists within list


rawDescription: Python: Sampling from a discrete distribution defined in an n-dimensional array


code:
from collections import namedtuple
Child = namedtuple('Child', 'fitness noise')
children = [Child(fitness=60, noise=5),
            Child(fitness=50, noise=8),
            Child(fitness=40, noise=6)]

rawDescription: Sorting based on two variables in python


rawDescription: processing a set of unique tuples

description: Processing a set of unique tuples


code:
replacements = [
    ('abc', 'x'),
    ('def', 'y'),
    ('ghi', 'z'),
]

trans = str.maketrans({ k: v for l, v in replacements for k in l })

rawDescription: Using multiple (similar) generator expressions


code:
from django.conf import global_settings

gettext = lambda s: s
LANGUAGES = (
   ('en', gettext('English')),
)

NEW_LANG_INFO = {
    'en': {
       'bidi': False, # right-to-left
       'code': 'en',
       'name': 'English',
       'name_local': u'English', #unicode codepoints here if necessary
    },
}

import django.conf.locale
LANG_INFO = dict(django.conf.locale.LANG_INFO.items() + NEW_LANG_INFO.items())
django.conf.locale.LANG_INFO = LANG_INFO

rawDescription: How to Create our own language package in django


rawDescription: python changing string to date

description: Python changing string to date


code:
output = {}
for key in d1.keys():
    output[key] = {}
    lst = d1[key]
    for name, count in (lst[i:i+2] for i in range(0, len(lst), 2)):
        output[key][name] = (int(count),)
for key in d2.keys():
    if key not in output:
        output[key] = {}
    lst = d2[key]
    for name, count in (lst[i:i+2] for i in range(0, len(lst), 2)):
        if name in output[key].keys():
            output[key][name] += (int(count),)
        else:
            output[key][name] = (int(count),)

rawDescription: merge to dictionaries preserving different values

description: Merge to dictionaries preserving different values


code:
import time

mydate = datetime.date(2010, 1, 12) + datetime.timedelta(days = 3)
time.mktime(mydate.timetuple())

rawDescription: How to convert date to timestamp using Python?

description: Convert date to timestamp using Python


rawDescription: numpy matrix rank incorrect result

description: Numpy matrix rank incorrect result


code: closeProgram = raw_input()

rawDescription: python dice roll simulator, issues with quit and roll again

description: Python dice roll simulator, issues with quit and roll again


code:
data = pipestr.split("|")
code = re.sub(
    r"([0-9a-f]+)",  # find all hexadecimals
    lambda match: data[int(match.group(1), 16)],  # replace them by indexing the data
    base64.b64decode(b64str)  # insert into the structure
)

rawDescription: How to decode a python string

description: Decode a python string


rawDescription: Python Pandas: Get index of rows which column matches certain value


code:
@vectorize('(float64, float64)', target='parallel')
def add_ufunc(a, b):
    return a + b

rawDescription: numba guvectorize target='parallel' slower than target='cpu'

description: Numba guvectorize target='parallel' slower than target='cpu'


code:
if ajax:
    template_values['my_template'] = 'base_ajax.html'
else:
    template_values['my_template'] = 'base.html'

rawDescription: Python / Django - If statement in template around extends


code:
from subprocess import check_output

out = check_output(["apt-cache", "policy","python"])
print(out)

rawDescription: How to lookup debian package info with Python

description: Lookup debian package info with Python


code:
all_bytes = "".join(map(chr, range(256)))
u1 = all_bytes.decode('cp1252', 'replace')
u2 = all_bytes.decode('mbcs', 'replace')
u1 == u2
[(i, u1[i], u2[i]) for i in xrange(256) if u1[i] != u2[i]]

rawDescription: how to read a file that can be saved as either ansi or unicode in python?

description: Read a file that can be saved as either ansi or unicode in python


code: something([np.atleast_2d(x), 0, x])

rawDescription: NumPy: 2D array from a list of arrays and scalars


rawDescription: Why is python returning a numbers from a string?


code:
def main(listOfLists):
    i = 1
    answer = listOfLists[0]
    while i<len(listOfLists):
        answer = commonBand(answer, listOfLists[i])
        if not answer:
            break
        i += 1
    return answer

rawDescription: Common Favorite Band Python

description: Common Favorite Band Python


rawDescription: pandas: function equivalent to SQL's datediff()?

description: Pandas: function equivalent to SQL's datediff()


rawDescription: Is there a simpler way to allocate value to a variable given a if condition - Python?


rawDescription: How to delete the current row in pandas dataframe during df.iterrows()

description: Delete the current row in pandas dataframe during df.iterrows()


code: frame = cv2.inRange(frame, lowerb, upperb)

rawDescription: Why doesn't OpenCV's inRange function convert my HSV image to Binary?


code:
x
y

rawDescription: Python calculations in two groups

description: Python calculations in two groups


code:
#!env python

import gevent
from gevent import local

data = local.local()
data.numbers = 12
#Declare data as a global variable.

def foo():
    print("IN FOO")
    data.numbers = 42
    #Change the value of data.numbers.

    print(data.__dict__)
    #Check the values in data in the function foo.

def bar():
    print("IN BAR")

    print(data.__dict__)
    #Check the values in data in the function bar.

def main():
    print("In Main")
    print(data.__dict__)
    #Check the values in data at beginning.

    foo_gl = gevent.Greenlet(foo)
    bar_gl = gevent.Greenlet(bar)
    foo_gl.start()
    bar_gl.start()
    gevent.joinall([foo_gl, bar_gl])

    print("Afeter all, In Main")
    print(data.__dict__)
    #Check the values in data at the end.

if __name__ == "__main__":
    main()

rawDescription: how to use gevent local module

description: Use gevent local module


code:
DF.to_dict()
DF.to_dict(orient="index")

rawDescription: How to use Pandas to create Dictionary from column entries in DataFrame or np.array

description: Use Pandas to create Dictionary from column entries in DataFrame or np.array


code:
plt.plot(x, [i for (i,j) in y], 'rs', markersize = 12 )
plt.plot(x, [j for (i,j) in y], 'bo', markeresize = 8)

rawDescription: Matplotlib scatter plot with 2 y-points per x-point


code:
class PositiveValuedProperty():
    def __init__(self, name):
        self.name = "_" + name

    def __get__(self, obj, cls=None):
        return getattr(obj, self.name)

    def __set__(self, obj, new_value):
        if new_value < 1:
            new_value = 1
        setattr(obj, self.name, new_value)

rawDescription: Python 3.4 - How to create a template property for many classes


code: type(Foo)

rawDescription: Why can `__subclasshook__` be monkeypatched onto the metaclass but `__instancecheck__` cannot?


code:
var = "MyClassName"
import sys
mod = sys.modules[__name__]
getattr(mod, var)()

rawDescription: Use class as string

description: Use class as string


code: filter(None, a.split('\n'))

rawDescription: split a string in python

description: Split a string in python


code: args, kwargs = self.__translate(*args, **kwargs)

rawDescription: Django : how could I overload Q in django.db.models.query QuerySet to use for a special purpose in my Manager


rawDescription: .fillna column if two cells are empty in Pandas


code:
series = df.a + ", " + df.b
series

rawDescription: make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy

description: Make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy


code:
urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',
    # (r'^$', index),
    url(r'^(?P<object_type>\w+)/$', music_object_list, name='music_object_list'),
    url(r'^(?P<object_type>\w+)/(?P<starts_with>\w)/$', music_object_list, name='music_object_list_x'),
    url(r'^(?P<object_type>\w+)/(?P<object_id>\d+)/$', music_object_detail, name='music_object_detail'),

)

rawDescription: Django: Named URLs / Same Template, Different Named URL


code:
new=[re.search(r'(.+)\1+',i).group(0) for i in s.split('**')]
new

rawDescription: A more complex version of "How can I tell if a string repeats itself in Python?"


code:
def calc(x=0, y=0, z=0):
    expression = raw_input('Enter an expression: ')

    return eval(expression, None, locals())

rawDescription: Sum of calculation in a variable

description: Sum of calculation in a variable


code:
datarr = ['PowUse', 'PowHea', 'PowSol', 'Top']
for i in range(len(dat)): exec(datarr[i]+'={}')

rawDescription: looping dictionaries of {tuple:NumPy.array}

description: Looping dictionaries of {tuple:NumPy.array}


code:
a
N = a.size
sparse_out.todense()

rawDescription: Convert a 2d matrix to a 3d one hot matrix numpy


rawDescription: Getting completely wrong fit from python scipy.optimize.curve_fit


rawDescription: Python pandas: check if any value is NaN in DataFrame


code: df.loc[...] = value

rawDescription: pandas dataframe view vs copy, how do I tell?

description: Pandas dataframe view vs copy, how do I tell


code: pprint.pprint(tup, depth=6)

rawDescription: How to easily display top level of data structure in python

description: Easily display top level of data structure in python


rawDescription: How do I loop through two lists of lists and avoid duplicate combinations for values at specific positions?

description: Loop through two lists of lists and avoid duplicate combinations for values at specific positions


code:
def make_list(levels, num_elems):
    if levels > 0:
       return range(num_elems) + [make_list(levels-1, num_elems)]
    else:
       return range(num_elems)

rawDescription: How would you create a nested list with recursion in Python?


code:
csv1 = "identifier1, identifier2, identifier3, identifier4"
csv2 = [['identifier3'], ['identifier1'], ['identifier4'], ['new_item_4']]

data = [item.strip() for item in csv1.split(",")]

for item in csv2:
    real_item = item[0]
    if real_item not in data:
        #this is a new one, we could add it to data
        data.append(real_item)

print(", ".join(data))
#identifier1, identifier2, identifier3, identifier4, new_item_4

rawDescription: Remove part of an element in python

description: Remove part of an element in python


rawDescription: Rounding integers

description: Rounding integers


code: D = np.intersect1d(a, b).view(A.dtype).reshape(-1, A.shape[1])

rawDescription: 'Remove' command for ND arrays in Python


code:
city.user_city.all()
# Bad: because this is a QuerySet of Profiles
# Better: related_name = 'users'

rawDescription: Using additional fields of a through m2m on template


code:
from lxml import etree, objectify

parser = etree.XMLParser(remove_comments=True)
tree = objectify.parse(xmlPath, parser=parser)

rawDescription: How to not load the comments while parsing XML in lxml

description: Not load the comments while parsing XML in lxml


code: pix = numpy.array(pic)

rawDescription: PIL and numpy

description: PIL and numpy


code:
new_venue = Venue(venue='Jeferson memorial', user=the_user) # careful with the quoting
db.put(new_venue)

rawDescription: How to query datastore when using ReferenceProperty?

description: Query datastore when using ReferenceProperty


code:
class Foo(object):
    @chainable
    def show(self):
        self.visibility = True

    @chainable
    def go_blue(self):
        self.color = 'blue'

rawDescription: DRYout a class-based chainable API

description: DRYout a class-based chainable API


code:
mydll = ctypes.CDLL('./mylib.so')
handle = mydll._handle
del mydll
while isLoaded('./mylib.so'):
    dlclose(handle)

rawDescription: How can I unload a DLL using ctypes in Python?

description: Unload a DLL using ctypes in Python


code:
from time import strftime
import os

if os.name == 'nt': # Windows
    basePath = 'C:\\working\\'
else:
    basePath = '/working/'

Fn = '%sSetup%s.csv' % ( basePath, strftime( '%y%m%d' ) )

rawDescription: Can python detect which OS is it running under?


code:
second_axes = pyplot.twinx() # create the second axes, sharing x-axis
second_axis.set_yticks([0.2,0.4]) # list of your y values
pyplot.show() # update the figure

rawDescription: Show the final y-axis value of each line with matplotlib


code:
my_string = "Hello World"
slice_of_my_string=my_string[0:5]
print(slice_of_my_string)

rawDescription: get the value from the strings in the list

description: Get the value from the strings in the list


code:
def find_weekend_indices(datetime_array):
    indices=[]
    for i in range(len(datetime_array)):
        if datetime_array[i].weekday()>=5:
            indices.append(i)
    return indices

def highlight_weekend(weekend_indices,ax):
    i=0
    while i<len(weekend_indices):
         ax.axvspan(weekend_indices[i], weekend_indices[i]+2, facecolor='green', edgecolor='none', alpha=.2)
         i+=2

rawDescription: Pandas Plots: Separate color for weekends, pretty printing times on x axis


code: (p == 1).sum(axis=0).sum(axis=0)

rawDescription: Search for value in a panel

description: Search for value in a panel


rawDescription: Unpack NumPy array by column

description: Unpack NumPy array by column


code:
from collections import Counter
d = {('a','b','c'): 'val1', ('a','d'): 'val2'}
counts = Counter(item for key in d for item in key)
counts
[item for item, count in counts.most_common() if count > 1]

rawDescription: How to quickly get a list of keys from dict

description: Quickly get a list of keys from dict


code:
pv = pd.crosstab(df["Child"], [df["Year"], df["Behaviour"]], dropna=False)
pv
pv[2020]/pv[1987] - 1

rawDescription: pandas percentage change with missing data

description: Pandas percentage change with missing data


rawDescription: Python: How to use functions inside numpy?


code:
{
    'KR': ['Server1'],
    'DE': ['Server1', 'Server2'],
    'IE': ['Server1', 'Server3', 'Server2', 'Server1', 'Server3']
}

rawDescription: How to carry out this aggregation in python

description: Carry out this aggregation in python


code:
import sys
1-sys.float_info.epsilon
numpy.nextafter(1, 0) - (1-sys.float_info.epsilon)
numpy.nextafter(1, 0) > (1-sys.float_info.epsilon)

rawDescription: How do I clip a floating-point number to just below a limit?

description: Clip a floating-point number to just below a limit


code:
from package import lib
lib.foo()

rawDescription: PYTHONPATH vs. sys.path (RELOADED)

description: PYTHONPATH vs. sys.path (RELOADED)


code:
values = [val1, val2, val3]
values_str = json.dumps(values)

# Then read it back
values = json.loads(values_str)

rawDescription: How to convert list of nested dictionaries into string and vice versa

description: Convert list of nested dictionaries into string and vice versa


rawDescription: Get list related objects

description: Get list related objects


code: ['•', 'I am a sentence •', 'I am another sentence']

rawDescription: NLTK Sentence Tokenizer, custom sentence starters


code: hi

rawDescription: Can a python script execute a function inside a bash script?


code: df.apply(lambda x: 'mike' in x.values, axis=1).any()

rawDescription: Check if one value exists in any rows of any columns in pandas?


code: from vendor.mymodule.mysubmodule.any_class import AnyClass

rawDescription: How to structure python application

description: Structure python application


code:
from rpy2.robjects.packages import importr, data
spep = importr("SpatialEpi")
pennLC_data = data(spep).fetch('pennLC')

rawDescription: rpy2 (version 2.3.10) - importing data from R package into python

description: Rpy2 (version 2.3.10) - importing data from R package into python


code:
import os

def fix_ownership(path):
    """Change the owner of the file to SUDO_UID"""

    uid = os.environ.get('SUDO_UID')
    gid = os.environ.get('SUDO_GID')
    if uid is not None:
        os.chown(path, int(uid), int(gid))

def get_file(path, mode="a+"):
    """Create a file if it does not exists, fix ownership and return it open"""

    # first, create the file and close it immediatly
    open(path, 'a').close()

    # then fix the ownership
    fix_ownership(path)

    # open the file and return it
    return open(path, mode)

rawDescription: Creating a file with python using sudo makes its owner root


code:
likes = db.Table('likes',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20))

    def __repr__(self):
        return "<User('%s')>" % self.username

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))

    likes = db.relationship('User', secondary = likes,
        backref = db.backref('posts', lazy='dynamic'))

    def __repr__(self):
        return "<Post('%s')>" % self.title

rawDescription: SQLAlchemy ordering by count on a many to many relationship


code:
exprs = [c.alias(a) for (a, c) in [
  ('etl_requests_usage', lit('DEV')),
  ('etl_datetime_local', current_date())]]

df.select("*", *exprs)

rawDescription: How to perform a Switch statement with Apache Spark Dataframes (Python)

description: Perform a Switch statement with Apache Spark Dataframes (Python)


code:
from django.db.models import Count, Max
MyModel.objects.values('a').annotate(count=Count("a"),latest_date=Max('created_ts'))

rawDescription: Can a Django Queryset be created to do this complex query?


code:
from django.db import models
class Hashtag(models.Model):
    name = models.CharField(max_length=80)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Post(models.Model):
    name = models.CharField(max_length=80)
    hashtags = models.ManyToManyField(Hashtag)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

rawDescription: ORM data modeling in Python Django

description: ORM data modeling in Python Django


code:
Vector(units).hitpoint = 50

# This also still works...
for unit in Vector(units):
    unit.hitpoint = 50

# This also still works...
Vector(unit)[2].hitpoint = 50

rawDescription: Python vectorization library?

description: Python vectorization library


code:
import numpy as np
from collections import Counter
Counter(np.loadtxt('abc.txt', usecols=(0,), dtype=np.int))

rawDescription: Count all +1's in the file python

description: Count all +1's in the file python


code:
import os
import tornado.database
import tornado.httpserver
import tornado.ioloop
import tornado.web

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

import da

class Application(tornado.web.Application):
    def __init__(self):
        from urls import handlers,ui_modules
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            cookie_secret="11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
            login_url="/signin",
            ui_modules=ui_modules,
            debug=True,
        )
        super(Application,self).__init__(handlers,**settings)
#       tornado.web.Application.__init__(self, handlers, **settings)
        # Have one global connection to the blog DB across all handlers
        self.db = da.db

def runserver():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    runserver()

rawDescription: How do I access my database level functions inside other classes/files in Tornado?

description: Access my database level functions inside other classes/files in Tornado


code:
import csv
import glob
import os
import sys

def inplace_csv_file_filter(filepath, col, look_for):
    """ Remove rows in given csv file that contain all of the strings specified
        in look_for in the row[col] field.
    """
    backup_filepath = filepath + os.extsep + '.bak'
    try: os.unlink(backup_filepath)
    except os.error: pass
    os.rename(filepath, backup_filepath)
    with open(backup_filepath, mode='rb') as inf, open(filepath, 'wb') as outf:
        incsv = csv.reader(inf, delimiter=',')
        outcsv = csv.writer(outf, delimiter=',')
        outcsv.writerows(row for row in incsv
                            if not all(str_ in row[col] for str_ in look_for))
    # os.remove(backup_filepath)  # uncomment to delete backup file

col = 0
directory = './Directory'
pattern = '*.csv'
look_for = 'This', 'mb'

for filepath in glob.glob(os.path.join(directory, pattern)):
    inplace_csv_file_filter(filepath, col, look_for)

rawDescription: Apply changes to several files in the same directory


code:
a = numpy.array([1,2,numpy.nan,4])
numpy.nan_to_num(a)

rawDescription: numpy 1D array to numpy arrays

description: Numpy 1D array to numpy arrays


code: filtered_list = [item for item in List1 if item[0] in List2 and item[3] in List2]

rawDescription: Searching items in two lists

description: Searching items in two lists


code:
def load_screen():
    user_1 = int(input("Please enter your first number.\n"))
    user_2 = int(input("Now please enter your second number.\n"))
    command_home( user_1, user_2) # Okay command_home I took 2 inputs!
                                  # Here they are work your magic!

def command_home(in1, in2): # Hey I need 2 varaibles to work, Ill call them in1 and in2.
                            # so based on the way command_home( user_1, user_2) is called
                            # in1 = user_1, in2 = user_2
    command = input("Now what would you like to do with these two numbers?\n").lower()
    if command == "add":
        calc_add(in1, in2) #Okay, now i need to add my two inputs,
                           # but calc_add is another function it wont be able to see MY
                           # in1, in2 ...  i better pass them over as parameters.
    elif command == "subtract":
        calc_subtract()
    elif command == "multiply":
        calc_multiply()
    elif command == "divide":
        calc_divide()

def calc_add(user_input_1,user_input_2 ): # Okay now i know where to look for user_input_1
                                          # and user_input_2, they will be passed to me
                                          # when someone calls me! Now i can find my varables
                                          # and i wont throw an error!
    add_result = (user_input_1 + user_input_2)
    print(add_result)

rawDescription: Issue with my 'very simple' Python Calculator


code:
from itertools import takewhile, islice,chain

def groups(l, keys, i, n):
    tk = takewhile(lambda x: x != i, l)
    return (dict(zip(keys, chain(islice(tk, n - 1),(i,)))) for i in tk)

rawDescription: Loop through list until value is found then breaking?


code: from math import *

rawDescription: Is the expression math.sqrt() necessary?

description: Is the expression math.sqrt() necessary


code:
def pagination(request, objects, pages):
    paginator = Paginator(objects, pages)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        results = paginator.page(page)
    except (EmptyPage, InvalidPage):
        results = paginator.page(paginator.num_pages)

    return results

rawDescription: Refactoring Index/Search View

description: Refactoring Index/Search View


code:
for entry in sorted(higharr.items(), key=lambda x: x[0], reverse=True):
    print(entry)

rawDescription: sorting dictionary values in python - descending alphabetically

description: Sorting dictionary values in python - descending alphabetically


rawDescription: Find closed shapes in image

description: Find closed shapes in image


code:
def expandtabs(string, n):
    result = ""
    pos = 0
    for char in string:
        if char == "\t":
            # instead of the tab character, append the
            # number of spaces to the next tab stop
            char = " " * (n - pos % n)
        if char == "\n":
            pos = 0
        else:
            pos += len(char)
        result += char
    return result

rawDescription: Python expandtabs string operation

description: Python expandtabs string operation


code:
probs = np.random.rand(200, 200)
heatmap(probs)
plt.show()

rawDescription: Generating Heatmaps in Python

description: Generating Heatmaps in Python


code:
...
for email in self.inbox.dex:
    email = email.readlines()
    ...

rawDescription: Can I apply a function to the variable in a for loop definition (Python)

description: Apply a function to the variable in a for loop definition (Python)


rawDescription: count numbers in the list are between 1 and 10 in python

description: Count numbers in the list are between 1 and 10 in python


code:
def _print_board(game_state):
    print(" ".join("{0:2d}".format(i) if i else "  " # or 0:02d to pad with zero
                   for i in range(len(game_state[0]) + 1)))
    for i, row in enumerate(game_state, 1):
        print("{0:2d}".format(i), end=" ")
        print("".join(" {0} ".format(col if col != NONE else ".") for col in row))

rawDescription: How do I print a grid from a list of lists with numbered rows and columns

description: Print a grid from a list of lists with numbered rows and columns


rawDescription: wxPython: How do you specify the width of a specific column using one of the wx.sizer classes?

description: WxPython: How do you specify the width of a specific column using one of the wx.sizer classes


code: c.StoreMagics.autorestore = True

rawDescription: ipython to run a file before open in each session

description: Ipython to run a file before open in each session


code:
mapped_value = sc.parallelize(
    [(1, "aabbc"), (1, "bab"), (2, "aacc"), (2, "acdd")]).mapValues(list)
mapped_value.first()
## (1, ['a', 'a', 'b', 'b', 'c'])

rawDescription: Finding top words per kmeans cluster

description: Finding top words per kmeans cluster


code:
rows = dict((x,y) for y,x in enumerate('ABC')) # rows' headers
cols = dict((x,y) for y,x in enumerate('def')) # cols' headers

len_cols = 3
len_rows = 3
matrix = [[0 for i in range(len_cols)] for j in range(len_rows)]

def update(row, col, val):
    matrix[rows[row]][cols[col]] = val

rawDescription: Create a matrix with headers and inserting values by calling the headers


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


code:
center = sum(convexhullpoints) / len(convexhullpoints)
size = 2 * sum(abs(p - center) for p in convexhullpoints) / len(convexhullpoints)

rawDescription: Width of an arbitrary polygon

description: Width of an arbitrary polygon


code:
import genelist
genelist.GeneList()

rawDescription: What is the Pythonic way of handling classes, modules, and packages with the same name?


code:
if 'gender' in json_dict:
    gender=json_dict['gender']

    if gender=='male':
        gender= unicode('M')
    elif gender=='female':
        gender=unicode('F')
else: pass# gender is not defined, NameError possible

rawDescription: Alternative to multiple try/except statements to check if a field exists


rawDescription: Summarizing dataframe into a dictionary

description: Summarizing dataframe into a dictionary


code: splitlist = [map(float, prices.split(',')) for prices in yourlist]

rawDescription: What is the most efficient method to assign an X and Y header for a list of the following nature?


code:
ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y,width=w,color='b',align='center')
ax.bar(x, z,width=w,color='g',align='center')
ax.bar(x+w, k,width=w,color='r',align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()

rawDescription: python matplotlib multiple bars

description: Python matplotlib multiple bars


code:
import contextlib
import sys
import cStringIO

@contextlib.contextmanager
def nostdout():
    save_stdout = sys.stdout
    sys.stdout = cStringIO.StringIO()
    yield
    sys.stdout = save_stdout

rawDescription: Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call


code:
class tagList(generics.ListAPIView,APIView):
    model = tags
    serializer_class = getAllTagsDetailSerializer

    def get_queryset(self):
        key = self.request.QUERY_PARAMS.get('appKey', None)
        getTagName = self.request.QUERY_PARAMS.get('tagName', None)
        keyData = app.objects.filter(appKey=key).exists()
        try:
            if keyData == True:
                return tags.objects.filter(tag=getTagName)
            else:
                raise exceptions.PermissionDenied
        except app.DoesNotExist:
            pass

rawDescription: backward many to many Django query

description: Backward many to many Django query


code:
rtc = wx.richtext.RichTextCtrl(self, style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER)
rtc.BeginTextColour((255, 0, 0))
rtc.WriteText("this color is red")
rtc.EndTextColour()
rtc.Newline()

rawDescription: different foreground colors for each line in wxPython wxTextCtrl

description: Different foreground colors for each line in wxPython wxTextCtrl


rawDescription: Python Pandas: Get single max numeric value from df with floats and characters/alphas


code:
from bulbs.neoj4server import Graph
g = Graph()
g.scripts.update('/path/to/gremlin.groovy')
script = g.scripts.get('batch_load')
params = dict(nodelist=your_node_list, label="follows")
g.gremlin.execute(script, params)

rawDescription: Retrieving nodes from index with transaction in neo4jrestclient


code:
def foo():
    x = 2
def bar():
    global x
    x = 3

x = 1
print(x) # --> 1
foo()
print(x) # --> 1
bar()
print(x) # --> 3

rawDescription: Python function replacing itself in the module namespace


code:
print("""Here are three other numbers.\
First number is {0:d}, second number is {1:d},
third number is {2:d}""" .format(7,8,9))

rawDescription: Very basic string formatting not working (Python)


code:
# insert contents of "/test1.txt" into "/test2.txt" at line 20
with open("/test1.txt", "r") as f1:
    t1 = f1.readlines()
with open("/test2.txt", "r") as f2:
    t2 = f2.readlines()
t2.insert(20, t1)
with open("/test2.txt", "w") as f2:
    f2.writelines(t2)

rawDescription: Inserting a file's text into another file at a specific line


code:
x = (
'a very long string - part 1' +
'a very long string - part 2' +
'a very long string - part 3' )
x

rawDescription: How to assign a value to a variable when writing the value takes multiple lines (python)

description: Assign a value to a variable when writing the value takes multiple lines (python)


code:
import numpy as np
a = np.array([ 0,  1,  3, 10,  1,  0,  0,  3,  6])
repr(a)

rawDescription: Is print the only way to display something in .py file


rawDescription: More Pythonic way of adding attributes to class?


rawDescription: Using XRC to create custom Dialog boxes

description: Using XRC to create custom Dialog boxes


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

np.random.seed(123)

# Total number of clusters
N = int(np.max(M[:,2]))

# Create a colour map
cmap = np.random.rand(N, 3)

# Store point sizes per cluster
sizes = np.array([10, 14, 18]);

plt.figure(); # Create blank figure. No need to hold on

for ii in range(N):
    # Determine those points belonging to the ith cluster
    ind = M[:,2] == (ii+1)

    # Get the x and y coordinates
    x = M[ind,0];
    y = M[ind,1];

    # Plot the points in a different colour
    # Also add in labels for legend
    plt.plot(x,y,'.',color=tuple(cmap[ii]), markersize=sizes[ii], label='Cluster #' + str(ii+1))

# Make our legend
plt.legend()

# Show the image
plt.show()

rawDescription: Scatter plot for a matrix of a given form


code:
import decimal
from decimal import localcontext
value1 = "992389829398023985092982398023923023.32598203985902"
value2 = "138582939807398509298239235233.3259822352359235203952093"

with localcontext() as ctx:
    #your desired precision in # of digits
    ctx.prec = 100
    print("{:.40f}".format(decimal.Decimal(value1) - decimal.Decimal(value2)))

rawDescription: Suppressing scientific notation when applying operators to very long decimal numbers using the standard library Decimal


code:
from MyModWithConstants import x
# and also we can do
import MyModWithConstants as MMWC

def somOtherFunc():
  dosomethingNew(x, MMWC.y)
  ## x and MMWC.y both refer to things in the other file

rawDescription: Constants in python?

description: Constants in python


rawDescription: Get folder name of the file in Python

description: Get folder name of the file in Python


code:
parser.add_argument('-s', '--sources'
    , dest = 'files'
    , default = [FileList('dir1'), FileList('dir2')] # exact file list
    , nargs = '*'
    , metavar = 'SOURCE'
    , action = ConcatAction
    , type = FileList
)

rawDescription: Python argparse: type conversion of a list of default arguments


code:
df = pd.DataFrame([(level,val) for level, dct in enumerate(result)
                   for val in dct.values()],
                  columns=['level', 'size'])

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

description: Dynamically update a plot in a loop


code:
import logging

logger = logging.getLogger('root')
logger.debug('submodule message')

rawDescription: Python: logging module - globally

description: Python: logging module - globally


code:
run /tmp/spam.py
c.keys()
c['Gregory'].most_common(10)

rawDescription: How to add words from a text file to a dictionary depending on the name?

description: Add words from a text file to a dictionary depending on the name


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

@user_passes_test(lambda u: u.is_superuser)
def my_view(request):
    ...

rawDescription: We have @login_required, wheres @admin_required


code:
dUp= delta[delta > 0]
dDown= delta[delta < 0]

rawDescription: Relative Strength Index in python pandas


code:
import selenium.webdriver.support.ui as UI

def test_text_saver(self):
    driver = self.driver
    wait = UI.WebDriverWait(driver, 5000)
    with open("textsave.txt","w") as textsave:
        list_of_links = driver.find_elements_by_xpath("//*[@id=\"learn-sub\"]/div[4]/div/div/div/div[1]/div[2]/div/div/ul/li/a")
        for link in list_of_links:  # 2
            link.click()   # 1
            text = wait.until(
                lambda driver: driver.find_element_by_xpath("//*[@id=\"learn-sub\"]/div[4]/div/div/div/div[1]/div[1]/div[1]/h1").text)
            textsave.write(text+"\n\n")
            driver.back()

rawDescription: Loop through links using Selenium Webdriver (Python)


code:
entries_set = {Entry('foo', 'bar'), Entry('foo', 'baz')}
entries_set
Entry('foo', 'spam') in entries_set

rawDescription: Searching for tuples in python based on the first part


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

    class Meta:
        abstract = True

rawDescription: Inherit/Extend Django Module or cram into same Module?


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

# pixel coordinates (integer)
x, y = np.mgrid[:100, :100]
# centroids (float)
cx, cy = np.random.rand(2, 9) * 100

# a Gaussian kernel to represent the PSF
def gausskern(x, y, cx, cy, sigma):
    return np.exp(-((x - cx) ** 2 + (y - cy) ** 2) / (2 * sigma ** 2))

# (nstars, ny, nx)
stars = gausskern(x[None, ...], y[None, ...],
                  cx[:, None, None], cy[:, None, None], 10)

# add some noise for extra realism
stars += np.random.randn(*stars.shape) * 0.5

fig, ax = plt.subplots(3, 3, figsize=(5, 5))
for ii in xrange(9):
    ax.flat[ii].imshow(stars[ii], cmap=plt.cm.hot)
    ax.flat[ii].set_axis_off()
fig.tight_layout()

rawDescription: Stacking star PSFs from an Image; aligning sub-pixel centers


code:
plotMax = len(plotData)

for i, data in enumerate(plotData):
    w = abs(abs(data['hist'].index[0]) - abs(data['hist'].index[1]))

    # Display
    plt.figure(figsize=(10, 6))
    ax = data['pdf'].plot(kind='line', label='Model PDF', legend=True, lw=2)
    ax.bar(data['hist'].index, data['hist'].values, label='Random Sample', width=w, align='center', alpha=0.5)
    ax.set_title(data['title'])

    # Grab figure
    fig = matplotlib.pyplot.gcf()
    # Output 'file'
    fig.savefig('~/Desktop/dist/'+data['title']+'.png', format='png', bbox_inches='tight')
    matplotlib.pyplot.close()

rawDescription: What do all the distributions available in scipy.stats look like?


code:
sentence = 'I? am. cal?led ,bob. Wh,at. is your .name?.'
... # above code
print(sentence) # => "I? am. call?ed bob,. What .i,s your .name?."

rawDescription: How to remove punctuation from a string and remember the position of it from the string

description: Remove punctuation from a string and remember the position of it from the string


code:
[i for i in range(10)]
i
i = 0
[i for i in range(10)]
i

rawDescription: Scope of class variable with list comprehension


code:
def checkparen(inp):
    return inp.count('(') == inp.count(')') and inp.count('[') == inp.count(']') and inp.count('{') == inp.count('}')

rawDescription: compare paranthesis in python

description: Compare paranthesis in python


code:
d = []
d.extend('hello')
print(d)

rawDescription: Array.extend(string) adds every character instead of just the string


rawDescription: Getting specific values from different lists and how to


rawDescription: Replicating Javascript bitwise operation in Python


rawDescription: Python argparse - creating subcommands with no labels


code:
from collections import Counter
Counter(x).most_common(1)[0]
Counter(y).most_common(1)[0]
Counter(z).most_common(1)[0]

rawDescription: How to find if consensus on answer

description: Find if consensus on answer


code:
a = range(10)
b = a
id(b)
id(a)
a.remove(1)
b
a

rawDescription: Pb in while with equal

description: Pb in while with equal


rawDescription: Best way to get 'hrefs' from CSS selector in BeautifulSoup?

description: Get 'hrefs' from CSS selector in BeautifulSoup


code:
import re
from BeautifulSoup import BeautifulSoup

html= '''

    Company Name
    CIK Number
    SIC Code

    A CONSULTING TEAM INC
    1040792
    7380

    A J&J PHARMA CORP
    1140452
    9995

'''

soup = BeautifulSoup(html)
table = soup.find("table", {"id":"cos"})
td = table.find('td', text='A J&J PHARMA CORP')
# ^ This return text node, not td.
print(td.parent.parent.findAll('td')[1].string)

rawDescription: Extract a row in html file without the html tags


code:
class Tee(object):
    """A file-like that writes to all the file-likes it has."""

    def __init__(self, *files):
        """Make a Tee that writes to all the files in `files.`"""
        self._files = files

    def write(self, data):
        """Write `data` to all the files."""
        for f in self._files:
            f.write(data)

rawDescription: How can I pythonically print and write the same string (two operations on one object)

description: Pythonically print and write the same string (two operations on one object)


code:
np.random.seed(0)
genes.iloc[:2] *= (1 + np.random.random([2, 4]) / 100)
genes.iloc[2:] *= (1 + np.random.random([3, 4]))

rawDescription: Pandas Dataframe Iterating

description: Pandas Dataframe Iterating


code:
arr = np.arange(108).reshape(9, 12)
rows, cols = arr.shape
arr.reshape(rows//3, 3, cols//3, 3).sum(axis=(1, 3))

rawDescription: Summing each 3x3 window of a M*N matrix, into a M/3*N/3 matrix with numpy


code:
class Task(models.Model):
    deliver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='task')
    tasktype = models.PositiveSmallIntegerField(db_index=True)
    description = models.CharField(max_length=500, null=True, blank=True)
    delivertime = models.DateTimeField(default=now,db_index=True)
    deadlinetime = models.DateTimeField(null=True,db_index=True)
    relatedresourceid = models.PositiveIntegerField(null=True)
    suggestspendtime = models.PositiveIntegerField(null=True)
    subjectid = models.PositiveIntegerField(null=True)

class Lesson(models.Model):
    name = models.CharField(max_length=200,null=True,blank=True)
    tasks = models.ManyToManyField(Task, related_name='lessons')

class Exam(models.Model):
    name = models.CharField(max_length=200,null=True,blank=True)
    tasks = models.ManyToManyField(Task, related_name='exams')

rawDescription: Django ORM: Dynamically determine another table name according one field value


rawDescription: How do I read a file to a list in python?

description: Read a file to a list in python


code:
class Player(Collidable, Movable, Drawable, Controllable):
    def __init__(name, **kwargs):
        self.name = name
        super(Player, self).__init__(**kwargs)

rawDescription: Pythonic way to have code-reuse in game Entity classes


code: print("test")

rawDescription: How to get input in Python 2.7?

description: Get input in Python 2.7


code:
with open("firstfile") as f:
    matched_rows = [ln for ln in f if ln.split(',')[0] in valid_ids]

rawDescription: how to make a efficient filter in python

description: Make a efficient filter in python


code:
return (jsonify({'username': user.username}), 201,
        {'Location': url_for('get_user', id=user.id, _external=True)})

rawDescription: Flask show return data on request

description: Flask show return data on request


rawDescription: Convert a list of tuples (3 elements each) to a dict {a: {b: set(c)}}


code:
import shutil
with open('command.fort.13', 'wb') as outFile:
    with open('command.info', 'rb') as com, open('fort.13', 'rb') as fort13:
        shutil.copyfileobj(com, outFile)
        shutil.copyfileobj(fort13, outFile)

rawDescription: Reproduce the unix cat command in python


code:
import sys

from twisted.internet.task import react
from twisted.internet.endpoints import clientFromString
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet.protocol import Factory
from twisted.internet.stdio import StandardIO

from twisted.protocols.basic import LineReceiver
from twisted.internet.fdesc import setBlocking

class HubClient(LineReceiver):
    def __init__(self, name, output):
        self.name = name
        self.output = output

    def lineReceived(self, line):
        self.output.transport.write(line + b"\n")

    def connectionMade(self):
        self.sendLine("identify {}".format(self.name).encode("utf-8"))

    def say(self, words):
        self.sendLine("say {}".format(words).encode("utf-8"))

class TerminalInput(LineReceiver, object):
    delimiter = "\n"
    hubClient = None
    def lineReceived(self, line):
        if self.hubClient is None:
            self.output.transport.write("Connecting, please wait...\n")
        else:
            self.hubClient.sendLine(line)

@inlineCallbacks
def main(reactor, name, connect="tcp:localhost:4321"):
    endpoint = clientFromString(reactor, connect)
    terminalInput = TerminalInput()
    StandardIO(terminalInput)
    setBlocking(0)
    hubClient = yield endpoint.connect(
        Factory.forProtocol(lambda: HubClient(name, terminalInput))
    )
    terminalInput.transport.write("Connecting...\n")
    terminalInput.hubClient = hubClient
    terminalInput.transport.write("Connected.\n")
    yield Deferred()

react(main, sys.argv[1:])

rawDescription: Using asyncore to create interactive sessions with client/server model


code:
# Recursive case: node has one or more child
if len( children ) >= 1 :
    # Loop through all the children
    for child in children:
        # call to recursion function
        getCoords( child, searchNode )

rawDescription: Xml parsing with Python using recursion. Problem with return value


code:
with open('Exchange.txt') as f:
    lines = [x.strip().split(",") for x in f.readlines()]
    #reverse = True for descending sorted order
    lines.sort(key=lambda x: float(x[-1]), reverse=True)
    print(lines)

rawDescription: Begineer's sorting with tuples

description: Begineer's sorting with tuples


rawDescription: unable to iterate tuple in python 2.7

description: Unable to iterate tuple in python 2.7


code: df

rawDescription: Joining same-key dictionaries into a dataframe in pandas


rawDescription: Where's Pyglet mainloop?

description: Where's Pyglet mainloop


rawDescription: Calculating the gap between pairs of twin primes in python


rawDescription: Get the list index range of a list depending on the values


code:
args.path = next(val for val in
                 [args.path, cfg.path, DEFAULT_PATH]
                 if val is not None)

rawDescription: Can I check if a value was supplied by the default or by the user?

description: Check if a value was supplied by the default or by the user


code: [tuple(d.get(x,x) for x in outer_tup) for outer_tup in li]

rawDescription: Finding and Replacing all Values inside of entries within a List


rawDescription: Turn dataframe into frequency list with two column variables in Python


code: set(dir(type)) - set(type.__dict__)

rawDescription: Get complete list of all possible Class Attributes


rawDescription: Numerical Differenciation as Matrix-Vector Product


code: [str(random.randint(1,60)) for _ in range(6)]

rawDescription: Python code that needs some overview

description: Python code that needs some overview


code:
wordset = collections.OrderedDict()
wordset = collections.OrderedDict.fromkeys(words)
[item for item in wordset if item.istitle() or item.title() not in wordset]

rawDescription: How to eliminate duplicate list entries in Python while preserving case-sensitivity?

description: Eliminate duplicate list entries in Python while preserving case-sensitivity


code:
class State:
    def __init__ (self):
        self.rate = 0
        self.wage = 0

    def apply (self, exposure):
        setattr(self, exposure, getattr(self, exposure) - 1)
        return getattr(self, exposure)

rawDescription: Access class variables with same function


code: map(b.get, a)

rawDescription: Replace a list item with the value of the item stored in dictionary in python


code: pprint(b)

rawDescription: Convert list into array dtype=int64 in Python


rawDescription: python advance for loop

description: Python advance for loop


code:
lines = set(chain.from_iterable(open(f, 'rU') for f in glob('./files/*.??')))

with open('listTogether.txt', 'w') as out:
    out.writelines(sorted(lines))

rawDescription: Merge all .txt files into one text file and alphabetise that text file


code:
c=C.new

c.instance_method
#=> instance_method
C.class_method
#=> class_method

rawDescription: What is the difference between Ruby and Python versions of"self"?


code:
dates = [[d1, m1, y1], ..., [dn, mn, yn]]
datedict = {}
for d, m, y in dates:
    yeardict = datedict.setdefault(y, {})
    monthset = yeardict.setdefault(m, set())
    monthset.add(d)

nested_dates = [(y, list((m, sorted(days))
                         for m, days in sorted(yeardict.items())))
                for y, yeardict in sorted(datedict.items())]

rawDescription: Looping over a tuple in jinja2

description: Looping over a tuple in jinja2


code:
from random import randint
a = []
for _ in range(100):
    b = 0
    c = set()
    while len(c) < 5:
        c.add(randint(1, 5))
        b += 1
    a.append(b)
d = round(sum(a)/len(a))
print("{}\nAverage loops: {}".format(c, d))

rawDescription: Python random numbers loop

description: Python random numbers loop


code: paras = ["".join(x.findAll(text=True)) for x in span.findAllNext("p")]

rawDescription: Scraping with BeautifulSoup and multiple paragraphs


code:
list_to_search =['TRC_BTM', 'TRC_HCI', 'TRC_L2CAP']
myDict = {'TRC_BTM': '6', 'TRC_HCI': '6', 'TRC_L2CAP': '6'}

filename ='file.conf'

with open(filename, 'rb+') as f:

    while True:
        line = f.readline()
        if not line: break
        for key in list_to_search:
            if key in line:
                f.seek(-len(line),1)
                f.write(key + '=' + myDict[key] + '\n')
                f.flush()

rawDescription: how to search values in a file and replace

description: Search values in a file and replace


code: subprocess.call("valgrind --track-origins=yes --leak-check=full -v ./a.out")

rawDescription: Getting Valgrind to detect memory leaks from C++ program called by Python Script:


code:
class MyTableClass(object):

    def __init__(self):
        self.tables = {
            'table1': PrettyTable(["Student Name", "Score Test 1"]),
            'table2': PrettyTable(["Student Name", "Score Test 2"]),
        }

    def addTable (self, newTable, **kwargs):
        self.tables[newTable] = PrettyTable(kwargs.values())

    def addTableRow(self, newTable, **kwargs):
        self.tables[newTable].add_row(kwargs.values())

rawDescription: Using Class method to add a Class variable


code:
from rest_framework.metadata import SimpleMetadata
from rest_framework.serializers import ModelField
from pbweb.models import RsTestField

class MyMetadata(SimpleMetadata):
    def get_field_info(self, field):
        field_info = super(MyMetadata, self).get_field_info(field)
        # I will add the info field only for RsTestField-ModelField
        if isinstance(field, ModelField) and isinstance(field.model_field, RsTestField):
            # access your info attribute HERE
            field_info['info'] = field.model_field.info
        return field_info

rawDescription: Django REST serializer and extra attributes from custom model fields


code:
class MyHandler:
    @authenticated
    def get(self):
        pass

rawDescription: How to implement a 'before' hook that can output an alternative response?

description: Implement a 'before' hook that can output an alternative response


code:
a = scipy.sparse.rand(100,100,format='coo')
a[2:5, 6:8]

rawDescription: Scipy: Do sparse matrices support advanced indexing?


rawDescription: I want to write the 'Class_Scores' to a csv file in rows(Name on one side score on the other), how do I do that?


code:
if len(self._channel.consumer_tags) == 0:
        LOGGER.info("Nobody is listening.  I'll come back in a couple of minutes.")
        ...

rawDescription: In Pika or RabbitMQ, How do I check if any consumers are currently consuming?


code:
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string('''
<LoginMain>:
    Label:
        text: 'hi'
    Button:
        text: 'press me'
''')

class LoginMain(BoxLayout):
    ...

rawDescription: Looking for a good way to organize big kivy project


code:
def iter_faces(M):
    for dim in range(M.ndim):
        for front_side in (True, False):
            yield get_face(M, dim, front_side)

rawDescription: Selecting (n-1)D array from (n)D array in numpy


code:
integers = [n for n in range(3, limit+1) if n % 2]
integers.insert(0, 2)

rawDescription: Python code structure & convention - Creating a elements for a list with a loop


code: (a == elem).sum(axis=1).argmax()

rawDescription: How to get the indexes of column and row in a 2-dimensional matrix(list) that have the most given elements in using numpy in python

description: Get the indexes of column and row in a 2-dimensional matrix(list) that have the most given elements in using numpy in python


code:
from itertools import product

def dashed_combos(inputstring):
    words = inputstring.split()
    for combo in product(' -', repeat=len(words) - 1):
        yield ''.join(w for pair in zip(words, combo + ('',)) for w in pair)

rawDescription: Python replace spaces in string iteratively


rawDescription: Merge dictionaries with key combinations


code:
{'url': '/webassets/kpna/catalog/pdf/en/1012741_4.pdf', 'title': 'Rough In/Spec Sheet'}
{'url': '/webassets/kpna/catalog/pdf/en/1012741_2.pdf', 'title': 'Installation and Care Guide with Service Parts'}
{'url': '/webassets/kpna/catalog/pdf/en/1204921_2.pdf', 'title': 'Installation and Care Guide without Service Parts'}
{'url': '/webassets/kpna/catalog/pdf/en/1011610_2.pdf', 'title': 'Installation Guide without Service Parts'}

rawDescription: Scraperwiki Python Loop Issue

description: Scraperwiki Python Loop Issue


code:
@asyncio.coroutine
def init(loop):
    return loop.create_server(web.Application().make_handler(), '0.0.0.0', 8080)

rawDescription: Pros and cons of using return (yield from some_function())


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter1d

x, y = np.loadtxt('spectrum.dat').T

# Smooth with a guassian filter
smooth = gaussian_filter1d(y, 10)

fig, ax = plt.subplots()
ax.loglog(x, y, color='black')
ax.loglog(x, smooth, color='red')
plt.show()

rawDescription: Smooth a curve in python with no error at the boundaries?


code:
class MyObject(object):
    __slots__ = []

x = MyObject()
x.__dict__

rawDescription: Creating inmutable types in Python using __new__()


code:
uid_to_orderid = {d['uid']: d['orderid'] for d in d2}
output = [dict(d, orderid=uid_to_orderid[d['uid']]) for d in d1]

rawDescription: Pythonic way to copy a key/value from one dict to another


code:
total_list = plan.investment_set.filter(
    maturity_date__gte= '%s-1-1' % current_year
).aggregate(Sum('maturity_amount'))

rawDescription: Calculating the sum of aggregate query set


rawDescription: python: combination of lists in dict, with various size of list

description: Python: combination of lists in dict, with various size of list


code:
titles = ('Hello', 'Umbrella')
artists = ('Adele', 'Rihanna')
songs = {'titles_artists': zip(titles, artist)}

rawDescription: How do you iterate tuple values in a dictionary for django context

description: Iterate tuple values in a dictionary for django context


code:
import mock

class A:
    def __init__(self, name):
        self.name = name

    def get_name(self):
        print("hi " + self.name)
        return self.name

class B:
    def __init__(self):
        self.a_map = {}

    def get_all_a_values(self, names):
        for name in names:
            a = A(name)
            self.a_map[a] = a.get_name()

def side_effect(name):
    mm = mock.MagicMock()
    mm.get_name.return_value = name
    return mm

with mock.patch('__main__.A') as mockA:
    b = B()
    mockA.side_effect = side_effect
    names = ['person0', 'person1', 'person2', 'person3', 'person4']
    b.get_all_a_values(names)
    print(b.a_map)
    assert len(b.a_map) == 5

rawDescription: Multiple instances of mock object

description: Multiple instances of mock object


rawDescription: How to use index to assign address and formula to arrays?

description: Use index to assign address and formula to arrays


code:
g = FloatWithUnit(9.81, 'm/s^2')
g
type(g)

rawDescription: creating class object that normally looks like a float

description: Creating class object that normally looks like a float


code:
def sequify(func, type_arg=1):
    def wrapped(*args, **kwargs):
        it = func(f, seq)
        try:
            len(args[type_arg])
        except:
            return it
        else:
            return type(seq)(it)
    return wrapped

rawDescription: `map`-like function preserving sequence-type


code: os.pread(f.fileno(), 2, 0)

rawDescription: Read first bytes of open file in Python

description: Read first bytes of open file in Python


code:
names = ['Andrea','21','Sophie',16]
people = zip(names[::2], names[1::2])
# people is now: [('Andrea', '21'), ('Sophie', 16)]

rawDescription: Check if a number is in a range of a list


code:
def __init__(self):
    self.host = 'some ip address'
    self.user = 'root'
    self.password = '123'
    self.mySqlUser = 'root'
    self.mySqlPassword = 'someotherpassword'
    self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
    self.cursor = self.connection.cursor()

rawDescription: Login into Server AND MySQL from Python

description: Login into Server AND MySQL from Python


code:
@app.route('/upload', methods=['POST'])
def upload_files():
    resp = flask.make_response()
    if authenticate_user(request.form):
        request.files['image'].save('path/to/file.jpg')
        resp.status_code = 204
    else:
        resp.status_code = 411
    return resp

rawDescription: Uploading an image from python client to a flask server


code: re.findall(r'^(\S+).*?inet addr:(\S+).*?Mask:(\S+)', ifconfig, re.S | re.M)

rawDescription: Algorithm to extract network info from ifconfig (ubuntu)


code:
def sliding(rdd, n):
    assert n > 0
    def gen_window(xi, n):
        i, x = xi
        return [(i - offset, x) for offset in xrange(n)]

    return (
        rdd.
        zipWithIndex(). # Add index
        flatMap(lambda xi: gen_window(xi, n)). # Generate pairs with offset
        groupBy(lambda ix: ix[0]). # Group to create windows
        # Sort values to ensure order inside window and drop indices
        mapValues(lambda vals: [x for (i, x) in sorted(vals)]).
        sortByKey(). # Sort to makes sure we keep original order
        values(). # Get values
        filter(lambda x: len(x) == n)) # Drop beginning and end

rawDescription: How to transform data with sliding window over time series data in Pyspark

description: Transform data with sliding window over time series data in Pyspark


code:
#!/usr/bin/python3

from gi.repository import Poppler

document = Poppler.Document.new_from_file("file:///home/me/some.pdf", None)
print(document.get_pdf_version_string())

rawDescription: Displaying PDF files with python3

description: Displaying PDF files with python3


code: parentId = models.ForeignKey("self")

rawDescription: Django self-referential foreign key

description: Django self-referential foreign key


rawDescription: PYTHON: Searching two files for common lines and collecting their contents into set


code:
views.py
from django.shortcuts import render_to_response

def index(request):
   """
   Main page.
   """
   return render_to_response('index.html') # display index.html

rawDescription: Where to put Python files to be redirected to by urls.py in Django?


rawDescription: Python Numpy Matrix - Return the value contained in the matrix?


code:
res = []
for l in range(2, len(arr)):
    for x in itertools.combinations(arr, l):
        res.append(x)
return res

rawDescription: In Python how do I create variable length combinations or permutations?


code:
@app.route("/")
def index():
    resp = myFunc(request.args.get('selectedOption'))
    return resp

rawDescription: Using info from GET request in jQuery to display transformed result through Flask


rawDescription: Regex to ensure group match doesn't end with a specific character


rawDescription: Retrieve locals() in order of variable declaration - python


code:
items = ["A", "B", "C", "D", "E"]
for page in grouper(2, items):
    print("::NewPage::")
    for item in page:
        if item is not None:
            print(item)

rawDescription: Python while, continue loops

description: Python while, continue loops


code:
UsrFCList = []  # You've added this name to the module-level namespace.

def usr_fc(*events):
   selctd_indices = lbox.curselection()
   lst_select = list(selctd_indices)
   for i in lst_select:
     UsrFCList.append(lbox.get(i))  # The interpreter looks for UsrFCList in the local function namespace, and since you're not assigning to that name, it look at the next biggest namespace, which is the module namespace.
   lbox.quit()

# You should now have access to any data you put in UsrFCList, outside the usr_fc function.

rawDescription: set new list variable equal to list generated in a function that has listbox values passed to it

description: Set new list variable equal to list generated in a function that has listbox values passed to it


code: dec = format(dec, '.2f') #Or change the precision to cater to your needs

rawDescription: Django modelfield, how do I get the actual value?


code:
idx = dst.argmin()
filename = paths[idx]

rawDescription: Face Recognition - How to return the correct image?


code:
tree = etree.parse(xmlFileUrl)
nsmap = {'def':'http://www.w3.org/2005/Atom'}
for entry in tree.xpath('//def:entry', namespaces=nsmap):
    category = entry.xpath('category')

rawDescription: Get Xpath dynamically using ElementTree getpath()


code:
def f(objects):
    yield from (("string_x" if isinstance(x[1], list) else "string_y", x[1])
                for x in objects)

rawDescription: python optimize function without looping

description: Python optimize function without looping


code:
@app.route('/my_service')
@crossdomain(origin='*')
def my_service():
    return jsonify(foo='cross domain ftw')

rawDescription: Cross-Origin Resource Sharing Multiple Sites


code:
result = as_class()
for key,value in dict_expr.items():
        result.__setitem__(key,value)

rawDescription: PYMongo : Parsing|Serializing query output of a collection


code: [s.translate(trs) for s  in  ['cheese', 'on', 'toast']]

rawDescription: Replacing multiple characters from an element in a list,


code: """%(name)s went to the store.""" % {"name": "John"}

rawDescription: Passing kwargs into a python string for rendering rather then using %s/%d...etc


code: table = raw_input("table: ")

rawDescription: In python, is there anyway to input a string without quotation marks?


code:
#!/usr/bin/python

import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax1 = fig.add_subplot(111)
mappable = ax1.scatter(xgrid,
                       ygrid,
                       c=be,                   # set colorbar to blaze efficiency
                       cmap=cm.hot,
                       vmin=0.0,
                       vmax=1.0)

cbar = fig.colorbar(mappable, pad=0.15)
cbar.set_label('Blaze Efficiency')

ax2 = ax1.twinx()
ax2.set_ylabel('Wavelength')

plt.show()

rawDescription: Plot multiple y-axis AND colorbar in matplotlib


code:
class CronTab(object):
    def __init__(self, *events):
        self.events = events
        for event in self.events:
             event.kwargs['cron'] = self
# rest of the calss remains unmodified

rawDescription: Removing an event from a cron-like-scheduler in python


code:
[{'errors': [u'Error generating report'],
  'exit code': u'1',
  'file name': u'C:/Something/'}]

rawDescription: Trying to parse an XML file with Python - what am I doing wrong?


code:
result = []

for sublist in response:
    for item in sublist:
        result.append(item)

rawDescription: Python's list comprehensions and other better practices


code:
dict={}
with open('sawyer.txt') as f:
    for i, l in enumerate(f):
            for word in l.strip().split(" "):
                    if word in dict.keys():dict[word].append(i)
                    else:dict[word]=[i]
dict

rawDescription: Print the line number of a text file for each word from a list in python 3 without importing anything


code:
new_console.py
from multiprocessing.connection import Client
import sys

address = '\\\\.\pipe\\new_console'
conn = Client(address)
while True:
    print(conn.recv())

rawDescription: Create new console for the same process

description: Create new console for the same process


rawDescription: Reshaping pandas dataframe, converting values of an existing column into new lower level columns with index ignored


code:
@register.simple_tag(take_context=True)
def some_simple_tag(context, arg1, arg2):
    # do some work
    return 'string result for template to display'

rawDescription: Is it possible to pass the evaluated result of one template tag as a parameter to another tag?


code:
inp=raw_input()
{inp+' '+i:len(inp+i) for i in a}

rawDescription: finding string length and storing in dict

description: Finding string length and storing in dict


code:
class ShortRib(object):
    def __init__(self, owner):
        self.owner = owner

class Cow(object):
    shortRib = None
    def __new__(cls, *args, **kwargs):
        if cls.shortRib == None:
            cls.shortRib = ShortRib(cls)
        return super(Cow, cls).__new__(cls, *args, **kwargs)

Cow()
Cow.shortRib.owner

rawDescription: Python: class static member pointing to itself?


rawDescription: Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?


code:
try:
    import json
except ImportError:
    import myutils.myjson as json

rawDescription: Supporting Multiple Python Versions In Your Code?


code:
import asyncio
from pydispatch import dispatcher
from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory

from ..transport import Transport

class Websocket(Transport):

    name = 'websocket'

    def __init__(self, socket):
        self.socket = socket

    def open(self):
        url = self.prepareUrl()

        factory = WebSocketClientFactory(url, debug = False)
        factory.protocol = Protocol

        websocket = self.socket.loop.create_connection(factory, host=self.socket.io.options.host, port=self.socket.options.port)

        dispatcher.connect(self.onOpen, signal='open', sender=dispatcher.Anonymous)

        self.socket.io.loop.run_until_complete(websocket)

    def onOpen(self):
        print('print me please!')

class Protocol(WebSocketClientProtocol):

    @asyncio.coroutine
    def onOpen(self):
        dispatcher.send(signal='open')

rawDescription: Callbacks from autobahn WebSocketClientProtocol to another object


rawDescription: How to hide excerpt from single post view in Hyde?

description: Hide excerpt from single post view in Hyde


code: profile = UserProfile.objects.create_profile(user, role)

rawDescription: How to save data in models with oneToOne relationship

description: Save data in models with oneToOne relationship


code:
def text1(word,x,y):
    font = pygame.font.SysFont(None, 25)
    text = font.render("{}".format(word), True, RED)
    return screen.blit(text,(x,y))

rawDescription: How to get an input from user in Pygame and save it as a variable?

description: Get an input from user in Pygame and save it as a variable


rawDescription: Changing image hue with Python PIL

description: Changing image hue with Python PIL


code:
@patch.multiple('module.ClassName', foo=DEFAULT, bar=DEFAULT)
def test(**mocks):
    mock_foo, mock_bar = mocks["foo"], mocks["bar"]
    mock_foo.return_value = 'foo'
    mock_bar.return_value = 'bar'

rawDescription: Python Mock patch.multiple argument names


rawDescription: Convert to UTC Timestamp

description: Convert to UTC Timestamp


code:
functions = [somefunction1, somefunction2, somefunction3]

for func in functions:
    var, msg = func()
    if not var:
        break

rawDescription: Exiting block of code when variable changes in python


code:
social = user.social_auth.get(provider='facebook')
userid = social.uid
first_name = social.extra_data['first_name']
last_name = social.extra_data['last_name']

rawDescription: Python-social-auth how can i get uid fullname etc. with facebook


code:
noise = ['go', 'check', 'walk']
commands = [word for word in move_input if word not in noise]
# process commands

rawDescription: Checking a partial match in input to a list of valid arguments with varying prefixes


code:
def extend(base, *others):
    [base + o for o in others] if others else [base]

rawDescription: Can python act like this, in bash?

description: Can python act like this, in bash


code:
userdata = { "data":[]}

def fil_userdata():
  for i in xrange(0,5):
    user = {}
    user["name"]=...
    user["age"]=...
    user["country"]=...
    add_user(user)

def add_user(user):
  userdata["data"].append(user)

rawDescription: Python | How to create dynamic and expandable dictionaries


code: plt.plot(a, np.log(1 + np.outer(a,r)).mean(1))

rawDescription: Plot parametric mean in Python

description: Plot parametric mean in Python


code:
class IndexView(generic.ListView):
    template_name = 'productions/index.html'
    context_object_name = 'productions_list'

    def get_queryset(self):
        # analyze `self.kwargs` and decide should you filter or not, just for example:
        is_all = self.kwargs['query'] == ''
        is_movie = self.kwargs['query'] == 'films'
        is_series = self.kwargs['query'] == 'series'

        return Production.objects.order_by('-release')  # TODO: filter movies or series

rawDescription: Filter content by url segments

description: Filter content by url segments


code:
list1 = [('A',0.75),('D',0.49),('Y',0.36)]
mainlist = [('A',10),('B',20),('C',30),('D',40),('E',50),('Y',250),('Z',260)]

keys = {k[0] for k in list1} # create a set with keys from list1
newlist = [k for k in mainlist if k[0] in keys] # get items from mainlist with good keys
print(newlist)

rawDescription: python : searching through nested list by key and storing it into nested list

description: Python : searching through nested list by key and storing it into nested list


rawDescription: finding bigrams in unicode text with nltk

description: Finding bigrams in unicode text with nltk


code:
def __init__(self, a = None, b = None, c = None):
    self.a = a

rawDescription: Automatically setting class member variables in Python


code:
x = not (letter.lower() in word)
y = not (letter.lower() in guessed_letters)
a = x or y

rawDescription: if statement syntax - different than taught

description: If statement syntax - different than taught


code: set([frozenset(x) for x in S.edges()])

rawDescription: Computing the Difference between two graphs 'edge wise' in networkx


rawDescription: Openstack: how to get client's IP in the python API


rawDescription: Merging two dicts in python with no duplication permitted


code:
s1 = set(['asd', '123', 'uniq','all'])
s2 = set(['asd', '123', 'all'])
s3 = set(['asd', 'all'])
s4 = set(['all'])

result = {}
shadow_list = []

l = [s1, s2, s3, s4]
nrof_lists = len(l)

for word in s1:
    times = sum([word in s for s in l])

    if times:
        result[word] = times*1.0/nrof_lists
    else:
        shadow_list.append(word)

# Output
print(result)
{'123': 0.5, 'all': 1.0, 'uniq': 0.25, 'asd': 0.75}
print(shadow_list)
[]

rawDescription: Combining boolean operators

description: Combining boolean operators


rawDescription: Equivalent of "in" keyword or subquery in pandas


code:
from dateutil.parser import parse
parse(datestr)

rawDescription: how to parse time stamps in Python from PyPI packages (eg. 12-Oct-2010 06:40)

description: Parse time stamps in Python from PyPI packages (eg. 12-Oct-2010 06:40)


code:
from itertools import repeat
import csv

with open('sample.txt','rb') as tsvin, open('new.csv', 'wb') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

rawDescription: reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

description: Reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)


rawDescription: Correct usage of scipy.interpolate.RegularGridInterpolator


code:
with open("test.txt") as termsdesk:
    for line in termsdesk:
        for word in line.split():
            if word in keyword_dictionary:
                print(keyword_dictionary[word])
                break

rawDescription: Python - reading complex lines of text into dictionary


code:
SCREEN_SIZE =  800, 600
SCREEN_COLOR  = pygame.Color("white")

rawDescription: why I'm getting a square instead of a circle in pygame?

description: Why I'm getting a square instead of a circle in pygame


code:
from itertools import groupby
temp = {k:list(g) for k,g in groupby(ca, lambda x: x['photo_id'])}
# I shortened the name comments_atomic to ca here

rawDescription: Pythonic ways to re-group / pivot database output


code:
import re
re.sub(r"\bor", "*", "organization")

rawDescription: regular expression pattern about word boundary in python

description: Regular expression pattern about word boundary in python


code:
def foo(x):
    return x['user__id']

rawDescription: Merge/join lists of dictionaries based on a common value in Python


rawDescription: Dataframe groupby - return delta time for log entries


code: l2 = [element.name for element in l]

rawDescription: Python convert list of objects to list of one object parameters


rawDescription: Numpy equivalent of itertools.product

description: Numpy equivalent of itertools.product


code:
from itertools import chain
from functools import reduce
from pyspark.sql.types import StructType
from pyspark.sql.functions import col, lit, max
from pyspark.sql import DataFrame

df1 = sc.parallelize([
    ("U1", 0, 1), ("U2", 1, 1)
]).toDF(["Key", "FeatureA", "FeatureB"])

df2 = sc.parallelize([
  ("U1", 0, 0, 1)
]).toDF(["Key", "FeatureC", "FeatureD", "FeatureE"])

df3 = sc.parallelize([("U2", 1)]).toDF(["Key", "FeatureF"])

dfs = [df1, df2, df3]

rawDescription: What's the most efficient way to accumulate dataframes in pyspark?


code:
num_charges = 4
charges = np.random.random_integers(-5,5,num_charges)
charges[charges==0] = 5
charges_positions = np.random.random((num_charges, 2))

y,x = np.mgrid[0:1:40j, 0:1:40j]
xdist = x - charges_positions[:,0].reshape(-1,1,1)
ydist = y - charges_positions[:,1].reshape(-1,1,1)

denom = ((xdist**2 + ydist**2)**1.5)
# Ignoring Coulomb's constant here...
Ex = (charges.reshape(-1,1,1) * xdist / denom).sum(axis=0)
Ey = (charges.reshape(-1,1,1) * ydist / denom).sum(axis=0)

rawDescription: Most Pythonic way to plot a vector function


code:
...
import janus

loop = asyncio.new_event_loop()
stdin_q = janus.Queue(loop=loop)
...

@asyncio.coroutine
def get_input():
  loop = asyncio.get_event_loop()
  return (yield from stdin_q.async_q.get())

class Control:

    def start(self):
        asyncio.set_event_loop(loop)
        self.loop = asyncio.get_event_loop()

        server = self.loop.run_until_complete(asyncio.start_server(client_connected_handler, '0.0.0.0', 2222))
        self.loop.run_forever()
        self.stop()

    def stop(self):
        self.loop.stop()
        self.loop.close()

...

if __name__ == "__main__":

    stdin_q.sync_q.put("\n")
    t = Thread(target=runner)
    t.start()
    sleep(2)
    _cmd = ""
    while _cmd.lower() != "exit":
        _cmd = input("")
        if _cmd == "":
          _cmd = "\r\n"

        stdin_q.sync_q.put(_cmd)

rawDescription: Python queue linking object running asyncio coroutines with main thread input


code: powd = DataFrame(data2)

rawDescription: Python: How can I use ggplot with a simple 2 column array?


code:
maxuserid = 7255
for i in range(maxuserid):
    result_liked = [] # form a separate list for each csv file
    with open('source/to/file/user_id%i.csv' %(i+1),'r') as fin:
        for row in csv.reader(fin, delimiter='\t'):
            if int(row[2]) >= 1:
                result_liked.append(row)

    if len(result_liked) < 3: # if list too few elements just go to next file
        continue
    training_data = result_liked[:2]
    test_data = result_liked[2:]
    ...

rawDescription: Loop through csv rows and check for a specific value


code:
import os.path
import zipfile

def zipbetter(target, source, env):
    # Open the zip file with appending, so multiple calls will add more files
    zf = zipfile.ZipFile(str(target[0]), 'a', zipfile.ZIP_DEFLATED)
    for s in source:
        # Find the path of the base file
        basedir = os.path.dirname(str(s))
        if s.isdir():
            # If the source is a directory, walk through its files
            for dirpath, dirnames, filenames in os.walk(str(s)):
                for fname in filenames:
                    path = os.path.join(dirpath, fname)
                    if os.path.isfile(path):
                        # If this is a file, write it with its relative path
                        zf.write(path, os.path.relpath(path, basedir))
        else:
            # Otherwise, just write it to the file
            flatname = os.path.basename(str(s))
            zf.write(str(s), flatname)
    zf.close()

# Make a builder using the zipbetter function, that takes SCons files
zipbetter_bld = Builder(action = zipbetter,
                        target_factory = SCons.Node.FS.default_fs.Entry,
                        source_factory = SCons.Node.FS.default_fs.Entry)

# Add the builder to the environment
env.Append(BUILDERS = {'ZipBetter' : zipbetter_bld})

rawDescription: How to make SCons not include the base dir in zip files?

description: Make SCons not include the base dir in zip files


code: not any(dict.itervalues())

rawDescription: Quick and easy way to check if all items in a dictionary are empty strings?


code:
sns.set_style("white")
g = sns.FacetGrid(f, col="measurement", row="type",
                 sharey=True, sharex=True)
g.map(sns.boxplot, "station", "value", palette=['r', 'g', 'b'])

(
g.set_axis_labels("", "val")
 .set_titles("{col_name}")
 .despine(bottom=True, left=True)
)

g.axes[0,0].set_ylabel("Error")
g.axes[1,0].set_ylabel("Correlation")

for h in g.axes[1,:]:
    h.set_title('')

rawDescription: Matplotlib clustered box and whisker plot with multiple series


code:
obj = CustomVal(wrapped_obj)
obj.SomeAttributeOfWrappedObj

rawDescription: Is it possible to create a class that represents another type in Python, when directly referenced?


code: df = pan.to_frame()

rawDescription: How to create an index on a ndarray using pandas

description: Create an index on a ndarray using pandas