code:
class Foo(object):
    def __init__(self):
        self.readonly = set()

    def set_readonly(self, attr, value):
        setattr(self, attr, value)
        self.readonly.add(attr)

    def __setattr__(self, attr, value):
        if hasattr(self, "readonly") and attr in self.readonly:
            raise AttributeError("Read only attribute: %s" % (attr,))
        object.__setattr__(self, attr, value)

rawDescription: Setting a property inside a Python method


code:
items = set(["Apple","Banana","Orange","Peach"])
{'Apple', 'Banana'} <= items
{'Banana', 'Apple'} <= items
{'Banana', 'Watermelon'} <= items

rawDescription: Comparing Permutation and Combinations

description: Comparing Permutation and Combinations


code: np.concatenate([g[:1], g[2:]])

rawDescription: Conditional index in 2d array in python

description: Conditional index in 2d array in python


code: n_perms = 256**len(passkey)

rawDescription: Python: Shorten ugly code?

description: Python: Shorten ugly code


code:
test = [[0.0] * 10] * 10
[id(x) for x in test]     #see all IDs are same

rawDescription: Initializing 2D lists in Python: How to make deep copies of each row?


code: bar(lambda x: foo(x,300))

rawDescription: pass function to function with different number of variables

description: Pass function to function with different number of variables


rawDescription: How many times is a particular row present?


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

data1 = 3 * np.random.random((10, 10))
data2 = 5 * np.random.random((10, 10))

levels = [0, 1, 2, 3, 4, 5]
colors = ['red', 'brown', 'yellow', 'green', 'blue']
cmap, norm = matplotlib.colors.from_levels_and_colors(levels, colors)

fig, axes = plt.subplots(ncols=2)
for ax, dat in zip(axes, [data1, data2]):
    im = ax.imshow(dat, cmap=cmap, norm=norm, interpolation='none')
    fig.colorbar(im, ax=ax, orientation='horizontal')
plt.show()

rawDescription: how to define colormap with absolute values with matplotlib

description: Define colormap with absolute values with matplotlib


code: [('foo', 'bar'), ('breakfast', 'spam,eggs'), ('blt', 'bacon,lettuce,tomato'), ('spam', 'spam')]

rawDescription: Regular expression to match comma separated list of key=value where value can contain commas


code:
import random

# prints an endless list of random numbers
while True:
    num = random.randint(0, 1000)
    print(num)

rawDescription: how to loop random.randint(0, 1000) to print all resuts at once line by line?

description: Loop random.randint(0, 1000) to print all resuts at once line by line


rawDescription: Edit an element in a list - python

description: Edit an element in a list - python


code: ['adam', 'lisa']

rawDescription: test list for membership and store only first true item + python

description: Test list for membership and store only first true item + python


code:
def handle_accept(self):
    pair = self.accept()
    if pair is not None:
        sock, addr = pair
        print ('Incoming connection from %s' % repr(addr))

rawDescription: Cant receive Data using Asyncore Python

description: Cant receive Data using Asyncore Python


code:
from sqlalchemy.orm.collections import collection, MappedCollection

class GroupedCollection(MappedCollection):

  def __init__(self):
    super(GroupedCollection, self).__init__(
      self,
      lambda e: e.resource_id # the key we want to group by
    )

  @collection.internally_instrumented
  def __setitem__(self, key, value, _sa_initiator=None):
    if key in self:
      # there is already another comment for that resource
      # we simply append the comment (or you could do something
      # more fancy here if you would like to order the comments)
      self[key]['comments'].append(value)
    else:
      # we create a new entry with a dictionary containing the
      # resource and comment
      super(GroupedCollection, self).__setitem__(
        key,
        {'resource': value.resource, 'comments': [value]},
        _sa_initiator
      )

rawDescription: How to construct query using the SQLAlchemy ORM

description: Construct query using the SQLAlchemy ORM


code: data = r.json()

rawDescription: storing data retrieved from REST api into variables in python

description: Storing data retrieved from REST api into variables in python


code:
orig_prettify = bs4.BeautifulSoup.prettify
r = re.compile(r'^(\s*)', re.MULTILINE)
def prettify(self, encoding=None, formatter="minimal", indent_width=4):
    return r.sub(r'\1' * indent_width, orig_prettify(self, encoding, formatter))
bs4.BeautifulSoup.prettify = prettify

rawDescription: Custom indent width for BeautifulSoup .prettify()


code:
with open('out.txt', mode = 'w') as filehandle:
    filehandle.write('\n'.join(results))

rawDescription: How to copy specific data out of a file using python?

description: Copy specific data out of a file using python


code:
base_url ='http://somewebsite.com/'
for i in range(0,len(parser.onclicks)):
    url = base_url + parser.onclicks[i][:-1] # use onclick without the last character (&)
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0')
    response = urllib2.urlopen(req)
    responseData = response.read()

rawDescription:
How to scrape onclick value (
<a id="FR123456" onclick=) and its name and image using python?

description:
Scrape onclick value (
<a id="FR123456" onclick=) and its name and image using python


rawDescription: interpolating a rotation through an angle with numpy

description: Interpolating a rotation through an angle with numpy


code: card = {'1 of hearts': 1, '2 of hearts': 2, 'ace of hearts':[1, 11]}

rawDescription: Assigning multiple values to a dictionary key- Python


code:
def Create_new_Table(_loc):
    global engine
    global metadata
    global Base
    Records = Table(_loc, metadata,
        Column('device', String(17), primary_key=True),
        Column('data1', Text()),
        Column('location', Text()),
        Column('data2', Text()),
        extend_existing=True
    )
    Base.metadata.create_all(bind=engine, checkfirst=True)
    Records.create(engine, checkfirst=True)

rawDescription: Python SQLAlchemy create dymanic unknown tables


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

fig, axes = plt.subplots(ncols=3)

for ax in axes:
    x = np.random.random(np.random.randint(3, 6))
    ax.pie(x)
    ax.axis('equal')

plt.show()

rawDescription: Creating Pie Subplots of Circular Type in Python


code:
timeit.timeit("sum(range(33000000))", number=1)
timeit.timeit("sum(range(33000000))", number=1)

rawDescription: Python : efficiency concerns in parallel async calls to fetch data from web services


code:
import datetime
datetime.timedelta(days=3)
print(datetime.timedelta(days=3))
print(datetime.timedelta(hours=3))

rawDescription: How to extract time and store in an Array/Structure

description: Extract time and store in an Array/Structure


code: array[xs]

rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


code: strings = [''.join(combo) for combo in product(*(mapping[d] for d in data))]

rawDescription: All combinations of a mapped list of lists in python


code:
min(xrange(len(a)), key=a.__getitem__)
min(enumerate(a), key=lambda L: L[1])[0]
import operator
min(enumerate(a), key=operator.itemgetter(1))[0]

rawDescription: For loops over a list

description: For loops over a list


code:
COLSIZE = 12
# Maybe COLSIZE = max(map(len,llegadas))+1
NUMCOLS = 7
formatstring = "{}{}{}".format("{:",COLSIZE,"}")*NUMCOLS
# {:COLSIZE}*NUMCOLS

headers = ["VUELO","AEROLINEA","PROCEDENCIA","FECHA","HORA","ESTADO","PUERTA"]

print(formatstring.format(*headers))
print(formatstring.format(*llegadas))

rawDescription: aligning, spacing in python 3

description: Aligning, spacing in python 3


code:
if __name__ == 'Mix_Meld':
    ClassName.mix()
    ClassName.meld()

rawDescription: Executing python class code located in folders


rawDescription: Is there a simpler code for defining next_date?


code:
def sum_even_odd(lst):
    if not lst:                      # empty list, we're done
        return (0, 0)                # counters are zero for empty list
    elif lst[0] % 2 == 0:            # current value is even
        x, y = sum_even_odd(lst[1:]) # recursive call
        return (lst[0] + x, y)       # increment even counter
    else:                            # current value is odd
        x, y = sum_even_odd(lst[1:]) # recursive call
        return (x, lst[0] + y)       # increment odd counter

rawDescription: how to sum even and odd numbers of an array using recursion

description: Sum even and odd numbers of an array using recursion


code: chosen_reads.append((ds, s2))

rawDescription: choosing reads with Hamming distance zero

description: Choosing reads with Hamming distance zero


code:
def do_something_remote():
    s = requests.session()
    blah = s.get('http://www.example.com/')
    return s

def other_function():
    s = do_something_remote()
    something_else_with_same_session = s.get('http://www.example.com/')

rawDescription: python-requests keep session between function

description: Python-requests keep session between function


code:
new_data = {u'rating': 0.0, u'name': u'Samsung NP550P5C-S02IN (3rd Gen Ci7/ 8GB/ 1TB/ Win7 HP/ 2GB Graphics)', u'price': 0.0, u'popularity': 9, u'brand_id': 1, u'category_id': 3, u'id': 3794}
full_list.append(new_data)

rawDescription: Creating a dictionary of dictionaries in Python


code:
IV = base64.b64decode(IV)
LastByte = IV[-1]
NewByte = chr(ord(LastByte) ^ x)
newIV = IV[:-1] + NewByte
newIV = base64.b64encode(newIV)

rawDescription: Altering the Last Byte of a String

description: Altering the Last Byte of a String


code:
import csv
import sys
d = {'A1137': {'Called': 10, 'hom_alt': 10, 'private_hom': 8},
     'A2160': {'Called': 10, 'hom_alt': 1, 'hom_ref': 9},
     'A2579': {'Called': 10, 'hom_alt': 1, 'hom_ref': 9},
     'A2594': {'Called': 9, 'hom_alt': 1, 'hom_ref': 8}}
fields = sorted(d)
stats = sorted(set().union(*d.values()))
w = csv.DictWriter(sys.stdout, delimiter='\t', fieldnames=['stats'] + fields)
w.writerow({'stats': '#Global Statistics:'})
w.writeheader()
for stat in stats:
    # produce a dictionary mapping field name to specific statistic for
    # this row
    row = {k: v.get(stat, 0) for k, v in d.items()}
    row['stats'] = stat
    w.writerow(row)

rawDescription: print nested dict to tsv format file

description: Print nested dict to tsv format file


code:
parser.add_argument("-l", "--lambda",
    help="Defines the quantity called lambda",
    type=float, dest='lambda_', metavar='LAMBDA')

rawDescription: Python: How to escape 'lambda'

description: Python: How to escape 'lambda'


code:
L = []
for a in list1:
    for b in list2:
        if a != b:
            L.append(a+' '+b)

L

rawDescription: Joining two list together into one without repeating


code:
class MyModel(models.Model):
    def __init__(self, *args, **kwargs):
        # Don't do any extra looping or anything in here because this gets called
        # at least once for every row in each query of this table
        self._meta.fields[2].model_instance = self
        super(MyModel, self).__init__(*args, **kwargs)
    field1 = models.TextField()
    field2 = models.PickleField()
    field3 = models.DateTimeField()

rawDescription: Django Pickle Field Access to its model instance on load


rawDescription: Using Windows 7 taskbar features in PyQt


code:
import configparser
my_config_parser = configparser.SafeConfigParser()
my_config_parser.read('name of your configuration file')
payload = {
    'action': my_config_parser.get('DEFAULT','action'),
    'email': my_config_parser.get('DEFAULT','email'),
    'password': my_config_parser.get('DEFAULT','password')
}

rawDescription: Python create windows exe with a config file to pass username and password


code: all = {group.get("id"): {value.get("id"): value.text for value in group.findall("value")} for group in root.findall("subroot")}

rawDescription: python - Values not being pulled from XML

description: Python - Values not being pulled from XML


code:
def setup_function(fun):
    print ("in setup function: " + fun.__name__)

def test_test():
    assert False

rawDescription: How to use xunit-style setup_function

description: Use xunit-style setup_function


code:
def find_max_var_amt(some_person):
    return max(len(value) for value in patients[some_person].__dict__.itervalues())

rawDescription: How to rewrite this Dictionary For Loop in Python?

description: Rewrite this Dictionary For Loop in Python


rawDescription: How to plot data with Python from text file

description: Plot data with Python from text file


code:
fs = fr.split()
print(min(int(i) for i in fs))
print(max(int(i) for i in fs))

rawDescription: How to find min and max in python?

description: Find min and max in python


rawDescription: I have a couple of questions on shelves in the module pickle?


code: return [("id",20,"integer"),("companyname",50,"text")] + getproducts() + ...

rawDescription: Partially flattening a list

description: Partially flattening a list


code:
import os
import sys
os.chdir(os.path.dirname(sys.argv[0]))

rawDescription: Python script executed from its own directory


code: dfs = {team:grp for team, grp in result.reset_index().groupby('team')}

rawDescription: Pandas: return a Dataframe with multiple aggregate values conditioned on another value


code:
for i in range(len(mylist)):
    for j in range(i + 1, len(mylist)):
        compare(mylist[i], mylist[j])

rawDescription: How to compare each item in a list with the rest, only once?

description: Compare each item in a list with the rest, only once


code:
parser.set_defaults(request=("get_all",None))

request_args = {"id":'get by id',
                "model_no":"get by model number",
                "color":"get by color"}

grp2 = parser.add_mutually_exclusive_group()
for arg_name, help_text in request_args.items():
    grp2.add_argument("--"+arg_name, help=help_text, dest="request",
                      type=(lambda x, arg_text=arg_name:(arg_text,x)))

rawDescription: Advice for using argparse

description: Advice for using argparse


code:
class TwoWayDict(dict):
    def __setitem__(self, key, value):
        # Remove any previous connections with these values
        if key in self:
            del self[key]
        if value in self:
            del self[value]
        dict.__setitem__(self, key, value)
        dict.__setitem__(self, value, key)

    def __delitem__(self, key):
        dict.__delitem__(self, self[key])
        dict.__delitem__(self, key)

    def __len__(self):
        """Returns the number of connections"""
        return dict.__len__(self) // 2

rawDescription: Two way/reverse map

description: Two way/reverse map


code:
COUNTRY_CODE = 'CL'
TIMEZONE = "America/Santiago"
LOCALE = "es_CL"
DEFAULT_PAGE_SIZE = 20

ENV = {
    'production': {
        'TABLE_NAME': "dynamodbTable",
        'BUCKET_NAME': "sssBucketName"

    },
    'testing': {
        'TABLE_NAME': "dynamodbTableTest",
        'BUCKET_NAME': "sssBucketNameTest"

    },
    'test-invoke-stage': {
        'TABLE_NAME': "dynamodbTableTest",
        'BUCKET_NAME': "sssBucketNameTest"
    }
}

rawDescription: Using different settings on a aws lambda function coded in python


code:
s = r'C:\Users\Client\tests\doc_test_hard.docx'
s

rawDescription: How to avoid '\n' and '\t' escaping sequence when string is assigned to a variable

description: Avoid '\n' and '\t' escaping sequence when string is assigned to a variable


code:
class MyInt(int):
    difference = int.__sub__

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code:
# models.py
class Page(models.Model):
    hits = models.PositiveIntegerField()

# views.py
def hit(request, page_pk):
    Page.objects.filter(pk=page_pk).update(hits=F('hits')+1)
    return HttpResponse()

rawDescription: Django AJAX increment

description: Django AJAX increment


code:
def test(x):
    return x + 6
test(1) # call test with the argument x = 1
a = test # assign the function "test" to a new variable "a" - this is not calling test
a
a(1) # now call that function again with the same value for x = 1

rawDescription: python executing nested functions

description: Python executing nested functions


code:
def collatz(number):
    print(number)
    while number != 1:
        if number % 2 == 0:
            number //= 2
        else:
            number = number * 3 + 1
        print(number)

rawDescription: Python, Loop - Do statements until specific answer is given


code:
dictionary = {}
with open('dict.txt', 'r') as file:
    for line in file:
        split_line = line.split()
        dictionary[split_line[0]] = split_line[1]

with open('input_file.txt', 'r') as input_file:
    with open('output_file.txt', 'w') as output_file:
        for line in input_file:
            for word in line.split():
                output_file.write(dictionary.get(word.lower(), 'UNKNOWN_WORD'))
                output_file.write(' ')
            output_file.write('\n')

rawDescription: How can I translate from one file to another using a dictionary?

description: Translate from one file to another using a dictionary


code: s = "submitted 1 year ago by bagelpirate to /r/books"

rawDescription: Removing a certain part of a string in python


code:
import json
json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')

rawDescription: Python: Access a dictionary that is located inside of a text file


code:
def shuffle(self, x, random=None, int=int):
    """x, random=random.random -> shuffle list x in place; return None.

    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.
    """

    if random is None:
        random = self.random
    for i in reversed(xrange(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random() * (i+1))
        x[i], x[j] = x[j], x[i]

rawDescription: oneliner scramble program

description: Oneliner scramble program


rawDescription: Login form for custom users in django

description: Login form for custom users in django


code:
mx = max((len(str(ele)) for sub in myArray for ele in sub))
for row in myArray:
    print(" ".join(["{:<{mx}}".format(ele,mx=mx) for ele in row]))

rawDescription: How to line up columns when printing from 2d array in Python?

description: Line up columns when printing from 2d array in Python


code: [my_functionb(my_functiona(x)) for x in a]

rawDescription: python "multiple" combine/chain list comprehension

description: Python "multiple" combine/chain list comprehension


code:
fill_color = (255,255,0) #define the colour as (R,G,B) tuple

highlightImage = Image.new(primaryImage.mode, #same mode as the primary
                           primaryImage.size, #same size as the primary
                           fill_color)#and the colour defined above

rawDescription: Overlaying coloured pixels on top of an image using Python Imaging Library


code:
import numpy as np
from scipy import ndimage
np.random.seed(2016)

labmat, n = ndimage.label(np.random.rand(30,30,30) > 0.5)
data_slices = ndimage.find_objects(labmat)
sizes = np.array([[s.stop-s.start for s in object_slice]
                  for object_slice in data_slices])
mask = (sizes > 1).all(axis=1)
idx = np.flatnonzero(mask)
for i in idx:
    print(labmat[data_slices[i]])

rawDescription: Objects' sizes along dimension?

description: Objects' sizes along dimension


code:
import time
from collections import namedtuple

SourceAddress = namedtuple('SourceAddress', ['ip', 'port'])
DestinationAddress = namedtuple('DestinationAddress', ['ip', 'port'])
RouteEntry = namedtuple('RouteEntry', ['source', 'destination', 'comment'])

def save_routes(table, sip, sport, dip, dport, key):
    src = SourceAddress(sip, sport)
    dst = DestinationAddress(dip, dport)
    entry = RouteEntry(src, dst, key)

    table.setdefault(int(time.time()), []).append(entry)

route_table = {}

save_routes(route_table, '192.168.249.132', '20275', '192.168.249.133', '80', 'll')
save_routes(route_table, '192.168.249.132', '9065', '192.168.249.133', '80', 'll')
save_routes(route_table, '192.168.249.132', '6266', '192.168.249.133', '80', 'He')
time.sleep(1)
save_routes(route_table, '192.168.249.132', '10867', '192.168.249.133', '80', 'o')
save_routes(route_table, '192.168.249.132', '20275', '192.168.249.133', '80', 'He')
save_routes(route_table, '192.168.249.132', '37189', '192.168.249.133', '80', 'o')

rawDescription: How to associate multiple things using dictionary?

description: Associate multiple things using dictionary


code:
a.third_attribute = 'three'
a.third_attribute

rawDescription: Python Class Fields

description: Python Class Fields


code:
def seek_newline_backwards(file_obj, eol_char='\n', buffer_size=200):
    if not file_obj.tell(): return # already in beginning of file
    # All lines end with \n, including the last one, so assuming we are just
    # after one end of line char
    file_obj.seek(-1, os.SEEK_CUR)
    while file_obj.tell():
        ammount = min(buffer_size, file_obj.tell())
        file_obj.seek(-ammount, os.SEEK_CUR)
        data = file_obj.read(ammount)
        eol_pos = data.rfind(eol_char)
        if eol_pos != -1:
            file_obj.seek(eol_pos - len(data) + 1, os.SEEK_CUR)
            break
        file_obj.seek(-len(data), os.SEEK_CUR)

rawDescription: Two simple questions about python

description: Two simple questions about python


code:
# example
import itertools
...
f.write(', '.join('{}({})'.format(string, number) for string, number in itertools.izip(w, prob5)))
#f.write(', '.join('{}({})'.format(string, number) for string, number in itertools.izip_longest(w, prob5))) # if w and prob5 have a different number of elements

rawDescription: How can I output the data in a customized way?

description: Output the data in a customized way


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

def message(request, socket, context, message):
    session = Session.objects.get(session_key=message['session_key'])
    uid = session.get_decoded().get('_auth_user_id')
    user = User.objects.get(pk=uid)

rawDescription: Getting User in django-socketio

description: Getting User in django-socketio


code: print ("hello world")

rawDescription: Python 2.7: What print() does to the string inside of it


code:
records = ["record_a:", "a", "b", "record_b:", "1", "2", "3", "4"]
records = list(chunkRecords(records))
records

rawDescription: chunking list by delimiter in Python

description: Chunking list by delimiter in Python


code:
cp /opt/hivemq/bin/init-script/hivemq-debian /etc/init.d/hivemq
chmod +x /etc/init.d/hivemq

rawDescription: HiveMQ and IoT control

description: HiveMQ and IoT control


code:
numpy.array(['hello', 'world!'])
numpy.array(['hello', 'world!'], dtype=object)

rawDescription: numpy array of python objects

description: Numpy array of python objects


code:
from email.parser import HeaderParser
msg = HeaderParser().parsestr(header) # or parsestr(msg) if you have the whole msg
return_path = msg.get('Return-Path')

rawDescription: Parsing "Return-Path:" in Python

description: Parsing "Return-Path:" in Python


code: coords=np.c_[xx.ravel(), yy.ravel()]

rawDescription: Numpy: How to create a grid-like array?

description: Numpy: How to create a grid-like array


rawDescription: Django - Use one models primary key in another model


code: reg_val_msb, reg_val_lsb = struct.pack('<H', 0xABCD)

rawDescription: How to split 16-bit unsigned integer into array of bytes in python?

description: Split 16-bit unsigned integer into array of bytes in python


code:
name = raw_input('Please enter search criteria: ')
name = name.strip() # remove whitespace at the beginning and the end of the string
name = name.capitalize() # capitilize the first letter

rawDescription: Searching dictionaries in Python

description: Searching dictionaries in Python


code: data = [[i.replace('%', '') for i in j] for j in data]

rawDescription: Find and Replace Percent Signs - Python

description: Find and Replace Percent Signs - Python


code: filter(lambda item: item % 2 != 0, a)

rawDescription: python for loop with "reducing" list

description: Python for loop with "reducing" list


code:
x = data[:, 18].astype(float)
y = data[:, 19].astype(float)
z = data[:, 6].astype(float)
f = (x+y) / z
average = np.average(f)

rawDescription: Selecting and operating on columns in a .csv


code: maximum = max(list2,key=lambda x:x[2])

rawDescription: What am I doing wrong? Python Reading and Distinguishing


code:
def printText(self, surface):
    if self.counter < 20:
        text = pygame.font.SysFont("Pixelated Regular", 30)
        label = text.render("Hello", 0, (0,0,0,))
        surface.blit(label, (100,100))
        self.counter += 1
    else:
        self.pressed = False

rawDescription: Pygame - Blitting Text even after the Key is Pressed


code:
keywords = ['if', 'def', 'class']
line = 'if def word'
len(set(line).intersection(set(keywords))) > 1
len(set(line.split()).intersection(set(keywords))) > 1

rawDescription: Returning lines containing two or more keywords


code:
def running_average():
  sum = 0
  count = 0
  while True:
    sum += cauchy(3,1)
    count += 1
    yield sum/count

rawDescription: Running average in Python

description: Running average in Python


code:
for _ in range(7):
    # instead of three separate variables, we use a list here
    # the nice thing is, that you can freely vary the number of
    # 'parallel' dice rolls this way
    dice = [random.randint(1, 6) for _ in range(3)]

    # this is more general and will break as soon as there are
    # duplicate (die) values in the list (meaning, break, if not all elements
    # are different)
    if len(dice) > len(set(dice)):
        break

rawDescription: Python - calculate die rolls and count doubles


code: [" ".join(g) for k, g in groupby(my_list, "\n".__ne__) if k]

rawDescription: Split list in and then join elements in sublists


code: x = x > 9 and 0 or x

rawDescription: Zero assignement in inline comparison

description: Zero assignement in inline comparison


code:
import helper

helper.some_helper()

rawDescription: Getting entry point scripts path in scripts called by it


code:
import time

current_milli_time = lambda: int(round(time.time() * 1000))

rawDescription: Get current time in milliseconds in Python?


code: df.pivot_table(rows='id', cols='colours', aggfunc=len, fill_value=0)

rawDescription: Grouping data in a dataframe to produce lists against unique ids in Pandas/Python


code:
old_sort = MyList.sort
def new_sort(self, key=None, reverse=None):
    if key is None:
        key = int
    return old_sort(self, key, reverse)
MyList.sort = new_sort

rawDescription: How do you use redefine a method and still use the original unmodified inherited method in the method?

description: Use redefine a method and still use the original unmodified inherited method in the method


code:
import math
def calculateRange (x1, x2, y1, y2):
  squareNumber = math.sqrt(math.pow ((x1-x2),2) + math.pow((y1-y2),2))
  return round(squareNumber, 1)
x = 2
y = 3
mxr = 30
inputlist = [
   {'town':'A', 'x':12, 'y':13},
   {'town':'B', 'x':100, 'y':43},
   {'town':'C', 'x':19, 'y':5}
]
for entry in inputlist:
    entry['r'] = min(mxr, calculateRange(x, entry['x'], y, entry['y']))

inputlist

rawDescription: Python iterate list of dicts and create a new one


rawDescription: how in python to split a string with unknown number of spaces as separator?

description: How in python to split a string with unknown number of spaces as separator


code:
import json
with open('a.txt','r') as f:
    pprint.pprint(json.load(f))

rawDescription: how do I import an array containing dictionary from a text file?

description: Import an array containing dictionary from a text file


code: somelist+=[[x+f(t) for x,t in zip(somelist[-1],itertools.count(someStartTime,delta))]]

rawDescription: Loop over time and over list elements with python -- one-dimensional lake temperature model simulation


rawDescription: How to extract 4 characters after '-' in a hostname

description: Extract 4 characters after '-' in a hostname


code:
def genDigit():
    from random import randint
    return randint(0, 9)

digits = [genDigit(), genDigit(), genDigit(), genDigit()]

rawDescription: Python function to create random numbers


rawDescription: More pythonic way to manage a list of callbacks


code:
import sqlite3
con = sqlite3.connect('simple.db')
c = con.cursor()

dic = {
    'x1':{'y1':1.0,'y2':0.0},
    'x2':{'y1':0.0,'y2':2.0,'y3':1.5},
    'x3':{'y2':2.0,'y3':1.5}
    }

# 1. Find the unique column names.
columns = set()
for cols in dic.values():
    for key in cols:
       columns.add(key)

# 2. Create the schema.
col_defs = [
    # Start with the column for our key name
    '"row_name" VARCHAR(2) NOT NULL PRIMARY KEY'
    ]
for column in columns:
    col_defs.append('"%s" REAL NULL' % column)
schema = "CREATE TABLE simple (%s);" % ",".join(col_defs)
c.execute(schema)

# 3. Loop through each row
for row_name, cols in dic.items():

    # Compile the data we have for this row.
    col_names = cols.keys()
    col_values = [str(val) for val in cols.values()]

    # Insert it.
    sql = 'INSERT INTO simple ("row_name", "%s") VALUES ("%s", "%s");' % (
        '","'.join(col_names),
        row_name,
        '","'.join(col_values)
        )
    c.execute(sql)

rawDescription: How to insert and call by row and column into sqlite3 python

description: Insert and call by row and column into sqlite3 python


code:
from functools import reduce

print("The product of the list is", reduce(lambda x,y:x*y, numbertotal))

rawDescription: How can I multiply numbers in a list (after removing duplicates)?

description: Multiply numbers in a list (after removing duplicates)


code:
for f, b in zip(foo, bar):
    print(f, b)

rawDescription: How can I iterate through two lists in parallel in Python?

description: Iterate through two lists in parallel in Python


code:
func_dict = {}

def collected_func(func):
    key = int("".join(c for c in func.__name__ if c.isdigit()))
    func_dict[key] = func
    return func

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

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


code:
data = randn(1000, 3)
data
data[rand(len(data)) > 0.5] = nan
data
df = DataFrame(data, columns=list('abc'))
df.head()
df.count()
df.notnull().sum()

rawDescription: Number of non-missing values in array? Len(x) excluding missing values?


code:
from communicate import *
x = execute_and_receive("2.py")
y = x + 2

rawDescription: How to Get Variable from another .py

description: Get Variable from another .py


code:
class Grepper(object):
    def __init__(self, patterns, debug=False):
        self.patterns = [re.compile(p) for p in patterns]
        self.debug = debug

    def matchline(self, debug):
        for line in sys.stdin:
            if all(p.search(line) for p in self.patterns):
                sys.stdout.write(line)
                if self.debug:
                    CodeTrace(line, self.patterns).trace(line)

rawDescription: Take multiple patterns from cli. argparse Python3


code: liststore.set_value(row_iter, col_n, 'new value')

rawDescription: pygtk - how update a gtk.liststore?

description: Pygtk - how update a gtk.liststore


code:
class CTest(tuple):
    def __new__(cls, arg):
        if type(arg) is tuple:
            return super(CTest, cls).__new__(cls, (2, 2))
        else:
            return super(CTest, cls).__new__(cls, arg)

rawDescription: Why does my Python inheritance/super example not work?


rawDescription: How to limit a number to be within a specified range? (Python)

description: Limit a number to be within a specified range? (Python)


code:
import re
src="hello\n#foo\n#bar\n#baz\nworld\n"
line_gen = (m.group(1) for m in re.finditer("(.*?)(\n|$)",src))
'\n'.join(s for s in line_gen if not s.startswith("#"))

rawDescription: How do I split a string and rejoin it without creating an intermediate list in Python?

description: Split a string and rejoin it without creating an intermediate list in Python


code: minutes = mytime.total_seconds() // 60

rawDescription: subtraction date - how to get result in minutes

description: Subtraction date - how to get result in minutes


code:
reelpos = []
for reel in reels:
    reelpos.append(list(zip(reel,
                            reel[1:] + reel[:1],
                            reel[2:] + reel[:2])))

rawDescription: Effectively generate slot machine outcome


code:
def plot(request, chartID = 'chart_ID', chart_type = 'line', chart_height = 500):
    data = ChartData.check_valve_data()

    chart = {"renderTo": chartID, "type": chart_type, "height": chart_height,}
    title = {"text": 'Check Valve Data'}
    xAxis = {"title": {"text": 'Serial Number'}, "categories": data['serial numbers']}
    yAxis = {"title": {"text": 'Data'}}
    series = [
        {"name": 'Mass (kg)', "data": data['mass']},
        {"name": 'Pressure Drop (psid)', "data": data['pressure drop']},
        {"name": 'Cracking Pressure (psid)', "data": data['cracking pressure']}
        ]

    return render(request, 'unit/data_plot.html', {'chartID': chartID, 'chart': chart,
                                                    'series': series, 'title': title,
                                                    'xAxis': xAxis, 'yAxis': yAxis})

rawDescription: Passing Django Database Queryset to Highcharts via JSON


rawDescription: Python 3 string formatting with filler more than one character long


code:
list = ['LnNlbHBtYXhlIGVzdSBvdCBlZXJmIGxlZUYgLnNldGlzYmV3IGNpZmZhcnQgaGdpaCBubyBub2l0YXNpbGFtcm9uZWQgZm8gdHBlY25vYyBlaHQgZWJpcmNzZUQgLjQ=', 'ZWxpZiBlbm8gbmkgZWIgdHN1TSApaXYgICAg', 'c25vaXRhY2lmaWNlcHMgOC1QRVAgdGVlbSB0c3VNICl2ICAgIA==', 'Ni4yIG5vaHR5UCBodGl3IGtyb3cgdHN1TSApdmkgICAg', 'c2VsdWRvbSByZWh0byB5YiBlbGJhdHJvcG1pIGViIGRsdW9ocyBzc2FsQyApaWlpICAgIA==']
for s in list:
    s = s.decode('base64', 'strict')
    print (s[::-1])

rawDescription: Decoding reversed mulitline string encoded in base64 format automatically


code:
def make_any_function_partial(i):
    def wrapped():
        return any_function(i)
    return wrapped
b = Button(app_name, text="..." , command = make_any_function_partial(7))

rawDescription: tkinter , python , buttons

description: Tkinter , python , buttons


code:
class Operation(Base):
    __tablename__ = 'operations'
    id = Column(Integer, primary_key=True)
    anesthesia_id = Column(Integer, ForeignKey('anesthesias.id'))
    anesthesia = relationship('Anesthesia', backref='used_in_operations')

rawDescription: multiple/split class associations in sqlalchemy

description: Multiple/split class associations in sqlalchemy


code:
from collections import Mapping

class MyDict(Mapping):
    def __init__(self, *args, **kwargs):
        self.update(dict(*args, **kwargs))

    def __setitem__(self, key, item):
        self.__dict__[key] = item

    def __getitem__(self, key):
        return self.__dict__[key]

    def __delitem__(self, key):
        del self.__dict__[key]

    def pop(self, k, d=None):
        return k,self.__dict__.pop(k, d)

    def update(self, *args, **kwargs):
        return self.__dict__.update(*args, **kwargs)

    def __iter__(self):
        return iter(self.__dict__)

    def __len__(self):
        return len(self.__dict__)

    def __repr__(self):
        return repr(self.__dict__)

rawDescription: Neat way of popping key, value PAIR from dictionary?


code:
d = DequeLL()
d.addFrontDLL('circle')
d.addFrontDLL('arc')
d.addRearDLL('123')
d.addFrontDLL('arc')
d.addFrontDLL('circle')
d.addRearDLL('123')

rawDescription: Python: Linklist deque addfront & addrear


code:
import os

def filterls(src, filter_func):
    for root, dirs, files in os.walk(src):
        for f in files:
            if filter_func(f):
                path = os.path.join(root, f)
                yield path[len(src)+1:]

rawDescription: Copying files recursively with skipping some directories in Python?


code:
class Foo(models.Model):
    ...

    def my_action_link(self, obj):
        return 'Action name' %obj.id
    my_action_link.short_description = 'My action'
    my_action_link.allow_tags = True

rawDescription: Customizing django admin site - in row buttons


code:
from test1 import MyClass
my_instance = MyClass()
my_instance.test()
print(my_instance.data[1])

rawDescription: What is best way to access variables from different python modules?


code:
import re
from IPython.core import splitinput
from IPython.core.inputsplitter import transform_escaped

# this is a one-character change, adding colon to the second group,
# so the line splitter will interpret ':' as an escape char
splitinput.line_split = line_split = re.compile("""
             ^(\s*)               # any leading space
             ([,;/%:]|!!?|\?\??)?  # escape character or characters
             \s*(%{0,2}[\w\.\*]*)     # function/method, possibly with leading %
                                  # to correctly treat things like '?%magic'
             (.*?$|$)             # rest of line
             """, re.VERBOSE)

# treat colon the same as percent:
transform_escaped.tr[':'] = transform_escaped._tr_magic

rawDescription: change IPython magic function prefix (from '%' to ':'), Anyway to?

description: Change IPython magic function prefix (from '%' to ':'), Anyway to


code:
sets, node = [{1, 4}, {4, 5}, {4, 10}], (0, 1, 2)
set.intersection(*(sets[x] for x in node))

rawDescription: Using a tuple (i,j,k,...) to construct an intersection list_of_sets[i] & list_of_sets[j] & list_of_sets[k]


code: df

rawDescription: python grouping similar categorical values

description: Python grouping similar categorical values


code:
class LDconfig:
    raw_location = 'C:/Users/OneDrive/raw/'
    output_location = 'C:/Users/OneDrive/output/'
    mtd_location = 'C:/Users/OneDrive/modified/'
    py_location = 'C:/Users/OneDrive/py_files/'

rawDescription: Creating a file to lookup paths and file names?


code:
from add import add
from divide import division
from multiply import multiply
from subtract import subtract
from adv.fib import fibonacci
from adv.sqrt import squareroot

rawDescription: Python - why can I import modules without __init__.py at all?


code:
for row in csvReader:
    dat = [s for s in row if '2015' in s]
    if dat: data.append(dat)

rawDescription: Selecting lists which contain a string value


rawDescription: Re-reading file when cycling over a file object in Python


rawDescription: python: creating histogram out of dictionary

description: Python: creating histogram out of dictionary


code: newList = [-1.0 if abs(x) < 0.5 else 1.0 for x in oldList]

rawDescription: Using Lambda Function in Python to generate a wavelength of numbers from -1.0 to 1.0


code:
import itertools
items = [['118', 'white'], ['118','Jack'], ['118','guilty'],  ['200','black'], ['200','mark'], ['200','not guilty']]
[[x[1] for x in g] for k, g in itertools.groupby(items, lambda x: x[0])]

rawDescription: Combine list of lists with similar values in python


code:
from functools import partial, reduce
combine = lambda *xs: partial (reduce, lambda v,x: x(v), xs)

rawDescription: Combine functions to later use in map

description: Combine functions to later use in map


code:
symlink
ln -s /etc/init.d/go.sh /home/myuser/go.sh

rawDescription: In Amazon EC2, how do I make it run a python script when I "clone" that instance?


Card name: NAMEn

Account holder: NAME

Status: Active

rawDescription: Convert a HTML Table to JSON

description: Convert a HTML Table to JSON


code:
string1 = 'polujsj'
string2 = 'ksjuhjjj'
firstLine = list(' ' + string1)
matrix = [firstLine] + [[c] + [0] * len(string1) for c in string2]

for line in matrix:
    print(' '.join(map(str, line)))

rawDescription: Filling in 2d array with particular values


code:
connector = TenaciousConnector()
client = connector.init_client("http://example.com/webservice/wsdl")
client.factory.create('Widget')

rawDescription: Python, suds - dealing with rotten WSDL caches and responses


code: {{ item.added__max }}

rawDescription: How to get max value in django ORM

description: Get max value in django ORM


code:
for num in xrange(rows):
    print(' '.join('*' * min(num + 1, rows - num)).center(rows))

rawDescription: diamond structure using asterix in python

description: Diamond structure using asterix in python


code:
def traverse(i):
    for d in i:
        c = d.get('childs')
        yield from (d['kw']+' '+j for j in (traverse(c) if c else ['']))

rawDescription: Walk recursively through childs of a list in Python


code:
def createfile():
    var = """
#!/bin/sh
echo ${test}
          """
    return var

v = createfile()

rawDescription: store formatted text in variable python

description: Store formatted text in variable python


code:
while (True):               # <- infinite while loop
    lo += 1
    for i in range(len(l)): # <- for loop
        if not l[i] < 3:
            break           # <- break the for loop
        print(lo)
    # while loop continues

rawDescription: python combine 'while loop' with 'for loop' to iterate through some data

description: Python combine 'while loop' with 'for loop' to iterate through some data


code:
def class_filter(elm):
    try:
        classes = elm["class"]
        return classes[0].startswith("dog-") and classes[1].endswith("-cat")
    except (KeyError, IndexError, TypeError):
        return False

rawDescription: Searching for pieces of an attribute with Beautiful Soup


code: issubclass(MetaClass, type)

rawDescription: Determine if a class in python is a metaclass


code:
if set(motherList) & set(fatherlist) & set(sonList):
    ans = "Mendelion"
else:
    ans = "Non-Medelian"

rawDescription: Comparing 3 lists in Python

description: Comparing 3 lists in Python


rawDescription: Findall regex in python

description: Findall regex in python


code:
wx.SIMPLE_BORDER
wx.RAISED_BORDER
wx.SUNKEN_BORDER
wx.NO_BORDER

rawDescription: How to add an outline border to a widget?

description: Add an outline border to a widget


rawDescription: How to modify elements of iterables with iterators? I.e. how to get write-iterators in Python?

description: Modify elements of iterables with iterators? I.e. how to get write-iterators in Python


code:
import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

rawDescription: Python - round up to the nearest ten

description: Python - round up to the nearest ten


code:
zip(li1, li2)
list(zip(li1, li2))

rawDescription: How to write parallel loop iterations in one line (lists have unequal lengths)

description: Write parallel loop iterations in one line (lists have unequal lengths)


rawDescription: Numpy genfromtxt issue with datetime with multiple columns


code:
import os
os.system("ls -l")

rawDescription: Python Script execute commands in Terminal


code:
list.sort();
list.unique();

rawDescription: Removing items in list, python style and c++ style


code:
def to_translation_map(iterable):
    return {key: None for key in iterable}
    #return dict((key, None) for key in iterable) #For old versions of Python without dict comps.

rawDescription: making difflib's SequenceMatcher ignore "junk" characters

description: Making difflib's SequenceMatcher ignore "junk" characters


code:
from struct import unpack

# data recieved, 88 random bytes for example purpose
data = b'\xdb[\x91wdI\t\xef\xc6c\xde\x14\xac\x1e\x08\x10.f\xc0\xbd\xfd\xa15\x8cP\x101\xed\xc5\xd9\x98X\xb5\xc2\x00Z\xd2\xb9\xb0Xa\x04\xfa\xb8\xceA\x94_7\xc7\xde\t\xf2kX\x9d2\xc3\x84\xb3\x19\x8e\xf5\x99\xc3\xba\x08\xaa0$\x17\xfbd\xbb\x7f\xfd&\xf5\x1aU\t`\x11@zD\xce\xff'

# unpack the struct into variables
(
    abcde, fw_ver, cur_layer, fs_radix,  # 0 needs parse
    fghij, knpl, fbg_thermistor,  # 1 needs parse
    tx_ambient_temp, reserved2,  # 2
    num_ffpi_peaks, num_fbg_peaks,  # 3
    num_dut2_peaks, num_dut1_peaks,  # 4
    num_dut4_peaks, num_dut3_peaks,  # 5
    reserved7, qr, acq_counter3,  # 6 needs parse
    serial_number,  # 7
    kernel_timestamp_microseconds,  # 8
    kernel_timestamp_seconds,  # 9
    kernel_src_buffer, kernel_buffers,  # 10
    error_and_kernel_rt_loc0,  # 11 needs parse
    header_length, header_ver, buffers,  # 12
    dut2_gain, dut1_gain,  # 13
    dut4_gain, dut3_gain,  # 14
    dut2_noise_thresh, dut1_noise_thresh,  # 15
    dut4_noise_thresh, dut3_noise_thresh,  # 16
    hw_clk_div, peak_data_rate_div,  # 17
    granularity,  # 18
    reserved4,  # 19
    starting_lambda,  # 20
    ending_lambda  # 21
) = unpack(
    '>'  # big endian
    'BBBB'  # 0 needs parse
    'BBH'  # 1 needs parse
    'HH'  # 2
    'HH'  # 3
    'HH'  # 4
    'HH'  # 5
    'BBH'  # 6 needs parse
    'I'  # 7
    'I'  # 8
    'I'  # 9
    'HH'  # 10
    'I'  # 11 needs parse
    'HBB'  # 12
    'HH'  # 13
    'HH'  # 14
    'HH'  # 15
    'HH'  # 16
    'HH'  # 17
    'I'  # 18
    'I'  # 19
    'I'  # 20
    'I',  # 21
    data
)

# 0 parse abcde
acq_triggered = bool(abcde & 0x80)
calibration_fault = bool(abcde & 0x40)
start_of_frame = bool(abcde & 0x20)
primary_fan_state = bool(abcde & 0x10)
secondary_fan_state = bool(abcde & 0x08)
s0_mux_state = bool(abcde & 0x04)
s1_mux_state = bool(abcde & 0x02)
s2_mux_state = bool(abcde & 0x01)

# 1 parse fghij
xfer_type = fghij >> 4
soa_therm_limit = bool(fghij & 0x08)
soa_current_limit = bool(fghij & 0x04)
tec_over_temp = bool(fghij & 0x02)
tec_under_temp = bool(fghij & 0x01)

# 1 parse knpl
operating_mode = knpl >> 6
triggering_mode = (knpl & 0x30) >> 4
sm041_mux_level = (knpl & 0x0c) >> 2
sw_position = knpl & 0x03

# 6 parse qr
nrz_command = qr >> 5
reserved6 = qr & 0x1f

# 11 parse
error = error_and_kernel_rt_loc0 >> 24
kernel_rt_loc0 = error_and_kernel_rt_loc0 & 0xffffff

rawDescription: Unpacking data structure with Python

description: Unpacking data structure with Python


code:
lst
[min(x) for x in lst]
min(x for sublist in lst for x in sublist)

rawDescription: How to pick the smallest value in a list when an iterative process is applied to the list

description: Pick the smallest value in a list when an iterative process is applied to the list


code:
import csv

lines = []
for t in soup.findAll('td', {'class': 'tablaslistOdd'}):
    text = t.text.replace("\t", "").replace("\r", "").replace('\n', '').encode('utf-8')
    lines.append(text)

with open('myCSVfile.csv', 'w') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(lines)

rawDescription: write a CSV file with Python after scraping text from website

description: Write a CSV file with Python after scraping text from website


code:
def main():
    val1, val2 = uInput()
    calc(val1, val2)

def uInput():
    value1 = int(input('Please put in the first number'))
    value2 = int(input('Please put in your second number'))
    return value1, value2

def calc(value1,value2):
    finalNumber = value1 + value2
    print (finalNumber)
main()

rawDescription: Python 3, Passing data from one function to another


rawDescription: Storing a single list of references to elements in several other lists in python


code: bp = df.boxplot(by='Group')

rawDescription: Pandas: boxplot of one column based on another column


code:
import struct, collections

class CStruct(object):

    def __init__(self, typename, format_defn, lead_char="!"):
        self.names = []
        fmts = [lead_char]
        for line in format_defn.splitlines():
            name, fmt = line.split()
            self.names.append(name)
            fmts.append(fmt)
        self.formatstr = ''.join(fmts)
        self.struct = struct.Struct(self.formatstr)
        self.named_tuple_class = collections.namedtuple(typename, self.names)

    def object_from_bytes(self, byte_str):
        atuple = self.struct.unpack(byte_str)
        return self.named_tuple_class._make(atuple)

if __name__ == "__main__":
    # do this once
    pkt_def = """\
        u1 B
        u2 H
        u4 I"""
    cs = CStruct("Packet1", pkt_def)
    # do this once per incoming packet
    o = cs.object_from_bytes(b"\xF1\x00\xF2\x00\x00\x00\xF4")
    print(o)
    print(o.u4)

rawDescription: How to elegantly send/receive a large C struct using Python?

description: Elegantly send/receive a large C struct using Python


code:
c=Camera()
c.add_node_attributes()

rawDescription: python subclasses have general functions shared across them

description: Python subclasses have general functions shared across them


code:
import __builtin__
__builtin__.wordList = loadWords()

rawDescription: Why I get "global name ... is not defined"?


rawDescription: Python string formatting incremental changes


code:
def custom_format(td):
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    formatted = '{:d}:{:02d}'.format(hours, minutes)
    if td.days:
        formatted = '{} day{} {}'.format(
            td.days, 's' if td.days > 1 else '', formatted)
    return formatted

rawDescription: Too many decimal places when using timedelta


code: new_x, new_y = zip(*sorted(zip(x, y)))

rawDescription: Python's Matplotlib plotting in wrong order


rawDescription: Python code for finding unique path from tuple list


rawDescription: How do I split a list at ones?

description: Split a list at ones


rawDescription: Generate random string from regex character set


code:
[r for r in listOfList
   if not any(lst[i] == 1 for i in r) and
      any(lst[i] == 0 for i in r)]

rawDescription: How to improve this list comprehension

description: Improve this list comprehension


code:
from optparse import OptionParser
import inspect
inspect.getmembers(OptionParser, predicate=inspect.ismethod)

rawDescription: C#: reflection-like mechanism into python file (get functions, parameters etc)


rawDescription: Convert DataFrame column type from string to datetime


rawDescription: remove something from each individual element from the array

description: Remove something from each individual element from the array


code: [ x for x in players['SEA'] if x.year == '2001' ]

rawDescription: Python data structure recommendation?

description: Python data structure recommendation


code:
phi = np.linspace(0,360, nphi)/180.0*np.pi
z = np.linspace(0,1.0,nz)

rawDescription: Rounding the edges of a cylinder in matplotlib poly3D


code:
import __future__
help(__future__)

rawDescription: Which python version needs from __future__ import with_statement?


code:
Name, Score
John, 500
Jake, 250

rawDescription: Matching parts of two csv files to return certain elements


animal: dogs

animal: cats

animal: birds

rawDescription: Python csv to json column order

description: Python csv to json column order


rawDescription: How to check if an element of a list is a number?

description: Check if an element of a list is a number


code:
['username1', 'username2', 'username3', 'username4', 'username5']
['User1', 'User2', 'User3', 'User4', 'User5']
['tech.sw.host']

rawDescription: capturing the usernames after List: tag

description: Capturing the usernames after List: tag


code:
while True:
    last_v = v
    ...
    if np.linalg.norm(v - last_v, 2) <= v_quadratic_error: break

rawDescription: PageRank python implementation, algorithm


code:
import boto3
import os

def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local)
        if result.get('Contents') is not None:
            for file in result.get('Contents'):
                if not os.path.exists(os.path.dirname(local + os.sep + file.get('Key'))):
                     os.makedirs(os.path.dirname(local + os.sep + file.get('Key')))
                resource.meta.client.download_file(bucket, file.get('Key'), local + os.sep + file.get('Key'))

rawDescription: Boto3 to download all files from a S3 Bucket


code:
import wx
class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        screenWidth = 500
        screenHeight = 400
        screenSize = (screenWidth,screenHeight)
        wx.Frame.__init__(self, None, id, title, size=screenSize)
        self.Bind(wx.EVT_CLOSE, self.closeWindow)  #Bind the EVT_CLOSE event to closeWindow()

    def closeWindow(self, event):
        pass #This won't let the app to close

if __name__=='__main__':
    app = wx.App(False)
    frame = GUI(parent=None, id=-1, title="Problem Demo-PSS")
    frame.Show()
    app.MainLoop()

rawDescription: Exit button doesn´t work - wxpython

description: Exit button doesn´t work - wxpython


code:
def stringify_children(node):
    from lxml.etree import tostring
    from itertools import chain
    parts = ([node.text] +
            list(chain(*([c.text, tostring(c), c.tail] for c in node.getchildren()))) +
            [node.tail])
    # filter removes possible Nones in texts and tails
    return ''.join(filter(None, parts))

rawDescription: Get all text inside a tag in lxml

description: Get all text inside a tag in lxml


code: ['square', 'cube']

rawDescription: Getting a list of locally-defined functions in python


code:
if letter in reps.values():
    print("You already defined that letter")

rawDescription: Updating dictionaries in python

description: Updating dictionaries in python


code: array[array >= 25] = 0

rawDescription: threshold in 2D numpy array

description: Threshold in 2D numpy array


code: files = {'file': ('filename.xls', open('filename.xls'), 'application/vnd.ms-excel', {})}

rawDescription: Multipart POST using python requests

description: Multipart POST using python requests


code:
# to utf-8
row.fieldname.encode('utf8')

# to ascii, ignore non-utf-8 characters
row.fieldname.encode('ascii', 'ignore')

# to ascii, replace non-utf-8 characters with ?
row.fieldname.encode('ascii', 'replace')

rawDescription: pyodbc remove unicode strings

description: Pyodbc remove unicode strings


code:
import numpy as np

def parse_date(datestr):
    return sum([multiplier*val for multiplier, val in
                zip((3600, 60, 1), map(float, datestr.split(':')))])

x = np.loadtxt('data', dtype={'names': ('time', 'magnitude'), 'formats': ('f8', 'f8')},
               converters={0:parse_date})
print(x)

rawDescription: Parsing a data matrix containing HH:MM:SS.mmm times using numpy.loadtxt


code:
def examplefunc(x):
    pass

rawDescription: Why list comprehension can be faster than map() in Python?


code:
data = [[0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1]]

mask = [[False, False,  True,  True],
 [False, False,  True,  True],
 [False, False,  True,  True]]

zipped = zip(data, mask) # [([0, 1, 1, 1], [False, False, True, True]), ([0, 1, 1, 1], [False, False, True, True]), ([0, 1, 1, 1], [False, False, True, True])]

masked = []
for lst, mask in zipped:
    pairs = zip(lst, mask)  # [(0, False), (1, False), (1, True), (1, True)]
    masked.append([num for num, b in pairs if b])

print(masked)  # [[1, 1], [1, 1], [1, 1]]

rawDescription: python numpy get masked data without flattening

description: Python numpy get masked data without flattening


code:
for row in reader:
    data = next(reader1)
    ...

rawDescription: Creating python list of floats from two files


code:
class HashtableTest(MappingTestBase):
    dictype = hashtable.HashDict

class OtherMappingTest(MappingTestBase):
    dictype = othermodule.mappingimpl

rawDescription: unittest tests reuse for family of classes

description: Unittest tests reuse for family of classes


code:
txt='''\
gene_name start_pos end_pos
gene_A 100 200
gene_B 300 400
gene_C 500 600
gene_D 700 800
gene_E 900 1000'''

genes=[(name, int(d1), int(d2)) for name, d1, d2 in [line.split() for line in txt.splitlines()[1:]]]
genes

rawDescription: Bisecting lists containing multi-value entries? Advice on approaching this task


code:
import random
random.sample(range(1, 100), 3)

rawDescription: Python, Generate 'n' unique random numbers within a range


code:
counter = {}
for entry in NewRecord:
    if entry in counter:
        counter[entry] += 1
    else :
        counter[entry] = 1

rawDescription: Changing variable names on the go, in Python


code:
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
def humansize(nbytes):
    if nbytes == 0: return '0 B'
    i = 0
    while nbytes >= 1024 and i < len(suffixes)-1:
        nbytes /= 1024.
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
    return '%s %s' % (f, suffixes[i])

rawDescription: Python libraries to calculate human readable filesize from bytes?


code:
parsed_query = urlparse.parse_qs(parsed_url.query)
parsed_query

rawDescription: Trying to find all unique values in specific part of string in Python


code: datetime.datetime(2014, 5, 23, 13, 13, 20) # is this right?

rawDescription: Convert SAS numeric to python datetime

description: Convert SAS numeric to python datetime


code: [round((x-1) % 2 - 1, 1) for x in seq]

rawDescription: Is there a way to mod a number so that it's in the range between -1 and 1?


code:
from nltk import sent_tokenize, word_tokenize
sentences = 'This is the first sentnece. This is the second. And this is the third'
sent_tokenize(sentences)

rawDescription: How to split sentences using the nltk.parse.stanford library

description: Split sentences using the nltk.parse.stanford library


code: a=subprocess.check_output('(grep -Ewo "[+-]?[0-9]" result.txt)', shell=True)

rawDescription: Bash variables to Python while executing bash script


code:
from subprocess import Popen,PIPE

directory = 'path'

p1 = Popen(["ls",directory, "-Ssp"], stdout=PIPE)

p2 = Popen(["grep", "-v", '/$'], stdin=p1.stdout, stdout=PIPE)

p1.stdout.close()
out, _err = p2.communicate()

files = out.splitlines()
total = files.pop(0)
print(total)
print(len(files))

rawDescription: Python executable to Linux list files with sizes


rawDescription: twisted python logging issue / confusion?

description: Twisted python logging issue / confusion


code:
from collections import defaultdict as dd
from pprint import pprint as pp

a = dd(dict)
for key in range(3):
    a[key][0] = key

pp(a)

rawDescription: Using dict.fromkeys(), assign each value to an empty dictionary


code:
start
a
b
d
f
end
d
c
e
end
b
c
e
end

rawDescription: Iterative preorder k-ary tree traversal

description: Iterative preorder k-ary tree traversal


code: Mary Jade,Jenn

rawDescription: Indexing lines of text in a .txt file

description: Indexing lines of text in a .txt file


code: ["{0:03}".format(i) for i in range(121)]

rawDescription: Generate numbers with 3 digits

description: Generate numbers with 3 digits


code: del type(MyClass)._instances[MyClass]

rawDescription: How to deregister a class entry from Metaclass?

description: Deregister a class entry from Metaclass


rawDescription: Plot sklearn RandomForestRegressor MSE

description: Plot sklearn RandomForestRegressor MSE


code:
import regex
m = input("Enter the line number:\n")
with open('file') as f:
    fil = f.readlines()[int(m)-1:]
    print(regex.search(r'{(?:(?0)|[^{}])*}', ''.join(fil)).group())

rawDescription: Go to line number and extract text in following matching brackets


rawDescription: searching for element in a dictionary key

description: Searching for element in a dictionary key


code:
for i in start_list[:]:  # a copy won't grow anymore.
    start_list.append(i ** 2)

rawDescription: How do I square each item in a list using append?

description: Square each item in a list using append


code:
import lxml.html
page = '
2233

Kevin
'
tree = lxml.html.fromstring(page)
tree.xpath('//span[@class="number"]/text() | //div[@class="dddd13"]/span/text()')

rawDescription: Python : lxml xpath get two different classes


rawDescription: BeautifulSoup webcrawling: How to get piece of text


code:
...

this.toolTitle = SPAN({'class': 'tipTitle'});
this.toolText = P({'class': 'tipText'});
this.toolModel = SPAN({'class': 'tipExtra'});
this.toolField = SPAN({'class': 'tipExtra'});
this. modelTitle = SPAN({'style': 'font-weight:bold;'}, _('Object')+' :: ')
this.fieldTitle = SPAN({'style': 'font-weight:bold;'}, _('Field')+' :: ')

...

rawDescription: Remove the tooltip when hover over "?" symbol


code: Ф

rawDescription: Subtracting depending on an if function in python


code:
from gi.repository import Gtk, Gdk, GLib

def run_dialog(_None):
    dialog = Gtk.FileChooserDialog("Please choose a folder", None,
    Gtk.FileChooserAction.SELECT_FOLDER,
        (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
        "Select", Gtk.ResponseType.OK))

    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print("Select clicked")
        print("Folder selected: " + dialog.get_filename())
    elif response == Gtk.ResponseType.CANCEL:
        print("Cancel clicked")

    dialog.destroy()
    Gtk.main_quit()

Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
Gtk.main()

rawDescription: Proper way to destroy a file chooser dialog in pygtk for python


code:
# The data is input as '1: 0.022,' format
def process_data(line):
    # for returning the new string that is cleaned up
    result_line = ''
    for character in line:
        # check if it is either a number or a letter
        if character.isdigit() or character.isalpha():
            result_line += character
        # we want the decimal point
        elif character == '.':
            result_line += character
        # else we replace it with space ' '
        else:
            result_line += ' '
    return result_line

my_list = []

with open('input.txt') as file:
    for lines in file:
        processed_line = process_data(lines)
        # temp_list has ['letter', 'frequency']
        temp_list = (processed_line.split())
        value = temp_list[0]
        # Require to cast it to a float, since it is a string
        frequency = float(temp_list[1])
        my_list.append([value, frequency])

print(my_list)

rawDescription: what is a good way of setting up ranges on a number line?

description: What is a good way of setting up ranges on a number line


code:
from ui_myform import Ui_myForm
from PyQt4.QtGui import QDialog

class MyForm(QDialog, Ui_myForm):

    def __init__(self, parent = None):
        QDialog.__init__(self, parent)

        self.setupUi(self)    #here Ui_myForm creates all widgets as members
                              #of this object.
                              #now you can access every widget defined in
                              #myForm as attributes of self

        #supposing you defined two pushbuttons on your .UI file:
        self.pushButtonB.setEnabled(False)

        #you can connect signals of the generated widgets
        self.pushButtonA.clicked.connect(self.pushButtonAClicked)

    def bucar_actualizaciones(self):
        self.pushButtonB.setEnabled(True)

rawDescription: Drag n Drop Button and Drop-down menu PyQt/Qt designer


code:
dx = math.cos(math.radians(degree))
dy = math.sin(math.radians(degree))
position = (position[0] + dx * SPEED, position[1] - dy * SPEED)

rawDescription: How would I make a car move the direction it's pointing (After use of pygame.translation.rotate)


rawDescription: How to have multiple get params in an URL?

description: Have multiple get params in an URL


code:
meta = MetaData()
meta.reflect(bind=someengine)
users_table = meta.tables['users']
addresses_table = meta.tables['addresses']

rawDescription: Pattern for a Flask App using (only) SQLAlchemy Core


code: reactor.callLater(0, f)

rawDescription: sound way to feed commands to twisted ssh after reactor.run()

description: Sound way to feed commands to twisted ssh after reactor.run()


code:
statBefore = pd.DataFrame({'q1': grouped['Value'].quantile(.25), \
'median': grouped['Value'].median(), 'q3' : grouped['Value'].quantile(.75)})

rawDescription: Python remove outliers from data

description: Python remove outliers from data


code: data, (ip, port) = s.recvfrom(1024)

rawDescription: Python: How to convert the address recieved from a recvfrom() function to a string?


code:
fig.x_range.start = x.max() - window_length
fig.x_range.end = x.max()
push_notebook()

rawDescription: Set x_axis_limit in Bokeh live plot embedded in Jupyter notebook


code:
link = browser.find_element_by_xpath('//div[@class="vbseo_liked"]/a[contains(@onclick, "return vbseoui.others_click(this)")]')
browser.execute_script('arguments[0].click();', link)

rawDescription: Executing a script in selenium python

description: Executing a script in selenium python


code:
import re
test_number = 123
str1="XXjdasjXX-123_dsajdfs"
x= re.search("{}".format(test_number),str1).group()
print (x)

rawDescription: python how to find exact match of a number in a string

description: Python how to find exact match of a number in a string


code:
covariance = lambda kernel, x, y, params: \
    np.array([[kernel(xi, yi, params) for xi in x] for yi in y])

rawDescription: Gaussian Process scikit-learn - Exception


code:
type(none)
type(None)

rawDescription: Looking for help designing a While loop in Python


code: Person.objects.raw("SELECT * FROM app_person <YOUR JOINS HERE>")

rawDescription: Queryset object

description: Queryset object


code:
AWS_ACCESS_KEY_ID = "xxxxxx"
AWS_SECRET_ACCESS_KEY = "xxxxxx"
IMAGES_STORE = "s3://bucketname/base-key-dir-if-any/"

rawDescription: how to store scrapy images on Amazon S3?

description: Store scrapy images on Amazon S3


rawDescription: Index of max element from two lists

description: Index of max element from two lists


rawDescription: Python Docstrings in Subclasses

description: Python Docstrings in Subclasses


rawDescription: is it possible to convert this loop into a list comprehension in python

description: Is it possible to convert this loop into a list comprehension in python


code:
def get_xbits_list(num, x):
    mask = 2**x - 1
    return [(num >> (i * x)) & mask for i in reversed(xrange(32/x))]

rawDescription: How to get each Xbits from a int with python

description: Get each Xbits from a int with python


code:
def drawCard():
    adPos = random.randrange(len(cardDeck))
    drawnCard = cardDeck[adPos]
    drawnCardValue = cardValues[adPos]
    return drawnCard, drawnCardValue

rawDescription: Using local variables outside their functions


code:
import itertools

for first, second in itertools.izip(l, l[1:]):
    ...

rawDescription: Iterate over all pairs of consecutive items from a given list


rawDescription: Permute rows and columns of a matrix

description: Permute rows and columns of a matrix


code:
# Calculating the mean of each group
means = [d.mean() for d in datasets]

# Standard deviation of each group
stdevs = [d.std() for d in datasets]

rawDescription: Python for & if loop not working?

description: Python for & if loop not working


rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


code: p = subprocess.Popen(['myjavaapp', 'afilename.txt'])

rawDescription: Related to executing Java programs through Python


code: [x + y for x, y in zip(msglist, keylist) if chr(x).isalpha()]

rawDescription: Vigenere Cipher List Processing

description: Vigenere Cipher List Processing


code:
inputlist = [('a', 'b'), ('b', 'a'), ('c','d')]
sset = SortingSet(inputlist)
sset
('d', 'c') in sset

rawDescription: Set of string tuples in python

description: Set of string tuples in python


code:
from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    return request.headers['Authorization']

with app.test_client() as c:
    r = c.post('/', headers={'Authorization': 'Bearer foo'}, data={'foo': 'bar'})
    print(r.data)

rawDescription: Setting header on test client doesn't seem to work


code:
from operator import itemgetter
from itertools import groupby

score_list = score()
score_list.sort(key=itemgetter(2), reversed=True)
for i, group in enumerate(groupby(score_list)):
    for item in group:
        print(item, i+1)

rawDescription: sorting a list in python

description: Sorting a list in python


code:
def rename(newname):
    def decorator(f):
        f.__name__ = newname
        return f
    return decorator

rawDescription: Possible to change function name in definition?


code:
def lenRecur(s):
    def characters_only(s):
        return ''.join([c for c in s if c.isalpha()])

    def len_recursive(s):
        if not s:
            return 0
        return 1 + len_recursive(s[1:])

    return len_recursive(characters_only(s))

rawDescription: Global variables in recursion. Python

description: Global variables in recursion. Python


code:
import requests
response = requests.get('http://geo.oiorest.dk/adresser.json',
                        params = dict(postnr=4320,
                                      vejnavn='Bispegårdsvej',
                                      husnr=2))

rawDescription: Encoding in Python - non-English characters into a URL


code:
from matplotlib import pyplot as plt

x = list(range(len(numbers)))
plt.bar(x, numbers)
plt.xticks(x, labels, rotation=90)
plt.savefig('hist.png', dpi=300)

rawDescription: how can i plot histogram like this?

description: Plot histogram like this


code:
class Shirt(Item):
    available_sizes = Field() # [(size1, amount1), (size2, amount2), ...] or {size1: amount1, size2: amount2, ...} if `size` is a hashable object

rawDescription: using scrapy to parse an arbitrary number of rows (key:value pairs) in an html table

description: Using scrapy to parse an arbitrary number of rows (key:value pairs) in an html table


code: [a+b for a,b in zip(first_list, second_list) if a not in special]

rawDescription: How to exempt a list item from iteration?

description: Exempt a list item from iteration


code:
df = pd.DataFrame({"cid": np.arange(64)//8, "price": np.arange(64)})
df.head()

rawDescription: Pivot each group in Pandas

description: Pivot each group in Pandas


rawDescription: Unique attributes for certain data

description: Unique attributes for certain data


code:
def sd(st):
    return sum(int(d) for d in st)

rawDescription: Python3.4 - math with index numbers

description: Python3.4 - math with index numbers


code:
df_temp = pd.merge(b_reset
           , df_reset
           , left_on = 'level_0'
           , right_on = 'index' )

rawDescription: Splitting and unpivoting a column in pandas


rawDescription: Pandas read_csv: parsing time field correctly


code:
ops1 = {
        "1": lambda: print("1"), # this value is now a FUNCTION, which you can call later
        "2": lambda: print("2"),
        "4": lambda: print("4")
} # when the dictionary is created, everything in it is evaluated, but the functions are not called

lis = [1, 2, 3]

for x in range(len(lis)): # goes through 0, 1, and 2
    if lis[x] in ops1: # lis[0] is 1, lis[1] is 2, lis[2] is 3
        ops1.get(str(lis[x]), print)() # look for '1', '2', and '3',
                                       # then call their values

rawDescription: Python, run functions from lookup table

description: Python, run functions from lookup table


code:
# Initial dataframe.
df = pd.DataFrame({'time': [1, 2.1, 2.13, 3.7, 10, 10.2],
                   'A': [1, 3, -1, 7, 2, 1]})

# Initial decay parameter.
decay_constant = 1

rawDescription: Pandas: Exponentially decaying sum with variable weights


code:
def writeDown(data, output_filename):

    data.write(output_filename)
    txt = file(output_filename).read()
    txt = txt.replace(unique+':','')
    file(output_filename,'w').write(txt)

rawDescription: lxml.etree and xml.etree.ElementTree adding namespaces without prefixes(ns0, ns1, etc.)

description: Lxml.etree and xml.etree.ElementTree adding namespaces without prefixes(ns0, ns1, etc.)


code:
from scipy import sparse
A = sparse.lil_matrix((4,28))
A.data = PORTION
A.rows = DATA

rawDescription: How to avoid loops for sparse Matrix?

description: Avoid loops for sparse Matrix


code:
def getKey():
    print("Enter the key you want to use to decrypt/encrypt the message")
    while True:
        key = int(input()) # key input
        if key >= 1 and key <= 26: #checking if key is in between range
            return key #giving back the key
        else: # this should run whenever the input is invalid
            print ("The key must be inbetween 1 and 26")
            # Don't stop the loop.  Just try again.

rawDescription: Recursion in function causing return variable to equal 'None'


code:
[
  (pacientes[0], inicios[0], finales[0]),
  (pacientes[1], inicios[1], finales[1]),
  ...
]

rawDescription: How can I iterate multiple key from a dictionary in Django template

description: Iterate multiple key from a dictionary in Django template


rawDescription: How can I get the product of all elements in a one dimensional numpy array

description: Get the product of all elements in a one dimensional numpy array


code:
def name_try(try_number, ub_tries):
    tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}
    return tries_dict.get(try_number, 'next')

rawDescription: use a range as a dictionary key in Python, what option do I have?

description: Use a range as a dictionary key in Python, what option do I have


rawDescription: Use multiple functions at once on a list


code:
h = Human(10)
h = Human('test')
h.name

rawDescription: Setting class attributes of the proper type


code: outerdict.setdefault(name, {})[type_] = [v1, v2, v3]

rawDescription: Python idiom for creating dict of dict of list


code:
phrase = 'Dati aggregati dell’attività amministrativa'
phrase[19]
print(ascii(phrase[19]))

rawDescription: Problems with encoding while parsing website (html) and getting strings


code: [x for x in sorted(creatureList,key=lambda x: x[2]+x[3])][-5:]

rawDescription: How do I create a group of lists from imported data from access?

description: Create a group of lists from imported data from access


code:
def refresh():
    global path,dirs,files,file_count,dirList
    path, dirs, files = os.walk(os.path.join(os.getcwd(), 'Input')).next()
    file_count = len(files)
    dirList = os.listdir(path)

rawDescription: Python: 'Refresh' specific variables within a script


code: a_string = 'This is a string'

rawDescription: How to display the first few characters of a string in Python?

description: Display the first few characters of a string in Python


code:
df['VOLUME'].resample('H', how='ohlc')
df['PRICE'].resample('H', how='ohlc')

rawDescription: How do you convert time series data with pandas and show graph via highstock

description: Convert time series data with pandas and show graph via highstock


code: replys.merge(users, on='reply_id')

rawDescription: Query CSV files maintaining foreign key relationship? Is this possible?


code:
def find_after_name(users, name):
    for i, user in enumerate(users):
        if user.name == name:
            return users[(i+1) % len(users)]

rawDescription: Find object from list that has attribute equal to some value and also get the next object after


code: pd.Panel.from_dict(d, orient='minor')  # default orient is items

rawDescription: create Panel at Pandas by multi-level dictionary

description: Create Panel at Pandas by multi-level dictionary


code:
@auto_attr_check
class Foo(object):
    bar = int
    baz = str
    bam = float

f = Foo()
f.bar = 5; f.baz = "hello"; f.bam = 5.0
f.bar = "hello"
f.baz = 5
f.bam = 3 + 2j

rawDescription: Force python class member variable to be specific type


code: df

rawDescription: Python Pandas value-dependent column creation


code:
x = numpy.empty([2], dtype=object)
x[:] = [[], []]

rawDescription: Numpy arrays containing iterable objects


code:
import re

f = open('EuroMenu.txt','w')

with open("menu.txt", "r") as ins:
    for line in ins:
        myArray = line.split()

        if myArray:
            m = re.search(r'\$(\d+(?:\.\d{1,2})?)\.?$', myArray[-1])
            if m:
                amount = m.groups()[0]
                myArray[-2] = str(float(amount)*0.75)
                myArray[-1] = 'euros'

        f.write(" ".join(myArray) + " \n")

f.close()

rawDescription: how to convert currency in python file

description: Convert currency in python file


code:
# assuming 'db' is your sqlite3 database
date_to_insert = '12/5/2013'
amount_to_add = 20
db.execute('INSERT OR IGNORE INTO table(Date) VALUES(?)', (date_to_insert,))
db.execute('UPDATE table SET Quantity = Quantity + ? WHERE Date = ?', (amount_to_add, date_to_insert))

rawDescription: SQLite insert if not exist else increase integer value


code: f(*tup1, *tup2)

rawDescription: How to unpack multiple tuples in function call

description: Unpack multiple tuples in function call


code:
i = "\xd9\x88"
print(i)

rawDescription: representing \xd9\x88 (UTF-8 literal) in its arabic character و in Python

description: Representing \xd9\x88 (UTF-8 literal) in its arabic character و in Python


code:
from itertools import cycle
names = cycle([1,2,3])
print(next(names))
print(next(names))
print(next(names))
print(next(names))
print(next(names))
print(next(names))
1
2
3
1
2
3

rawDescription: Python function that rotates files per call


code:
lis = ['heeeeellllooo','world','low','higggghhh']
[x.upper() if len(x)>5 else x for x in lis] # this is a new list

rawDescription: Python - indexing an element in a list

description: Python - indexing an element in a list


code: ['foo', 'foo bar', 'bar']

rawDescription: Python regular expression to match either a quoted or unquoted string


code:
print(timeit("normal(sound)", locals()))
print(timeit("onlyMax(sound)", locals()))

rawDescription: timing two algorithms (python) using timeit or time

description: Timing two algorithms (python) using timeit or time


code:
@accepts(int, (int,float))
def func(arg1, arg2):
    return arg1 * arg2

func(3, 2) # -> 6
func('3', 2) # -> AssertionError: arg '3' does not match <type 'int'>

rawDescription: How to use Python decorators to check function arguments?

description: Use Python decorators to check function arguments


code:
import my_class as mc

ca = mc.MyClassA()

rawDescription: Importing an own python file, Class not defined


rawDescription: Pass list of different named tuples to different csv by tuple name


code: 'a b c'.split(None, 1)

rawDescription: Python: str.split() - is it possible to only specify the "limit" parameter?


code: [file for key in word_count_dict["Britain"]]

rawDescription: how to find frequency of the keys in a dictionary across multiple text files?

description: Find frequency of the keys in a dictionary across multiple text files


code: ax.tick_params('both', length=2, width=0.3, which='major', color=grey)

rawDescription: Set tick egde color in matplotlib rc

description: Set tick egde color in matplotlib rc


rawDescription: plotting a range of data that satisfies conditions in another column in matplotlib python

description: Plotting a range of data that satisfies conditions in another column in matplotlib python


code:
splittime = timeit.timeit("hours,minutes = s.split(':'); mins=int(hours)*60 + int(minutes)", "s='02:40'", number=100000)/100000
splittime
splittime/parsetime

rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


code:
class C(object):
    a = 17
    b = staticmethod(lambda x : x+1)

rawDescription: Can't have a function as a class attribute in Python


rawDescription: How do I modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9?

description: Modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9


rawDescription: Load rectangle data from txt file with Python?


code:
N = 10
xs = [(random(), random()) for x in range(1000000)]

rawDescription: Understanding performance difference

description: Understanding performance difference


code:
author_lists = {}

for i in range(3):
    author_lists['an'+str(i)] = []

author_lists

rawDescription: Create multiple list with different variables


code:
from functools import wraps

class MyCustomError(Exception):
    def __init__(self):
        print('in MyCustomError')

# Common implementation
def wrap(func,cb=None):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            if cb is not None:
                cb()
            raise MyCustomError()
    return wrapper

# No parameters version
def wrap_error(func):
    return wrap(func)

# callback parameter version
def wrap_error_cb(cb):
    def deco(func):
        return wrap(func,cb)
    return deco

@wrap_error
def foo(a,b):
    print('in foo',a,b)
    raise Exception('foo exception')

def callback():
    print('in callback')

@wrap_error_cb(callback)
def bar(a):
    print('in bar',a)
    raise Exception('bar exception')

rawDescription: Python decorator with optional argument (which is function)


code:
def writeToCsv(list, max):
    writer = csv.writer(open('file.csv', 'wb'), delimiter=' ')
    for x in range(0,max):
        writer.writerow([list[x]['year'], list[x]['name']])

rawDescription: How to write to consecutive CSV columns in Python

description: Write to consecutive CSV columns in Python


code:
from settings import XMLFILES_FOLDER
path = XMLFILES_FOLDER+'area.xml'

rawDescription: How can I use relative path to read local files in Django app?

description: Use relative path to read local files in Django app


code: {k: prices[k]*stock[k] for k in prices}

rawDescription: Multiplying and then summing values from two dictionaries


code:
new_url = "http://foo.bar2"
nodes = idx["url"][new_url]
if len(nodes):
    rel = nodes[0].relationships.all(types=[tag_node["tag"]])[0]
    rel["count"] += 1
else:
    new_url_node = gdb.nodes.create(url=new_url, type="URL")
    new_url_node.relationships.create(tag_node["tag"], tag_node, count=1)
    idx["url"][new_url_node["url"]] = new_url_node

rawDescription: Indexing nodes in neo4j in python

description: Indexing nodes in neo4j in python


rawDescription: Iterate through XML to get all child nodes text value


code:
from math import sin, cos, tan
li = [sin, cos, tan]

rawDescription: python evaluate commands in form of strings

description: Python evaluate commands in form of strings


rawDescription: Match string with normal characters with special characters in python


code: ordered_d = OrderedDict(l)

rawDescription: Python sort by values that are lists of numbers


code:
seen_not = False
output_list = []
for item in input_list:
    if seen_not:
        output_list.append("NOT_" + item)
    else:
        output_list.append(item)

    if item == "not":
        seen_not = True

rawDescription: How do I modify all terms following a specific term in a list of terms?

description: Modify all terms following a specific term in a list of terms


code:
class DictRange(dict):
    def __getitem__(self, val):
        for key in self.keys():
            if val in key:
                return super(DictRange,self).__getitem__(key)

rawDescription: Associative array in python with keys as a fragment of array


code:
def view_of_test():
    post = request.get_json()
    param = post.get('param_name')

rawDescription: Sending a POST request with Angularjs and get parameters in a Flask backend


code:
from numpy.lib.stride_tricks import as_strided
arr_pairs = as_strided(arr, shape=(len(arr)-2+1,2), strides=arr.strides*2)
arr_pairs

rawDescription: numpy array partial sums with weights

description: Numpy array partial sums with weights


code: send("{RCTRL}{RSHIFT}")

rawDescription: Changing language typing direction using selenium


code:
def doppelstring(s):
    letter_groups = ((val, list(group)) for val, group in itertools.groupby(s))
    max_vector = ((val, min(len(group), 2)) for val, group in letter_groups)
    vector_components = ([dim * (l + 1) for l in range(maxlen)] for dim, maxlen in max_vector)
    return [''.join(letters) for letters in itertools.product(*vector_components)]

rawDescription: python limit repeating letters

description: Python limit repeating letters


code:
from pprint import pprint
first_list_ordered = ["id1", "id2", "id3", "id4", "id5", "id6", "id7"]
second_list_unordered = [{"id": "id6", "content": "sth"},
                         {"id": "id4", "content": "sth"},
                         {"id": "id1", "content": "sth"},
                         {"id": "id3", "content": "sth"}]
indices = {c: i for i, c in enumerate(first_list_ordered)}
sorted(second_list_unordered, key=lambda d: indices.get(d['id']))
pprint(_)

rawDescription: Sort list of dictionaries by appearance of key in a second ordered list


code:
def total_counts(die_n=2, max_num=6):
    return Counter(map(sum, enumerate_rolls(die_n, max_num)))

print(total_counts())
print(total_counts(5, 4))

rawDescription: itertools dice rolls: doubles roll twice

description: Itertools dice rolls: doubles roll twice


code:
import re
filename = 'snackbox_xx.dat'
filename_new = re.sub(r'_[A-Za-z0-9]{2}', '', filename)

rawDescription: Python - Truncate unknown file names

description: Python - Truncate unknown file names


code: user_key = ndb.Key('Info_model', 'Bill')

rawDescription: Retrieving Datastore Object With Key

description: Retrieving Datastore Object With Key


code:
{'code': 'format', 'value': 'CC'}
{'code': 'Input', 'value': '10N'}
{'code': 'Method', 'value': 'BASIC'}
{'code': 'Convention', 'value': 'LEFT'}
{'code': 'Bounding', 'value': 'BUFFERED'}

rawDescription: Parsing an XML file using ElementTree

description: Parsing an XML file using ElementTree


rawDescription: Operation on current, precedent, and succeeding element in a list


code:
locals().update(o.vars)
x

rawDescription: Easily dumping variables from/to namespaces/dictionaries in Python


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

blues = plt.cm.Blues(np.linspace(0,1,200))
reds = plt.cm.Reds(np.linspace(0,1,200))
colors = np.vstack((blues[0:128,:], reds[-129:,:]))

i = np.linspace(0,1,256)
r = np.column_stack((i, colors[:-1,0], colors[1:,0]))
g = np.column_stack((i, colors[:-1,1], colors[1:,1]))
b = np.column_stack((i, colors[:-1,2], colors[1:,2]))
d = dict(red=r, green=g, blue=b)
mycmap = mcolors.LinearSegmentedColormap('mymap', d, N=256)

plt.imshow(KS_imshow, extent=[5, 8, 0, 22], origin='lower',
        interpolation='nearest', aspect='auto', cmap=mycmap,
        vmin=0., vmax=1.)

cbar = plt.colorbar()

plt.show()

rawDescription: How can I have straight contourlines in matplotlib?

description: Have straight contourlines in matplotlib


code:
found = False
for person in Person.personslist:
    if prompt_fname == person.fname and prompt_lname == person.lname:
        found = True
        break
if not found:
    Person(prompt_fname, prompt_lname)

rawDescription: Python: Checking whether an object already exists before creating a new one


code:
def both_sides(df, name):
    keep = [c for c in df.columns if c.startswith(name)
            and c.endswith(name)]
    return df[keep]

rawDescription: Convert a user function to be a dataframe method (or equivalent)


rawDescription: Retrieving .loc index values in pandas dataframe


rawDescription: What does "symbolic" mean in this sentence?


code:
m = re.match(r"^\s*(\w+)\s*\|((?:\s*\w+\s*)*)$", " network | level1 level2 leveln ")
m.groups()
m.groups()[1].strip().split()

rawDescription: regex help using repreated groups

description: Regex help using repreated groups


rawDescription: Why does numpy indexing work differently in higher dimensions?


code:
data = "foobar"
map(''.join, zip(data, data[1:]))

rawDescription: Parse String every 2 letters

description: Parse String every 2 letters


code: con.autocommit = true #before inserts

rawDescription: why cx_Oracle and sqlplus give different results for the same select query

description: Why cx_Oracle and sqlplus give different results for the same select query


code:
import numpy as np
import Tkinter as tk
import matplotlib as mpl
from matplotlib.patches import Rectangle
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg

# custom toolbar with lorem ipsum text
class CustomToolbar(NavigationToolbar2TkAgg):
    def __init__(self,canvas_,parent_):
        self.toolitems = (
            ('Home', 'Lorem ipsum dolor sit amet', 'home', 'home'),
            ('Back', 'consectetuer adipiscing elit', 'back', 'back'),
            ('Forward', 'sed diam nonummy nibh euismod', 'forward', 'forward'),
            (None, None, None, None),
            ('Pan', 'tincidunt ut laoreet', 'move', 'pan'),
            ('Zoom', 'dolore magna aliquam', 'zoom_to_rect', 'zoom'),
            (None, None, None, None),
            ('Subplots', 'putamus parum claram', 'subplots', 'configure_subplots'),
            ('Save', 'sollemnes in futurum', 'filesave', 'save_figure'),
            )
        NavigationToolbar2TkAgg.__init__(self,canvas_,parent_)

class MyApp(object):
    def __init__(self,root):
        self.root = root
        self._init_app()

    # here we embed the a figure in the Tk GUI
    def _init_app(self):
        self.figure = mpl.figure.Figure()
        self.ax = self.figure.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.figure,self.root)
        self.toolbar = CustomToolbar(self.canvas,self.root)
        self.toolbar.update()
        self.plot_widget = self.canvas.get_tk_widget()
        self.plot_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.toolbar.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.canvas.show()

    # plot something random
    def plot(self):
        self.ax.imshow(np.random.normal(0.,1.,size=[100,100]),cmap="hot",aspect="auto")
        self.figure.canvas.draw()

def main():
    root = tk.Tk()
    app = MyApp(root)
    app.plot()
    root.mainloop()

if __name__ == "__main__":
    main()

rawDescription: Matplotlib/Tkinter - customizing toolbar tooltips


rawDescription: Regex return everthing but compound expression


code:
set(
 deg_course_cat.objects
 .exclude(degree_code__isnull=True)
 .exclude(degree_code__exact='')
 .values_list('degree_code', flat=True)
)

rawDescription: Django ORM command to get distinct values without empty fields


code:
cps = CasePreservingSet(*l)
cps
'#treNdinG' in cps

rawDescription: How to get Case Insensitive Python SET

description: Get Case Insensitive Python SET


code:
import matplotlib
import matplotlib.pyplot as plt

min_val = 0
max_val = 1

my_cmap = matplotlib.cm.get_cmap('jet')
norm = matplotlib.colors.Normalize(min_val, max_val)

cmmapable = matplotlib.cm.ScalarMappable(norm, my_cmap)
cmmapable.set_array(range(min_val, max_val))

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

# set opacity to 0
cbar = plt.colorbar(cmmapable, ax = ax1, ticks=[0, 1], alpha = 0)

# remove the tick labels
cbar.ax.set_yticklabels(['', ''])
# set the tick length to 0
cbar.ax.tick_params(axis = 'y', which = "both", length = 0)

# set everything that has a linewidth to 0
for a in cbar.ax.get_children():
    try:
        a.set_linewidth(0)
    except:
        pass

plt.show()

rawDescription: Matplotlib - Same padding as the one used by a `colorbar`


code:
#!/usr/bin/env python
import glob, csv
if __name__ == '__main__':

    infiles = glob.glob('./*.csv')
    out = 'temp.csv'
    data = {}
    fields = []

    for fname in infiles:
        df = open(fname, 'rb')
        reader = csv.DictReader(df)
        for line in reader:
            # assuming the field is called ID
            if line['ID'] not in data:
                data[line['ID']] = line
            else:
                for k,v in line.iteritems():
                    if k not in data[line['ID']]:
                        data[line['ID']][k] = v
            for k in line.iterkeys():
                if k not in fields:
                    fields.append(k)
        del reader
        df.close()

    writer = csv.DictWriter(open(out, "wb"), fields, dialect='excel')
    # write the header at the top of the file
    writer.writeheader()
    writer.writerows(data)
    del writer

rawDescription: Merge multiple *.csv, *.txt, or *.ascii files based on a common field using python


rawDescription: removing something from a list of tuples

description: Removing something from a list of tuples


code:
class AddressSerializer(serializers.HyperlinkedModelSerializer):
    bae_addr_hex = serializers.Field(source='get_hexadecimal')
    class Meta:
        model = Address
        fields = ('bae_addr_hex', ...)

rawDescription: How to change the model column value while returning json data using django-rest framewrok

description: Change the model column value while returning json data using django-rest framewrok


code: subprocess.Popen(["start", "perl.exe", "update.pl", arg], stdin=subprocess.PIPE, shell=True)

rawDescription: Launch two different scripts in two separate cmd windows using subprocess in python


code: my_form = MyFormClass(request.POST, request.FILES)

rawDescription: Django: Open uploaded file while still in memory; In the Form Clean method?


code:
class foo(object):
    def go(self, method):
        getattr(self, method)()

    def a(self):
        ...

    def b(self):
        ...

rawDescription: Method entry points in a class variable

description: Method entry points in a class variable


rawDescription: Counting the Number of keywords in a dictionary in python


rawDescription: python multidimensional boolean array?

description: Python multidimensional boolean array


code:
from itertools import chain
data = [[1,2,3],[10,20,30]]
" ".join(str(i) for i in chain(*data))

rawDescription: Fastest way to convert lists into plain text?


code: questions.append(Question("What is a new question", 1, ["This is."]))

rawDescription: Python trivia game

description: Python trivia game


code: value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))

rawDescription: Python: How to check if keys exists and retrieve value from Dictionary in descending priority


code:
class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

rawDescription: Return different value from function depending on suffix


code: series1.apply(lambda x: x.month)

rawDescription: Pandas series of datetimes in python

description: Pandas series of datetimes in python


code: html = ''.join('<p>'+L+'</p>' for L in text.split('\n'))

rawDescription: Transform textarea input to paragraphed HTML


code:
for mem in memberlist[:]:
    ...

rawDescription: Simplifying a list filter in Python

description: Simplifying a list filter in Python


code: txt = open(filename, 'r')

rawDescription: Making a simple card game in python 2.7

description: Making a simple card game in python 2.7


code:
matrix_multiply(matrices, vectors[..., None])
np.einsum('ijk,ik->ij', matrices, vectors)

rawDescription: Broadcasting matrix-vector dot product

description: Broadcasting matrix-vector dot product


code: script_dir = os.path.dirname(__file__)

rawDescription: Where does python look for files in a script?


code: my_array = my_array.reshape((50, 50)).astype('uint8')*255

rawDescription: Convert black and white array into an image in python?


code:
import re
s = "<_io.TextIOWrapper name='C:/Python34/abcd.txt' mode='w' encoding='cp1252'>"
re.search(r"<[^>]*\bname='([^']*)", s).group(1)

rawDescription: python regex to remove and obtain required string

description: Python regex to remove and obtain required string


code:
rating = pd.DataFrame({"BMW":[7, 8, 9, 8], "Fiat":[2, 1, 10, 3], "Toyota":[3, 8, 7,9]})
own = pd.DataFrame({"BMW":[1, 0, 0, 0], "Fiat":[1, 1, 0, 1], "Toyota":[0, 1, 1, 1]})

r = rating.unstack().reset_index(name='value')
o = own.unstack().reset_index(name='value')
res = DataFrame({"Brand":r["level_0"], "Rating": r["value"], "Own": o["value"]})
res = res.groupby(["Own", "Brand"]).mean().reset_index()
res.pivot(index="Own", columns="Brand", values="Rating")

# result
# Brand       BMW  Fiat  Toyota
# Own
# 0      8.333333    10       3
# 1      7.000000     2       8

rawDescription: Pandas: Pivoting with multi-index data

description: Pandas: Pivoting with multi-index data


code:
for sensor in sensors.find():
    lat = sensor['location']['latitude']
    lng = sensor['location']['longitude']
    location = {
        "type" : "Feature",
        "geometry" : {
            "type" : "Point",
            "coordinates" : [lat ,lng]
        },
        "properties": {
            "name": sensor['name']
        }
    }

    sensors.update({'webid': sensor['webid']} , {"$set": {'location': location}})

rawDescription: Pymongo - Mod on _id not allowed

description: Pymongo - Mod on _id not allowed


code:
@classmethod
def mocked_method(cls):
    print('I want this method to get called')

with mock.patch.object(MyClass, 'my_method', mocked_method):
    MyClass.my_method()

rawDescription: TypeError: unbound method when trying to mock a classmethod


code:
class MainQuerySet(QuerySet):
    def translate(self, lang):
       for obj in MainI18N.filter(language=lang, main__in=self).select_related('main'):
           main = obj.main
           main.i18n = obj
           yield main

rawDescription: django reverse query

description: Django reverse query


rawDescription: How to decode a list of int into a string in Python 3?

description: Decode a list of int into a string in Python 3


code:
from collections import defaultdict

indexes = defaultdict(list)
for i, val in enumerate([4,6,7,21,1,7,3]):
    if val <= 4:
        indexes[val].append(i)

rawDescription: How to extract from a Python list while also accounting for the position of the extracted elements?

description: Extract from a Python list while also accounting for the position of the extracted elements


code:
#!/usr/bin/env python
from datetime import datetime, timedelta
import pytz  # $ pip install pytz

utc_offset = timedelta(hours=5, minutes=30)  # +5:30
now = datetime.now(pytz.utc)  # current time
print({tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set)
       if now.astimezone(tz).utcoffset() == utc_offset})

rawDescription: Getting timezone name from UTC offset

description: Getting timezone name from UTC offset


code:
import random, string, pprint

def randsym():
    res =[]
    for i in range(4):
        res.append(random.choice(string.uppercase))
    return ''.join(res)

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
days = range(1,29)
years = range(1980,2010)
def randdate():
    return "%s-%s-%s" % (random.choice(months),
                         random.choice(days),
                         random.choice(years))

data = {}
for i in range(15000):
    data[randsym()] = (randdate(), "Dec-27-2010")

with open("data.py", "w") as f:
    f.write("data=")
    f.write(pprint.pformat(data))

rawDescription: What is the best way to keep an almost static data for web application?