code:
def alpha():
  b = open("Class X.txt" , "r")
  fo = b.readlines()
  for x in sorted (fo):
      print(x)
def beta():
  b = open("Class Y.txt" , "r")
  fo = b.readlines()
  for x in sorted(fo):
      print(x)
def charlie():
  b = open("Class Z.txt" , "r")
  fo = b.readlines()
  for x in sorted(fo):
      print(x)

rawDescription: Python - Highest with alphabetical order from text file


code:
from operator import itemgetter
from itertools import groupby
from pprint import pprint
pprint ([list(g) for k, g in groupby(c, key=itemgetter(0))])

rawDescription: In Python / numpy, how do I unravel / split an array according to its first column, which is an index?


code:
import csv

all_values = []

with open('scores.txt', newline='') as infile:
    reader = csv.reader(infile)
    for row in reader:
        all_values.extend(row)

rawDescription: How to append from file into list in Python?

description: Append from file into list in Python


code:
# this route will serve your form POST submission
@route('/your_route', method='POST')
def route_handler():

    # here you're reading selected values from request
    year1 = request.forms.get('year1')
    month1 = request.forms.get('month1')
    day1 = request.forms.get('day1')

    # and here you're setting that values back to the template to write a logic html side
    return template('your_template', year1=year1, month1=month1, day1=day1)

rawDescription: dowpdown shold display the selected value upon submission of form

description: Dowpdown shold display the selected value upon submission of form


rawDescription: How can I create a user defined data structure in python

description: Create a user defined data structure in python


code:
class Product(models.Model):
    name = models.CharField(max_length=50)
    product_rank = models.OneToOneField('ProductRank')

class ProductRank(models.Model):
    rank = models.IntegerField(default=0)

rawDescription: How to do this join query in Django

description: Do this join query in Django


code: myproc()

rawDescription: Suddenly, I can not run python code

description: Suddenly, I can not run python code


code:
def dictobject(d):
    """Return the PyDictObject lying behind the Python dict `d`."""
    if not isinstance(d, dict):
        raise TypeError('cannot create a dictobject from %r' % (d,))
    return cast(id(d), POINTER(PyDictObject)).contents

rawDescription: python 3.3 dict: how to convert struct PyDictKeysObject to python class?

description: Python 3.3 dict: how to convert struct PyDictKeysObject to python class


code:
bobinstance = BOB('spam', 'red', 'square')
bobinstance.__dict__
bobinstance.modify_attrs(['lencolor', 'lenname'])
bobinstance.__dict__

rawDescription: How to input a list of attributes into a function

description: Input a list of attributes into a function


code: item2 = [x for x in list2 if x["name"] == item1["name"]]

rawDescription: Python - Log the changes needed for one list of dictionaries to be updated to another


code:
import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile, delimiter=',', quoting=csv.QUOTE_NONE)

for row in reader:
    if not row[0] or not row[1]:
        continue
    print (row[0][0] + row[1]).lower()

rawDescription: (Simple Python) CSV input to usernames

description: (Simple Python) CSV input to usernames


code:
elm = driver.find_element_by_tag_name("iframe")
driver.switch_to.frame(elm)

rawDescription: searching web-client for python that can handle frames

description: Searching web-client for python that can handle frames


code:
def splitOnChars(text, chars):
    answer = []
    start = 0
    for i,char in enumerate(text):
        if char in chars:
            answer.append(text[start:i+1])
            start = i+1
    answer.append(text[i+1:])
    return answer

rawDescription: split on char, but leave that char - python

description: Split on char, but leave that char - python


code:
from scapy.all import *
results, unanswered = sr(ARP(op=ARP.who_has, psrc='192.168.1.2', pdst='192.168.1.1'))
results
result = results[0]
result
original_packet, answer = result
original_packet
answer

rawDescription: Python Scapy --arp request and response

description: Python Scapy --arp request and response


code:
('Property Damage', 4364)
('Possession/Sale/Dist', 2893)
('Fraud', 1844)
('Forgery', 712)
('Family Offense', 661)
('Rape', 597)
('Weapons Law Violation', 595)
('Sex Offense Other', 387)
('Homicide', 189)
('Embezzlement', 184)
('Prostitution', 175)
('Stolen Property', 147)
('Homicide', 189)
('Embezzlement', 184)
('Prostitution', 175)
('Stolen Property', 147)

rawDescription: Python: Replace value with the value from a dictionary key value pair


code: html_sidebars = {'**': ['my_custom_sidebar.html', 'searchbox.html']}

rawDescription: Enabling sidebar on Python-Sphinx documentation based on a sphinx-bootstrap-theme


code: [{u'payload': u'example message payload', u'exchange': u'example_exchange', u'routing_key': u'my.rtkey', u'payload_bytes': 23, u'message_count': 2, u'payload_encoding': u'string', u'redelivered': False, u'properties': []}]

rawDescription: Getting number of messages in a RabbitMQ queue


code:
mask = ~np.isnan(x)
mask[mask] &= x[mask] < -1000
x[mask] = np.nan

rawDescription: inequality comparison of numpy array with nan to a scalar

description: Inequality comparison of numpy array with nan to a scalar


code: execl ("/usr/bin/sleep", "notsleep", "60", NULL);

rawDescription: First parameter of os.exec*

description: First parameter of os.exec*


code:
POST /test_index/_search
{
   "query": {
      "match": {
         "model": {
            "query": "iPhone 5s",
            "operator": "and"
         }
      }
   },
   "sort": [
      {
         "memory": {
            "order": "asc"
         }
      }
   ],
   "size": 1
}
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": null,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "482",
            "_score": null,
            "_source": {
               "id": 482,
               "memory": 16,
               "model": "iPhone 5s 16GB"
            },
            "sort": [
               16
            ]
         }
      ]
   }
}

rawDescription: Elasticsearch - match_phrase query sort by int


code: [u'Hello this is a string.', u'-2.34', u' This is an example1 string.']

rawDescription: Trying to split strings into multiple parts with Python


code:
range(5)
range(3,8)
zip(range(5), range(3,8))

rawDescription: How to simultaneously process 2 FASTA generators

description: Simultaneously process 2 FASTA generators


rawDescription: Python script loop to assign timeslot to each line in input file


rawDescription: python - saving numpy array to a file (smallest size possible)

description: Python - saving numpy array to a file (smallest size possible)


code:
import pysal as ps

def dbf2DF(dbfile, upper=True):
    "Read dbf file and return pandas DataFrame"
    with ps.open(dbfile) as db:  # I suspect just using open will work too
        df = pd.DataFrame({col: db.by_col(col) for col in db.header})
        if upper == True:
           df.columns = map(str.upper, db.header)
        return df

rawDescription: Way to convert dbf to csv in python?

description: Way to convert dbf to csv in python


rawDescription: Python Array Function

description: Python Array Function


rawDescription: Delete multiple Pandas DataFrame row where column value is this or that


code:
def diskstats_parse(dev=None):
    file_path = '/proc/diskstats'
    result = {}

    # ref: http://lxr.osuosl.org/source/Documentation/iostats.txt
    columns_disk = ['m', 'mm', 'dev', 'reads', 'rd_mrg', 'rd_sectors',
                    'ms_reading', 'writes', 'wr_mrg', 'wr_sectors',
                    'ms_writing', 'cur_ios', 'ms_doing_io', 'ms_weighted']

    columns_partition = ['m', 'mm', 'dev', 'reads', 'rd_sectors', 'writes', 'wr_sectors']

    lines = open(file_path, 'r').readlines()
    for line in lines:
        if line == '': continue
        split = line.split()
        if len(split) == len(columns_disk):
            columns = columns_disk
        elif len(split) == len(columns_partition):
            columns = columns_partition
        else:
            # No match
            continue

        data = dict(zip(columns_disk, split))
        if dev != None and dev != data['dev']:
            continue
        for key in data:
            if key != 'dev':
                data[key] = int(data[key])
        result[data['dev']] = data

    return result

rawDescription: Python collect System Stats

description: Python collect System Stats


code:
domain = ['a','b','c','d']
allf = [{'a':'a','b':'c','c':'d', 'd':'d'}, {'a':'b', 'b':'c', 'c':'d', 'd':'a'}]

def dictfunky():
    dictfuncts = []
    for item in allf:
        di = dict(item)
        dictfuncts.append(di)
    return dictfuncts

def functmatnoz():
    matlist = []
    for f in dictfuncts:
        elems = []
        for element in domain:
            forward = [f[element], f[f[element]], f[f[f[element]]], f[f[f[f[element]]]]]
            forward.reverse()
            back = forward
            elems.append(back)
        matlist.append(elems)
    return matlist

def sigma():
    sigmamat = []
    for mat in matlist:
        col = []
        for element in domain:
            num_elem = []
            for results in mat:
                count = results.count(element)
                num_elem.append(count)
            col.append(num_elem)
        sigmamat.append(col)
    return sigmamat

dictfuncts = dictfunky()
matlist = functmatnoz()
sigmamat = sigma()

print('dictfuncts: {}'.format(dictfuncts))
print('   matlist: {}'.format(matlist))
print('  sigmamat: {}'.format(sigmamat))

rawDescription: From matrix as lists of lists: count number of elements from a set x in each column. (python3)


code:
class TakingCourse(models.Model):
    course = models.ForeignKey(Course)
    term = models.ForeignKey(Term)

    class Meta:
        unique_together = ('course', 'term')

rawDescription: Django models: Use multiple values as a key?


code: [['G{}{}'.format(i, j) for j in range(l)] for i in range(l)]

rawDescription: Best pythonic way of mapping a specific function with multiple arguments


code:
X, Y = map(list, zip(*L))
X
Y

rawDescription: Grab all the x values from stacked array? Python


rawDescription: Pygame scaling a sprite

description: Pygame scaling a sprite


code:
from bs4 import BeautifulSoup
import urllib

urlData = urllib.urlopen('https://www.facebook.com/photo.php?fbid=10152055005350906')
data = str(urlData.readlines())
bs = BeautifulSoup(data)
imgUrl = bs.find('img', attrs={'class': 'fbPhotoImage img'}).get('src')
urllib.urlretrieve(imgUrl, "plane.jpg")

rawDescription: Getting actual facebook and twitter image urls using python


code:
def all_perms(elements):
    if len(elements) <=1:
        yield elements
    else:
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                # nb elements[0:1] works in both string and list contexts
                yield perm[:i] + elements[0:1] + perm[i:]

rawDescription: How to generate all permutations of a list in Python

description: Generate all permutations of a list in Python


code:
re.split('\.gds|\.cdl', "im fine.gds how are you")
re.split('\.gds|\.cdl', "im fine.cdl how are you")
re.split('\.gds|\.cdl', "im fine.cdl how are.gds you")

rawDescription: parameter passing to split function from if condition

description: Parameter passing to split function from if condition


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

x=np.linspace(-np.pi,np.pi,101)
y=np.sin(x)+np.sin(3*x)/3
y1=np.sin(x)+np.sin(2*x)/3
y2=np.sin(x)+np.sin(3*x)/2

colors = plt.cm.hot(np.linspace(0,1,10))
plt.gca().set_color_cycle(colors)

plt.plot(x,y)
plt.plot(x,y1)
plt.plot(x,y2)
plt.show()

rawDescription: how to use matplotlib's set_cmap()?

description: Use matplotlib's set_cmap()


rawDescription: Transposing (pivoting) a dict of lists in python


code:
S.seek(0)
S.readlines()

rawDescription: how to read numpy 2D array from string?

description: Read numpy 2D array from string


rawDescription: How do I load a file into the python console?

description: Load a file into the python console


code:
import datetime

ts_dict = {}
for company in df['Name'].unique():
    tmpdf = df[df['Name'] == company][['Year', 'Qtr 1', 'Qtr 2', 'Qtr 3', 'Qtr 4']].reset_index(drop=True)
    tmpdf.columns = tmpdf.iloc[0]
    tmpdf = tmpdf.drop(0).set_index('Year').unstack().reset_index(name=company)
    tmpdf.index = (tmpdf['Year'].apply(str) + tmpdf[0]).apply(lambda x: datetime.datetime.strptime(x, "%Y%b.%d"))
    ts_dict[company] = tmpdf[company]
pd.DataFrame.from_dict(ts_dict)

rawDescription: Munge tuples of yearly fiscal data with element date-labels into a time-series in Python Pandas


code: foo = [chr(random.randint(32,126)) for _ in xrange(11)]

rawDescription: More efficient for loops in Python (single line?)


code:
def getvalues(params):
    def deco(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if len(args) == 1 and not kwargs and isinstance(args[0], Mapping):
                return func(**{key: value for key, value in args[0].items()
                               if key in params})
            else:
                return func(*args, **kwargs)
        return wrapper
    return deco

rawDescription: Python decorator to find key exist, and pass it as argument


code:
g = df.groupby('col_a', as_index=False)
g.apply(add_col_c)

rawDescription: Enumerate each row for each group in a DataFrame


code:
a = [1,2]
a_rev = a[::-1]  #new list -- if you just want an iterator, reversed(a) also works.

rawDescription: Sort list of lists by unique reversed absolute condition


code:
df1 = df1.drop_duplicates()
data = set()
for vid, grp in df1.groupby(['Vehicle_ID']):
    for c1, c2 in IT.combinations(grp['City'], 2):
        if c1 > c2:
            c1, c2 = c2, c1
        data.add((c1, c2, vid))
df = pd.DataFrame(list(data), columns=['City_x', 'City_y', 'Vehicle_Count'])
#   City_x City_y  Vehicle_Count
# 0      B      C              3
# 1      A      C              1
# 2      B      C              1
# 3      A      C              2
# 4      A      B              1
result = df.groupby(['City_x', 'City_y']).count()

rawDescription: Count by combination

description: Count by combination


code:
class ScriptParser(object):

    # See 'to_python' to check out what this does
    mapping = {'^':'**', '!':' not ', '&':' and '}

    def to_python(self, calc):
        '''
        Parse the calculation syntax from the script grammar to the python one.
        This could be grown to a more complex parser, if needed. For now it will
        simply assume any operator as defined in the grammar used for the script
        has an equivalent in python.
        '''
        for k, v in self.mapping.items():
            calc = calc.replace(k, v)
        return calc

    def feed(self, lfs):
        '''
        Parse a line of the script containing a function defintion
        '''
        signature, calc = lfs.split(':=')
        funcname, variables = [s.strip() for s in signature.split('(')]
        # as we stripped the strings, it's now safe to do...'
        variables = variables[:-1]
        setattr(self, funcname,
                eval('lambda ' + variables + ' : ' + self.to_python(calc)))

def main():
    lines = ['f0(x, y, z) := x^2',
             'f1(x) := x**2 + x**3 + x*1000']
    sp = ScriptParser()
    for line in lines:
        sp.feed(line)
        print('Script definition  : %s' % line)
    for i in range(5):
        res0 = sp.f0(i, None, None)
        res1 = sp.f1(i)
        print('f0(%d) = %d' % (i, res0))
        print('f1(%d) = %d' % (i, res1))
        print('--------')

if __name__ == '__main__':
    main()

rawDescription: Implementation of functions with very basic scripting


code:
names = list(set(row['name'] for row in joined))

rect(names,    # x (categorical) coordinate for each rectangle
     names,    # y (categorical) coordinate for each rectangle
     0.9, 0.9, # use 0.9 for both width and height of each rectangle
     color = some_colors, # color for each rect
     x_range = names, # sequence of categorical coords for x-axis
     y_range = names, # sequence of categorical coords for y-axis
)

rawDescription: Plot topics with bokeh or matplotlib

description: Plot topics with bokeh or matplotlib


code:
big_array
np.delete(big_array, d, axis=1)

rawDescription: Remove elements from several lists simultaneously


code:
def splits(s,seps):
    l,_,r = s.partition(seps[0])
    if len(seps) == 1:
        return [l,r]
    return [l] + splits(r,seps[1:])

rawDescription: Is it possible to split a string on multiple delimiters in order?


code:
import user1
# It prints:
# list_vars = ['001']
# var =
import user2
# It prints:
# list_vars = ['001']
# var = 002

rawDescription: Static variables in Python that are shared across files


code:
idx = [i for i, t in enumerate(zip(c1,d1,c2,d2)) if t[:2] == t[2:]]
print([(a[i], b[i]) for i in idx])

rawDescription: Getting values OF a set in Python

description: Getting values OF a set in Python


code:
import sys, atexit
sys.stdout = open(sys.argv.pop(), "w+") #Replaces stdout with a file returned from sys.argv (command line arguments)
def saveClose():
    sys.stdout.write("--%s--"%sys.stdout.name) #Just to indicate if the script closed
atexit.register(saveClose) #Register with atexit to execute the function at...exit

rawDescription: Provide feedback from Python script to PHP


code:
mysubset = ["d","f"]
df[sorted(df, key=lambda x: x not in mysubset)]

rawDescription: How to change the column order in a pandas dataframe when there are too many columns?

description: Change the column order in a pandas dataframe when there are too many columns


code: parsed_result = client.service.PersonSearch(__inject={'reply': raw_reply})

rawDescription: How to get unparsed XML from a suds response, and best django model field to use for storage

description: Get unparsed XML from a suds response, and best django model field to use for storage


code:
while True:
    line = raw_input()
    if not line:
        break
    # so something with line

rawDescription: How to process raw data (in python)?

description: Process raw data (in python)


code:
from tkinter import *
import tkinter.simpledialog as simpledialog

class YourApp():
    def __init__(self):
        self.root = Tk()
        Button(self.root, text='Quit', command=self.root.destroy).pack(pady=20)
        self.ask_button = Button(self.root, text='Add users', command=self.add_users)
        self.ask_button.pack(padx=50, pady=50)
        self.root.mainloop()
    def add_users(self):
        self.users_count = 0
        self.user_name = StringVar()
        self.frame = Frame(self.root)
        self.frame.pack()

        self.users_count = simpledialog.askinteger('', 'How many users are you going to put in?', initialvalue=1, minvalue=1, maxvalue=10)
        self.user_entry = Entry(self.frame, textvariable=self.user_name)
        self.user_entry.pack(pady=10)
        self.user_entry.bind('<Key-Return>', self.on_new_user)
        self.user_entry.focus_set()
    def on_new_user(self, event):
        # your code
        print(self.user_name.get())
        Label(self.frame, text='User Inputted: %s' % self.user_name.get()).pack()
        self.users_count -= 1
        if not self.users_count:
            self.user_entry.destroy()
        self.user_name.set('')

YourApp()

rawDescription: Get the same input multiple times in python tkinter?


code:
#First we need to access the module that lets us connect to Excel
import win32com.client

# Next we want to create a variable that represents Excel
app = win32com.client.Dispatch("Excel.Application")

# Lastly we will assume that the sheet with the names is the active sheet
sheet = app.ActiveSheet

rawDescription: In excel with python, how do you find words, from an entire column, in a cell containing multiple words?


code:
def combs(idx,array,current=[]):
    for item in array[idx]:
        current_copy = current[:]
        current_copy.append(item)
        if idx + 1 < len(array):
            yield from combs(idx+1,array,current_copy)
        else:
            yield current_copy

rawDescription: Python Recursive Generator

description: Python Recursive Generator


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: How can I make a for-loop pyramid more concise in Python?

description: Make a for-loop pyramid more concise in Python


code: process = subprocess.Popen(['cmd','/c', batchCmd ,'&&', 'cd %MYDIR%\SOURCE\FILES', '&&', perlCmd, perlValues], shell=False, stdin = subprocess.PIPE, stdout = subprocess.PIPE, env = myenv)

rawDescription: How to set environment variables and call a perl script with parameters in python subprocess.popen?

description: Set environment variables and call a perl script with parameters in python subprocess.popen


rawDescription: Pandas: Select from date in MultiIndex

description: Pandas: Select from date in MultiIndex


code:
for key in ('log', 'bin', 'pid', 'conf'):
    if key in kwargs:
        setattr(self, key, kwargs[key])

rawDescription: kwargs parsing best practice

description: Kwargs parsing best practice


code:
import io
open('test.txt', 'wb').write('One\nTwo\rThree\r\n')
open('test.txt', 'rb').readlines()
io.open('test.txt', 'r', newline='').readlines()

rawDescription: Python, read CRLF text file as is, with CRLF


code:
import numpy as np
np.sqrt(-1)

rawDescription: numpy.arctanh(x) for x >= 1 returns NaN but I want complex

description: Numpy.arctanh(x) for x >= 1 returns NaN but I want complex


code:
from flask import Flask
app = Flask(__name__)

@app.route('/index')
def index():
    pass

rawDescription: Encapsulate flask api in class for testing purposes


code:
import xmlrpclib
server = xmlrpclib.ServerProxy("http://athomas:password@localhost:8080/trunk/login/xmlrpc")
server.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read()))

rawDescription: How to base64 encode a PDF file in Python

description: Base64 encode a PDF file in Python


code: rect_size = pygame.Rect(position_x + x, position_y + y, position_x, position_y)

rawDescription: How do I check to see if a mouse click is within a rectangle for each rectangle in this pygame program?

description: Check to see if a mouse click is within a rectangle for each rectangle in this pygame program


code:
new_list = []
for line in lines:
    new_list.append(line)

rawDescription: Assigning a string from a .txt file into a variable


code:
class Command( object ):
    name= "name"
    def setup_opts( self, parser ):
        """Add any options to the parser that this command needs."""
        pass
    def execute( self, context, options, args ):
        """Execute the command in some application context with some options and args."""
        raise NotImplemented

rawDescription: command line arg parsing through introspection

description: Command line arg parsing through introspection


code:
a = [1, 2, 3]
b = a
a = []
print(a)
print(b)

rawDescription: Clearing Python lists

description: Clearing Python lists


code:
outervar = None # this is global

def foo():
    if(outervar): #this refers to the local variable
       outervar = "you fail it" # this creates a local variable

rawDescription: Python: Persistent variable in a module without a class?


rawDescription: Python List with ranges

description: Python List with ranges


code:
import os,sys
READ = os.read(0,100)
if str(READ,sys.stdin.encoding) == os.linesep:
   READ = "C:\\temp"

rawDescription: Python 3.2.2 READ from console

description: Python 3.2.2 READ from console


code:
func_list = []

def listed_func(func):
    func_list.append(func)
    return func

@listed_func
def foo1():
   pass

@listed_func
def foo2():
   pass

rawDescription: python function that returns a function from list of functions

description: Python function that returns a function from list of functions


code: re.match('^inhe.{4}', word)

rawDescription: Python 3 - Regular Expression - Match string with one character less


code:
def somewhere():
  old_eq = obj.__eq__
  def new_eq(a, b):
    return False
  obj.__eq__ = new_eq
  # ^^^ Will fail here because you can't assign new __eq__ to the object
  if not obj == obj:
    print('Well, ok...')
  obj.__eq__ = old_eq

rawDescription: Is there any way to override locally the __eq__ function/operator and restore the old one after?


code:
for x in range(50, 149):
    print(x, end='; ')
print(149)

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:
import numpy as np
import matplotlib.pyplot as plt

rawDescription: Issues with isolating color channels in Pylab


code:
new_df = pd.DataFrame()
for index, cols in df.iterrows():
    extract_df = pd.DataFrame.from_dict({'datetime': cols.ix['datetime'], 'values': cols.ix['values']})
    extract_df = pd.concat([extract_df, cols.drop(['datetime', 'values']).to_frame().T], axis=1).fillna(method='ffill').fillna(method='bfill')
    new_df = pd.concat([new_df, extract_df], ignore_index=True)

rawDescription: Pandas: How do I split multiple lists in columns into multiple rows?


code: len( set( a ) ) == len( a )

rawDescription: How to check whether elements appears in the list only once in python?

description: Check whether elements appears in the list only once in python


code:
a = Foo()
b = Foo()
c = Foo(1)
a == b
b == c
s = set([a, b, c])
s
s.add(Foo())
s

rawDescription: What is the correct way to implement a set that checks type in the add method in python 2.7?


rawDescription: counting up and then down a range in python

description: Counting up and then down a range in python


code: return float(output) / len(nums)

rawDescription: Arithmetic Mean Number of a List - Python


code:
from itertools import product

tests = [
    lambda a, b, c, d, e, f, g, h, i: a ^ b ^ c ^ d ^ g == 0,
    lambda a, b, c, d, e, f, g, h, i: a ^ b ^ c ^ e ^ h == 0,
    lambda a, b, c, d, e, f, g, h, i: a ^ b ^ c ^ f ^ i == 1,
    lambda a, b, c, d, e, f, g, h, i: a ^ d ^ e ^ f ^ g == 0,
    lambda a, b, c, d, e, f, g, h, i: b ^ d ^ e ^ f ^ h == 0,
    lambda a, b, c, d, e, f, g, h, i: c ^ d ^ e ^ f ^ i == 1,
    lambda a, b, c, d, e, f, g, h, i: a ^ d ^ g ^ h ^ i == 1,
    lambda a, b, c, d, e, f, g, h, i: b ^ e ^ g ^ h ^ i == 1,
    lambda a, b, c, d, e, f, g, h, i: c ^ f ^ g ^ h ^ i == 1
]

sols = []
for a, b, c, d, e in product([0,1], repeat=5):
    f = b ^ c ^ e
    g = a ^ b ^ c ^ d
    h = a ^ b ^ c ^ e
    i = 1 - (a ^ e)
    if all(test(a,b,c,d,e,f,g,h,i) for test in tests):
        sols.append(
            "{}   {} {} {} {} {} {} {} {} {}"
            .format(sum([a,b,c,d,e,f,g,h,i]), a,b,c,d,e,f,g,h,i)
        )
sols.sort()
print("\n".join(sols))

rawDescription: Minimize the sum of solution of linear equation


code:
# assert "/filepath/to" in sys.path
import your_script # import module defined in your_script.py

your_script.copyfile(srcfile, dest)

rawDescription: Python: To Subprocess or Not To Subprocess into Another Python Subprocess?


code:
success = {k:(v if k in data else '') for (k,v) in client_order.items()}
success

rawDescription: Comparing the keys and values of multiple dictionaries using python


code:
dd = {'A': set(['Apple', 'Orange', 'Strawberries']),
      'B': set(['Banana', 'Dates', 'Kiwi', 'Orange', 'Strawberries']),
      'C': set(['Apple', 'Grapes', 'Kiwi']),
      'D': set(['Apple', 'Banana', 'Lemon', 'Orange'])}

rawDescription: Cumulative count of unique values in a dictionary


code: [':'.join(group) for group in zip(*[iter(lst)]*2)]

rawDescription: How to connect the list to get ip address with port?

description: Connect the list to get ip address with port


code:
lineEdits = []
for _ in range(5):
    myLineEdit = QtGui.QLineEdit("myLineEdit")
    lineEdits.append(myLineEdit)

myLayout = QtGui.QHBoxLayout()
for lineEdit in lineEdits:
    myLayout.addWidget(lineEdit)

rawDescription: PyQt: Creating QT Widgets Programmatically


code:
##views.py
def YourViewsHere(request):
   if request.method == 'GET':
       do_something()
   elif request.method == 'POST':
       ## access you data by playing around with the request.POST object
       request.POST.get('data')

rawDescription: How pass javascript function 's value to Django view?


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

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


code:
list = []

with open("exam2data.txt") as f:
    for data in f:
        data = f.readline()
        xCounter = 0
        yCounter = 0
        zCounter = 0
        line = data.rstrip("\n")
        try:
            lineFloat = float(line)
            if lineFloat < 1:
                if len(line) == 3:
                    if line[2] == 0:
                        pass
                    else:
                        list.append(lineFloat)
                        xCounter += 1

                elif len(line) == 4:
                    if line[3] == 0:
                        pass
                    else:
                        if line[2] == 0:
                            pass
                        else:
                            y = float(line[3])
                            if (y % 2 == 0):
                                list.append(lineFloat)
                                yCounter += 1
                            else:
                                pass

                elif len(line) == 5:
                     if line[4] == 0:
                        pass
                     else:
                        if line[3] == 0:
                            pass
                        else:
                            if line[2] == 0:
                                pass
                            else:
                                y = float(line[3])
                                z = float(line[4])
                                if (y % 2 == 0):
                                    if (z % 2 == 1):
                                        list.append(lineFloat)
                                        zCounter += 1
                                    else:
                                        pass
                                else:
                                    pass

        except:
            pass

print(len(list))
print(', '.join(map(str, list)))

rawDescription: Having trouble sorting the data from a file


code:
import types
types.FunctionType(code_obj, globals={}, name='x')(1)

rawDescription: code objects in python - passing parameters

description: Code objects in python - passing parameters


rawDescription: File name encoding in Python 2.7

description: File name encoding in Python 2.7


rawDescription: Recursive algorithm for generating a acyclic directed graph


rawDescription: Sum of precipitation per Timeframe in pandas DataFrame


code: result = q.enqueue(what_function, 'http://stackoverflow.com')

rawDescription: How to present a class as a function?

description: Present a class as a function


code: board = [x[:] for x in [[0]*n]*n]

rawDescription: Python: Recursive pass by value, 4 queens


rawDescription: Copy all values in a column to a new column in a pandas dataframe


code:
import numpy

x = numpy.arange(5) + 1
print (x)

r = numpy.reciprocal(x.astype(float))
print (r)

rawDescription: In Numpy, how do I find element wise inverse (reciprocal) of a given vector?


code: main()

rawDescription: Python list data analysing

description: Python list data analysing


code:
import json
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route("/", methods=['GET','POST'])
def calculation():
    if request.method=='POST':
        results = json.loads(request.data)
        # do stuff to result here
        # you will need to pass a dictionary back into jsonify()
        return jsonify(results)
    return render_template('calculation.html')

if __name__ == "__main__":
    app.run(debug=True)

rawDescription: Trouble with Flask Requests - returns GET before any actions


code: self.storage = {'key_A':[], 'key_B':[]}

rawDescription: Combine methods with identical structure but different parameters


rawDescription: numpy matrix rank incorrect result

description: Numpy matrix rank incorrect result


code: import fakeutils as utils

rawDescription: Best way to override a installed packge method

description: Override a installed packge method


rawDescription: Remaximize Tkinter window in Python

description: Remaximize Tkinter window in Python


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

time=np.linspace(0,15,5*1024)

def derivN(N, t):
    """Return the derivative of the vector N, which represents
    the tuple (N1, N2). """

    N1, N2  = N
    return np.array([N1*(1 - N1 - .7*N2), N2*(1 - N2 - .3*N1)])

def coupled(time, init, ax):
    """Visualize the system of coupled equations, by passing a timerange and
    initial conditions for the coupled equations.

    The initical condition is the value that (N1, N2) will assume at the first
    timestep. """

    N = integrate.odeint(derivN, init, time)
    ax[0].plot(N[:,0], N[:,1], label='[{:.1f}, {:.1f}]'.format(*init))  # plots N2 vs N1, with time as an implicit parameter
    l1, = ax[1].plot(time, N[:,0], label='[{:.1f}, {:.1f}]'.format(*init))
    ax[1].plot(time, N[:,1], color=l1.get_color())

rawDescription: Solve Lotka-Volterra model using SciPy

description: Solve Lotka-Volterra model using SciPy


code:
import copy
def export_with_name(arg):
    """ Export variable's string representation with it's name as filename """
    for k, v in iter(copy.copy(globals()).items()):
        if arg == v:
            with open(k, 'w') as handle:
                handle.writelines(repr(arg))

rawDescription: Export function that names the export file after the input variable


code: main(favoriteBandLists)

rawDescription: Common Favorite Band Python

description: Common Favorite Band Python


code: {(frozenset(item)) for item in a} == {(frozenset(item)) for item in b}

rawDescription: Assert list of list equality without order in Python


code: {item: [] for item in my_list}

rawDescription: How do I create a dictionary with keys from a list and values separate empty lists?

description: Create a dictionary with keys from a list and values separate empty lists


code:
class Robot:
    Price = PositiveValuedProperty()

class Box:
    Weight = PositiveValuedProperty()

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


rawDescription: How to put timedelta in django model?

description: Put timedelta in django model


code:
unanticipated_konnor
furnacelike_marlene
unfulminating_deacon
mangiest_ima

rawDescription: Sort strings by splitted words

description: Sort strings by splitted words


rawDescription: Appending data to a scapy packet

description: Appending data to a scapy packet


code:
from functools import total_ordering

@total_ordering
class Point():
    def __init__(self, x, y, distance):
        self.x = x
        self.y = y
        self.distance = distance

    def __eq__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented  # only the same type or subclasses
        return (self.x, self.y, self.distance) == (other.x, other.y, other.distance)

    def __lt__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented  # only the same type or subclasses
        if (self.x, self.y) == (other.x, other.y):
            return False  # same coordinates makes them equalish?
        return self.distance < other.distance

rawDescription: How to choose the attribute of a user-defined class that will be evaluated for built-in min() and max() functions?

description: Choose the attribute of a user-defined class that will be evaluated for built-in min() and max() functions


rawDescription: Checking column values in python panda

description: Checking column values in python panda


code:
set_current_uarfcn("11000")
proc_stdout = ran_cmd(ran_update_uarfcn)

rawDescription: change string value further on in function

description: Change string value further on in function


code:
def setEditorData(self, editor, index):
    value = index.model().data(index, Qt.EditRole)
    editor.setCurrentIndex(editor.findText(value))

rawDescription: How to restore the index of a QComboBox delegate in a QTableView?

description: Restore the index of a QComboBox delegate in a QTableView


code:
class LinearRegression_Multi:
    def stacked_lstsq(self, L, b, rcond=1e-10):
        """
        Solve L x = b, via SVD least squares cutting of small singular values
        L is an array of shape (..., M, N) and b of shape (..., M).
        Returns x of shape (..., N)
        """
        u, s, v = np.linalg.svd(L, full_matrices=False)
        s_max = s.max(axis=-1, keepdims=True)
        s_min = rcond*s_max
        inv_s = np.zeros_like(s)
        inv_s[s >= s_min] = 1/s[s>=s_min]
        x = np.einsum('...ji,...j->...i', v,
                      inv_s * np.einsum('...ji,...j->...i', u, b.conj()))
        return np.conj(x, x)

    def center_data(self, X, y):
        """ Centers data to have mean zero along axis 0.
        """
        # center X
        X_mean = np.average(X,axis=1)
        X_std = np.ones(X.shape[0::2])
        X = X - X_mean[:,None,:]
        # center y
        y_mean = np.average(y,axis=1)
        y = y - y_mean[:,None]
        return X, y, X_mean, y_mean, X_std

    def set_intercept(self, X_mean, y_mean, X_std):
        """ Calculate the intercept_
        """
        self.coef_ = self.coef_ / X_std # not really necessary
        self.intercept_ = y_mean - np.einsum('ij,ij->i',X_mean,self.coef_)

    def scores(self, y_pred, y_true ):
        """
        The coefficient R^2 is defined as (1 - u/v), where u is the regression
        sum of squares ((y_true - y_pred) ** 2).sum() and v is the residual
        sum of squares ((y_true - y_true.mean()) ** 2).sum().
        """
        u = ((y_true - y_pred) ** 2).sum(axis=-1)
        v = ((y_true - y_true.mean(axis=-1)[None].T) ** 2).sum(axis=-1)
        r_2 = 1 - u/v
        return r_2

    def fit(self,X, y):
        """ Fit linear model.
        """
        # get coefficients by applying linear regression on stack
        X_, y, X_mean, y_mean, X_std = self.center_data(X, y)
        self.coef_ = self.stacked_lstsq(X_, y)
        self.set_intercept(X_mean, y_mean, X_std)

    def predict(self, X):
        """Predict using the linear model
        """
        return np.einsum('ijx,ix->ij',X,self.coef_) + self.intercept_[None].T

rawDescription: How to solve several independent time series at the same time using scikit linear regression model

description: Solve several independent time series at the same time using scikit linear regression model


code:
df['Day'] = df['Week'].str.extract(r'^(\d{4}-\d{2}-\d{2})')
df = df[['Day', 'rossmann']]
print(df)

rawDescription: Pandas date range to single dates

description: Pandas date range to single dates


rawDescription: How to apply a modifier in Python, creating a new mesh?

description: Apply a modifier in Python, creating a new mesh


code:
import sys
import os

path_to_script = sys.argv[0]
path_to_script_dir = os.path.dirname(os.path.abspath(path_to_script))

rawDescription: Make python save to a folder created in the directory of the py file being run


code:
source
import logging, sys

import concurrent.futures as cf
from requests_futures.sessions import FuturesSession

URL = 'http://localhost'
NUM = 3

logging.basicConfig(
    stream=sys.stderr, level=logging.INFO,
    format='%(relativeCreated)s %(message)s',
    )

session = FuturesSession()
futures = {}

logging.info('start')
for n in range(NUM):
    wibble = "%04d" % n
    payload = {
        'name':'test',
        'genNum':wibble,
        'Button1':'Push+Now'
    }
    future = session.get( URL, data=payload )
    futures[future] = payload

logging.info('requests done, waiting for responses')

for future in cf.as_completed(futures, timeout=5):
    res = future.result()
    logging.info(
        "wibble=%s, %s, %s bytes",
        futures[future]['genNum'],
        res,
        len(res.text),
    )

logging.info('done!')

rawDescription: python requests-futures slow - not threading properly?

description: Python requests-futures slow - not threading properly


code:
import re                        # Import the regex library
s = "AAAKBBBBR"                  # Define the input string
re.findall(r'[^KR]*[KR]', s)     # Find all the matches in the string

rawDescription: Translate perl split to python split

description: Translate perl split to python split


code:
t0 = time.time()
total_size = 0
while True:
    if time.time() - t0 > time_limit:
        raise Exception("Too much time taken")
    if total_size > size_limit:
        raise Exception("Too large")
    data = r.raw.read(8192)
    if data == "":
        break  # end of file
    total_size += len(data)
    output_file.write(data)

rawDescription: Protection against downloading too big files


code:
d={u'identifier': {u'identifier': u'the_real_identifier'},
   u'identifier1': {u'identifier1': u'the_real_identifier1'}}
res = [value[key] for key,value in d.items()]
print(res)
# ['the_real_identifier', 'the_real_identifier1']

rawDescription: Remove part of an element in python

description: Remove part of an element in python


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

cmap = plt.get_cmap('rainbow')
cmap.set_under('white')  # Color for values less than vmin

data = np.random.random((10, 10))
data[3:5, 7:] = 0

# Very small float such that 0.0 != 0 + eps
eps = np.spacing(0.0)

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', vmin=eps, cmap=cmap)
fig.colorbar(im, extend='min')
plt.show()

rawDescription: How to create matplotlib colormap that treats one value specially?

description: Create matplotlib colormap that treats one value specially


code: find_key = find('*' + row[3] + '*', '/home/ro/Desktop/search/IDBUF')

rawDescription: How to find the path of files in a directory from a column of a CSV (PYTHON)

description: Find the path of files in a directory from a column of a CSV (PYTHON)


code: user_id = next((item['id'] for item in beta['data'] if item['username'] == xy), None)

rawDescription: Finding the exact match of many usernames stored in a variable while looping


code: autoplay = lambda link: link + '&autoplay=1'

rawDescription: Generating Links to Youtube Audio

description: Generating Links to Youtube Audio


code:
def g(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        func_value = func(*args, **kwargs)
        return -func_value
    return wrapper

rawDescription: is there a way to change the return value of a function without changing the function's body?

description: Is there a way to change the return value of a function without changing the function's body


code: p = subprocess.Popen(["ffmpeg", "-i", fpath, "-vf", "cropdetect=24:16:0", "-vframes", "500", "-f", "rawvideo", "-y", "/dev/null"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

rawDescription: ffmpeg crop detect python using subprocess

description: Ffmpeg crop detect python using subprocess


code:
if isinstance(somelist, list):
    if len(somelist) == 1:
        return somelist[0]
    else:
        return somelist
else:
    return somelist

rawDescription: pythonic method to find the inner value of a list

description: Pythonic method to find the inner value of a list


code: 'Dave' in total['Name']

rawDescription: Find specific dictionary element without looping


code:
r, t, d = symbols('rate time short_life')
d = r*t; d
r=80; t=2; d    # we haven't changed d, only r and t
d=r*t; d        # now d is using the current values of r and t

rawDescription: Sympy "global" substitution

description: Sympy "global" substitution


code:
import pandas as pd
import numpy as np

begin = pd.datetime(2013,1,1)
end = pd.datetime(2013,2,20)

dtrange = pd.date_range(begin, end)

p1 = np.random.rand(len(dtrange)) + 5
p2 = np.random.rand(len(dtrange)) + 10

df = pd.DataFrame({'p1': p1, 'p2': p2}, index=dtrange)

rawDescription: Resampling with custom periods

description: Resampling with custom periods


code: cmd = subprocess.Popen(['ls'], stdout=file('output', 'w'))

rawDescription: is there a limit to command.getstatusoutput() buffer in python

description: Is there a limit to command.getstatusoutput() buffer in python


code:
import crcmod
crc = crcmod.mkCrcFun(0x104C11DB7, 0, True, 0)

rawDescription: Recreating a C CRC32 algorithm in Python with crcmod


code:
for combo in itertools.permutations(["an", "de", "si", "ta"], 4):
    print(''.join(combo))

rawDescription: Add permutation outcomes into a string and break line between them


code:
def weight(node):
  if node == None:
      return 0
  node.pathweight=node.val+max(weight(node.left),weight(node.right))
  return node.pathweight

def heavy_edge(node):
  if not node.left:
    lweight=0
  else:
    lweight=node.left.pathweight
  if not node.right:
    rweight=0
  else:
    rweight=node.right.pathweight
  if lweight>rweight:
    return [node.val,heavy_edge(node.left)]
  else:
    return [node.val,heavy_edge(node.right)]

weight(t) #Precalculate the pathweight of all the nodes in O(n) time
heavy_edge(T) #Use the precalculated pathweights to efficient find list the heaviest path in O(lg n) time

rawDescription: Finding the heaviest path in a binary tree efficiently - python


code:
def validated_input(prompt, valid_values):
    valid_input = False
    while not valid_input:
        value = input(prompt + ': ' + '/'.join(valid_values))
        valid_input = value.lower() in valid_values
    return value

rawDescription: How to redo an input if user enters invalid answer

description: Redo an input if user enters invalid answer


code:
yax = ax.get_yaxis()
yax.set_tick_params(pad=pad)

rawDescription: Matplotlib: Aligning y-ticks to the left


code: all([True, True])

rawDescription: Split Pandas Dataframe into separate pieces based on column values


code:
Output
[u'en', u'ru', u'zh-CN']

rawDescription: Python - can I detect unicode string language code?


code:
for group_name, df_group in df.groupby(pd.TimeGrouper("M")):
    y,X = dmatrices('value1 ~ value2 + value3', data=df_group,
    return_type='dataframe')

rawDescription: Pandas - Split dataframe into multiple dataframes based on dates?


code:
import re

fileName = "A011C009_140914_FPS025/Proxy/A011C009_140914_FPS25.1001.jpg"
regExpression = "FPS([^./]+)\\."

print ( re.findall(regExpression, fileName) )
['25']

rawDescription: Python Regex, word in between two words matches correctly, but not with dot


code:
from itertools import groupby, takewhile

with open("in.txt") as f:
    grps = groupby(f,key=lambda x: x.isupper())
    for k, sec in grps:
        # if we hit a title line
        if k:
            # pull all paragraphs
            v = next(grps)[1]
            # skip two empty lines after title
            next(v,""), next(v,"")

            # take all lines up to next empty line/second paragraph
            print(list(takewhile(lambda x: bool(x.strip()), v)))

rawDescription: print first paragraph in python

description: Print first paragraph in python


code:
sample = ['fileA.jpg', 'fileB.jpg', 'images/'] * 30
import random
random.shuffle(sample)
from timeit import timeit
import re
def re_partition(pattern=re.compile(r'/$')):
    for e in sample:
        if pattern.search(e): pass
        else: pass

def endswith_partition():
    for e in sample:
        if e.endswith('/'): pass
        else: pass

timeit('f()', 'from __main__ import re_partition as f, sample', number=10000)
timeit('f()', 'from __main__ import endswith_partition as f, sample', number=10000)

rawDescription: What is best to distinguish between file and dir path in a string


code:
"""
It creates a list with random length filled with lists of random lengths containing random integers

"""

import random

MIN_LIST_OF_LISTS_LENGTH = 1
MAX_LIST_OF_LISTS_LENGTH = 10

MIN_LIST_LENGTH = 1
MAX_LIST_LENGTH = 5

MIN_LIST_ELEMENT = 1
MAX_LIST_ELEMENT = 10

#This is the list which will containt all the lists
solitaire = list(range(random.randint(MIN_LIST_OF_LISTS_LENGTH,MAX_LIST_OF_LISTS_LENGTH)))

for i, pile in enumerate(solitaire):
    solitaire[i] = [
        random.randint(MIN_LIST_ELEMENT, MAX_LIST_ELEMENT) for x in
        range(0, random.randint(MIN_LIST_LENGTH, MAX_LIST_LENGTH))
    ]

print(repr(solitaire))

rawDescription: Random's randint won't work in a for-loop


code:
def get_form_kwargs(self, *args, **kwargs):
    kwargs = super(Create, self).get_form_kwargs(*args, **kwargs)
    kwargs['user'] = self.request.user
    return kwargs

rawDescription: django - prevent duplicates for users

description: Django - prevent duplicates for users


code: guess in (word[0], word[1], word[2], word[3], word[4], word[5])

rawDescription: Python while/if statements not working

description: Python while/if statements not working


code: reduce(lambda x,y: np.dot(x,y), T, np.eye(2))

rawDescription: Multiplying matrices that are stored in an array in Python


code: sum(group[:-1] > group[-1])

rawDescription: Comparing single dataframe value to previous 10 in same column


code:
class Allergies(object):
   # other methods here

   def __init__(self, name):
      self.allergies = []  # an empty list, to store allergies
      self.name = name

   def add_allergy(self, allergy):
      self.allergies.append(allergy)

   def is_allergic_to(self, allergy):
      return allergy in self.allergies

rawDescription: Does this code imply a class and method "relationship?"


rawDescription: Python enums with complex types

description: Python enums with complex types


code:
def handle(request):

    # Post request containing the key.
    if request.method == 'POST' and 'path' in request.POST.keys():

        # Retrieving the value.
        current_title = request.POST['path']
        # You can also do |ttl = current_title.encode('utf-8')| to make sure.

    # ...

rawDescription: Python3.4 handling UTF encoded POST data


code: minimize(objective_function, x0 = (0., 0.), callback=generate_print_callback())

rawDescription: print currently evaluated params during scipy minimization

description: Print currently evaluated params during scipy minimization


code:
x1, y1 = position
x2, y2 = self.circle.center
distance = math.hypot(x1 - x2, y1 - y2)

rawDescription: Pygame circle and its associated rect for collision detection


code:
wordpower = {
        "positive": ("best" , "up" , "awesome" , "fantastic" , "happy" , "better" , "wonderful" , "good" ),
        "negative": ("worst" , "down" , "terrible" , "horrible" , "sad" , "worse" , "dreadful" , "bad" )
        }
reverse = {}
for k, v in wordpower.iteritems():
    for word in v:
        reverse[word] = k
pprint(reverse)

rawDescription: Data structure to implement reverse functionality of a dictionary


rawDescription: How to increase the performance for estimating `Pi`in Python

description: Increase the performance for estimating `Pi`in Python


code: df.groupby('nr').agg({'name': lambda x: len(x.unique())})

rawDescription: python pandas: Simplest way to perform group by and extract count of unique entities?

description: Python pandas: Simplest way to perform group by and extract count of unique entities


code:
#header file1
foo
bar

spam
eggs

python
file

rawDescription: concatenate several file remove header lines

description: Concatenate several file remove header lines


code:
def __init__(self, *args, **kwargs):
     #load the file here
     super(DmozSpider, self).__init__()
     for url in some_file:
         self.start_urls.append[url]

rawDescription: Python Scrapy project, how can I scrap 1000 pages with the same spider?


rawDescription: process.call and cmd.exe

description: Process.call and cmd.exe


code:
e = people['e']
e_in_advisor_tree_and_grad_in_1990 = [p for p in people if p.has_advisor(e) and p.year == 1990]

rawDescription: python - recursive call

description: Python - recursive call


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


code:
width = 8 #8bit width
output = [int(x) for x in '{:0{size}b}'.format(0x15,size=width)]
output = map(int, [x for x in '{:0{size}b}'.format(0x15,size=width)])

rawDescription: How do I convert an integer to a list of bits in Python

description: Convert an integer to a list of bits in Python


code:
import itertools as it
def mycombinations(iterable, r, maxGapSize):
    maxGapSizePlusOne = maxGapSize+1
    for indices in it.combinations(range(len(iterable)),r):
        previous = indices[0]
        for k in indices[1:]:
            if k-previous>maxGapSizePlusOne:
                break
            previous = k
        else:
            yield indices
            # print(indices)

rawDescription: Help with logic within generator function


code:
from lxml.etree import fromstring, tostring

data = """<FirstLevel>
    <item1>Val1</item1>
    <item2>Val2</item2>
    <item3>Val3</item3>
    <item4>Val4</item4>
    <item5>Val5</item5>
    <item1>Val1</item1>
    <item2>Val2</item2>
    <item3>Val3</item3>
    <item4>Val4</item4>
    <item5>Val5</item5>
</FirstLevel>
"""

tree = fromstring(data)

item1_list = tree.findall("item1")

for item1 in item1_list:
    next_node = item1.getnext()
    while next_node.tag != "item5":
        tree.remove(next_node)
        next_node = item1.getnext()

print(tostring(tree))

rawDescription: Deleting multiple XML elements between too elements


code: qtylist[x.finished_case] = x.qty

rawDescription: Page Refresh Disrupts Sort Order. Server Restart Restores It


code:
class Counter(object):
    def __init__(self):
        self.count = 0

    def __add__(self, incr):
        self.count += incr

    def __str__(self):
        return str(self.count)

c = Counter()
watcher = Watcher(c)
watcher.print_current_value()
# prints 0
c += 3
watcher.print_current_value()
# hooray! prints 3

rawDescription: Watching a variable in python?

description: Watching a variable in python


code: xml.xpath("//*[text()='dive into mark']", namespaces=ns)

rawDescription: remove newline and whitespace parse XML with python Xpath

description: Remove newline and whitespace parse XML with python Xpath


code:
def deepdelete(branch, keys):
    if len(keys) > 1:                                  # not at the leaf
        empty = deepdelete(branch[keys[0]], keys[1:])  # recursion
        if empty:
            del branch[keys[0]]                        # delete branch
    else:                                              # at the leaf
        del branch[keys[0]]                            # delete the leaf
    return len(branch) == 0                            # could return len

deepdelete(d, delkeys)

rawDescription: How to delete from an arbitrarilly deeply nested dictionary

description: Delete from an arbitrarilly deeply nested dictionary


rawDescription: Iterate over Python list, preserving structure of embedded lists


code:
import re

text =  "blahblahblah $%word$% blablablabla $%car$%"
words = dict(word="wassup", car="toyota")

def replacement(match):
    try:
        return words[match.group(1)]  # Lookup replacement string
    except KeyError:
        return match.group(0)  # Return pattern unchanged

pattern = re.compile(r'\$%(\w+)\$%')
result = pattern.sub(replacement, text)

rawDescription: python regex for string replacement

description: Python regex for string replacement


code:
# main.py
import Tkinter as tk
from module1 import Module1
from module2 import Module2

# create the main window; every Tkinter app needs
# exactly one instance of this class
root = tk.Tk()
m1 = Module1(root)
m1.pack(side="top", fill="both", expand=True)

# create a second window
second = tk.Toplevel(root)
m2 = Module2(second)
m2.pack(side="top", fill="both", expand=True)

# run the event loop
root.mainloop()

rawDescription: When importing modules written with tkinter and ttk, stuff doesn't work


rawDescription: Django authentication with custom user model with email-id as unique key


code:
try:
    gender=json_dict['gender']

    if gender=='male':
        gender= unicode('M')
    elif gender=='female':
        gender=unicode('F')
except:
    pass

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


code: self.Sidebar.sizer.Add(block, 0, wx.EXPAND|wx.ALIGN_LEFT|wx.BOTTOM, 5)

rawDescription: BoxSizer issue: Not expanding to fit contents of StaticText


code: from package import MyClass, my_function, my_etc

rawDescription: Django - Reusing views in different templates


code:
import re

def open_chunk(readfunc, delimiter, chunksize=1024):
    """
    http://stackoverflow.com/a/17508761/190597
    readfunc(chunksize) should return a string.
    """
    remainder = ''
    for chunk in iter(lambda: readfunc(chunksize), ''):
        pieces = re.split(delimiter, remainder + chunk)
        for piece in pieces[:-1]:
            yield piece
        remainder = pieces[-1]
    if remainder:
        yield remainder

with open('data', 'r') as infile:
    chunks = open_chunk(infile.read, delimiter=r'(PMID.*)')
    for i, (chunk, delim) in enumerate(zip(*[chunks]*2)):
        chunk = chunk+delim
        chunk = chunk.strip()
        if chunk:
            print(chunk)
            print('-'*80)
            # uncomment this if you want to save the chunk to a file named dataXXX
            # with open('data{:03d}'.format(i), 'w') as outfile:
            #     outfile.write(chunk)

rawDescription: how to split txt file to multiple file base on content

description: Split txt file to multiple file base on content


code:
from django.forms import Modelform
from django.forms.widgets import HiddenInput

class SomeForm(ModelForm):

    def __init__(self, *args, **kwargs):
        # call constructor to set up the fields. If you don't do this
        # first you can't modify fields.
        super(SomeForm, self).__init__(*args, **kwargs)

        try:
            # make somefunc return something True
            # if you can change the driver.
            # might make sense in a model?
            canchangedriver = self.instance.somefunc()
        except AttributeError:
            # unbound form, what do you want to do here?
            canchangedriver = True # for example?

        # if the driver can't be changed, use a input=hidden
        # input field.
        if not canchangedriver:
            self.fields["Drivers"].widget = HiddenInput()

    class Meta:
        model = SomeModel

rawDescription: django: exclude certain form elements based on a condition

description: Django: exclude certain form elements based on a condition


code: r'JUNE|JULY'

rawDescription: Splitting members of series using regular expressions with strings


code:
def __init__(self):
    QtGui.QMainWindow.__init__(self)
    super(DashBoard, self).__init__()

    # setup UI
    self.setupUi(self)
    self.newOrderBtn.clicked.connect(self.newOrder)

    self.soTab = []

rawDescription: Python crash when closing qmainwindow with qdialog open


code:
btn = tk.Button(...)
btn.grid(...)

rawDescription: python button change text after click

description: Python button change text after click


code: height * np.exp( - ((x-mean)/Gamma2sigma(width))**2 )

rawDescription: Making Gaussians Constrained by the FWHM


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

x = np.arange(8)
y = np.arange(6)
xx, yy = np.meshgrid(x, y)
z = xx + yy

plt.pcolormesh(x, y, z, cmap='Blues')
plt.colorbar()
plt.show()

rawDescription: Plotting a 2D histogram using x, y and a cartesian product array. (Python)


code:
import mymodule
result = mymodule.my_function(5)
# But internal functions (not imported) won't be visible...
mymodule._subfunc1(5)

rawDescription: choosing between a class or function in edge programming case

description: Choosing between a class or function in edge programming case


code:
from random import randint
import pickle
l = [randint(0, 100000) for i in range(0, 1000)]
bf = open("out.bin", "wb") # binary file
tf = open("out.txt", "w")  # ASCII file
pickle.dump(l, bf, -1) # write file with highest possible protocol (binary)
for i in l:
    tf.write(str(i) + " ")
bf.close()
tf.close()

rawDescription: Save list as file in python (The file should be accepted in other programming languages as well )


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

def fill_list(l, promt):
    while True:
        x = input(promt)
        if not x:
            break

        l.append(x)

if __name__ == '__main__':
    first_names = list()
    last_names = list()

    fill_list(first_names, "Input first name: ")
    print('first_names: {}'.format(first_names))

    fill_list(last_names, "Input last name: ")
    print('last_names: {}'.format(last_names))

    for first, last in zip(first_names, last_names):
        print('{}.{}@abc.mail.com'.format(first, last))

rawDescription: A program which creates emails

description: A program which creates emails


code:
@property
def valid(self):
    return all(self.__dict__[k] is not None for k in self.__dict__)

rawDescription: More Pythonic way of adding attributes to class?


code:
from scipy import ndimage

x = np.linspace(0,2*np.pi,100)
sine = np.sin(x)

im = sine * sine[...,None]
d1 = ndimage.gaussian_filter(im, sigma=5, order=1, mode='wrap')
d2 = ndimage.gaussian_filter(im, sigma=5, order=2, mode='wrap')

plt.figure()

plt.subplot(131)
plt.imshow(im)
plt.title('original')

plt.subplot(132)
plt.imshow(d1)
plt.title('first derivative')

plt.subplot(133)
plt.imshow(d2)
plt.title('second derivative')

rawDescription: Python finite difference functions?

description: Python finite difference functions


code: df

rawDescription: Pandas: top N rows, top N rows per group, equivalent for ROW_NUMBER OVER(PARTITION BY ... ORDER BY ...)


code:
start_ip = '100.71.9.98'
end_ip = '100.71.9.100'
map(int, start_ip.split('.'))  # list(map(int, ...))  in Python 3.x
map(int, end_ip.split('.'))

rawDescription: Verify IP string is greater or less than another IP string in python


rawDescription: Fill NaN values in dataframe with pandas


rawDescription: Using pandas fillna() on multiple columns


rawDescription: What is the most elegant way of selecting a subset of columns using pytables?


code:
def find_a_1():
    for row_i, row in enumerate(matrix):
        if '1' in row:
            return {
                'row': row_i,
                'col': row.index('1'),
            }

def walk_the_matrix(point):
    """ Clear current point and move to adjacent cells that are "1s" """
    # check if this is a valid cell to work on:
    try:
        if point['row'] < 0 or point['col'] < 0:
            raise IndexError  # prevent negative indexes
        if matrix[point['row']][point['col']] == '0':
            return  # nothing to do here, terminate this recursion branch
    except IndexError:
        return  # we're outside of the matrix, terminate this recursion branch
    # clear this cell:
    matrix[point['row']][point['col']] = '0'
    # recurse to all 8 directions:
    for i in (-1, 0, 1):
        for j in (-1, 0, 1):
            if (i, j) == (0, 0):
                continue
            walk_the_matrix({
                'row': point['row'] + i,
                'col': point['col'] + j,
            });

rawDescription: Check if matrix elements are continuous

description: Check if matrix elements are continuous


rawDescription: Inserting a variable in MongoDB specifying _id field


rawDescription: Update values in list of list of tuples

description: Update values in list of list of tuples


code:
class hello():
    def __setitem__(self, k, v):
        self.__dict__.update(zip(k, v) if type(k) is tuple else [(k, v)])

rawDescription: modify setattr to mass-assign multiple attributes to different values

description: Modify setattr to mass-assign multiple attributes to different values


code: b = subprocess.Popen("ovs-vsctl add-br '%s'" % (BR_EX, ), ...)

rawDescription: how to give raw_input to subprocess

description: Give raw_input to subprocess


code:
segments = []
# From 3 to 0.
for n in range(3, -1, -1):
    p = 256 ** n
    segments.append(str(ip_dec // p))
    ip_dec %= p
ip_dotted = '.'.join(segments)

rawDescription: Sqlalchemy change decimal IP address to dotted


rawDescription: Creating list of individual list items multiplied n times


code: data = [line.split(';') for line in open(filename)]

rawDescription: How can i split text data to a list?

description: Split text data to a list


rawDescription: Countdown function with two parameters

description: Countdown function with two parameters


rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


code: C = [(x + '*') if ((x + '*') in B) else x for x in A]

rawDescription: python lists: merge and replace

description: Python lists: merge and replace


code:
mystr = '''It's a "string"'''
mystr

rawDescription: How can I read this string if it has " and ' ? Python

description: Read this string if it has " and ' ? Python


code:
comp, dte = text2.rsplit("-",1)
print(comp,dte)
('CompanyB-XYZ', '057999_31.12.2000')

rawDescription: Split string by two conditions - wildcard


code:
from django.db.models import Q

datafilter = Q()
for i in xrange(1, now.day+1):
    datafilter = datafilter | Q(publish_date__day=i)
datafilter = datafilter & Q(publish_date__month=now.month)
posts = TodaysObject.objects.filter(datafilter)

rawDescription: Django date filter by day of month

description: Django date filter by day of month


code:
import random

userInput = input('Type roll to roll the dice!\n')

if userInput == 'roll':
    roll = random.randint(1,6)
    print('You rolled: ', roll)
elif userInput == '':
    print('Exit')

rawDescription: How do I have python run (if statements) based on the users input.?

description: Have python run (if statements) based on the users input.


code:
width = right - left + 1
height = bottom - top + 1

rawDescription: How to control the size of the Windows shell window from within a python script?

description: Control the size of the Windows shell window from within a python script


code:
if not any(t[0] == id for t in tuple_set):
    tuple_set.add((id, some_name))

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


code:
'FEDCBA'[0]
'FEDCBA'[5]

rawDescription: Generating several variable outputs without using if statements


code:
A = A[mask].reshape(5, 3)
A

rawDescription: Python: Optimize deletion of elements not aligned in a numpy array


code:
from collections import defaultdict
counts = defaultdict(int)
for (word, tag) in pos_tag(word_tokenize("John's big idea isn't all that bad.")):
    counts[tag] += 1

rawDescription: Part of speech tagging and entity recognition - python


code:
from PyQt4 import QtCore, QtGui
from pyUI import UiDialog ### your UI file, pyUI is the file name and UiDialog is the Ui Class name
import sys

class GUI(QtGui.QDialog):

    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.ui = UiDialog()
        self.ui.setupUi(self)
        self.ui.show.pressed.connect(self.populate)

    def populate(self):
        self.ui.table.setRowCount(len(all_data))
        self.ui.table.setColumnCount(4)
        self.ui.table.setHorizontalHeaderLabels(['Number', 'Keys', 'Time', 'Tries'])
        for i, item in enumerate(all_data):
            number = QtGui.QTableWidgetItem(str(item[0]))
            keys =   QtGui.QTableWidgetItem(item[1])
            time =   QtGui.QTableWidgetItem(str(item[2]))
            tries =  QtGui.QTableWidgetItem(str(item[3]))
            self.ui.table.setItem(i, 0, number)
            self.ui.table.setItem(i, 1, keys)
            self.ui.table.setItem(i, 2, time)
            self.ui.table.setItem(i, 3, tries)
        self.setWindowTitle("ANOTHER TITLE")

con = db.connect('results.db', isolation_level=None)
cur = con.cursor()
cur.execute("SELECT * FROM Results")
all_data = cur.fetchall()

app = QtGui.QApplication(sys.argv)
dailog = GUI()
dailog.show()
sys.exit(app.exec_())

rawDescription: PyQT change dynamically a QMainWindow title


code: create_tag_image(make_tags(sorted_wordscount[:],maxsize=200), 'filename.png', size=(1300,1150), background=(0, 0, 0, 255), layout=LAYOUT_MIX, fontname='Molengo', rectangular=True)

rawDescription: How to build a clean word cloud using pytagcloud without a crowded image - Python

description: Build a clean word cloud using pytagcloud without a crowded image - Python


code:
from django.views.generic.detail import DetailView
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from App.apps.event.menu import add_menu_node
from App.apps.event.models import Event

class EventMenuMixin(object):
    def get_context_data(self, **kwargs):
        context = super(EventMenuMixin, self).get_context_data(**kwargs)
        member = self.request.user

        if 'pk' in self.kwargs.keys():
            event = Event.objects.get(id=self.kwargs['pk'])
            if event.is_registered_to_event(member):
                add_menu_node(_('Unregister from this event'), reverse("unregister_from_event"))
            else:
                add_menu_node(_('Register to participate in this event'), reverse("register_to_event", args=(self.kwargs['pk'])))

        add_menu_node(_("Create new events"), reverse("admin:event_event_add"))
        return context

class EventDetailView(EventMenuMixin, DetailView):
    model = Event
    template_name = 'event/event_detail.html'
    context_object_name = 'event'

rawDescription: Get view pk from django-cms CMSAttachMenu


code: self.list.GetItem(row, col).GetText()

rawDescription: python print contents from wx.ListCtrl

description: Python print contents from wx.ListCtrl


code:
def greatest_max_iter(values):
    max_value = max(v for k, v in values)
    return (k for k, v in values if v == max_value)

rawDescription: Is there a more pythonic way of writing the following maximum-value function:


code:
def word_dict(file_path):
    with open(file_path, 'r') as input_file:
        words = {line.strip(): i for i, line in enumerate(input_file, 1)}
    return words

print(word_dict('words2.txt'))

rawDescription: For line in : not returning all lines

description: For line in : not returning all lines


code:
from __future__ import print_function
import timeit

prep_code = '''\
import random
import string
x = [''.join(random.sample(string.ascii_letters, 7)) for _ in range(10)]
y = [str(random.randint(0, 1000)) for _ in range(10)]
z = [str(random.random()) for _ in range(10)]
'''

try_method = '''\
def converter_try(vals):
    resline = []
    for item in vals:
        try:
            resline.append(int(item))
        except ValueError:
            try:
                resline.append(float(item))
            except ValueError:
                resline.append(item)

'''

re_method = '''\
import re
int_match = re.compile(r'[+-]?\d+$').match
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def converter_re(vals):
    resline = []
    for item in vals:
        if int_match(item):
            resline.append(int(item))
        elif float_match(item):
            resline.append(float(item))
        else:
            resline.append(item)

'''

fn_method = '''\
from fastnumbers import fast_real
def converter_fn(vals):
    resline = []
    for item in vals:
        resline.append(fast_real(item))

'''

print('Try with non-number strings', timeit.timeit('converter_try(x)', prep_code+try_method), 'seconds')
print('Try with integer strings', timeit.timeit('converter_try(y)', prep_code+try_method), 'seconds')
print('Try with float strings', timeit.timeit('converter_try(z)', prep_code+try_method), 'seconds')
print()
print('Regex with non-number strings', timeit.timeit('converter_re(x)', prep_code+re_method), 'seconds')
print('Regex with integer strings', timeit.timeit('converter_re(y)', prep_code+re_method), 'seconds')
print('Regex with float strings', timeit.timeit('converter_re(z)', prep_code+re_method), 'seconds')
print()
print('fastnumbers with non-number strings', timeit.timeit('converter_fn(x)', prep_code+fn_method), 'seconds')
print('fastnumbers with integer strings', timeit.timeit('converter_fn(y)', prep_code+fn_method), 'seconds')
print('fastnumbers with float strings', timeit.timeit('converter_fn(z)', prep_code+fn_method), 'seconds')
print()

rawDescription: Fast checking if a string can be converted to float or int in python


code:
from operator import eq
idx = map(eq, w1, w2).index(False)

rawDescription: Python: How to find the position of the character that makes the levenshtein distance


code: check_instance.k=6  #this works just fine.

rawDescription: using variables in class functions in another class (python)

description: Using variables in class functions in another class (python)


rawDescription: Howto NOT escape a string function parameter in python


code:
import wx

app = wx.PySimpleApp()
frame = wx.Frame(None)
btn = wx.Button(frame, -1, "anurag")
btn.Bind(wx.EVT_BUTTON, lambda e:wx.MessageBox("Wow it works"))
frame.Show()
app.SetTopWindow(frame)
app.MainLoop()

rawDescription: wxPython - How to get the ID of a widget when you passed in -1?

description: WxPython - How to get the ID of a widget when you passed in -1


code:
{
    '/api/auth/me': 'ApiController.hello',
    '/api/auth/login/guest': 'ApiController.guest_login',
    '/': 'BaseController.hello',
    '/api/auth/login/member': 'ApiController.member_login'
}

rawDescription: python recursive dictionary converting to strings

description: Python recursive dictionary converting to strings


code:
from bson.objectid import ObjectId
Document.query.get(_id=ObjectId('51e46f782b5f9411144f0efe'))

rawDescription: How to find by _id in ming?

description: Find by _id in ming


code:
import functools
import operator
add_3 = functools.partial(operator.add,3)
add_3(2)
add_3(7)

rawDescription: python pandas: apply a function with arguments to a series

description: Python pandas: apply a function with arguments to a series


code:
mod = importlib.import_module(testName)
mod.HelloWorld()

rawDescription: Import file using string as name

description: Import file using string as name


rawDescription: Numpy indexing multidimensional arrays with array and slice


code:
from collections import defaultdict
from os import path
from ntpath import basename
d = defaultdict(list)

for sub in l:
    spl = basename(sub).rsplit("-", 5)
    k = spl[0]+"-" + "-".join(spl[3:5])
    d[k].append(sub)

rawDescription: Sorting and Matching a Python list

description: Sorting and Matching a Python list


code:
def measure(n):

    m1 = np.random.normal(size=n)
    m2 = np.random.normal(size=n)
    return m1,m2

a = scipy.stats.gaussian_kde( np.vstack(measure(1000)) )
print(int1(a,-10,-10))
print(int2(a,-10,-10))
print(int1(a,0,0))
print(int2(a,-0,-0))

rawDescription: Different integration results using Monte Carlo vs scipy.integrate.nquad


rawDescription: How to effectively flip a multidimensional numpy array?

description: Effectively flip a multidimensional numpy array


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


code:
import pprint
pprint.pprint(enzimes[0])

rawDescription: Extracting a table from web with different hierarchical tags


code:
def is_categorical(array_like):
    return array_like.dtype.name == 'category'

rawDescription: Check if dataframe column is Categorical


code:
def pad_text(text, multiple):
    extra_bytes = len(text) % multiple

    padding_size = multiple - extra_bytes

    padding = chr(padding_size) * padding_size

    padded_text = text + padding

    return padded_text

def unpad_text(padded_text):
    padding_size = ord(padded_text[-1])

    text = padded_text[:-padding_size]

    return text

rawDescription: Encrypt / decrypt data in python with salt


rawDescription: Get complete list of all possible Class Attributes


code:
from flask import g

@app.before_request
def connect_data():
    # an instance is created before every request
    g.data_service = DataIO()

rawDescription: Can't access attribute set on g object in request


code: zip(*test)

rawDescription: Transpose of a Matrix

description: Transpose of a Matrix


code:
import time
import asyncio
import functools
from concurrent.futures import ProcessPoolExecutor

def do_work(loop, value):
    return loop.run_in_executor(executor, functools.partial(process_action, value))

def process_action(value):
    print("Processing %i" % value)
    time.sleep(1)
    return value

@asyncio.coroutine
def main(loop):
    tasks = [do_work(loop, i) for i in range(5)]
    for fut in asyncio.as_completed(tasks):
        result = yield from fut
        print("Success : %s" % result)

if __name__ == "__main__":
    executor = ProcessPoolExecutor(max_workers=3)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))

rawDescription: Running asyncio in two different threads to process actions on-the-fly


code:
diffs = A[:,None]-B
C = np.einsum('ijkl,ijkl->ij',diffs,diffs)

rawDescription: numpy - Computing "element-wise" difference between two arrays along first axis

description: Numpy - Computing "element-wise" difference between two arrays along first axis


code:
def compute (A, B, C1, C2):
    one = dic.get(A) if dic.get(A) else self.a(o, A)
    two = dic.get(B) if dic.get(B) else self.b(one,B)
    three = dic.get([C1,C2]) if dic.get([C1,C1]) else self.c(two, C1, C2)
    return img

rawDescription: Checking input values to methods to reduce the number of computations


code: print(key, len(filter(bool, value)))

rawDescription: Counting how many values were attributed to a key an a python (3.2) dictionary


code:
data = serializer.data
data["field"] = json_obj
return Response(data)

rawDescription: django-rest-framework: How Do I Serialize a Field That Already Contains JSON?

description: Django-rest-framework: How Do I Serialize a Field That Already Contains JSON


code:
data = struck.pack('Q', raw)
data = data[:6]  # Drop the 16 MSB

rawDescription: Float to Real48

description: Float to Real48


code:
n = 3
rdd = sc.parallelize([(4, 'a'), (12, 'e'), (2, 'u'), (49, 'y'), (6, 'p')])

rdd.sortByKey().zipWithIndex().filter(lambda xi: xi[1] < n).keys()

rawDescription: Return RDD of largest N values from another RDD in SPARK


code: from my_modules import *

rawDescription: Python: how to import from all modules in dir?


code:
import gzip
import StringIO
zippy = gzip.GzipFile(fileobj=StringIO.StringIO(data))
uncompressed_data = zippy.read()

rawDescription: Read a file in buffer from FTP python

description: Read a file in buffer from FTP python


code: l = find_text(x,y)

rawDescription: How to return elements of a list as variables?

description: Return elements of a list as variables


code:
self.agent_channel = self.transport.open_session()
self.agent_handler = paramiko.agent.AgentRequestHandler(self.agent_channel)

rawDescription: DSA key forwarding using Paramiko?

description: DSA key forwarding using Paramiko


code:
from selenium import webdriver

browser = webdriver.Firefox()
url = 'http://kmbsapps.konicaminolta.us/wheretobuy/main_search.jspx?productCategory=Office+Systems&sl_zip='

with open('1.txt') as f:
    for line in f:
        cod = line.strip()
        browser.get(url+cod)
        name = browser.find_elements_by_xpath('//tr/td/span[@class="largecol"]')
        address = browser.find_elements_by_xpath('//tr/td/span[@class="smallcol"]')
        name = [n for n in name if n.text.strip()]  # Remove empty names
        for n, a in zip(name, address):
            print(n.text, a.text)

rawDescription: please help me in lxml

description: Please help me in lxml


rawDescription: Better way to find common words in a tuple?


code:
weight ,meas = ingredientList['flour']
print(weight,meas)
(500, 'grams')

rawDescription: Python: How to store multiple values for one dictionary key


rawDescription: Numpy search for elements of an array in a subset


code:
import errno
import posix

try:
    posix.open('fifo', posix.O_WRONLY | posix.O_NONBLOCK)
except OSError as ex:
    if ex.errno == errno.ENXIO:
        pass # try later

rawDescription: Can I open a named pipe on Linux for non-blocked writing in Python?

description: Open a named pipe on Linux for non-blocked writing in Python


rawDescription: Adding 1 to a set containing True does not work


code:
import os
if os.uname()[1] == 'my.development.server.com':
    LOCAL = True
else:
    LOCAL = False

rawDescription: Most optimal way to programmatically check if site is running locally or on a server with Django?


code:
def runScript():
    script = "%s %s %s@%s %s::%s %s" %(rdiff,rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir)
    os.system(script)

rawDescription: Scripting Python for Linux commands

description: Scripting Python for Linux commands


code:
def extract(arr, start, finish):
    if start < 0 or finish > len(arr)-1:
        return "Please enter valid start/end points"
    lst = arr[start:finish]
    if len(lst) == 1:
        return lst[0]
    if len(lst) == 0:
        return 0
    num = max(lst)
    occ = lst.count(num)
    for i in range(occ):
        lst[lst.index(num):lst.index(num)+1] = ''
    return max(lst)

rawDescription: List slicing and finding second highest value python


code:
from sqlalchemy import TypeDecorator, type_coerce, String
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import BinaryExpression
import operator
class IsDistinctFrom(BinaryExpression):
    pass

@compiles(IsDistinctFrom, "postgresql")
def pg_is_distinct_from(element, compiler, **kw):
    return "%s IS DISTINCT FROM %s" % (
                    compiler.process(element.left, **kw),
                    compiler.process(element.right, **kw),
                )

@compiles(IsDistinctFrom, "mysql")
def mysql_is_distinct_from(element, compiler, **kw):
    return "%s <=> %s" % (
                    compiler.process(element.left, **kw),
                    compiler.process(element.right, **kw),
                )

class AdvancedNullComparisons(TypeDecorator):
    impl = String

    class comparator_factory(TypeDecorator.Comparator):
        def __ne__(self, other):
            expr = type_coerce(self.expr, String)
            # this step coerces a literal into a SQL expression,
            # this can be done without the private API here but the private
            # function does the most thorough job, this could also be made
            # public
            other = self._check_literal(expr, operator.ne, other)
            return IsDistinctFrom(self.expr, other, operator.ne)

rawDescription: NULL safe inequality comparisons in SQL Alchemy?


code:
C.f1
C.f1.im_func is f1

rawDescription: What is the difference between a function, an unbound method and a bound method?


code:
cmd = """echo $(date) HELLO $(date)"""
p = subprocess.Popen(["sh", "-c", cmd])

rawDescription: Passing a "shell script" as a string to Python subprocess.Popen


code:
data = {"Bob": {"Age": 20, "Hobby": "Surfing"}}
data["Bob"]["Age"]

rawDescription: Python: change value inside dual key dictionary


rawDescription: For Python 3.3, how can I make a list of functions using one lambda statement?


code: df[[ x in y.split() for x, y in zip(df.one, df.two) ]]

rawDescription: With pandas: if, in a row, a word in a column does not occur in string in other column, drop row


code:
def f(x):
    return 2*x + 5

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

description: Use index to assign address and formula to arrays


code:
class ABRed(A): __slots__='a','b'

abr=ABRed()
abr.a = abr.b = 23

rawDescription: Python: How does inheritance of __slots__ in subclasses actually work?


code: answer

rawDescription: split list into nested lists by values in a loop (iterating values)

description: Split list into nested lists by values in a loop (iterating values)


rawDescription: Regex + Python to remove specific trailing and ending characters from value in tab delimited file


code: url(r'^', include('search.urls')),

rawDescription: Logging Django Haystack search keyword

description: Logging Django Haystack search keyword


code: x.loc[index1, 3] += x.loc[index2, 2].values

rawDescription: Editing values in a pandas dataframe using data from another part of the dataframe


code:
resFoo = sm.OLS(endog=foofoo, exog=X).fit()
resBar = sm.OLS(endog=barbar, exog=X).fit()
resSpam = sm.OLS(endog=spamspam, exog=X).fit()
resham = sm.OLS(endog=hamham, exog=X).fit()

rawDescription: Linear Regression with 3 input vectors and 4 output vectors?


code:
with monkey_patched_open():
     ...

rawDescription: Best way to read file contents of a file and set to empty string if exception happen

description: Read file contents of a file and set to empty string if exception happen


code:
block =''
with open(filename, 'r') as fil:
    for line in fil:
        if line.startswith('//'):
            if block:
                do_something_with(block)
            block = line
        else:
            block += line
if block:
    do_something_with(block)

rawDescription: Do something to line and next lines until a symbol is hit


code:
from sympy import binomial, latex
sympy.init_printing(use_latex='mathjax')
n = 4
r = 2
binomial(n, r) # outputs 6

rawDescription: How to construct combinatorics expressions in Python Sympy Latex?

description: Construct combinatorics expressions in Python Sympy Latex


code:
unit_ids = ('0A1',)
cur.execute("SELECT COUNT(*) FROM test WHERE unit_id IN %s", (unit_ids,))

rawDescription: How can I prevent extra quotations being inserted into MySQLdb statement from Python?

description: Prevent extra quotations being inserted into MySQLdb statement from Python


code:
data = {}

with open('in.txt', 'r') as fh:
    for line in fh:
        if '=' not in line:
            continue
        line = line.replace('"', '')
        data[(line.split('='))[0].strip()] = (line.split('='))[1].strip()

for k, v in data.items():
    print("{}: {}".format(k, v))

rawDescription: Reading unformatted name/value pairs from a file, formatting it, and printing it out in Python 2 dictionary


code:
# How many values you want to grab for each row
x = 3

# Length of the last column in the matrix
last = len(matrix)

rawDescription: Transpose and copy column data to each row


code:
x = string("test")
x
x.sayHello()

rawDescription: Add custom method to string object

description: Add custom method to string object


rawDescription: RegEx - Find Position of last found symbol in String


code:
f1 = rownowaga(u, y)
f2 = rownowaga_numba(u_np, y_np)

rawDescription: Numba : cell vars are not supported

description: Numba : cell vars are not supported


code:
def valid_ip(addr):
    try:
        addr = addr.strip().split(".")
    except AttributeError:
        return False
    try:
        return len(addr) == 4 and all(octet.isdigit() and int(octet) < 256
                                      for octet in addr)
    except ValueError:
        return False

rawDescription: Validate IP address from list

description: Validate IP address from list


code:
import argparse
import textwrap as _textwrap
import re

class PreserveWhiteSpaceWrapRawTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
    def __add_whitespace(self, idx, iWSpace, text):
        if idx is 0:
            return text
        return (" " * iWSpace) + text

    def _split_lines(self, text, width):
        textRows = text.splitlines()
        for idx,line in enumerate(textRows):
            search = re.search('\s*[0-9\-]{0,}\.?\s*', line)
            if line.strip() is "":
                textRows[idx] = " "
            elif search:
                lWSpace = search.end()
                lines = [self.__add_whitespace(i,lWSpace,x) for i,x in enumerate(_textwrap.wrap(line, width))]
                textRows[idx] = lines

        return [item for sublist in textRows for item in sublist]

rawDescription: Python argparse.RawTextHelpFormatter with line wrap


code:
from functools import total_ordering

@total_ordering
class One:
    # ...
    def __lt__(self, other):
        if not isinstance(other, type(self)): return NotImplemented
        return self.attrOne < other.attrOne

    def __eq__(self, other):
        if not isinstance(other, type(self)): return NotImplemented
        return self.attrOne == other.attrOne

rawDescription: Get the object with the max attribute's value in a list of objects


code:
import numpy as np
import scipy.stats as sps
from scipy.spatial.distance import cdist

np.random.seed(0)

def correlateOneWithMany(one, many):
    """Return Pearson's correlation coef of 'one' with each row of 'many'."""
    pr_arr = np.zeros((many.shape[0], 2), dtype=np.float64)
    pr_arr[:] = np.nan
    for row_num in np.arange(many.shape[0]):
        pr_arr[row_num, :] = sps.pearsonr(one, many[row_num, :])
    return pr_arr

obs, varz = 10 ** 3, 500
X = np.random.uniform(size=(obs, varz))

pr = correlateOneWithMany(X[0, :], X)

c = 1 - cdist(X[0:1, :], X, metric='correlation')[0]

print(np.allclose(c, pr[:, 0]))

rawDescription: Accelerating one-to-many correlation calculations in Python


code:
@celery.task
def do_costly_database_update(some_data):
    # do stuff
    pass

# And then in a view...
do_costly_database_update.delay(some_data)

rawDescription: Using Threading to Update Database on Heroku?


code:
best_model <- h2o.getModel(auc_table@model_ids[[1]])
h2o.auc(best_model, valid = TRUE)

rawDescription: H2O R api: retrieving optimal model from grid search


code: df[df['mybool']==True]

rawDescription: basic panda questions related to slicing and aggregating tables

description: Basic panda questions related to slicing and aggregating tables


code:
import datetime
start_time = datetime.time(13, 00)
end_time = datetime.time(14, 00)
list(time_slots(start_time, end_time))

rawDescription: Create 15-min slots between two hours in Django


code:
def get_form(exclude_list):
    class MyForm(ModelForm):
        class Meta:
            model = Passenger
            exclude = exclude_list
    return MyForm

form_class = get_form(('field1', 'field2'))
form = form_class()

rawDescription: Dynamically update ModelForm's Meta class


rawDescription: Slice Array Given Range from another array in Python


code:
def AutoCorrelation(x):
    x = np.asarray(x)
    y = x-x.mean()
    result = np.correlate(y, y, mode='full')
    result = result[len(result)//2:]
    result /= result[0]
    return result

In [189]: AutoCorrelation([1,2,1,2,1,2,1,2])
Out[189]: array([ 1.   , -0.875,  0.75 , -0.625,  0.5  , -0.375,  0.25 , -0.125])

rawDescription: Statistical Scaling of autocorrelation using numpy.fft


code: y = np.minimum(y, 10.)

rawDescription: Capping linear regression prediction values using scikit


code: data.get(num) or data[min(data.keys(), key=lambda k: abs(k-num))]

rawDescription: Python: find closest key in a dictionary from the given input key


code:
ln.remove()
im.remove()

rawDescription: Matplotlib - How to remove a specific line or curve


code:
with open(save_file, "w") as outputfile:
    for line in contents.split("\n"):
       outputfile.write(line+"\n")

rawDescription: tkinter asksaveas not saving data

description: Tkinter asksaveas not saving data


code:
Celtic, general
Irish, undefined
Welsh, undefined
Hindu, undefined
Jewish, undefined
Hawaii, undefined
So. Am. Indian, Apapocuvá-Guarani
Africa, Fang

rawDescription: Using Regex to find Groups ( ) with Repeat { }


code:
old_init = thirdpartymodule_a.SomeClass.__init__
def new_init(self, *k, **kw):
    old_init(self, *k, **kw)
    self.a = 43

rawDescription: Monkey patching a class in another module in Python


rawDescription: Python Selenium: 2 buttons with same class?


code: first = lambda s: next((x for x in s if x), None)

rawDescription: Why don't Python's any/all return the found objects?


code:
search_set = set().union(searchlst1, searchlst2, searchlst3)
search_set
mainlst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
mainlst = [x for x in mainlst if x not in search_set]
mainlst

rawDescription: Check list item against multiple lists and remove if present in any of them. Python


code: request.session.modified = True

rawDescription: Django Session Variable resetting

description: Django Session Variable resetting


code:
import OSC
import time, random
client = OSC.OSCClient()
client.connect( ( '127.0.0.1', 57120 ) )
msg = OSC.OSCMessage()
msg.setAddress("/print")
msg.append(500)
client.send(msg)

rawDescription: Using supercollider with python

description: Using supercollider with python


code:
#relative_import_helper.py
import sys, os, importlib

def relative_import_helper(path,nivel=1,verbose=False):
    namepack = os.path.dirname(path)
    packs = []
    for _ in range(nivel):
        temp = os.path.basename(namepack)
        if temp:
            packs.append( temp )
            namepack = os.path.dirname(namepack)
        else:
            break
    pack = ".".join(reversed(packs))
    sys.path.append(namepack)
    importlib.import_module(pack)
    return pack

rawDescription: How to use relative import without doing python -m?

description: Use relative import without doing python -m


code:
import module1
import module2
module1.cool_func()
module2.cool_func()

rawDescription: Some confusion regarding imports in Python


code:
import bisect
candidates = []
n = 0
with open(textFile) as inFile:
    for line in inFile:
        n += 1
        if valid_candidate(line): # use regex here
            rank = get_rank(n) # use n to determine the bucket and assign a rank, lower numbers are higher rank
            bisect.insort(candidates, (rank, n, line))
results = []
for rank, n, line in candidates[:x]:
    analysisResult = analyze_the_match(line)
    results.append(analysisResult)

rawDescription: How to efficiently read lines of large text file in Python in different orders: a) random line each time, b) starting in middle...?

description: Efficiently read lines of large text file in Python in different orders: a) random line each time, b) starting in middle...


code:
hugeequal1 = [10]*30000
hugeequal2 = [10]*30000
timeit(hugeequal1, hugeequal2, 10000)

rawDescription: Is there a faster way to test if two lists have the exact same elements than Pythons built in == operator?


code:
def readfile(pathname):
    f = open(sti + '/testdata.txt')
    for line in f.readlines():
        line = line.strip()
        x, y = line.split(',')
        x, y = float(x),float(y)
        yield x, y

rawDescription: Extracting minimum and maximum x-values Python


code:
from yaml.constructor import Constructor

def add_bool(self, node):
    return self.construct_scalar(node)

Constructor.add_constructor(u'tag:yaml.org,2002:bool', add_bool)

rawDescription: PyYAML automatically converting certain keys to boolean values


code:
HeaderTablesCount = doc.Sections(1).Headers(1).Range.Tables.Count
FooterTablesCount = doc.Sections(1).Footers(1).Range.Tables.Count

rawDescription: Reading Table Contet In Header And Footer In MS-Word File Using Python


code: '{"message":"Hello there, wayfaring stranger"}'

rawDescription: Pushover Acknowlage in python

description: Pushover Acknowlage in python


rawDescription: Decimal error in list

description: Decimal error in list


rawDescription: Numpy: given a vector of 0s and 1s, how to efficiently use Numpy functions manipulate values in another array, based on 0/1 value of first array?


code:
def extract_hash_tags(s):
   return set(part[1:] for part in s.split() if part.startswith('#'))
extract_hash_tags("#test http://example.org/#comments #test")

rawDescription: Parsing a tweet to extract hashtags into an array in Python


code: a.area = 3

rawDescription: Rectangle OOP/classes

description: Rectangle OOP/classes


rawDescription: Django REST serializer: create object without saving


code:
from random import choice
def Number_recursive(N,M=None):
    M = M or N
    if N < 0:
        raise ValueError('N must be positive')
    if N == 0:
        return []
    return [[choice((0, 1)) for _ in range(M)]] + Number_recursive(N-1,M)
Number_recursive(4)

rawDescription: Recursive List containing Lists

description: Recursive List containing Lists


rawDescription: How to pass list elements as arguments

description: Pass list elements as arguments


rawDescription: How to perform functions over groupby results in pandas in python?

description: Perform functions over groupby results in pandas in python


rawDescription: How to index and automate processing of list using input csv file

description: Index and automate processing of list using input csv file


rawDescription: Use BeautifulSoup to get a value after a specific tag


code:
import itertools

def group_with_index(l):
    i = 0

    for k, vs in itertools.groupby(l):
        c = sum(1 for _ in vs)
        yield (k, c, i)
        i += c

rawDescription: Finding consecutively repeating strings in Python list


code:
def CheckUserExists(user):
    with open("C:/~/database.txt", 'r') as file:
        if re.search('^{0}$'.format(re.escape(user)), file.read(), flags=re.M):
            return True
        else:
            return False

username = input("Please enter you Username: ")
if CheckUserExists(username): # it's redundant to check if == True here
    print("You exist!")
else:
    print("This user does not exist...")

rawDescription: Check if string exists in a text file

description: Check if string exists in a text file


code: {1: {1: "Where's this?", 2: 'Yosemite, CA'}, 2: {3: 'Nice photo!'}}

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


code:
from collections import namedtuple

MySlottedClassAB = namedtuple("MySlottedClassAB", ['a', 'b'])
MySlottedClassABC = namedtuple("MySlottedClassABC", ['a', 'b', 'c'])

class MySlottedClassBA(namedtuple("MySlottedClassBA", ['b', 'a'])):
    def addAB(self):
        return self.a + self.b

msc1 = MySlottedClassAB(a=1, b=2)
msc2 = MySlottedClassBA(b=2, a=1)
msc3 = MySlottedClassABC(1, 2, 3)

print(msc1)
print(msc2)
print(msc3)
print("{} == {} is {}".format(msc1, msc1, msc1==msc1))
print("{} == {} is {}".format(msc1, msc2, msc1==msc2))
print("{} == {} is {}".format(msc1, msc3, msc1==msc3))
print("msc2.addAB() is {}".format(msc2.addAB()))

rawDescription: More Pythonic way to define custom __eq__ method using try, assert, except


code: mask = (df['date'] > start_date) & (df['date'] <= end_date)

rawDescription: Select dataframe rows between two dates

description: Select dataframe rows between two dates