code: np.clip(Mat, 0, np.inf, out=Mat)

rawDescription: python array conditional change on elements check numpy

description: Python array conditional change on elements check numpy


code:
p = pd.MultiIndex.from_product(df1.index.levels, names=df1.index.names)
df1.reindex(p, fill_value='UNKNOWN')

rawDescription: ensuring the Cartesian product of keys appears in a Pandas table

description: Ensuring the Cartesian product of keys appears in a Pandas table


code:
gpg = gnupg.GPG()
v = gpg.verify(data)
v.fingerprint

rawDescription: python-gnupg: retrieve public key of a signed message

description: Python-gnupg: retrieve public key of a signed message


code:
doc = db.collections.find_one({'_id': "12-char-mongodb-type-id"})
doc = db.collections.find_one({'_id': 12345})

rawDescription: How to have mongodb (pymongo) return _id as key value pair in response instead of object structure?

description: Have mongodb (pymongo) return _id as key value pair in response instead of object structure


code:
command_line = 'mail -s "おお様からの天気予報" abc@gmail.com < foo'
process = subprocess.Popen(command_line, shell=True)

rawDescription: Send email in python using subprocess module


code:
mylist = ["shirt","pants","shoes","tie","jacket"]

str_data ="""shirt Zara
shirt GAP
shirt Old Navy
shirt Banana_Republic
shoes Banana_Republic
shoes Zenga
shoes Zara
shoes Nike
shoes Adidas
tie Hermes
tie Ferragamo
tie Alfani
jacket Alfani
jacket Under_Armour
jacket Nike
jacket Polo
jacket The_North_Face"""

#dict list
data_dicts = [{line.split()[1]: line.split()[0]} for line in str_data.split("\n")]

clothes_matches = {}

#turn into a single dictionary
for data_dict in data_dicts:
    for key, value in data_dict.items():
        try:
            clothes_matches[key].append(value)
        except KeyError:
            clothes_matches[key] = [value]

#count the number of o occurrences for each brand
result = []
for key,value in clothes_matches.items():
    if len(value) >= 2:
        result.append(key)

print(result)

rawDescription: Return Shared Values using Python Dictionary


rawDescription: Put a symbol between every letter in a list of strings


rawDescription: python matplotlib -- regenerate graph?

description: Python matplotlib -- regenerate graph


code: df.plot(x='date', y='units')

rawDescription: Time Series Plot Python

description: Time Series Plot Python


code: it = iter(function, sentinel)

rawDescription: python: iterator from a function

description: Python: iterator from a function


code: np.nanmin(data), np.nanmax(data)

rawDescription: Python: Leave Numpy NaN values from matplotlib heatmap and its legend


code:
id(foo)
id(bar)
id(other)

rawDescription: Comparing lists by reference vs value in Python


code:
['new_option']
['new_option', 'new_option']
['new_option', 'new_option', 'new_option']

rawDescription: Mutable Default Method Arguments In Python


rawDescription: How can I find the missing value more concisely?

description: Find the missing value more concisely


code:
_global_user_data = {0: {'x': None}}
user = User(0)
user.x
user.x = -1
user.x = 1
user.x

rawDescription: Use __getattr__ instead of a getter and still have a setter?


rawDescription: Defined dict entries Python

description: Defined dict entries Python


code:
def select(lst, subselect, select):
    return [sublst[slice(*subselect)] for sublst in lst[slice(*select)]]

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
select(A, (1, 3), (0, 3))

rawDescription: python select range from list of list

description: Python select range from list of list


code: {v.lower() for v in l}

rawDescription: How to get Case Insensitive Python SET

description: Get Case Insensitive Python SET


code:
from collections import defaultdict

meta_list = defaultdict(list)

for file in files:
    with open(file, 'rb') as f:
          line_num = 1
          for line in f:
              if condition_met(line):
                  meta_list[line_num].append(float(line))
              line_num = line_num + 1

rawDescription: Python: gathering corresponding lines that meet certain condition from multiple files


code: num1,num2 = map(float, raw_input('Enter a range: ').split(','))

rawDescription: input 2 variables separated by a comma in a single line

description: Input 2 variables separated by a comma in a single line


code:
def dot(x, y):
    return sum(float(x)*y for x, y in zip(x, y))

rawDescription: How to decorate a function while adding variables in Python

description: Decorate a function while adding variables in Python


code:
from random import randint

class Cheese(object):
    def __init__(self, num_holes=0):
        "defaults to a solid cheese"
        self.number_of_holes = num_holes

    @classmethod
    def random(cls):
        return cls(randint(0, 100))

    @classmethod
    def slightly_holey(cls):
        return cls(randint(0, 33))

    @classmethod
    def very_holey(cls):
        return cls(randint(66, 100))

gouda = Cheese()
emmentaler = Cheese.random()
leerdammer = Cheese.slightly_holey()

rawDescription: Python using classmethod for multiple constructors


code:
[w for w in (''.join(c) for i in xrange(len(words)+1)
                      for c in combinations(words,i))
                              if sorted(w) == letters]
# ['DUMMYEARTH']

rawDescription: Python code that will find 2 words concatenated made out of specific letters. Letters must be used once only


code:
base, ext = os.path.splitext(os.path.basename(r'C:\abc.txt'))
base

rawDescription: Is there a function that gives me a file name without path?


code:
# this needs to be there unconditionally.
import contract
contract.checkmod(__name__)

if __name__ == '__main__':
   import doctest, GA
   doctest.testmod(GA)

rawDescription: PyContract check functions in an imported module


rawDescription: Sorting by Date string in pandas - Python 2.7


code:
import telnetlib

host    = "host.example.com"
port    = 223
timeout = 9999

try:
    session = telnetlib.Telnet(host, port, timeout)
except socket.timeout:
    print ("socket timeout")
else:
    session.write("command1\n")
    session.write("command2\n")
    output = session.read_all()
    # output now contains the text you want
    # so now you can do something with it:
    with open("test.xml", "w") as logfile:
        logfile.write(output)

rawDescription: Python 3.3 telnet issue

description: Python 3.3 telnet issue


code:
def date_range(start, end, intv):
    from datetime import datetime
    start = datetime.strptime(start,"%Y%m%d")
    end = datetime.strptime(end,"%Y%m%d")
    diff = (end  - start ) / intv
    for i in range(intv):
        yield (start + diff * i).strftime("%Y%m%d")
    yield end.strftime("%Y%m%d")

rawDescription: Given a date range how can we break it up into N contiguous sub-intervals?


Python: convert "5,4,2,4,1,0" into [[5, 4], [2, 4], [1, 0]]


code:
def get_group_pairs(grp):
    pairs = combinations(grp.index, 2)
    data = [grp.loc[p, ('Name', 'Z')].values.flatten('F') for p in pairs]
    return pd.DataFrame(data, columns=['Name1', 'Name2', 'Z1', 'Z2'])

namepairs = df.groupby('Frame').apply(get_group_pairs).reset_index(level=1, drop=True)

rawDescription: How to Process Row Pairs Preserving an ID Column without Dictionaries using Pandas?


code: [(a, b, c) for (a, b, c) in df[['LastName', 'FirstName', 'MiddleInitial']].values]

rawDescription: Using a for loop to concatenate columns in Pandas


code: [ x for x in l if x[1] == 1 ]

rawDescription: python - iterating over a subset of a list of tuples

description: Python - iterating over a subset of a list of tuples


code:
import shutil
shutil.move(src, dest)

rawDescription: How to move a file with a complicated filename in python

description: Move a file with a complicated filename in python


code:
import lxml.html as LH
import urllib2

category_url = 'http://www.localsearch.ae/en/category/Advertising-Agencies/1013'
doc = LH.parse(urllib2.urlopen(category_url))
for category in doc.xpath(
    '//div[@class="category"]|//div[@class="categories"]'):
    b = category.find('b')
    category.remove(b)
    print(LH.tostring(category))

rawDescription: Python - BeautifulSoup4 decompose() isn't working


code:
import sys
for tweet in sys.stdin:
    t, u, w = tweet.split('\t')
    if 'No Post Title' in t:
        continue
    sys.stdout.write( tweet )

rawDescription: Processing a huge file (9.1GB) and processing it faster -- Python


rawDescription: Use a colourmap to change line colour

description: Use a colourmap to change line colour


code:
{'axes.axisbelow': True,
 'axes.edgecolor': 'white',
 'axes.facecolor': '#EAEAF2',
 'axes.grid': True,
 'axes.labelcolor': '.15',
 'axes.linewidth': 0,
 'font.family': 'Arial',
 'grid.color': 'white',
 'grid.linestyle': '-',
 'image.cmap': 'Greys',
 'legend.frameon': False,
 'legend.numpoints': 1,
 'legend.scatterpoints': 1,
 'lines.solid_capstyle': 'round',
 'pdf.fonttype': 42,
 'text.color': '.15',
 'xtick.color': '.15',
 'xtick.direction': 'out',
 'xtick.major.size': 0,
 'xtick.minor.size': 0,
 'ytick.color': '.15',
 'ytick.direction': 'out',
 'ytick.major.size': 0,
 'ytick.minor.size': 0}

rawDescription: Best way to display Seaborn/Matplotlib plots with a dark iPython Notebook profile

description: Display Seaborn/Matplotlib plots with a dark iPython Notebook profile


code:
from urllib import urlencode
import urllib2

payload = {'key1': 'value1', 'key2': 'value2'}
params = urlencode(payload)
r = urllib2.urlopen('http://httpbin.org/get?' + params)

rawDescription: Python to PHP valuables

description: Python to PHP valuables


code:
from functools import wraps

def cachedProperty(name=None):
    def decorator(func):
        if decorator.name is None:
            decorator.name = func.__name__
        @wraps(func)
        def _get(self):
            try:
                return self.__dict__[decorator.name]
            except KeyError:
                value = func(self)
            self.__dict__[decorator.name] = value
            return value
        def _del(self):
            self.__dict__.pop(decorator.name, None)
        return property(_get, None, _del)
    decorator.name = name
    return decorator

rawDescription: python decorator arguments with @ syntax

description: Python decorator arguments with @ syntax


rawDescription: Using .join() in Python

description: Using .join() in Python


rawDescription: Convert an int to a CSS colour

description: Convert an int to a CSS colour


code:
def classify(iterable, condition):
    """ Returns a list that matches the condition and a list that
    does not """
    true_list = []
    false_list = []
    for item in iterable:
        if condition(item):
            true_list.append(item)
        else:
            false_list.append(item)
    return true_list, false_list

a = [1, 2, 2, 3, 4, 5]
b, a = classify(a, lambda x: x > 2)
print(a)  # [1, 2, 2]
print(b)  # [3, 4, 5]

rawDescription: Python list comprehension- "pop" result from original list?


rawDescription: Regular expression syntax in python

description: Regular expression syntax in python


code:
def finalURL(x):
    return ...

db = sqlite3.connect(...)
db.create_function("finalURL", 1, finalURL)

rawDescription: How to update the value of a specific column of every row in DB with the output of a function that was passed in the original value.

description: Update the value of a specific column of every row in DB with the output of a function that was passed in the original value.


rawDescription: How do you extract an embedded attribute value from a previous attribute value in an XPath query?

description: Extract an embedded attribute value from a previous attribute value in an XPath query


code:
from math import ceil
ceil(8.3)
ceil(8.48237)

rawDescription: controlling if the number is being rounded up or down in python

description: Controlling if the number is being rounded up or down in python


rawDescription: How to quickly used format to print a list?

description: Quickly used format to print a list


code: y = core(x)

rawDescription: Return a value from a function called in while loop


rawDescription: PyWin32 get network information/statistics


code:
#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

Builder.load_string("""
<MenuScreen>:
    GridLayout:
        cols: 1
        Button:
            text: 'HI'
            on_press: root.change()
        GridLayout:
            id: w_10
            rows:1
            Button:
                background_disabled_normal: ''
                text: '1'
                background_normal: ''
                background_color:(0.207, 0.635, 0.423, 0.9)
            Button:
                background_disabled_normal: ''
                text:'2'
                background_normal: ''
                background_color:(0.207, 0.635, 0.423, 0.9)
""")

# Declare both screens
class MenuScreen(Screen):
    def change(self):
        self.ids['w_10'].disabled = True

sm = ScreenManager()
menu = MenuScreen(name='menu')
sm.add_widget(menu)

class TestApp(App):
    def build(self):
        return sm

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

rawDescription: How to change color of disabled widget in Kivy?

description: Change color of disabled widget in Kivy


code: phonemes('abort', explain=True)

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


code: rr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)

rawDescription: Generating recurring dates using python?

description: Generating recurring dates using python


code:
import  pandas as pd
dct = {}
test = {'A': 1, '-A': 1, '-C': 1}
test2 = {'A': 1, '-A': 1, '-C': 1}
dct['key1'] = test
dct["keys2"] = test2

print(pd.DataFrame([[d.items()] for d in dct.values()]))

rawDescription: turning dictionary of of dictionary into dataframe with one row, one column of tuples

description: Turning dictionary of of dictionary into dataframe with one row, one column of tuples


code:
zap()
thing()

rawDescription: Why does foo = function() run the function in Python?


code: command: toggle_tabs

rawDescription: Sublime Text 2 shortcut for show/hide tabs


code:
from pprint import pprint
pprint(results.text)
pprint(json.loads(results.text))
pprint(json.loads(json.loads(results.text)))

rawDescription: Convert jsonString to something parseable in Python?


code:
import socket
socket.gethostbyname('google.com')
socket.gethostbyname('foo')           # no host 'foo' exists on the network

rawDescription: python: check if a hostname is resolved

description: Python: check if a hostname is resolved


code: graph_sort = sorted(graph.iteritems(), key=lambda x: x[0][0])

rawDescription: Complex Sorting - Multi Key

description: Complex Sorting - Multi Key


code:
np.all( diffs['data'] == net.blobs['data'].diff )  # >> True
np.all( diffs['conv1/7x7_s2'] == net.blobs['conv1/7x7_s2'].diff )  # >> True

rawDescription: Finding gradient of a Caffe conv-filter with regards to input


code:
def label_function():
    month = use_by.strftime('%b')
    year = use_by.strftime('%y')
    day = use_by.strftime('%d')
    return year, month, day

year, month, day = label_function()
result = year + month_code[month] + day

rawDescription: Need to convert 3 letter month code to two letter month code python


code: from compiler.ast import flatten

rawDescription: Flatten an iterable of iterables

description: Flatten an iterable of iterables


code: r, c = divmod(reindex, matrix.shape[1])

rawDescription: Sorting cells of big numpy matrices

description: Sorting cells of big numpy matrices


code:
df3 = pd.melt(df2, id_vars=['day_of_week', 'dayofmonth'], value_name='app_id')
df3

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


code:
idx = dst.argmin()
closest = a[idx]

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


code:
def foo1(annot, simi_matrix_word):
    N = annot.shape[0]
    simi_matrix_img = np.zeros((N,N))
    for i in range(N):
        for j in range(i + 1):
            if i != j:
                x_idx = np.nonzero(annot[i])[0]
                y_idx = np.nonzero(annot[j])[0]
                idx = np.ix_(x_idx, y_idx)
                # print(idx, simi_matrix_word[idx])
                score = simi_matrix_word[idx].mean()
                simi_matrix_img[i, j] = score
            else:
                simi_matrix_img[i, j] = 1.0
    return simi_matrix_img

rawDescription: How can I accelerate the array assignment in python?

description: Accelerate the array assignment in python


code:
import re
b = open ('Filter_Lines.txt','w')
with open('Lines.txt') as f:
    for line in f:
        repl = (re.sub('(D:.*\\\\)|(D:.*/)','',line).rstrip('\n'))
        b.write(repl + '\n')

b.close()

rawDescription: Remove file path with backslash (////) from a text file


code:
cursor.execute("SELECT * FROM mytable")
for row in cursor:
   do_something_with(row)

rawDescription: Retrieving Data from MySQL in batches via Python


code:
dic = {'PhysicalDrive0': ['0', '1', '2'], 'PhysicalDrive1': ['0', '1']}
dic['PhysicalDrive0'].append('3')
dic['PhysicalDrive1'].append('2')
dic

rawDescription: Python 2,7 Dictionary Advice

description: Python 2,7 Dictionary Advice


code:
i, n = symbols('i n', integer=True)
p, a = symbols('p a', cls=Function)
summation(p(a(i))*a(i), (i, 0, n))

rawDescription: Expected value with symbolic probabilities in SymPy


code: print( MaxVal.UI32 )

rawDescription: retrive minimum maximum values of a ctype

description: Retrive minimum maximum values of a ctype


code:
output[0]['query'].format(**fill)
#'SELECT DISTINCT column FROM $test_schema.$test_table'

rawDescription: Replace multiple values in dictionary in Python 3


code: d = a[..., None] + c[None, None, :]

rawDescription: copy 2D array into 3rd dimension, N times (Python)

description: Copy 2D array into 3rd dimension, N times (Python)


code: [int(i.get('x')) for i in l]

rawDescription: Python dict values to list of integers

description: Python dict values to list of integers


code: np.kron(np.eye(n), a)

rawDescription: Create block diagonal numpy array from a given numpy array


code:
def main():
    fn = "matrix1.txt"
    matrix = readMatrix(fn)
    n = int(input("Enter col number: "))
    colSum(matrix, n)

def readMatrix(fn):
    matrix = []
    with open(fn) as f: # a with block will auto close your file after the statements within it
        for line in f:
            line = line.strip() # strip off any trailing whitespace(including '\n')
            matrix.append(line.split())
    return matrix

def colSum(matrix, colNum):
    result = sum(int(row[colNum]) for row in matrix)
    print("The sum of col {} = {}".format(colNum, result))

main()

rawDescription: Python reading matrix from file

description: Python reading matrix from file


code: [i.decode("ascii") for i in re.findall(rb"[^\x00-\x1f\x7f-\xff]+", a)]

rawDescription: Pulling valid data from bytestring in Python 3


code:
from TestLibrary import Test
Test.Test1()
Test.Test2()
Test.Test3(1, 3)
Test.Test4(1, 3)
Test.Test5(1, 3)
Test.Test6(1, 3)
Test.Test7(1, 3, 5)
Test.Test8(1, 3, 5)
from System import Array
array = Array.CreateInstance(int, 10)
array
Test.Test9(1, 3, 5, array)
array

rawDescription: (Iron)Python - defining a variable of specific type


code: ' '.join(sorted(k + ':' + v for k,v in d.items()))

rawDescription: Parse a unicode string in python to a dictionary


code: field = models.CharField(max_length=200, verbose_name="your_language_here")

rawDescription: Django - how to override form template tag in html


code:
def add_to_ui(name, age):
    p = Person(name, age)
    set_of_persons.add(p) # if already there won't be re-added and it's O(1)
    persons_count[person] += 1
    # add it to the UI

rawDescription: Removing list item if not in another list - python


code:
re.search("^[a-zA-Z]\d{2}$", "S07").string
re.search("^[a-zA-Z]\d{2}$", "S07E01 - Meet the New Boss.avi") is None
re.search("^[a-zA-Z]\d{2}$", "S07E01 - Meet the New Boss.avi") is None
re.search("[a-zA-Z]\d{2}", "S07E01 - Meet the New Boss.avi").string

rawDescription: Find 1 letter and 2 numbers using RegEx

description: Find 1 letter and 2 numbers using RegEx


code:
from string import strip
[map(strip, s.split(',')) for s in industries_list]

rawDescription: How to split a python list by comma

description: Split a python list by comma


code:
def upgrade(self, attribute, value):
  if hasattr(self, attribute):
    setattr(self, attribute, getattr(self, attribute) + value )
  else:
    raise AttributeError("Can't upgrade non-existent attribute '{}'.".format(attribute))

rawDescription: Modifying a variable class attribute

description: Modifying a variable class attribute


code:
from flask import Flask, Request

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

rawDescription: Rejecting files greater than a certain amount with Flask-Uploads?


code:
from collections import defaultdict
def tree(): return defaultdict(tree)
my_dict = tree()
my_dict['foo']['bar']['spam']['egg'] = 0
my_dict

rawDescription: Correct way to edit dictionary value python


rawDescription: Pandas merge dataframes based on closest match


code: matching = [i for i, x in enumerate(my_list) if any(thing in x for thing in things_to_find)]

rawDescription: Find list index of list items within other list items


rawDescription: Get nearest time value and convert format


code:
import example
example.oldmain()

rawDescription: Python/SWIG: Output an array

description: Python/SWIG: Output an array


code:
edges = {e for p in pathDict.values() for e in zip(p[:-1],p[1:])}
oG = Graph(edges)

rawDescription: How can i optimize my graph using nx.single_source_shortest_path?

description: Optimize my graph using nx.single_source_shortest_path


code:
class User(MyResource):
    method_decorators = {
        'get': [Users.auth.login_required],
        'post': [Admin.auth.login_required]
    }

    def get(self):
        '''..etc'''

    def post(self):
        '''..etc'''

restful_api.add_resource(User,'/User')

rawDescription: flask-restful with flask-auth :multiple HTTP method with different authentication

description: Flask-restful with flask-auth :multiple HTTP method with different authentication


code:
def interleave(original, tag, replacements):
    items = original.split(tag)
    return "".join((text+repl for text,repl in zip(items, replacements+[""])))

rawDescription: How to change a string in a file to strings froma a list

description: Change a string in a file to strings froma a list


rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
def process_mother(relation_dict,name):
    #Processes the mother command
    #Returns the ouput string
    output_str = ''
    name_found = search_name(relation_dict,name)
    if not name_found:
        output_str = "person not found"
    else:
        person = find_parent(relation_dict,name)
        if person is None:
            output_str = "mother not known"
        else:
            output_str = "mother - %s" %(person)
    return output_str

def process_ancestors(relation_dict,name):
    output_str = ''
    name_found = search_name(relation_dict,name)
    if not name_found:
        output_str = "person not found"
    else:
        #Loop through to find the mother till dead - end (None) is not reached
        ancestor_list = []
        person = name
        while True:
            person = find_parent(relation_dict,person)
            if person == None:
                #Top of the ancestor found
                break
            else:
                ancestor_list.append(person)
        if ancestor_list:
            output_str = ",".join(ancestor_list)
        else:
            output_str = "No known ancestors"
    return output_str

def process_commands(commands,relation_dict):
    output = []
    for c in commands:
        coms = c.split()
        if len(coms) < 2:
            output.append("Invalid Command")
            continue
        action = coms[0]
        param = coms[1]
        if action == "mother":
            new_output = process_mother(relation_dict,param)
        elif action == "ancestors":
            new_output = process_ancestors(relation_dict,param)
        if new_output:
            output.append(new_output)
    return output

rawDescription: Looping dictionary values

description: Looping dictionary values


code:
import pexpect

process = pexpect.spawn("python")
process.expect_exact(">>> ")
process.sendline('print("It works")')
process.expect("\n.*\n")
response = process.after.strip()
print(response)

rawDescription: Using Python to send commands to a subshell


rawDescription: Fast way to read interleaved data?

description: Fast way to read interleaved data


code:
class property_writable_doc(property):
    pass

rawDescription: How to automatically document my class properties with decorators

description: Automatically document my class properties with decorators


code:
with get_store('test.h5',mode='w',complib='blosc',complevel=9) as store:
    store.put('test',df)

rawDescription: Pandas sparse dataframe larger on disk than dense version


code:
n=5
np.array(zip(*(A[i:] for i in range(n))))

rawDescription: Consecutive, Overlapping Subsets of Array (NumPy, Python)


code:
seen_items = set()
filtered_dictlist = (x for x in dict_list if (x["id"],x["type"]) not in seen_items and not seen_items.add((x["id"],x["type"])))
sorted(filtered_dictlist,key=lambda x:(x["type"],x["id"]),reverse=True)

rawDescription: How to sort dict list with multiple key attributes - python

description: Sort dict list with multiple key attributes - python


code:
@classmethod
def get_status_list(self):
    status_list = Status.objects.all().values_list('id', 'status')
    status_list.insert(0, ('', 'no selected'))
    return status_list

rawDescription: how to fill out the form initial data?

description: Fill out the form initial data


code: trees = log.findall('element1') or log.findall('element2')

rawDescription: Can .findall() match multiple values in python etree?


code:
pfuncExtB = POINTER(FUNC).in_dll(mutdll,'pfuncExtB')
pfuncExtB.contents(1,2) # exception!

rawDescription: Assigning Python function to ctypes pointer variable


code:
f=open("file.txt")
a=f.read()
f.close()

rawDescription: How to release memory after replacing big data in python?

description: Release memory after replacing big data in python


code:
if extern_key.startswith(b('ssh-dss ')):
    # This is probably a public OpenSSH key
    keystring = binascii.a2b_base64(extern_key.split(b(' '))[1])
    keyparts = []
    while len(keystring) > 4:
        length = struct.unpack(">I", keystring[:4])[0]
        keyparts.append(keystring[4:4 + length])
        keystring = keystring[4 + length:]
    if keyparts[0] == b("ssh-dss"):
        tup = [bytes_to_long(keyparts[x]) for x in (4, 3, 1, 2)]
        return self.construct(tup)

rawDescription: Validating a DSA key pair with pycrypto ( getting pqg values )


code:
import os
os.system('cls')

rawDescription: Is there a way to clear your printed text in python?


code:
for name, prop in props.iteritems():
    value = prop.GetValue()
    value[0][0] = random()
    value[1][0] = random()
    value[2][0] = random()
pg.Refresh()

rawDescription: Dramatic memory leak in wxpython application


code: bin(data).count('1') % 2

rawDescription: How to xor hex value in Python (1 bit answer)

description: Xor hex value in Python (1 bit answer)


code:
def on_pick(evt):
    if evt.artist is lines:
        ind = evt.ind[0]
        selected[:] = 0
        selected[ind] = 1
        lines.set_color(normal_selected_color[selected])
        fig.canvas.draw_idle()

rawDescription: how to highlight line collection in matplotlib

description: Highlight line collection in matplotlib


code:
X
Y
t

rawDescription: Numpy array, removing one arbitrary element per row


code:
import matplotlib.pyplot as plt

#First normal figure
fig, axarr = plt.subplots(2,2, figsize=(6,6))
for i,ax in enumerate(axarr.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=10)
    ax.set_xlabel('x'+str(i), fontsize=10)
    ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()
plt.savefig('myfigure_100.png', dpi=100)
plt.savefig('myfigure_200.png', dpi=200)

rawDescription: Adjusting figure quality in matplotlib

description: Adjusting figure quality in matplotlib


code: replacepattern = r'\g<1>' + os.getcwd().encode('unicode_escape').decode('ascii')

rawDescription: Python 3: How can I get os.getcwd() to play nice with re.sub()?


code:
command = "C:\\progra~1\\itms\\iTMSTransporter.cmd -m verify -f D:\\TEMP -u username -p password -o D:\\TEMP\\LOGFILE.txt -s provider -v eXtreme"
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
if slotNumber == 1:
    self.process1 = Popen(command, startupinfo=startupinfo, shell=False)
elif slotNumber == 2:
    self.process2 = Popen(command, startupinfo=startupinfo, shell=False)
elif slotNumber == 3:
    self.process3 = Popen(command, startupinfo=startupinfo, shell=False)
elif slotNumber == 4:
    self.process4 = Popen(command, startupinfo=startupinfo, shell=False)

rawDescription: Popen process not quitting / releasing when finished in Python


code: Term("index","<=",stamp)

rawDescription: Missing one value when retrieving Pandas DataFrame from HDFStore using select with terms on DateTimeIndex


code:
if 'token' in canvas.gettags(canvas.find_withtag('current')):
    canvas.delete('current')

rawDescription: Capability to delete all items with certain object tag tkinter


code:
B.attribute[6]
# KeyError

rawDescription: Best practice: update/extend subclass class attribute


code:
import Tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.createWidgets()

    def createWidgets(self):
        self.outputbox = tk.Text()
        self.outputbox["width"] = 20
        self.outputbox["height"] = 1
        self.outputbox.grid()
        self.outputbox.bind('<Return>', self.FireonEnter)

    def FireonEnter(self, event):
        print('Enter pressed')

root = tk.Tk()
app = Application(root)
root.mainloop()

rawDescription: Python Tkinter: textfield enter command

description: Python Tkinter: textfield enter command


code: gen = (d * v for d, v in zip(data, flag))

rawDescription: Grouping 0s and 1s in python

description: Grouping 0s and 1s in python


rawDescription: max row sequence from sorted list for each index

description: Max row sequence from sorted list for each index


code:
def get_conn(self):
    if self.conn is None:
        self.conn = MySQLdb.connect(host = self.host,
                                    port = self.port,
                                    db = self.name,
                                    user = self.user,
                                    passwd = self.password)
    return self.conn

rawDescription: Writing an object-oriented MySQLdb connection


code:
dict3['fx245']
name, num = dict3['fx245']
name
num

rawDescription: How to mixing two dictionaries in Python?

description: Mixing two dictionaries in Python


code: [{'k': c, 'v': c if c in other_list else 0} for c in correct_list]

rawDescription: Python lists comparing and merging

description: Python lists comparing and merging


code:
pylab.ion()
x = np.linspace(0, 10, 1000)
y = np.sin(x)
pylab.plot(x, y)

rawDescription: pylab.show() forgets previous plots

description: Pylab.show() forgets previous plots


code:
from nltk.tokenize import PunktSentenceTokenizer
from nltk.corpus import reuters
pst = PunktSentenceTokenizer()
pst.train(reuters.raw())
text = "Batts did not take questions or give details of the report's findings... He did say that the city's police department would continue to work on the case under the direction of the prosecutor's office. Gray was injured around the time he was arrested by Baltimore police and put in a police van on 12 April."
print(pst.sentences_from_text(text))

rawDescription: NLTK PunktSentenceTokenizer ellipsis splitting


rawDescription: Numpy find indices of matching columns

description: Numpy find indices of matching columns


code: DataFrame([ aa[0:4], aa[5:8] ],columns=list('ABCD'))

rawDescription: Appending Tuples to Pandas DataFrame

description: Appending Tuples to Pandas DataFrame


code:
buf, offset = b'', 0
with open('myfile.bin', 'rb') as f:
    if len(buf) < record.size:
        buf, offset = buf[offset:] + f.read(8192), 0
        if not buf:
            break
    yield record.unpack_from(buf, offset)
    offset += record.size

rawDescription: Can someone explain Python struct unpacking?


code: msg.attach(MIMEText(text, 'html'))

rawDescription: sendmail with HTML message

description: Sendmail with HTML message


code:
__builtins__.vars
__builtins__.vars()

rawDescription: How to see the "hidden" python built-in?

description: See the "hidden" python built-in


code:
## Handle GET requests
mapper.connect("/user", controller=user_controller, action="get_user", conditions=dict(method=["GET"]))
## Handle all other, non-GET requests
mapper.connect("/user", controller=user_controller, action="add_user")

rawDescription: Python Routes, giving request method

description: Python Routes, giving request method


code:
category = soup.find("ol", {"class":"breadcrumb"}).findAll('li')[1:]
catname = BeautifulSoup(str(category).strip()).get_text().encode("utf-8")

rawDescription: BeautifulSoup: Get generic tags from a specific class only


code: [i for i in os.listdir('.') if os.path.splitext(i)[1] in ('.png','.jpg','.jpeg')]

rawDescription: Python logical or operator acting strange


code:
import subprocess
subprocess.call([ 'ssh', 'localhost', 'echo $(hostname)'])

rawDescription: How to escape ssh quoted shell commands in Python

description: Escape ssh quoted shell commands in Python


code:
from PyQt4 import QtCore, QtGui, Qt

class QRoundProgressBar(QtGui.QWidget):

    StyleDonut = 1
    StylePie = 2
    StyleLine = 3

    PositionLeft = 180
    PositionTop = 90
    PositionRight = 0
    PositionBottom = -90

    UF_VALUE = 1
    UF_PERCENT = 2
    UF_MAX = 4

    def __init__(self):
        super().__init__()
        self.min = 0
        self.max = 100
        self.value = 25

        self.nullPosition = self.PositionTop
        self.barStyle = self.StyleDonut
        self.outlinePenWidth =1
        self.dataPenWidth = 1
        self.rebuildBrush = False
        self.format = "%p%"
        self.decimals = 1
        self.updateFlags = self.UF_PERCENT
        self.gradientData = []
        self.donutThicknessRatio = 0.75

    def setRange(self, min, max):
        self.min = min
        self.max = max

        if self.max < self.min:
            self.max, self.min = self.min, self.max

        if self.value < self.min:
            self.value = self.min
        elif self.value > self.max:
            self.value = self.max

        if not self.gradientData:
            self.rebuildBrush = True
        self.update()

    def setMinimun(self, min):
        self.setRange(min, self.max)

    def setMaximun(self, max):
        self.setRange(self.min, max)

    def setValue(self, val):
        if self.value != val:
            if val < self.min:
                self.value = self.min
            elif val > self.max:
                self.value = self.max
            else:
                self.value = val
            self.update()

    def setNullPosition(self, position):
        if position != self.nullPosition:
            self.nullPosition = position
            if not self.gradientData:
                self.rebuildBrush = True
            self.update()

    def setBarStyle(self, style):
        if style != self.barStyle:
            self.barStyle = style
            self.update()

    def setOutlinePenWidth(self, penWidth):
        if penWidth != self.outlinePenWidth:
            self.outlinePenWidth = penWidth
            self.update()

    def setDataPenWidth(self, penWidth):
        if penWidth != self.dataPenWidth:
            self.dataPenWidth = penWidth
            self.update()

    def setDataColors(self, stopPoints):
        if stopPoints != self.gradientData:
            self.gradientData = stopPoints
            self.rebuildBrush = True
            self.update()

    def setFormat(self, format):
        if format != self.format:
            self.format = format
            self.valueFormatChanged()

    def resetFormat(self):
        self.format = ''
        self.valueFormatChanged()

    def setDecimals(self, count):
        if count >= 0 and count != self.decimals:
            self.decimals = count
            self.valueFormatChanged()

    def setDonutThicknessRatio(self, val):
        self.donutThicknessRatio = max(0., min(val, 1.))
        self.update()

    def paintEvent(self, event):
        outerRadius = min(self.width(), self.height())
        baseRect = QtCore.QRectF(1, 1, outerRadius-2, outerRadius-2)

        buffer = QtGui.QImage(outerRadius, outerRadius, QtGui.QImage.Format_ARGB32)
        buffer.fill(0)

        p = QtGui.QPainter(buffer)
        p.setRenderHint(QtGui.QPainter.Antialiasing)

        # data brush
        self.rebuildDataBrushIfNeeded()

        # background
        self.drawBackground(p, buffer.rect())

        # base circle
        self.drawBase(p, baseRect)

        # data circle
        arcStep = 360.0 / (self.max - self.min) * self.value
        self.drawValue(p, baseRect, self.value, arcStep)

        # center circle
        innerRect, innerRadius = self.calculateInnerRect(baseRect, outerRadius)
        self.drawInnerBackground(p, innerRect)

        # text
        self.drawText(p, innerRect, innerRadius, self.value)

        # finally draw the bar
        p.end()

        painter = QtGui.QPainter(self)
        painter.drawImage(0, 0, buffer)

    def drawBackground(self, p, baseRect):
        p.fillRect(baseRect, self.palette().background())

    def drawBase(self, p, baseRect):
        bs = self.barStyle
        if bs == self.StyleDonut:
            p.setPen(QtGui.QPen(self.palette().shadow().color(), self.outlinePenWidth))
            p.setBrush(self.palette().base())
            p.drawEllipse(baseRect)
        elif bs == self.StylePie:
            p.setPen(QtGui.QPen(self.palette().base().color(), self.outlinePenWidth))
            p.setBrush(self.palette().base())
            p.drawEllipse(baseRect)
        elif bs == self.StyleLine:
            p.setPen(QtGui.QPen(self.palette().base().color(), self.outlinePenWidth))
            p.setBrush(Qt.Qt.NoBrush)
            p.drawEllipse(baseRect.adjusted(self.outlinePenWidth/2, self.outlinePenWidth/2, -self.outlinePenWidth/2, -self.outlinePenWidth/2))

    def drawValue(self, p, baseRect, value, arcLength):
        # nothing to draw
        if value == self.min:
            return

        # for Line style
        if self.barStyle == self.StyleLine:
            p.setPen(QtGui.QPen(self.palette().highlight().color(), self.dataPenWidth))
            p.setBrush(Qt.Qt.NoBrush)
            p.drawArc(baseRect.adjusted(self.outlinePenWidth/2, self.outlinePenWidth/2, -self.outlinePenWidth/2, -self.outlinePenWidth/2),
                      self.nullPosition * 16,
                      -arcLength * 16)
            return

        # for Pie and Donut styles
        dataPath = QtGui.QPainterPath()
        dataPath.setFillRule(Qt.Qt.WindingFill)

        # pie segment outer
        dataPath.moveTo(baseRect.center())
        dataPath.arcTo(baseRect, self.nullPosition, -arcLength)
        dataPath.lineTo(baseRect.center())

        p.setBrush(self.palette().highlight())
        p.setPen(QtGui.QPen(self.palette().shadow().color(), self.dataPenWidth))
        p.drawPath(dataPath)

    def calculateInnerRect(self, baseRect, outerRadius):
        # for Line style
        if self.barStyle == self.StyleLine:
            innerRadius = outerRadius - self.outlinePenWidth
        else:    # for Pie and Donut styles
            innerRadius = outerRadius * self.donutThicknessRatio

        delta = (outerRadius - innerRadius) / 2.
        innerRect = QtCore.QRectF(delta, delta, innerRadius, innerRadius)
        return innerRect, innerRadius

    def drawInnerBackground(self, p, innerRect):
        if self.barStyle == self.StyleDonut:
            p.setBrush(self.palette().alternateBase())

            cmod = p.compositionMode()
            p.setCompositionMode(QtGui.QPainter.CompositionMode_Source)

            p.drawEllipse(innerRect)

            p.setCompositionMode(cmod)

    def drawText(self, p, innerRect, innerRadius, value):
        if not self.format:
            return

        text = self.valueToText(value)

        # !!! to revise
        f = self.font()
        # f.setPixelSize(innerRadius * max(0.05, (0.35 - self.decimals * 0.08)))
        f.setPixelSize(innerRadius * 1.8 / len(text))
        p.setFont(f)

        textRect = innerRect
        p.setPen(self.palette().text().color())
        p.drawText(textRect, Qt.Qt.AlignCenter, text)

    def valueToText(self, value):
        textToDraw = self.format

        format_string = '{' + ':.{}f'.format(self.decimals) + '}'

        if self.updateFlags & self.UF_VALUE:
            textToDraw = textToDraw.replace("%v", format_string.format(value))

        if self.updateFlags & self.UF_PERCENT:
            percent = (value - self.min) / (self.max - self.min) * 100.0
            textToDraw = textToDraw.replace("%p", format_string.format(percent))

        if self.updateFlags & self.UF_MAX:
            m = self.max - self.min + 1
            textToDraw = textToDraw.replace("%m", format_string.format(m))

        return textToDraw

    def valueFormatChanged(self):
        self.updateFlags = 0;

        if "%v" in self.format:
            self.updateFlags |= self.UF_VALUE

        if "%p" in self.format:
            self.updateFlags |= self.UF_PERCENT

        if "%m" in self.format:
            self.updateFlags |= self.UF_MAX

        self.update()

    def rebuildDataBrushIfNeeded(self):
        if self.rebuildBrush:
            self.rebuildBrush = False

            dataBrush = QtGui.QConicalGradient()
            dataBrush.setCenter(0.5,0.5)
            dataBrush.setCoordinateMode(QtGui.QGradient.StretchToDeviceMode)

            for pos, color in self.gradientData:
                dataBrush.setColorAt(1.0 - pos, color)

            # angle
            dataBrush.setAngle(self.nullPosition)

            p = self.palette()
            p.setBrush(QtGui.QPalette.Highlight, dataBrush)
            self.setPalette(p)

rawDescription: Any PyQt circular progress bar?

description: Any PyQt circular progress bar


code:
def drawarcsincurve(amplitude, period, horShift, verShift):
    plot_scale = 100 # Arbitrary value - up to you - similar to "zoom"
    turtle.speed(1)
    turtle.penup()
    startPoint = -1
    turtle.goto(plot_scale*startPoint, plot_scale*math.asin(startPoint))
    turtle.pendown()
    for angles in range(-100,100):
        sinval = 1.0 * angles / 100 # this will run -1 to 1 in 0.01 steps
        y = math.asin(sinval)
        turtle.goto(plot_scale*sinval,plot_scale*y)

rawDescription: Zoom function in python? (2.7.9)

description: Zoom function in python? (2.7.9)


rawDescription: Avoiding bias in randomly generated subtraction problems


code:
def vals(x):
    if isinstance(x, dict):
        result = []
        for v in x.values():
            result.extend(vals(v))
        return result
    else:
        return [x]

rawDescription: Get final elements of nested dictionary in Python


rawDescription: How to save and load an array of complex numbers using numpy.savetxt?

description: Save and load an array of complex numbers using numpy.savetxt


code:
import re

abb_pattern = re.compile(r'^ABB+$')

def has_abb(string):
    return abb_pattern.match(string) is not None

rawDescription: Checking a String's format

description: Checking a String's format


code:
class MetaBase(type):
    definitions = {}
    def __init__(cls, name, bases, dct):
        for attr in dct.keys():
            cls.__class__.definitions[attr] = cls

class parent(metaclass=MetaBase):
    findMe = 5
    def __init__(self):
        print(self.__class__.definitions["findMe"])

rawDescription: How can one locate where an inherited variable comes from in Python?


code: TempClass.counterInit = max(Database.xoomDatabase, key = lambda x:x['Num Orden'])

rawDescription: Setting up a counter to know in which number to start


rawDescription: How to get unknown local variable to other namespace

description: Get unknown local variable to other namespace


code:
class gmres_counter(object):
    def __init__(self, disp=True):
        self._disp = disp
        self.niter = 0
    def __call__(self, rk=None):
        self.niter += 1
        if self._disp:
            print('iter %3i\trk = %s' % (self.niter, str(rk)))

rawDescription: Getting the number of iterations of scipy's gmres iterative method


code: data = pd.read_csv('PIRDATA.csv', index_col=0, parse_dates=0)

rawDescription: How do create a step chart in Pandas with time series data from two seperate data sources


code: ones = df['one'].value_counts()

rawDescription: Convert a list of timestamped state columns into a time-indexed list for each state during that time, as told with Chutes and Ladders


code: obj_2 = type (obj)(2)

rawDescription: Creating copy of arbitrary object in Python and calling constructor


rawDescription: Parsing data from JSON file using Python


code:
def f(a): # whatever arguments you like
    return a

# create a bunch of functions that return f(x)
flist = [functools.partial(f, x) for x in range(5)]

def g(a, b):
    return a + b

# create a bunch of functions that take a single argument (b), but have a set to
# 0..4:
flist = [functools.partial(g, x) for x in range(5)]

some_g = flist[0]
some_g(1) # returns 0 + 1

rawDescription: Function name is not reusable (python)

description: Function name is not reusable (python)


rawDescription: Dropping values from a list of tuples

description: Dropping values from a list of tuples


rawDescription: Python 3.5 for OS X El Capitan

description: Python 3.5 for OS X El Capitan


code:
string_version = repr(''.join(map(chr, S)))
# print, copy, paste, etc.
list_version = list(map(ord, ast.literal_eval(string_version)))

rawDescription: Clean conversion from int list to character and then back to int list, in Python


code:
class Parent(object):

    V_1 = set()
    V_2 = set()

    @property
    def ALL_V_ELEMENTS(self):
       return V_1 | V_2

rawDescription: Class variable V3 dependent on V1 and V2. How to define V3 in children classes


code:
import numpy as np

def ndim_interp(A, ranges, p):
    # A: array with n dimensions
    # ranges: list of n lists or numpy arrays of values along each dimension
    # p: vector of values to find (n elements)

    # iterate through all dimensions
    for i in range(A.ndim):
        # check if we are overrange; if we are, use the edgemost values
        if p[i] <= ranges[i][0]:
            A = A[0]
            continue
        if p[i] >= ranges[i][-1]:
            A = A[-1]
            continue

        # find the nearest values
        right = np.searchsorted(ranges[i], p[i])
        left = right - 1

        # find the relative distance
        d = (p[i] - ranges[i][left]) / (ranges[i][right] - ranges[i][left])

        # calculate the interpolation
        A = (1 - d) * A[left] + d * A[right]

    return A

rawDescription: How to interpolate using nearest neighbours for high dimension numpy python arrays

description: Interpolate using nearest neighbours for high dimension numpy python arrays


rawDescription: Numpy vectorization for nearest neighbor calculation in semi-sparse arrays


code:
import pandas as pd
import numpy as np
import pprint

arrays = [np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4]),
          np.array([1, 2, 3, 1, 2, 1, 2, 3, 4, 5, 1, 2])]

df = pd.DataFrame(np.arange(24).reshape(12,2),
                  index=arrays, columns=['Longitude', 'Lattitude'])

dd = {"type":"Feature",
      "geometry":{"type":"Linestring",
                  "coordinates":None
                 },
      "properties":{"prop0":'red',
                    "prop1":'dashed'
                   }
     }

for _, group in df.groupby(level=0):
    dd["geometry"]["coordinates"] = group.to_json(orient='values')
    pprint.pprint(dd)

rawDescription: How to write a Python loop to convert a large amount of coordinates into the GeoJSON LineString format?

description: Write a Python loop to convert a large amount of coordinates into the GeoJSON LineString format


code: package_dir = {'': 'src'}

rawDescription: Is it really possible to use a different convention to lay out source directory without breaking intra-package references?


rawDescription: reshaping ndarrays versus regular arrays in numpy?

description: Reshaping ndarrays versus regular arrays in numpy


code:
from scipy.linalg import qr

def qr_null(A, tol=None):
    Q, R, P = qr(A.T, mode='full', pivoting=True)
    tol = np.finfo(R.dtype).eps if tol is None else tol
    rnk = min(A.shape) - np.abs(np.diag(R))[::-1].searchsorted(tol)
    return Q[:, rnk:].conj()

Z = qr_null(A)

rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
@periodic_task(run_every=crontab(minute="*/5"))
def PeriodicUpdateStockItems():
    """
    A task to add Stock items to the stockstets table and to update the stock_sets_id in the sims table
    """
    res = Session.query(
        Sims.purchase_order, func.count(Sims.iccid), Sims.create_stamp, Sims.status, Sims.network
    ).filter(
        Sims.stock_sets_id == None
    ).filter(
        Sims.purchase_order != None
    ).group_by(Sims.purchase_order).first()
    log.debug(res)
    stock_sets_id = None
    if res:
        stockset = Session.query(
            StockSets.id
        ).filter(
            StockSets.purchase_order == res.purchase_order
        ).first()
        if not stockset:
            stockset = StockSets()
            stockset.purchase_order = res.purchase_order
            stockset.sim_count = res[1]
            stockset.create_stamp = res.create_stamp
            stockset.status = res.status
            stockset.network = res.network
            Session.add(stockset)
            transaction.savepoint()
            stock_sets_id = stockset.id
            log.debug(stock_sets_id)
            transaction.commit()
        else:
            stock_sets_id = stockset.id
            log.debug(stock_sets_id)
        Session.query(
            Sims
        ).filter(
            Sims.purchase_order == res.purchase_order
        ).update(
            {'stock_sets_id': stock_sets_id}
        )
        transaction.commit()

rawDescription: Prevent duplication with SQLAlchemy query


code:
#!/usr/bin/env python3
from re import match
from collections import namedtuple
from pprint import pprint
from random import choice

Mail = namedtuple('Mail', 'subject, body')

def parseMails(filename):
    mails = {}
    with open(filename) as f:
        index = ''
        subject = ''
        body = ''
        for line in f:
            m = match(r'^\[(.+)\]$', line)
            if m:
                if index:
                    mails[index] = Mail(subject, body)
                index = m.group(1)
                body = ''
            elif line.startswith('Subject: '):
                subject = line[len('Subject: '):-1]
            else:
                body += line[len('Body: '):]
        else:
            mails[index] = Mail(subject, body)
    return mails

mails = parseMails('mails.txt')
index = choice(list(mails.keys()))
mail = mails[index]
pprint(mail)

rawDescription: Python: Email content configuration file


rawDescription: Pandas: How to edit values in a column

description: Pandas: How to edit values in a column


code:
import urllib

query = """http://phx01.companyA.com:8000/?query={query}&country_id=1&lang_id=1&linkin_id=8073631&sbh_id=120555,1&weight_group_id=80&request_id=p20.b6894b85df2f81d54003&brand_id=14623&request_type=SRS"""

value = "kindle fire"
query = query.format(query=urllib.quote_plus(value))

rawDescription: URL call with string keyword substitution


code:
def initiate(n):
    return [ {'num': i, 'blah': 0, 'doubleblah': 0} for i in range(n) ]

rawDescription: Weird Extra Looping

description: Weird Extra Looping


code: [t for testrec in testrecord for t in testrec['testdata'] if t.get('color') == 'green']

rawDescription: Nested list of dicts comprehension syntax


code:
players = addplayers(playerlist)
print(players[0])

rawDescription: Function adding objects to a class through a list - calling objects


code:
# make a dict keyed on the filename before the extension
# with the other two fields as its value
file2dict = dict((row[0][:-4], row[1:])
                     for row in (line.split() for line in file2))

# then add to the end of each row
# the values to it's first column
output = [row + file2dict[row[0]] for row in (line.split() for line in file1)]

rawDescription: How to combine lines in two files with condition in python?

description: Combine lines in two files with condition in python


code:
regex = r'^home/(?P<text>(.){10})$'
re.search(regex, "home/1@#$%^& &*").group(1)
re.search(regex, "home/1@bcd^& &*").group(1)

rawDescription: Django URL matching any 140 characters

description: Django URL matching any 140 characters


code:
fieldnames = [ 'field%s' % (i, ) for i in range(1, 11) ]
for part in parts:
     existing_part = Part.objects.get(pk=part.pk)
     for fn in fieldnames:
          self.assertEqual(getattr(existing_part, fn),
                           getattr(part,          fn),
                           "Problem in part %s field %s" % (part.pk, fn))

rawDescription: writing test for importing contents of text file into database using python and django

description: Writing test for importing contents of text file into database using python and django


code:
max(int(link.text)
    for link in soup.find('div', class_='pagination').find_all('a')
    if link.text.strip().isdigit())

rawDescription: List comprehension to return highest value


rawDescription: How to show a png image in Gtk3 with Python?

description: Show a png image in Gtk3 with Python


code:
from fabric.api import env, run, local, cd

env.hosts = ['other_host']

def setenv(foo):
    env.hosts = ['myhost']

def mycmd(foo):
    setenv(foo)
    print('env.hosts inside mycmd: %s' % env.hosts)
    run('ls')

rawDescription: How can I properly set the `env.hosts` in a function in my Python Fabric `fabfile.py`?

description: Properly set the `env.hosts` in a function in my Python Fabric `fabfile.py`


code:
a = 0
def f():
    global a
    a += 10

rawDescription: Explanation of program's behavior (Python)


code:
class Bar(Base):
    __tablename__ = "bar"
    __table_args__ = (UniqueConstraint("baz", "qux"),)

    id = Column(Integer, primary_key=True)
    baz = Column(Integer, ForeignKey("foo.id"))
    qux = Column(Integer, ForeignKey("foo.id"))

class Cruft(Base):
    __tablename__ = "cruft"
    __table_args__ = (UniqueConstraint("bar", "qux"),)

    id = Column(Integer, primary_key=True)
    bar = Column(Integer, ForeignKey("foo.id"))
    qux = Column(Integer, ForeignKey("foo.id"))

rawDescription: SQLAlchemy not producing proper SQL statement for multi column UniqueConstraints


code:
def reorient(x, y, z):
    xyz = np.vstack([x.ravel(), y.ravel(), z.ravel()])
    cov = np.cov(xyz)

    # Find the eigenvectors of the covariance matrix
    vals, vecs = np.linalg.eigh(cov)
    idx = np.argsort(vals)
    # The eigenvalues vals are not needed below, but this puts them in
    # the same order as the eigenvectors, should they be needed in future
    # versions of this code:
    vals, vecs = vals[idx], vecs[:, idx]

    # In this case, we actually want the second eigenvector to be the x-axis
    vecs = vecs[:, [1, 0, 2]]

    # Now let's perform a change-of-basis into the new coordinate system
    return np.linalg.inv(vecs).dot(xyz)

rawDescription: Finding the opening of a 3D surface

description: Finding the opening of a 3D surface


code:
my_list = range(10)
my_list
my_list[::2]
my_list[1::2]

rawDescription: Access certain elements of a list

description: Access certain elements of a list


rawDescription: Converting column from int64 to datetime in hdf5 file using Python's Pandas package


code:
datafile = open(b'C:\Users\j\Desktop\helloworld.csv', 'r')
data = []
for row in datafile:
   data.extend(row.strip().split())
print(data)

rawDescription: Create a column from a CSV list in Python 3


code: x(*chain.from_iterable((f(month), g(month)) for month in months))

rawDescription: Python: How to pass functions to another function as arguments?


rawDescription: stretch, scale, or double up an array with numpy?

description: Stretch, scale, or double up an array with numpy


code:
@cache.cached(timeout=50)
def index():
    return render_template('index.html')

rawDescription: Using render_templete and static file, which one is faster in Flask


code:
class DomTreeItem(TreeItem):
   def __init__(self, node, dbl_click_bindings = None):
      self.node = node
      self.dbl_click_bindings = [] if (dbl_click_bindings == None) else dbl_click_bindings

   [...]
   def OnDoubleClick(self):
      self.fireDblClick()

   def bind(self, event, callback):
      '''mimic tkinter bind
      '''
      if (event != "<<TreeDoubleClick>>"):
         print("err...")
      self.dbl_click_bindings.append(callback)
   def fireDblClick(self):
      for callback in self.dbl_click_bindings:
         callback.double_click(self.GetText())

rawDescription: Python Tkinter: Tree selection

description: Python Tkinter: Tree selection


code:
game = {'weight': 5, 'color': 'blue'}
G.add_edge(white, black, **game)

rawDescription: what is the signification of ** in python (when not a mathematical expression)

description: What is the signification of ** in python (when not a mathematical expression)


rawDescription: Python regex equivalent of bash's {1..4}


rawDescription: Splitter window issue

description: Splitter window issue


code:
values = ['abc', 'def', 'ghi']
# a list of unsaved Entry model instances
aList = [Entry(headline=val) for val in values]

rawDescription: Django 1.4 - bulk_create with a list

description: Django 1.4 - bulk_create with a list


code:
dt=np.dtype({"names": columns, "formats" : ['i'] + ['int8'] * (len(columns) - 1)})
mat=np.zeros((10,),dtype=dt)
for i in range(1,7,3):
    mat[dt.names[i]]=default_age
    mat[dt.names[i+1]]=default_height
    mat[dt.names[i+2]]=default_shoe_size

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

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


rawDescription: Python re.split() vs nltk word_tokenize and sent_tokenize


code:
def get_score(grade, grade_to_score = None):
    if grade_to_score == None:
        grade_to_score = {'A': 10, 'B': 8, 'C': 6, 'D': 4, 'F': 0}
    return grade_to_score.get(grade, -1)

rawDescription: local variable optimization in python method

description: Local variable optimization in python method


code:
# now add this widget to the QMdiSubWindow
mdisubwindow.setWidget(widget)

rawDescription: how to put widgets inside a PyQt QMdiSubWindow

description: Put widgets inside a PyQt QMdiSubWindow


code:
d = wordnet.synset('donation.n.01')
g = wordnet.synset('gift.n.01')

rawDescription: using python nltk to find similarity between two web pages?

description: Using python nltk to find similarity between two web pages


code:
tup.sort( key = lambda x: (x[1],x[0]) )
ssd = [[]]
cnt = 0
ssd[0].append(tup[0][1])
for i in tup:
    if i[1] == ssd[cnt][0]:
        ssd[cnt].append(i[2])
    else:
        cnt = cnt + 1
        ssd.append([])
        ssd[cnt].append(i[1])
        ssd[cnt].append(i[2])

rawDescription: Merging duplicate lists and deleting a field in each list depending on the value in Python


code:
from collections import Counter
name = ["Anne", "Jack", "Mary"]
n1 = [[0,0,3], [0,5,5], [1,3,3]]
{name_: Counter(data) for name_, data in zip(name, n1)}

rawDescription: Make dictionary from two lists using Counter object


code:
import subprocess
p = subprocess.Popen("java -jar ExposeAMethod.jar", shell=True)
sts = os.waitpid(p.pid, 0)

rawDescription: How to call java objects and functions from CPython?

description: Call java objects and functions from CPython


code:
# Twitter settings
TWITTER_KEY = 'xxxxxx'
TWITTER_SECRET = 'xxxxxxxx'

rawDescription: How can I use Django Social Auth to connect with Twitter?

description: Use Django Social Auth to connect with Twitter


rawDescription: Grouping 2D numpy array in average

description: Grouping 2D numpy array in average


rawDescription: Python - How to return a double with eval()


code:
from urlparse import urlparse
from urlparse import parse_qs
urlparse('http//www.domain.com/path?a=1&b=2')
parse_result = urlparse('//www.domain.com/path?a=1&b=2')
parse_qs(parse_result[4])

rawDescription: Need to parse something like a GET request in python


code: counts

rawDescription: Counting number of documents

description: Counting number of documents


code: screen.blit(font.render(output_string, True, WHITE), (150, 110))

rawDescription: Pygame not displaying text

description: Pygame not displaying text


code:
parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group()
group.add_argument('--arg1')
group.add_argument('--arg2')

rawDescription: How to disable an argument if another is present?

description: Disable an argument if another is present


code: listb = ['&'.join(t)for t in product(*[['%s=%s'%(i,v)for v in j.split(',')]for i,j in[s.split('=')for s in lista]])]

rawDescription: How to get different combinations in python?

description: Get different combinations in python


code:
def song_download(request, song_id):
    try:
        song = Song.objects.get(id=song_id)
        response = HttpResponse()
        response['Content-Type'] = 'application/mp3'
        response['X-Accel-Redirect'] = '/files/' + song.filenamename
        response['Content-Disposition'] = 'attachment;filename=' + song.filename
    except Exception:
        raise Http404
    return response

rawDescription: Django: Serving Media Behind Custom URL

description: Django: Serving Media Behind Custom URL


code: final = path2 + w

rawDescription: Adding a simple value to a string

description: Adding a simple value to a string


code: {'Countries': {'USA': 1, 'Technical Fault': 0, 'No Connections': 0, 'Delayed': 0, 'Connections': {'17 Flights': 0, '10 Flights': 0, '11 Flights': 0, 'More than 25 Flights': 0, '14 Flights': 0, '15 Flights': 0, '12 Flights': 0, '18 Flights': 0, '16 Flights': 0, '1 Flights': 0, '13 Flights': 0}, 'Single Connections': 0, 'Others': 0}}

rawDescription: Python : nested key value data parsing

description: Python : nested key value data parsing


code:
class UserSerializer(serializers.ModelSerializer):
    phones = PhoneSerializer(required=False, many=True)

    class Meta:
        model = User
        fields = ('email', 'phone_number')

    def create(self, validated_data):
        phones_data = validated_data.pop('phones', [])
        user = super(UserSerializer, self).create(validated_data)
        for phone_data in phones_data:
            user.phone_set.create(phone_number=phone_data['phone_number'])
        return user

    def update(self, instance, validated_data):
        phones_data = validated_data.pop('phones', [])
        user = super(UserSerializer, self).update(instance, validated_data)
        # delete old
        user.phone_set.exclude(phone__in=[p['phone_number'] for p in phones_data]).delete()
        # create new
        for phone_data in phones_data:
            user.phone_set.get_or_create(phone_number=phone_data['phone_number'])
        return user

rawDescription: django rest framework nested fields with multiple models

description: Django rest framework nested fields with multiple models


code:
import requests
r = requests.get('http://www.merdeka.com')
r.text

rawDescription: Python Sometimes Returns Strange Result When Reading HTML from URL


code:
total = sum(int(i) for sublist in outerlist for i in sublist)
length = sum(len(sublist) for sublist in outerlist)
average = total / length

rawDescription: Average of imported list (python)

description: Average of imported list (python)


code:
l = [[1,2,3,4,5,6,7,8],[9,8,8,4,3,4,5,7,8],[5,6,7,4,9,9,9,8],[0,0,1,4,7,6,3,8]]

p = [i for i, j in enumerate(zip(*l)) if all(j[0]==k for k in j[1:])]

# p == [3] - because of some typo in your original list, probably too many elements in the second list.

rawDescription: Compare equal length lists to find positions that share the same element


code:
def y_better(foo, bar=None):
    try: y(foo, bar)
    except TypeError:
        if foo == bar: # detect foobar condition
            raise FoobarError()
        else:          # not foobar, so re-raise the exception
            raise

rawDescription: Distinguishing between same exception by where it was called


code:
from django.contrib.auth.models import User
my_user = User.objects.create_user('ea87', 'ea@gmail.com', '666monkeysAndDogs777')
my_user.save()
my_user.password
my_user.username
from django.contrib.auth import authenticate
authenticate(username='ea87', password='666monkeysAndDogs777')
print(authenticate(username='ea87', password='wrong password'))
from django.contrib.auth.hashers import check_password
check_password('666monkeysAndDogs777', my_user.password)
exit()

rawDescription: How to use Bcrypt to encrypt passwords in Django

description: Use Bcrypt to encrypt passwords in Django


code:
def my_sum(l, i):
    return [
        [x[0], sum(y[1] for y in l[j: j + i])] for j, x in enumerate(l[:-i], 1)
    ]

rawDescription: Data type for summing next few items

description: Data type for summing next few items


rawDescription: Comparing two tuples in two different file


code:
# Iterate over all the words
# Use enumerate because we're going to modify the word in-place in the words list
for word_idx, word in enumerate(words):
    # If the current word is in the `word_substitutes` dict, then we know its in the
    # 'common' words, and can be replaced by the symbol
    if word in word_substitutes:
        # Replaces the word in-place
        replacement_symbol = word_substitutes[word]
        words[word_idx] = replacement_symbol

rawDescription: How do I optimize the speed of my python compression code?

description: Optimize the speed of my python compression code


rawDescription: Python: modify element in a nested dict

description: Python: modify element in a nested dict


code:
from pyspark.sql.functions import sum, abs

gpd = df.groupBy("f")
gpd.agg(
    sum("is_fav").alias("fv"),
    (count("is_fav") - sum("is_fav")).alias("nfv")
)

rawDescription: PySpark count values by condition

description: PySpark count values by condition


code:
class MyInlineFormset(generic.generic_inlineformset_factory(MyModel)):
    def __init__(self, *args, **kwargs):
        super(MyInlineFormset, self).__init__(*args, **kwargs)
        self.can_delete = False

rawDescription: Django: disallow can_delete on GenericStackedInline


code:
search_string = 'search'
with open('infile.txt', mode='r') as infile:
    for line in infile:
        if search_string in line:
            with open('outfile.txt', mode='a') as outfile:
                outfile.writelines([line, next(infile), next(infile)])

rawDescription: using python, Search for a text and print next few lines in python

description: Using python, Search for a text and print next few lines in python


code: uploaded_file = request.FILES['file']

rawDescription: Is there any way django does not save the file uploaded with form


rawDescription: how to ADD a one list to another in python?

description: ADD a one list to another in python


code:
@sower
def someSum():
    return sum(sow(x**2 + 1) if (x**2 + 1) % 2 == 0 else x**2 + 1 for x in xrange(1, 11))
someSum()
reap(someSum())

rawDescription: Python equivalent of Mathematica's Sow/Reap


code:
from collections import OrderedDict
ord_dict = OrderedDict()

for i in tmp:
    ord_dict[i] = d[i]
print(ord_dict)
OrderedDict([('2013-04-18', 7), ('2013-04-19', 9), ('2014-06-30', 2)])

rawDescription: Python copying defaultdict to dict with new order of key


code: aapl.groupby(pd.TimeGrouper('M')).Close.agg({'max date': 'idxmax', 'max price': np.max})

rawDescription: Getting the monthly maximum of a daily dataframe with the corresponding index value


rawDescription: Comparing two dictionaries in list in python


rawDescription: Turn a non-symmetric 3 dimensional list into a 2 dimensional list of lists in python


code:
my_list = ['abs',[1,2,[3,4]]]
tmp = reduce(l, my_list)
reduce(l, tmp)
['abs', 1, 2, 3, 4]

rawDescription: Flatten a list and a string

description: Flatten a list and a string


code:
import json
import codecs

with codecs.open('/path/to/file', 'w', encoding='utf8') as output:
    json.dump(obj, output, ensure_ascii=False)

rawDescription: Make utf8 readable in a file

description: Make utf8 readable in a file


code:
xml_data = """<?xml version="1.0" encoding="UTF-8"?>
<root>my data here</root>
"""

#construct and send the header

webservice = httplib.HTTP("example.com")
webservice.putrequest("POST", "/rcx-ws/rcx")
webservice.putheader("Host", "example.com")
webservice.putheader("User-Agent", "Python post")
webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
webservice.putheader("Content-length", "%d" % len(xml_data))
webservice.endheaders()
webservice.send(xml_data)

rawDescription: Simple XML over http web service

description: Simple XML over http web service


code:
import itertools

def limit_files(file_list, at_a_time=10):
    d, r = divmod(len(file_list), at_a_time)
    num_keys = d + 1 if r > 0 else d

    chunks = itertools.izip_longest(*([iter(x)] * at_a_time))
    return dict((x, y) for x, y in enumerate(chunks))

rawDescription: Split list into dictionary

description: Split list into dictionary


code: self.assertTrue(3 <= myInt <= 8)

rawDescription: Is there a python assert() method which checks between two boundaries?


code:
# Store the variables that represent the slice in a list/tuple
# Make a slice with the unzipped tuple using the slice() command
# Use the slice on your array

rawDescription: python: extracting one slice of a multidimensional array given the dimension index

description: Python: extracting one slice of a multidimensional array given the dimension index


rawDescription: How to convert timezone to country code in Python?

description: Convert timezone to country code in Python


code:
data =[[0, 0, 0] for line in range(3)]
x = ['A', 'B', 'C']
# we need the permutations of the indexes
xv = range(len(x))
for i,j in itertools.permutations(xv,2):
    #combinations of A
    if 'A' in (x[i], x[j]):
        data[i][j] += 1
    #combinations of B
    if 'B' in (x[i], x[j]):
        data[i][j] += 10

rawDescription: python iterate over list elements for all combinations and perfom some action

description: Python iterate over list elements for all combinations and perfom some action


code:
class PublicC(C):
    def internal(self):
        raise Exception('This is a private method')

rawDescription: How to design a library public api avoiding to expose internals?

description: Design a library public api avoiding to expose internals


code:
week = df.groupby(pd.TimeGrouper('W'))
is_week_min = week['value'].apply(lambda x: x == x.min()).astype(int)  # possibly the astype is not needed in 0.13
is_week_min.resample('D', how='sum')  # count occurences in the day which are week min

rawDescription: Daily frequency count with pandas

description: Daily frequency count with pandas


code:
a = int(a)
h = float(h)

rawDescription: Just an input in Python

description: Just an input in Python


code:
def level_dict(adj_list,curr_elems,order=0):
    if not curr_elems:    # This check ensures that for empty `curr_elems` list we return empty dictionary
            return {}
    d = {}
    new_elems = []
    for elem in curr_elems:
            d.setdefault(order,[]).append(elem)
            new_elems.extend(adj_list.get(elem,[]))
    d.update(level_dict(adj_list,new_elems,order+1))
    return d

rawDescription: How to convert a binary tree in to a dictionary of levels

description: Convert a binary tree in to a dictionary of levels


code: asString = [prettyPrint(value) for value in values]

rawDescription: A smarter & faster way to convert numpy ndarray to string in python


code: int_list = [int(x) for x in raw_input("Enter integers:").split()]

rawDescription: Input n elements seperated by space in python


rawDescription: Concatenate rows of pandas DataFrame with same id


rawDescription: How to find a missing number from a list

description: Find a missing number from a list


code:
def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        try:
            pr=test.__name__+': '+test.__docstring__
        except AttributeError:
            pr=test.__name__
        msg = '{}=={}; Test: {}'.format(var, value, pr)
        assert test(value), msg

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    _between.__docstring__='must be between {} and {}'.format(lo,hi)
    return _between

def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
    validate(f, locals())
    print(x,y)

rawDescription: -> in python function definition

description: -> in python function definition


code:
import os
import pathlib
p = pathlib.Path("/foo/bar/baz/txt")
onedir = os.path.join(*p.parts[-2:])

rawDescription: Pythonic way to extract the file name and its parent directory from the full file path?


code:
r = requests.get("http://www.transfermarkt.co.uk/championship/marktwerte/wettbewerb/GB2", headers={
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"
})

rawDescription: Python requests not responding

description: Python requests not responding


code:
class A(object):
    def set(self):
            pass
    def test(self, x=set):
            return x

set
A().test()

rawDescription: Python class has method "set", how to reference builtin set type?


rawDescription: Adding numpy arrays

description: Adding numpy arrays


code:
v = IntVar()

Radio1 = Radiobutton(Dialog, text="Radio 1", value=1, variable=v)
...
Radio2 = Radiobutton(Dialog, text="Radio 2", value=2, variable=v)
...
...

rawDescription: radio button status verification

description: Radio button status verification


code:
def mapNumber(a):
    return (a + 1000.) / 10.

rawDescription: Mapping numbers

description: Mapping numbers


code:
c = get_config()

c.InteractiveShellApp.exec_lines = [
    'import pandas as pd',
    'pd.options.display.mpl_style = \'default\'',
    'pd.options.display.max_rows = 30',
    'pd.options.display.max_columns = 6',
    'pd.options.display.expand_frame_repr = False',
    'pd.options.display.max_colwidth = 28',
    'pd.options.display.precision = 5',
    'import numpy as np',
    'np.set_printoptions(precision=4, linewidth=90, threshold=25)',
    'import matplotlib.pyplot as plt'
]

rawDescription: Changing a table's look in Pandas

description: Changing a table's look in Pandas


code:
class ListDrop(wx.PyDropTarget):
  """
    Utility class - Required to support List Drag & Drop.
    Using example code from http://wiki.wxpython.org/ListControls.
  """
  def __init__(self, setFn, dataType, acceptFiles = False):
    wx.PyDropTarget.__init__(self)

    self.setFn = setFn

    # Data type to accept.
    self.data = wx.CustomDataObject(dataType)

    self.comp = wx.DataObjectComposite()
    self.comp.Add(self.data)

    if acceptFiles:
      self.data2 = wx.FileDataObject()
      self.comp.Add(self.data2)

    self.SetDataObject(self.comp)

  def OnData(self, x, y, d):
    if self.GetData():
      if self.comp.GetReceivedFormat().GetType() == wx.DF_FILENAME:
        self.setFn(x, y, self.data2.GetFilenames())
      else:
        self.setFn(x, y, self.data.GetData())

    return d

rawDescription: Python Simple GUI Windows Drag&Drop

description: Python Simple GUI Windows Drag&Drop


code:
from rest_framework.renderers import JSONRenderer

class EmberJSONRenderer(JSONRenderer):

    def render(self, data, accepted_media_type=None, renderer_context=None):
        data = {'element': data}
        return super(EmberJSONRenderer, self).render(data, accepted_media_type, renderer_context)

rawDescription: Override JSONSerializer on django rest framework


code:
d = uobj({'a': 'asdf'})
s = uobj('qwer')
'{0:s} {d[a]}'.format(s, d=d)

# ouputs: 'qwer<asdf'

rawDescription: Python/Cython custom formatter string presentation types


code: input('Press enter to continue: ')

rawDescription: How to wait for ENTER key press in Python (2.7 + )?

description: Wait for ENTER key press in Python (2.7 + )


rawDescription: Matrix with identical diagonals

description: Matrix with identical diagonals


rawDescription: NLTK Brown Corpus - adding own tagged sentences


code:
somefiltering(adict, lambda d:d['process'], lambda d:d['length']>5)
# Result: [2]

somefiltering(adict, lambda d:d['length'] < 20)
# Result: [1, 3]

somefiltering(adict, lambda d:d['process'], lambda d:d['length']<5)
# Result: []

rawDescription: Filter items in a dict of dict

description: Filter items in a dict of dict


code:
from operator import itemgetter
items_2_and_5 = itemgetter(2, 5)
items_2_and_5(range(10))
items_2_and_5('hello world!')

rawDescription: Python Split() - Optimum way to get multiple fields?


code:
links = [link
         for link in links
         if {"source":link["target"], "target":link["source"]} in links
        ]

rawDescription: does the for each loop in python based index?

description: Does the for each loop in python based index


code:
y, x = np.mgrid[0.0:3.0:100j, 0.0:5.0:100j]
H = 50.0 * np.exp( -(x**2 + y**2) / 4.0 )
levels = [0, 1, 2, 3, 6, 9, 20, 50]

H1 = -50.0 * np.exp( -(x**2 + y**2) / 4.0 )
levels1 = [-50, -20, -9, -6, -3, -2, -1, 0]

fig, ax = plt.subplots(2, 2, gridspec_kw={'width_ratios':(20, 1), 'wspace':0.05})

im0 = ax[0, 0].contourf(x, y, H, levels, cmap='jet', norm=PiecewiseNorm(levels))
cb0 = fig.colorbar(im0, cax=ax[0, 1])
im1 = ax[1, 0].contourf(x, y, H1, levels1, cmap='jet', norm=PiecewiseNorm(levels1))
cb1 = fig.colorbar(im1, cax=ax[1, 1])

plt.show()

rawDescription: define custom Normalisation function in matplotlib when using plt.colorbar()

description: Define custom Normalisation function in matplotlib when using plt.colorbar()


code:
response_data = {
                     "status":200, "message":"comment_stored",
                     "parent": True,
                     "parent_id": parent_comment.id,
                     "comment_count": parent_comment.comment_count()
                 }
return JsonResponse(response_data)

rawDescription: how to use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this?

description: Use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this


code:
import math
days_per_year = 365.2425
hours_per_day = 24
ax1.xaxis.set_major_locator(plt.FixedLocator(
                            range(0, x1[-1], math.ceil(hours_per_day * days_per_year))))
ax1.xaxis.set_ticklabels(range(math.ceil(x1[-1] / (hours_per_day * days_per_year))))

rawDescription: Add years to x-axis in Matplotlib

description: Add years to x-axis in Matplotlib


code: x: my_var

rawDescription: What type of declaration is `def m_test(x: my_var) -> list:`


code:
from matplotlib import pyplot as plt
from matplotlib import _cntr as cntr

z = np.array([[0.350087, 0.0590954, 0.002165],
              [0.144522,  0.885409, 0.378515],
              [0.027956,  0.777996, 0.602663],
              [0.138367,  0.182499, 0.460879],
              [0.357434,  0.297271, 0.587715]])

x, y = np.mgrid[:z.shape[0], :z.shape[1]]
c = cntr.Cntr(x, y, z)

# trace a contour at z == 0.5
res = c.trace(0.5)

# result is a list of arrays of vertices and path codes
# (see docs for matplotlib.path.Path)
nseg = len(res) // 2
segments, codes = res[:nseg], res[nseg:]

fig, ax = plt.subplots(1, 1)
img = ax.imshow(z.T, origin='lower')
plt.colorbar(img)
ax.hold(True)
p = plt.Polygon(segments[0], fill=False, color='w')
ax.add_artist(p)
plt.show()

rawDescription: Python: find contour lines from matplotlib.pyplot.contour()


code:
def partition(pred, iterable):
    trues = []
    falses = []
    for item in iterable:
        if pred(item):
            trues.append(item)
        else:
            falses.append(item)
    return trues, falses

rawDescription: python equivalent of filter() getting two output lists (i.e. partition of a list)

description: Python equivalent of filter() getting two output lists (i.e. partition of a list)


code:
with open("test.csv") as file_handle:
    file_reader = csv.reader(file_handle)
    file_handle.readline()
    file_handle.readline()  #skip first 2 lines due to column header titles
    for row in file_reader:
        revenue[int(float(row[0].split()[0]) * 100)] = row[0].split()[1] #assign revenue at each price-point

rawDescription: KeyError when assigning values

description: KeyError when assigning values


code: [values[index] for index in indices]

rawDescription: Extract list from given list and given indices


code:
samples = '''\
2, -9, -35
4, -13, 3
-6, 13, 5
5, -6, 6
-2, 5, -3
4, 12, 9
0.5, 1, 1
1, -0.5, -0.5
0.25, Fraction(-1, 3), Fraction(1, 9)'''.splitlines()
safe_callables = {'Fraction': fractions.Fraction}
for line in samples:
    print(literal_eval_with_callables(line, safe_callables))

rawDescription: Is my eval implementation completely safe?


code:
def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

rawDescription: Finding the indices of matching elements in list in Python


code:
vals = ['a','b','c']
this = ListPointer(vals)
this()
this('d')
vals
this.pp()
this()
print(this)

rawDescription: List element Pointer in Python

description: List element Pointer in Python


code:
LT = Button(root, width=16, height=8, bg = 'white')
LT.configure(command=colour_changer(LT))

rawDescription: How do I use itertools.cycle with multiple objects?

description: Use itertools.cycle with multiple objects


rawDescription: Is there a Python equivalent to Erlang's pattern matching?


code:
tmp.recursive_bubble_ands_up(((('and', 'a', 'b'), 'x'), 'y' ))
tmp.recursive_bubble_ands_up((('and', ('a', 'x'), ('b', 'x')), 'y'))

rawDescription: replacing values in a nested tuple with the whole tuple

description: Replacing values in a nested tuple with the whole tuple


code: fundict = {'hello' : hello}

rawDescription: Syntax for a dictionary of functions?

description: Syntax for a dictionary of functions


code: OutputFile = open(FileNameOut, 'w')

rawDescription: Saving data into a text file

description: Saving data into a text file


code:
for item in data:
    InfoDB(id=item['id'], data=item['data']).put()

rawDescription: Google App Engine NDB Read Operation Optimization


code:
import random

def noncontiguoussample(n,k):
    # How many numbers we're not picking
    total_skips = n - k

    # Distribute the additional skips across the range
    skip_cutoffs = random.sample(range(total_skips+1), k)
    skip_cutoffs.sort()

    # Construct the final set of numbers based on our skip distribution
    samples = []
    for index, skip_spot in enumerate(skip_cutoffs):
        # This is just some math-fu that translates indices within the
        # skips to values in the overall result.
        samples.append(1 + index + skip_spot)

    return samples

rawDescription: Finding k non contiguous random numbers with uniform probability in the range 1..n


code:
import scrapy
from scrapy.selector import Selector
from scrapy_splash import SplashRequest

class CartierSpider(scrapy.Spider):
  name = 'cartier'
  start_urls = ['http://www.cartier.co.uk/en-gb/collections/watches/mens-watches/ballon-bleu-de-cartier/w69017z4-ballon-bleu-de-cartier-watch.html']

  def start_requests(self):
    for url in self.start_urls:
      yield SplashRequest(url, self.parse, args={'wait': 0.5})

  def parse(self, response):
    yield {
      'title': response.xpath('//title/text()').extract_first(),
      'link': response.url,
      'productID': response.xpath('//span[@itemprop="productID"]/text()').extract_first(),
      'model': response.xpath('//span[@itemprop="model"]/text()').extract_first(),
      'price': response.css('div.price-wrapper').xpath('.//span[@itemprop="price"]/text()').extract_first(),
    }

rawDescription: Scrapy selector not working on Splash response


code:
for week, data in df.groupby(level=0):
    data.to_excel('{}.xlsx'.format(week))

rawDescription: Report with Pivot Tables like in Excel using Python


code:
list_ = [4]
list_[0]
array_ = np.array([4])
array_[0]

rawDescription: Convert list or numpy array of single element to float in python


code:
ggplot(aes(x='at_k', y='value', colour='variable'), data=df2) +\
    geom_point()

rawDescription: Convert from matplotlib to ggplot2 within python


code: norm(ev-D)

rawDescription: Using ARPACK solving eigenvalueproblem, but getting inconsistent results with Matlab


rawDescription: retrieving columns based on condition in data frame

description: Retrieving columns based on condition in data frame


code:
while True:
    print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
    menu = input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")
    if menu == "1":
        rq.countryChoice()
    elif menu == "2":
        rq.cityChoice()
    elif menu == "3":
        rq.forecastChoice()
        for line in rq.data.splitlines():
            print(line)

rawDescription: How do I get input out of a class and into the main script

description: Get input out of a class and into the main script


code:
from math import sqrt

def pf(n):
    if n == 1:
        return
    if n % 2 == 0:
        print(2)
        pf(n/2)
        return
    for i in range(3, int(sqrt(n))+1, 2):
        if n % i == 0:
            for j in range(3, int(sqrt(i))+1, 2):
                if i % j == 0:
                    break
            else:
                print(i)
                pf(n/i)
                return
    print(n)

rawDescription: Python code stucks in Iterating although it found the solution


code:
from random import shuffle
def shuffle_word(word):
   word = list(word)
   shuffle(word)
   return ''.join(word)

rawDescription: Are there any way to scramble strings in python?


code:
setup_code = """
  from PerformanceTests.Vectors import NaiveVector
  left = NaiveVector([1,0,0])
  right = NaiveVector([0,1,0])
"""

rawDescription: Managing Setup code with TimeIt

description: Managing Setup code with TimeIt


code:
string = "foo"
res = [bin(ord(i)) for i in string]

rawDescription: Converting to binary in MATLAB and Python


code:
words = []
for word in string.split(' '):
    # your existing code
    words.append(word)
print(' '.join(words))

rawDescription: How do I make part of a string lowercase in python?

description: Make part of a string lowercase in python


code:
from bs4 import BeautifulSoup

html = """

"""
soup = BeautifulSoup(html, 'lxml')

for elm in soup.select("div[class=aa]"):
    print(str(elm))

rawDescription: How to use Beautiful4 to filter multi class

description: Use Beautiful4 to filter multi class


code:
def join(t1,t2,column):
    result = []
    for entry in t2:
        for match in [d for d in t1 if d[column] == entry[column]]:
            result.append(dict((k,v) for k,v in entry.items()+match.items()))
    return result

rawDescription: Join two lists of dictionaries around a single non-unique key


code: match3 = re.findall(r'<div class="wx-temperature">\w\w',f)

rawDescription: Python-Regex-Distinguish and use repeated pattern in a string


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://datafireball.com")
# I am using Chrome Developer Tool to get the Xpath, you might want to use your own code.
pic = driver.find_element_by_xpath('//*[@id="post-174"]/div/p[5]/a/img')
position = pic.location
print(position)

rawDescription: Finding a position of web images in a scrape


code:
# set up a better mapping
name_amount_dict = {field["name"]: field["amount"] for field in top_level_dict["fields"]}

# use it to look up a value we want
print(name_amount_dict["col_1"])

rawDescription: Python parsing Nested Ordereddict

description: Python parsing Nested Ordereddict


rawDescription: Python adding extra area to image

description: Python adding extra area to image


code:
N=3
int(str(num)[:N])

rawDescription: Truncating a int

description: Truncating a int


code:
def get_section_links(sec_url):
    cont = requests.get(sec_url).content
    xml = fromstring(cont, HTMLParser())
    return set(xml.xpath("//div[@class='section-stream-content']//a/@url"))

rawDescription: Why does my webcrawler not follow into the next link containing keywords


code:
import datetime as dt

def round_time(dto, round_to=60):
    seconds = (dto - dto.min).seconds
    rounding = (seconds+round_to/2) // round_to * round_to
    return dto + dt.timedelta(0,rounding-seconds,-dto.microsecond)

rawDescription: Python: Compare Filenames in Folder

description: Python: Compare Filenames in Folder


code:
import sys
print(sys.argv)

rawDescription: How to pass empty argument to Popen (with shell=False)?

description: Pass empty argument to Popen (with shell=False)


rawDescription: find submit button in selenium without id

description: Find submit button in selenium without id


code:
from collections import defaultdict

data = """\
r1,s1,1
r1,s2,1
r1,s3,2
r1,s4,2
r2,s1,2
r2,s2,2
r2,s3,1
"""

d = defaultdict(dict)

for line in data.split():
    a, b, c = line.split(",")
    d[a].setdefault(int(c), []).append(b)

d = dict(d)
print(d)

rawDescription: CSV data to Nested Dictionaries

description: CSV data to Nested Dictionaries


code: [list(x) for x in zip(*data)]

rawDescription: Restructure / rearange list

description: Restructure / rearange list


code:
import re
re.findall(r'From:\s*[^,]+,\s*To:\s[^,]+,\s*Downtime:[\w ]+',  mystring)

rawDescription: Finding a string along with a few other words


code:
from requests import Session

class MySession(Session):
    def request(self, method, url, **kwargs):
        print('Hello World!')
        return super().request(method, url, **kwargs)

rawDescription: How to override the .get() method in requests?

description: Override the .get() method in requests


code:
if (a < read < b) or (b < read < a):
    return print("Yes")
else:
    return print("No")

rawDescription: Comparing three numbers?

description: Comparing three numbers


code: nums.sort(key=functools.cmp_to_key(lambda x, y: cmp(y+x, x+y)))

rawDescription: How to convert sort using cmp from python 2 to python 3?

description: Convert sort using cmp from python 2 to python 3


code: ['little', 'lamb', 'which', 'was', 'very']

rawDescription: Creating a smaller list from an existing list


rawDescription: Finding which rows have all elements as zeros in a matrix with numpy


code:
import requests

headers = {'X-API-TOKEN': 'your_token_here'}
payload = {'title': 'value1', 'name': 'value2'}

r = requests.post("http://foo.com/foo/bar", data=payload, headers=headers)

rawDescription: how to make post request in python

description: Make post request in python


code:
if first[0] <= second[0] <= third[0]:
    print(True)

rawDescription: Creating a program that prints true if three words are entered in dictionary order


code:
import collections

d = {'a':5,'b':5,'c':5,'d':1,'e':6}
my_d = collections.defaultdict(list)
for key, val in d.items():
    my_d[val].append(key)

ranked_key_list = []
n = v = 1
for _, my_list in sorted(my_d.items()):
    v = n + (len(my_list)-1)/2
    for e in my_list:
        n += 1
        ranked_key_list.append((e, v))

rawDescription: python ranking a list of values, using average rank for non-unique values

description: Python ranking a list of values, using average rank for non-unique values


code: max(mydict, key=lambda k: mydict[k]['c'])

rawDescription: Grabbing key of dictionary in dictionary with highest value


code:
def refresh():
    global variable4, variable5
    variable4 = variable1 + variable2 + variable3
    variable5 = variable3 - variable2 / variable1

rawDescription: Refreshing a list of variables with one command


code:
import numpy as np
main_list = [12, 10, 30, 10, 11,10, 31]
get_indices = [1, 0, 1, 1, 0, 0, 0]
main_array = np.array(main_list)
get_ind_array = np.array(get_indices).astype(bool)
main_array[get_ind_array]
main_array[~get_ind_array]

rawDescription: Use bool list to retrieve elements from another list - Python


code: df['newColumn'] = df.oldColumn.rank()

rawDescription: Add a column to a pandas data frame using a pandas operation


code:
useFunction(addOne, 4)
useFunction(addOne, 9)
useFunction(addOne, 8)
useFunction(addOne, 6)

rawDescription: how can i call function inside another function.?

description: Call function inside another function.


code: mx = [map(int, line.split(',')) for line in f]

rawDescription: How should you read a 2D integer array?

description: How should you read a 2D integer array


code:
#BAD
from numpy import *
#GOOD
from numpy import array #or whatever it is you need
#GOOD
import numpy as np #if you need lots of things, this is better

rawDescription: vectorized assignment statement for selected elements of 2d array in numpy

description: Vectorized assignment statement for selected elements of 2d array in numpy


code:
import imp
mod = imp.load_source("test", "test")
mod.a

rawDescription: Import a python module without .py extension,


code:
import urllib
urllib.urlencode({'command': 'command', 'nonce': 10000})
urllib.urlencode([('command', 'command'), ('nonce', 10000)])

rawDescription: Go and Python HMAC libraries give different results


code:
import timeit
import operator
import numpy as np
import pandas as pd

N = 10000
df = pd.DataFrame(
    {'ID': np.random.randint(100, size=(N,)),
     'PRICE': np.random.random(N),
     'date': np.random.random(N)})

def using_mask(df):
    def mask_first(x):
        result = np.ones_like(x)
        result[0] = 0
        return result

    mask = df.groupby(['ID'])['ID'].transform(mask_first).astype(bool)
    return df.loc[mask]

def using_apply(df):
    return df.groupby('ID').apply(lambda group: group.iloc[1:, 1:])

def using_apply_alt(df):
    return df.groupby('ID', group_keys=False).apply(lambda x: x[1:])

timing = dict()
for func in (using_mask, using_apply, using_apply_alt):
    timing[func] = timeit.timeit(
        '{}(df)'.format(func.__name__),
        'from __main__ import df, {}'.format(func.__name__), number=100)

for func, t in sorted(timing.items(), key=operator.itemgetter(1)):
    print('{:16}: {:.2f}'.format(func.__name__, t))

rawDescription: Python: Pandas - Delete the first row by group


code:
def loadMap(self, event):
    global mainFrame # or wherever you stored the reference to it
    # ...
    # remove this:
    # mainFrame = MainFrame()
    # set the sPath to the OBJECT mainFrame not the CLASS MainFrame
    mainFrame.sPath = str(mapFile.readline()).strip("\n")
    mainFrame.srcTc.SetValue(MainFrame.sPath)

rawDescription: Changing an element in a different Frame in wxPython


code:
import urlparse
inputurl = 'http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFcQAQ4S3H5xUuU4N-LoM2I9tLxJg&url=http://www.washingtonpost.com/blogs/going-out-guide/wp/2013/11/08/dallas-buyers-club-thor-the-dark-world-and-other-new-movies-reviewed/'
qs = urlparse.urlsplit(inputurl).query
urlparse.parse_qs(qs).get('url', [None])[0]

rawDescription: Python Regular Expression to Remove Unwanted Parts of URL


rawDescription: Slice specific characters in CSV using python


rawDescription: Formulating an efficient DB query with highly challenging requirements (Django app)


code:
mylist = list(range(10000))
mylist[:] = []
print (mylist)

rawDescription: Delete all objects in a list

description: Delete all objects in a list


code: del foo.fields[-1]

rawDescription: How can I remove an item from a repeated protobuf field in python?

description: Remove an item from a repeated protobuf field in python


code:
if json_data["name"] not in ["f"]:
    raise Exception("forbidden function!")

rawDescription: Can JSON for Python Encode/decode functions from text files?


code:
cons = []
for d in [0.1, 0.2, 0.3]:
    cons += {'type': 'ineq', 'fun': lambda x: -1*bounds(x) + d}

rawDescription: Dynamic dictionary including keywords/ lambda function


code:
# apply() will take date in df1 and find the first row in df2
# such that the date is between START_DATE and END_DATE and
# then return the row.
df1.actn_dt.apply(lambda x: find_pay_period(x, df2))

rawDescription: pandas between statement for two dates from another dataset

description: Pandas between statement for two dates from another dataset


code:
def myfunc(x):
    try:
       x = x.splitlines(True)
    except AttributeError:
       pass #likely a file

    for line in x:
       doSomething(line)

rawDescription: writing Python function to iterate over lines -- accepting either string or file-like object

description: Writing Python function to iterate over lines -- accepting either string or file-like object


code:
class MySpider(CrawlSpider):
    def __init__(self, user_id='', *args, **kwargs):
        self.user_id = user_id

        super(MySpider, self).__init__(*args, **kwargs)

rawDescription: Using arguments in scrapy pipeline on __init__


code:
# find minimum pair by second elements summed
minpair = min(paired, key=lambda pair: pair[0][1] + pair[1][1])
minimum = min(minpair, key=itemgetter(1))

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code: from pyspark.ml.feature import Word2Vec

rawDescription: Error in PySpark trying to run Word2Vec example


code:
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

rawDescription: How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?


rawDescription: Use Column and Row Multi-Index values in Pandas Groupby without unstacking


code: 'The Quick Brown Fox'.replace(' ', '-')

rawDescription: Inserting another character in place of spaces in Python


rawDescription: How to get the IP prefix while we have subnet and IPv4 address using python-netaddr?

description: Get the IP prefix while we have subnet and IPv4 address using python-netaddr


rawDescription: Python Split Operator

description: Python Split Operator