code:
from django.db import models

class CompressedField(models.TextField):
    """ Standard TextField with automatic compression/decompression. """

    description = 'Field which compresses stored data.'

    def to_python(self, value):
        return value

    def get_db_prep_value(self, value, **kwargs):
        return super(CompressedField, self).get_db_prep_value(value, prepared=True)

class JSONField(models.TextField):
    """ JSONField with automatic serialization/deserialization. """

    description = 'Field which stores a JSON object'

    def to_python(self, value):
        return value

    def get_db_prep_save(self, value, **kwargs):
        return super(JSONField, self).get_db_prep_save(value, **kwargs)

class CompressedJSONField(JSONField, CompressedField):
    __metaclass__ = models.SubfieldBase

class TestModel(models.Model):

    name = models.CharField(max_length=150)
    #compressed_field = CompressedField()
    #json_field = JSONField()
    compressed_json_field = CompressedJSONField()

    def __unicode__(self):
        return self.name

rawDescription: Django custom field with multiple inheritance


code:
def filterls(ls, opts):
    """
    ls - list
    opts - dict - {id: match_info}
    """
    results = []
    for l in ls:
        for (i, t) in opts.items():
            if l[i] != t:
                break
        else:
            results.append(l)
    return results

rawDescription: Python list with filter function (excel-way)


code:
eligible_players = pd.Series([10,20,30], index=["A","B","C"])
list(eligible_players)
"A" in eligible_players

rawDescription: Problems with isin pandas

description: Problems with isin pandas


code: new_img = nib.NiftiImage(result)

rawDescription: Iterating through a multidimensional array


code: cap_count = sum(ch.isupper() for ch in word)

rawDescription: python filter rewrite filter

description: Python filter rewrite filter


code:
import re

sentence = 'bean likes to sell his beans'

sentence = re.sub(r'\bbean\b', 'robert', sentence)
# 'robert likes to sell his beans'

rawDescription: How to replace all occurrences of specific words in Python

description: Replace all occurrences of specific words in Python


code:
from dis import Instruction, HAVE_ARGUMENT

def to_bytes(self):
    res = bytes([self.opcode])
    if self.opcode >= HAVE_ARGUMENT:
        res += (self.arg or 0).to_bytes(2, byteorder='little')
    return res

Instruction.to_bytes = to_bytes

rawDescription: Strange behaviour when creating a function directly from CodeType and FunctionType in python


code:
def __init__(self, courseName, capacity):
    # existing stuff
    self.student = {}

rawDescription: assigning objects to another object python

description: Assigning objects to another object python


code:
def index_by_identity(lst, target):
    try:
        return next(i for i, obj in enumerate(lst) if obj is target)
    except StopIteration:
        # no object matches
        raise IndexError(target)

rawDescription: Using .index() with duplicate values that have separate identifiers


code:
page = '''\
Monte le son

    "Rubin_Steiner"
    Fare maohi
'''
links = {}
soup = BeautifulSoup(page)
for link in soup.select('a[href^=http://pluzz.francetv.fr/videos/]'):
    title = link.get_text().strip()
    if title and title not in (u'Voir cette  vidéo', u'Lire la vidéo'):
        url = link['href']
        links.setdefault(url, []).append(title)

from pprint import pprint
pprint(links)

rawDescription: Python BeautifulSoup extracting titles according to id


code:
string = ""
s = "abcd:"
str1, str2 = s.split(':')
str1
str2
str2 == string

rawDescription: Assigning empty value or string in Python


rawDescription: FFT in Matlab and numpy / scipy give different results


code: ['filecopy.py', 't1.txt', 't2.txt']

rawDescription: Shutil.copy Won't Copy

description: Shutil.copy Won't Copy


code:
idx = pd.IndexSlice
df.loc[idx[0, ['AR','CN','SC']],:]

rawDescription: Multi-index slicing of dataframe with list


code: min(l_one + l_two)

rawDescription: Python find min & max of two lists

description: Python find min & max of two lists


code: from django import forms

rawDescription: Unable to sort a user ForeignKey in Django


code: teamid = json.loads(playerdata1)

rawDescription: Parsing json element

description: Parsing json element


code:
from traits.api import HasTraits, Array, Str
from traitsui.api import View, Item, TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import dtype

test_dtype = dtype([('Integer#1', 'int'),
                    ('Integer#2', 'int'),
                    ('Float', 'float')])

class TestArrayAdapter1(TabularAdapter):

    columns = [('Col1 #', 0), ('Col2', 1), ('Col3', 2)]

    even_bg_color = 0xf4f4f4  # very light gray

    width = 125

    def get_format(self, object, name, row, column):
        formats = ['%04d', '%d', '%.4f']
        return formats[column]

class TestArrayAdapter2(TabularAdapter):

    columns = [('Col1 #', 0), ('Col2', 1), ('Col3', 2)]

    even_bg_color = 0xf4f4f4  # very light gray

    width = 125

    object_0_format = Str("%04d")
    object_1_format = Str("%d")
    object_2_format = Str("%.4f")

class Test(HasTraits):

    test_array = Array(dtype=test_dtype)

    view = \
        View(
            Item(name='test_array', show_label=False,
                 editor=TabularEditor(adapter=TestArrayAdapter1())),
            Item(name='test_array', show_label=False,
                 editor=TabularEditor(adapter=TestArrayAdapter2())),
        )

test = Test()
test.test_array.resize(5, refcheck=False)
test.configure_traits()

rawDescription: different formats for TabularAdapter columns?

description: Different formats for TabularAdapter columns


letter: a

letter: b

letter: c

rawDescription: How to build a nested ordered dict from a csv?

description: Build a nested ordered dict from a csv


code:
import datetime
str1 = "\n".join(data)

# Get the current date and time
now = datetime.datetime.now()
now_str = now.strftime("%Y-%m-%d")

# Write out to a file for today
outfilename = 'sampledata-{}.csv'.format(now_str)

outFile = open(outfilename, 'write')
outFile.write(str1)
outFile.close()

rawDescription: How do I Auto-Name Each Subsequent .CSV File of Scraped Date?


rawDescription: How to create a matrix with values as dictionaries in python

description: Create a matrix with values as dictionaries in python


code:
df
df['variance'] = df['budget'] + df['actual']
df

rawDescription: summing two columns in a pandas dataframe

description: Summing two columns in a pandas dataframe


rawDescription: how to get a dict of instance fields with in a class definition in python?

description: Get a dict of instance fields with in a class definition in python


code:
id(a)
id(b)
id(c)

rawDescription: Elements of the original list changes when a deep copy of changes


code:
reduce(
    lambda a, b: a if a[1] + b[1] > 8 else (a[0] + b[0], a[1] + b[1]),
    map(lambda x: (1, x), input))

rawDescription: Stopping a Reduce() operation mid way. Functional way of doing partial running sum


code: destinations = set(n[0] for n in packagelist)

rawDescription: Removing duplicate from tuple in list

description: Removing duplicate from tuple in list


code: audio_playlist = random.randint(1,91)

rawDescription: Pythonic way of setting path from list

description: Pythonic way of setting path from list


code:
class GUI:
    def __init__(self, root):

        # ... omitted rest of initialization code

        self.canvas.config(scrollregion=self.canvas.bbox(ALL))
        self.scale = 1.0
        self.orig_img = Image.open(File)
        self.img = None
        self.img_id = None
        # draw the initial image at 1x scale
        self.redraw()

        # ... rest of init, bind buttons, pack frame

    def zoom(self,event):
        if event.num == 4:
            self.scale *= 2
        elif event.num == 5:
            self.scale *= 0.5
        self.redraw(event.x, event.y)

    def redraw(self, x=0, y=0):
        if self.img_id:
            self.canvas.delete(self.img_id)
        iw, ih = self.orig_img.size
        size = int(iw * self.scale), int(ih * self.scale)
        self.img = ImageTk.PhotoImage(self.orig_img.resize(size))
        self.img_id = self.canvas.create_image(x, y, image=self.img)

        # tell the canvas to scale up/down the vector objects as well
        self.canvas.scale(ALL, x, y, self.scale, self.scale)

rawDescription: Adding Zooming in and out with a Tkinter Canvas Widget in Python


rawDescription: NLTK tagger reading from txt

description: NLTK tagger reading from txt


rawDescription: How do I split without removing delimeter, if it's whitespace

description: Split without removing delimeter, if it's whitespace


code:
while heads_counter + tail_counter <= 3:
    a= random.randint (1,2)
    if a==1:
        print ("heads",heads_counter)
        heads_counter+=1

    else:
        print ("tails",tails_counter)
        tails_counter+=1

print ("heads total",heads_counter)
print ("tails total",tails_counter)

rawDescription: Python while loop, coin toss 3 times

description: Python while loop, coin toss 3 times


code: new_value = value[0].strip("'")  # for single-quoted strings

rawDescription: Adding string values (varchars) to MySQL table without quotation marks with Django/Python


rawDescription: How to find a index of an item in a string?

description: Find a index of an item in a string


code:
aaa
bbb
mask
orig(aaa,bbb,pos)
new

rawDescription: Conditionally changing elements of Pandas Dataframe in a more Pythonic way


code:
def parse_listing_info(listing_info):
    for id, info in listinginfo.iteritems():
        try:
           yield id, info["converted_price_per_unit"], info["converted_fee_per_unit"]
        except KeyError:
           pass

rawDescription: python- How to properly send http GET requests to different Host-IPs but same host

description: Python- How to properly send http GET requests to different Host-IPs but same host


code:
['spam', 'bar', 'ds<hai bye>sd', 'baz', 'eggs',
 'ZQ<boo <abv> foo>WX']

rawDescription: Tokenization using regexp in Python

description: Tokenization using regexp in Python


code: 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')

rawDescription: What is the equivalent in python to this code line in perl $conf{svnlook} log --revision $rev $repo


code:
def parse_options():
    parser = argparse.ArgumentParser(description='A Tool')
    subparsers = parser.add_subparsers(help='sub-command help')

    #create the parser for the 'download' command
    download_parser = subparsers.add_parser('download', help='download help')
    download_parser.add_argument('--interval', type=int, help='interval help')
    download_parser.add_argument('--from', type=int)
    download_parser.add_argument('--build', type=int)

    opt=parser.parse_args()
    from_interval=[getattr(opt,key) is not None for key in ('from','interval')]
    if opt.build is not None:
        if any(from_interval):
            sys.exit('error!')
    elif not all(from_interval):
        sys.exit('error!')
    return opt

rawDescription: python argparse subcommand with dependency and conflict

description: Python argparse subcommand with dependency and conflict


rawDescription: Iterating List of lists- Return only one list out of four lists


rawDescription: How to get inheritance to work from parent to child class python34

description: Get inheritance to work from parent to child class python34


code:
from itertools import cycle

L = [10, 20, 30]
cycled_list = cycle(L)

rawDescription: Cycle Through List Items

description: Cycle Through List Items


rawDescription: Fill 2D numpy array from three 1D numpy arrays


code: a = np.random.randint(-3, 3, 100).reshape(10,10)

rawDescription: How to compare diagonally opposed element of a multidimensional array with numpy

description: Compare diagonally opposed element of a multidimensional array with numpy


code:
import numpy as np
ans_list = np.array([1,2,3,4,5])
ans_ind = 3
ans_list[ans_list != ans_ind]

rawDescription: Python what does this code do? list = list[ list != value]


rawDescription: Python optimization problem?

description: Python optimization problem


code: checked and all(checkbox.isChecked() for checkbox in checkboxes)

rawDescription: PyQt - How to connect multiple signals to the same widget


code:
def login(request, *args, **kwargs):
    from django.contrib.auth.forms import AuthenticationForm
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            # login successful
            do_something()
    from django.contrib.auth.views import login as authlogin
    return authlogin(request, *args, **kwargs)

rawDescription: Hacking Django Admin, hooks for login/logout


code: average

rawDescription: Trying to take the average of strings in a list and compare there counts in list to input file


rawDescription: Translating Numpy code into C#

description: Translating Numpy code into C#


code:
src_name = ["foo", "goo", "zoo"]
a = "hello values: [xxxxx], have a good day"
result = (a.replace("xxxxx", d) for d in src_name)
for i in result:
    print (i)

rawDescription: string replace in Python

description: String replace in Python


code:
import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--log', default=sys.stdout, type=argparse.FileType('w'))
args = parser.parse_args()
with args.log:
    args.log.write('log message')
# sys.stdout may be closed here

rawDescription: Context manager for optionally redirected I/O


rawDescription: Can't reach Eve REST API

description: Can't reach Eve REST API


code:
www.companya.domainurl.com   # short_url is companya
test.domainurl.com           # short_url is test

rawDescription: Django multi tenancy

description: Django multi tenancy


code:
requested_vendor = raw_input('Enter vendor name: ')
credentials = vendors.get(requested_vendor.lower())
if credentials:
    print('The username is {} the password is {}'.format(credentials['uname'],
                                                         credentials['password']))
else:
    print("Sorry, there is no vendor by the name {}".format(requested_vendor))

rawDescription: How can I select a dictionary according to the user's choice?

description: Select a dictionary according to the user's choice


code:
def ngrams(seq, n=2):
    return [seq[i:i+n] for i in range(len(seq) - n + 1)]

rawDescription: Getting next variable in a for loop

description: Getting next variable in a for loop


code:
import numpy as NP
A = NP.random.randint(10, 100, 40).reshape(8, 5)
a = NP.random.randint(1, 3, 8).reshape(8, -1)    # add column of primary keys
A = NP.column_stack((a, A))

B = NP.random.randint(0, 10, 4).reshape(2, 2)
b = NP.array([1, 2])
B = NP.column_stack((b, B))

rawDescription: Moving large SQL query to NumPy

description: Moving large SQL query to NumPy


code:
def pr(text):
  print(text)

def frun(func):
  func()

frun(lambda: pr(*pr_args))

rawDescription: send arguments for function arguments in python

description: Send arguments for function arguments in python


code: dictAB = {k: [dictA[k], dictB[k]] for k in dictA.viewkeys() & dictB.viewkeys()}

rawDescription: Refactoring with python dictionary comprehension


code:
zipped = list(zip(Openmarket, someotherlist, someotherotherlist))
filtered = list(filter(lambda elems: "FX" not in elems[0], zipped))
Openmarket, someotherlist, someotherotherlist = zip(*filtered)

rawDescription: Filtering a python list, while coupling non-filtered terms to other lists.


code:
import re
pat = re.compile('\\fc \+ \\fr(.*?)\\fc\*')
main, new = zip(*[(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]])
new = [n.strip() for n in new if n]
main
new

rawDescription: append match to new list and delete match from original list

description: Append match to new list and delete match from original list


rawDescription: Making a simple card game in python 2.7

description: Making a simple card game in python 2.7


code:
from scipy.spatial import cKDTree

tr = cKDTree(C)
dist, dist_idx = tr.query(data, k=1)

rawDescription: More efficient way to get nearest center


rawDescription: if Python doesn't support method overloading, then why does this method overload work while this other does not?

description: If Python doesn't support method overloading, then why does this method overload work while this other does not


code: Image.composite(image, Image.new('RGB', image.size, 'white'), image).show()

rawDescription: Opening PNG with PIL/Pillow

description: Opening PNG with PIL/Pillow


rawDescription: Accessing original decorated function for test purposes


code:
# client.py
import socket
from time import sleep

s = socket.socket()
s.connect(('localhost',1234))

s.send('hello 1')
# wait around for a while so that the socket in server.py goes out of scope
sleep(5)
s.send('hello 2')

rawDescription: talking between python tcp server and a c++ client

description: Talking between python tcp server and a c++ client


rawDescription: Creating formula based on binary tree leaves


code:
def factorial(x):             # define factorial as a function
    f = 1
    for n in range(2, x + 1):
        f = f * n
    return f

def main():                   # define another function for user input
    x = int(input("Please enter a number greater than or equal to 0: "))
    f = factorial(x)          # call your factorial function
    print(x,'factorial is',f)

if __name__ == "__main__":    # not executed when imported in another script
    main()                    # call your main function

rawDescription: Python: Using def in a factorial program


code:
example = [0 for _ in range(MAX_ITEMS)]
#delete
example[x-1] = 0
#add
example[x-1] = data

rawDescription: python insert into list at constant x position

description: Python insert into list at constant x position


code:
...
cursor.execute('SELECT ID, CNT FROM table_name ORDER BY ID')
item_count_vector = [
    [cnt for id_, cnt in grp]
    for key, grp in itertools.groupby(cursor.fetchall(), key=lambda row: row[0])
]

rawDescription: From MySQL table to Python list

description: From MySQL table to Python list


rawDescription: How should I subtract two dataframes and in Pandas and diplay the required output?


rawDescription: Difference between nonzero(a), where(a) and argwhere(a). When to use which?


code:
import tifffile

fp = r'path\to\image\image.tif'

with tifffile.TIFFfile(fp) as tif:
    data = tif.asarray()

rawDescription: numpy.array of an "I;16" Image file

description: Numpy.array of an "I;16" Image file


code:
from django.utils.translation import get_language
import re

def strip_lang(path):
    pattern = '^(/%s)/' % get_language()
    match = re.search(pattern, path)
    if match is None:
        return path
    return path[match.end(1):]

rawDescription: internalization set language redirect view. how to redirect to the same page?

description: Internalization set language redirect view. how to redirect to the same page


code:
master = Tk()
master.title('Enter New Password')

rawDescription: Can't cope with Dialog and Gridgeometry manager


code:
a = np.zeros((5,10))
i,j = np.indices(a.shape)

rawDescription: Make special diagonal matrix in Numpy

description: Make special diagonal matrix in Numpy


code:
from django import template
from django.contrib.contenttypes.models import ContentType

register = template.Library()

@register.filter
def content_type(obj):
    if not obj:
        return False
    return ContentType.objects.get_for_model(obj)

rawDescription: Django get ContentType in a template

description: Django get ContentType in a template


code:
mylist=['A','B']
newelement='X'
[mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]

rawDescription: Inserting values into specific locations in a list in Python


code:
...
self.childvariable1 = 2
def childfunction1(self):
    ...

rawDescription: How could I make a good application architecture in Python with PyQt?


code:
b.A
a.A
f(a,b).A

rawDescription: Comparing two scipy.sparse matrices in python


rawDescription: How to reference an element of a list inside itself?

description: Reference an element of a list inside itself


code:
mylist = [[1, 2, 3], [3, 4, 5]]
rows = []
for row in mylist:
   s=""
   for v in row:
       s+=str(v)+"\t"
   rows.append(s.rstrip())
rows
['1\t2\t3', '3\t4\t5']

rawDescription: List Comprehension to For Loop

description: List Comprehension to For Loop


code: account_uid = SocialAccount.objects.filter(user_id=request.user.id, provider='facebook')

rawDescription: Getting information about the user from Facebook using django_facebook


rawDescription: transpose part of a table with Python

description: Transpose part of a table with Python


code:
df1 = pd.pivot_table(df, index='Sequence', columns='Level', values='Count')
df1.plot(kind='bar', stacked=True)

rawDescription: Convert categorical data into various columns for plotting in pandas


code:
# At this moment, `address` does not exist yet.

firstFormat = 'Your new contact email address {} has been confirmed'
secondFormat = 'Your new contact email address %s has been confirmed'
thirdFormat = 'Hi, %s! Your new contact email %s has been confirmed'

# Now, somehow, `address` does now exists.

firstSentence = firstFormat.format(address);
secondSentence = secondFormat % address
thirdSentence = thirdFormat % ('Pyderman', address)

rawDescription: How to account for string formatting in Python variable assignment?

description: Account for string formatting in Python variable assignment


code:
for s in strings:
    if findWholeWord(s)(line) != None:
        print (jd['user_id'], jd['text'])
        break

rawDescription: Python iterative loop

description: Python iterative loop


code:
class Base(object):
    # snipped

    def Bar(self):
        Base.Foo(self)  # this will now call Base.Foo regardless of if a subclass
                        # overrides it

# snipped

x = Composite()
x.Foo()  # executes Mixin.Foo, perfect
x.Bar()  # prints "Base.Foo"

rawDescription: Python: How to distinguish between inherited methods


code:
class DomainCheckMiddleware(object):
    def process_request(self, request):
        if request.META['HTTP_HOST'] == "example2.com":
            request.IS_EXAMPLE2 = True
        else:
            request.IS_EXAMPLE2 = False
        return None

rawDescription: Achieve different behaviour when accessing from other domain


code: [list(t) for t in zip(*list_of_tuples)]

rawDescription: Most pythonic way to convert a list of tuples


code: import my_module

rawDescription: Modifying global variables in Python unittest framework


code:
checkList = ['cookieAck', 'newkey', 'tempCelsius']
query = UserSetting.query(Setting.name!=checkList[0])
for check in checkList[1:]:
  query = query.filter(ndb.AND(UserSetting.name!=check))

settings = query.fetch()

rawDescription: Google App Engine - NDB - best way of inversing the IN(list)


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for z,height in enumerate(H):
    cs = [c] * len(xs)
    cs[0] = 'c'
    ax.bar(np.arange(3), height, zs=z, zdir='y', color=cs, alpha=0.8)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

rawDescription: 2D Histogram from a 3x3 array in PYTHON

description: 2D Histogram from a 3x3 array in PYTHON


code:
results = []
while condition:
    a = do_stuff()
    results.append(a)
results = np.array(results)

rawDescription: Optimal way to append to numpy array

description: Optimal way to append to numpy array


code:
import pandas as pd
import numpy as np
#just random numbers
df = pd.DataFrame(np.random.rand(20000,30), columns=range(0,30))
#convert half the columns to text
for i in range(15,30):
    df[i].apply(str)
    df[i] = 'text' + df[i].astype(str)
writer = pd.ExcelWriter(STATS_FILE)
df.to_excel(writer,'Sheet1')
writer.save()

rawDescription: Optimize add row in xls file with xlwt

description: Optimize add row in xls file with xlwt


rawDescription: How can I disable logging while running unit tests in Python Django?

description: Disable logging while running unit tests in Python Django


code:
class A(object): # subclass object for newstyle class
    def func(self, rules=[]):
        if not rules:
            rules[:] = [8, 7, 6]
        rules.append(4)
        return rules

rawDescription: Initializing static member variable in a function


code:
car = Car()
car.repair()
car.take_to_repair_shop()

rawDescription: What is the best way to alias method names in python?


rawDescription: How to split string before number

description: Split string before number


code: ps = subprocess.Popen("ssh -o BatchMode=yes -l mygroup %s 'df -k /some/directory'" % server, stdout=subprocess.PIPE, shell=True)

rawDescription: subprocess timeout when exceeds a certain time limit

description: Subprocess timeout when exceeds a certain time limit


code:
class StatusManager(models.Manager):
    def successful(self):
        return self.get(code=1)

    def failed(self):
        return self.get(code=0)

class Status(models.Model):
    code = models.IntegerField()
    text = models.CharField(maxlength=255)

    objects = StatusManager()

rawDescription: Django model class methods for predefined values


code:
address = '7fffde53bf80'
address.decode('hex')[::-1]

rawDescription: Convert string to packed data in Python

description: Convert string to packed data in Python


code:
rotated_img = pill_img.rotate(90)
rotated_img.show()

rawDescription: Rotate photo via python

description: Rotate photo via python


code: np.random.multivariate_normal([0, 0], [[1, 0], [0, 1]], 5)

rawDescription: Syntax in Python (.T)

description: Syntax in Python (.T)


code:
Object("parameter")
Object("foobar")   # returns the same instance as the above call

rawDescription: Passing arguments to singletons in python


code:
url(r'^activate/(?P<activation_key>\w+)/$',
    activate,
    {'backend': 'custombackend.RedirectBackend'},
    name='registration_activate'),
url(r'^register/$',
    register,
    {'backend': 'custombackend.RedirectBackend'},
    name='registration_register'),

rawDescription: Getting `django-registration` to send you to the page you were originally trying to visit


code:
out = np.ones(a.shape,dtype=bool)
np.fill_diagonal(out,0)

rawDescription: How to get indices of non-diagonal elements of a numpy array?

description: Get indices of non-diagonal elements of a numpy array


rawDescription: Python check for online ip addresses

description: Python check for online ip addresses


code:
##
# Embossing filter.

class EMBOSS(BuiltinFilter):
    name = "Emboss"
    filterargs = (3, 3), 1, 128, (
        -1,  0,  0,
        0,  1,  0,
        0,  0,  0
        )

rawDescription: Image embossing in Python with PIL -- adding depth, azimuth, etc


code: pd.merge(df1_mod, df2, on=['Code', 'Date'])

rawDescription: How to merge two data frames based on nearest date

description: Merge two data frames based on nearest date


code:
factory = PBServerFactory(...)
...
serverEndpoint.listen(factory)

rawDescription: Can Perspective Broker be used over stdio instead of TCP?


code:
import pandas
import numpy as np
data = pandas.DataFrame(
    {'pid' : [1,1,1,2,2,3,3,3],
     'tag' : [23,45,62,24,45,34,25,62],
     })

bytag = data.groupby('tag').aggregate(np.count_nonzero)
tags = bytag[bytag.pid >= 2].index
print(data[data['tag'].isin(tags)])

rawDescription: Python Pandas: remove entries based on the number of occurrences


code:
class B(models.Model):
    name = models.ForeignKeyField(A, to_field="name", db_column="name")

rawDescription: Non-primary foreign keys in Django

description: Non-primary foreign keys in Django


code:
with open("CountryCodes.csv",'r') as CountryCodes:
    genc = (line.split(',') for line in CountryCodes)

    c2n = dict((c_fields[0].strip(),c_fields[1].strip())
               for c_fields in genc)

with open("CountryData.csv",'r') as CountryData:
    gend = (line.split(',') for line in CountryData)

    the_data = [ (c2n[d_fields[0].strip()], # data_country_code
                  int(d_fields[1]),         # country_pop
                  d_fields[2].strip(),      # country_area
                  d_fields[3].strip(),      # country_gdp
                  d_fields[4].strip())      # country_lit_rate
                 for d_fields in gend ]

the_data.sort(key = lambda x: x[1])

p = 10
for i in xrange(0,len(the_data),p):
    if i:  raw_input("  Press ENTER to continue\n")
    print ('\n'.join("%-10s \t %-10s \t %-10s \t %-10s \t %s"
                     % el for el in the_data[i:i+p]) )

rawDescription: Comparing in lists in Python

description: Comparing in lists in Python


code:
ser = serial.Serial('/dev/ttyUSB-17', 115200, timeout=1)
output = open("/var/log/messages", "rb")

rawDescription: how to read command output from serial device using python

description: Read command output from serial device using python


code:
anArray
_,id = np.unique(anArray,return_inverse=True)
(id.max() - id + 1).reshape(anArray.shape)

rawDescription: Numpy Array Rank All Elements

description: Numpy Array Rank All Elements


rawDescription: Best way to isolate one coefficient of a multivariate polynomial in sympy

description: Isolate one coefficient of a multivariate polynomial in sympy


code:
image = Image.open(Image_Location)
image = image.resize((250, 250), Image.ANTIALIAS) #The (250, 250) is (height, width)
self.pw.pic = ImageTk.PhotoImage(image)

rawDescription: Resizing pictures in PIL in Tkinter

description: Resizing pictures in PIL in Tkinter


rawDescription: Get Attribute type of a model in Django

description: Get Attribute type of a model in Django


code:
def close_pairs_pdist(X,max_d):
    d = pdist(X)
    k = (d<max_d).nonzero()[0]
    return condensed_to_pair_indices(X.shape[0],k)

rawDescription: Find all point pairs closer than a given maximum distance


rawDescription: Filter a pandas dataframe using values from a dict


code: {k: sum(v > 0 for v in d.values()) for k,d in myDict.items()}

rawDescription: Working out certain values from a nested dictionary


code:
class DecimalEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):
        if isinstance(o, decimal.Decimal):
            # wanted a simple yield str(o) in the next line,
            # but that would mean a yield on the line with super(...),
            # which wouldn't work (see my comment below), so...
            return (str(o) for o in [o])
        return super(DecimalEncoder, self)._iterencode(o, markers)

rawDescription: Python JSON serialize a Decimal object

description: Python JSON serialize a Decimal object


code:
np.copyto(x,[0,0,31,41],where=mask)
x

rawDescription: Write to a masked array in numpy

description: Write to a masked array in numpy


code:
from __future__ import division, absolute_import, print_function
from scipy.special import betaln
from scipy.misc import logsumexp
import numpy as np

def binomln(n, k):
    # Assumes binom(n, k) >= 0
    return -betaln(1 + n - k, 1 + k) - np.log(n + 1)

for n in range(2, 1000, 10):
    m = 2.2*n/np.log(n)

    a = np.arange(1, n + 1)[np.newaxis,:]
    b = np.arange(n + 1)[:,np.newaxis]

    v = (binomln(n, a)
         + binomln(n - a, b)
         + m*binomln(a + b, a)
         - m*(a+b) * np.log(2))

    term = np.exp(logsumexp(v))
    print(term)

rawDescription: How to compute an expensive high precision sum in python?

description: Compute an expensive high precision sum in python


rawDescription: Count occurences of a row with pandas in python


code:
from itertools import repeat
[repeated for value in x for repeated in repeat(value, 4)]

rawDescription: How can I increase the size of, and pad, a python list?

description: Increase the size of, and pad, a python list


code:
costs = {}

item_name = input("What do you want to buy? ")
costs[item_name] = input('Price? ')

rawDescription: Combine/ "concatenate" two variables, one being a user input


code:
def merge_file(infile, outfile, separator = ""):
    print(separator.join(line.strip("\n") for line in infile), file = outfile)

def merge_files(paths, outpath, separator = ""):
    with open(outpath, 'w') as outfile:
        for path in paths:
            with open(path) as infile:
                merge_file(infile, outfile, separator)

rawDescription: Merging multiple text files into one and related problems


rawDescription: Duplicates when extracting data from html table using lxmk.html.xpath()


code:
import matplotlib.pyplot as plt
plt.imshow(bitmask)
plt.show()

rawDescription: getting the bitmask of a text string in python

description: Getting the bitmask of a text string in python


code:
requests.post('http://mypage.com/add', data=params,
              headers = headers, proxies = proxy, timeout = max_timeout)

rawDescription: Python requests post not sending string

description: Python requests post not sending string


rawDescription: split ndarray into chunks - whilst maintaining order

description: Split ndarray into chunks - whilst maintaining order


rawDescription: First common element from different lists of numbers


code:
number = sum((10 ** power) * test[character]
             for power, character in enumerate(reversed(user_input)))

rawDescription: How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)?

description: Make a 'while' loop print the results of the loop's conditional into a single line(concatenated)


rawDescription: Numpy array.resize() - zeros 'first'

description: Numpy array.resize() - zeros 'first'


code:
class XMLFORMTable(tables.Table):
      eliminar = tables.CheckBoxColumn(accessor='pk')
      class Meta:
            model = XML_FORM
            exclude = ['id_form','obs']

rawDescription: Django delete formset

description: Django delete formset


code:
#!/usr/bin/env python

import fnmatch
import os

filter_pattern = "*.txt"

path = "."
for dirpath, dirnames, filenames in os.walk(path):
    # comment this out if you don't want to filter
    filenames = [fn for fn in filenames if fnmatch.fnmatch(fn, filter_pattern)]

    if len(filenames) == 2:
        # comment this out if you don't want the 2 filenames to be sorted
        filenames.sort(key=str.lower)

        filepath1, filepath2 = [os.path.join(dirpath, fn) for fn in filenames]
        with open(filepath1, 'r') as fin1, open(filepath2, 'r') as fin2:
            print("do something with " + str(fin1) + " and " + str(fin2))

rawDescription: Iterate over 2 files in each folder and compare them


rawDescription: Grouping data points into series

description: Grouping data points into series


code:
trailers = {film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])]
            for film in j}

rawDescription: Read a dict of dicts in a list

description: Read a dict of dicts in a list


code:
import pymongo
client = pymongo.MongoClient()
db = client.test
collection = db.collection

rawDescription: Passing variables onto a MongoDB Query

description: Passing variables onto a MongoDB Query


code:
import csv

totals = {}

# Aggregate sales by company, state, and quarter.
for row in csv.reader(open('data.csv')):
  if row[3] == 'Sales':
    key = (row[2], row[1][:2], row[0])
    totals[key] = totals.setdefault(key, 0) + float(row[4])

# Write aggregated data to file.
with open('aggregated.csv', 'w') as out_file:
  writer = csv.writer(out_file)
  for key, value in sorted(totals.items()):
    row = list(key) + [value]
    writer.writerow(row)

rawDescription: How to aggregate column values from a CSV file in Python

description: Aggregate column values from a CSV file in Python


code:
CONVERSION_DICT = {
    'kelvin': lambda x: x - 273.15,
    'romer': lambda x: (x - 7.5) * 40 / 21
}

def convert_to_celsius_lambda_once(temp, source):
    return CONVERSION_DICT[source](temp)

rawDescription: Recommended usage of Python dictionary, functions as values


code:
html = t.render(Context({'html_map':html_map}))
return HttpResponse(html)

rawDescription: Django Javascript Output

description: Django Javascript Output


code:
def unpack(first, *rest):
  return first, rest
first, rest = unpack( *seq )

rawDescription: How to unpack tuple of length n to m<n variables

description: Unpack tuple of length n to m<n variables


code:
from more_itertools import unique_everseen
list(unique_everseen(lst, key=len))

rawDescription: pythonic way to filter list for elements with unique length

description: Pythonic way to filter list for elements with unique length


code:
list_of_lists = [[header0,  header1,  header2 ],
                 [r1c0data, r1c1data, r1c2data],
                 [r2c0data, r2c1data, r2c2data]]

rawDescription: Add specific columns to a single row list (might be a little basic)


rawDescription: Fermi Surface Plots

description: Fermi Surface Plots


code:
file1_names = {}
for obj1 in file1:
    if 'name' not in obj1:
        continue
    file1_names.setdefault(obj1['name'], []).append(obj1)

rawDescription: There must be a more optimal way to parse two files


code:
for row in enumerate(items):
    if row[1] == itemname:
        print("SIN: %s" % row[0])
        print("Itemname: %s" % row[1])
        print("Retail price: %s" % row[2])
        print("Costprice: %s" % row[3])
        print("Quantity Available: %s" % row[4])
        choice = input("Would you like to update quantity? y/n")
        if choice == 'y':
            newquantity = input("Enter new quantity: ")
            row[4] = newquantity
            print(', '.join(row))
            writetrue = '1'
        else:
            startup()

rawDescription: Rewriting array to text file, need to put each part on new line


code:
x_y = [(xy[i], xy[i+1]) for i in xrange(len(xy)-1)]
x_y

rawDescription: convert a list of x and y coordinates into multistring

description: Convert a list of x and y coordinates into multistring


code:
from ast import parse, Call, walk
import importlib
import inspect

mod = "test"
mod = importlib.import_module(mod)
p = parse(inspect.getsource(mod))

from ast import literal_eval

vals = []
for node in p.body:
    if isinstance(node, FunctionDef) and node.name == "my_method":
        for node in walk(node):
            if isinstance(node,Call) and node.func.id == "foobar":
                vals.append([literal_eval(val) for val in node.args])

print(vals)

[['apple', 'pear', 6], [1, 2, 3], ['a', 'b']]

rawDescription: Getting method calls and their arguments from method object


code:
class Product(models.Model):

    location_name = models.CharField(max_length=12)
    product_name = models.CharField(max_length=200)
    quantity = models.IntegerField(default=1)
    mpn = models.CharField(max_length=200)

    location = models.ForeignKey(Location)

    def save(self, *args, **kwargs):
        isle = self.location_name[0]
        segment = self.location_name[1]
        shelf = self.location_name[2]
        box = self.location_name[3]
        self.location = Location.objects.get_or_create(
                            isle=isle,
                            segment=segment,
                            shelf=shelf,
                            box=box)
        super(Product, self).save(*args, **kwargs)

rawDescription: Set parent of model during creation

description: Set parent of model during creation


code:
# Get access to your .NET API
import clr
clr.AddReference("MyAPI")
import MyAPI

# Define the Ping call to call into your .NET API
def Ping(Message):
  MyAPI.Ping(Message)

rawDescription: Calling a function with named arguments in a hosted application


code:
gene1, gene2 = None, None
for line in file:
    if matches_gene1(line):
        gene1 = parse_gene1(line)
    elif matches_gene2(line):
        gene2 = parse_gene2(line)
    elif matches_gene0(line):
        gene0 = parse_gene0(line)
        do_stuff_with(gene0, gene1, gene2)
        gene1, gene2 = None, None

rawDescription: how to keep data from lines in file until condition met later in file python

description: Keep data from lines in file until condition met later in file python


code:
from functools import partial
TRANSFORM_PIPELINE = [
    partial(do_xslt, 'pass1.xsl'),
    partial(do_xslt, 'pass2.xsl'),
    partial(do_xslt, 'pass3.xsl')
]

rawDescription: How to give a constant and a dynamic argument to functions which are stored in an array

description: Give a constant and a dynamic argument to functions which are stored in an array


rawDescription: Is it possible to speed up interactive IPython Notebook plots by not generating new figures every time?


code:
import somemodule
import sys
dirname = os.path.dirname(os.path.abspath(somemodule.__file__))
sys.path.append(dirname)

rawDescription: How do I resolve sys.path differences in Python and IronPython

description: Resolve sys.path differences in Python and IronPython


code:
class ConditionsValidator(Orange.core.RuleValidator):
    """ prunes rules with 'isgreater' conditions """
    def __call__(self, rule, data, weight_id, target_class, prior):
        for c in rule.filter.conditions:
            if c.oper == Orange.data.filter.ValueFilter.Greater:
                return False
        return True

rawDescription: How to avoid same variable being used twice in an Orange CN2 rule?

description: Avoid same variable being used twice in an Orange CN2 rule


rawDescription: Python Image Processing - Move an Image

description: Python Image Processing - Move an Image


code: stretch_to(range(8), 20)

rawDescription: Stretching a list in Python

description: Stretching a list in Python


code:
grouped = df.groupby(['animal'])
fig, ax = plt.subplots()
for key, group in grouped:
    group.plot('day', 'count', label=key, ax=ax)

rawDescription: How to plot values for multiple factors from one column across several dates in pandas + matplotlib?

description: Plot values for multiple factors from one column across several dates in pandas + matplotlib


code:
from flow import Flow
import falcon
import threading
import storage

__version__ = 0.1
__author__ = 'weldpua2008@gmail.com'

app = falcon.API(
    media_type='application/json')

app.add_route('/flow', Flow())

THREADS_COUNT = 1
# adding the workers to process queue of command
worker = storage.worker
for _ in xrange(THREADS_COUNT):
    thread = threading.Thread(target=worker)
    thread.daemon = True
    thread.start()

rawDescription: How to store response when http client closed a connection?

description: Store response when http client closed a connection


code:
from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

rawDescription: How to import a module given the full path?

description: Import a module given the full path


rawDescription: ValueError: operands could not be broadcast together with shapes


code:
group_key = itemgetter(Col["KEY_FIELD"])
data = sorted(data, key=group_key)

for key, group in groupby(data, group_key):
    group = list(group)
    status_r = any(item[Col["STATUS"]] == "R" for item in group)
    for item in group:
        if status_r:
           item[Col["STATUS"]] = "R"

rawDescription: Changing elements within a groupby

description: Changing elements within a groupby


rawDescription: Parsing Lines in Python: Use RE or Not?

description: Parsing Lines in Python: Use RE or Not


rawDescription: Python - Plotting a raster image/contour plot with XY and Z points


code:
@hybrid_property
def complicated_property(self):
    if 17 <= self.a <= 173:
        return a_complicated_math_function(self.a + self.b)
    return another_complicated_math_function(self.a * self.b ** 2)

@complicated_property.expression
def complicated_property(cls):
    # Here you will need to use a CASE statement most likely.
    # If you want to turn it into SQL, you obviously need to know
    # what SQL you want to turn it into...
    return case(
        None,
        (cls.a.between(17, 173), fn.math(fn.more_math(cls.a, 1.23))),
        default=fn.another_complicated_math(cls.a))

rawDescription: Defining virtual fields in peewee

description: Defining virtual fields in peewee


rawDescription: python find and match exact string

description: Python find and match exact string


code:
#!/usr/bin/env python
import requests # $ pip install requests
from PIL import Image # $ pip install pillow

r = requests.get(url, stream=True)
r.raw.decode_content = True # handle spurious Content-Encoding
im = Image.open(r.raw)
print(im.format, im.mode, im.size)

rawDescription: temporarily retrieve an image using the requests library

description: Temporarily retrieve an image using the requests library


code:
scores = []
for i in range(5):
    new_score = int(input("test score?"))
    scores.append(new_score)

rawDescription: Ask for five values, subtract the lowest and take the average


code:
import version2
versions = ["1.7.0", "1.7.0rc2", "1.7.0rc1", "1.7.1", "1.11.0"]
sorted(versions, key=lambda v: version2.NumberedVersion(v, '.', ['rc']))

rawDescription: Sort Versions in Python

description: Sort Versions in Python


code:
class unpatch:
    def __init__(self, name, method):
        compare = patch(name)
        self.patcher = next((
            p for p in method.patchings
            if p.target == compare.getter()
            and p.attribute == compare.attribute
        ), None)
        if self.patcher is None:
            raise ValueError(name)

    def __enter__(self):
        self.patcher.__exit__()

    def __exit__(self, *exc_info):
        self.patcher.__enter__()

rawDescription: Python: calling stop on mock patch class decorator


code:
def assignments(n, m, used=0):
    """Generate assignments of `n` items to `m` indistinguishable
    buckets, where `used` buckets have been used so far.

        >>> list(assignments(3, 1))
        [(0, 0, 0)]
        >>> list(assignments(3, 2))
        [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]
        >>> list(assignments(3, 3))
        [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 1, 2)]

    """
    if n == 0:
        yield ()
        return
    aa = list(assignments(n - 1, m, used))
    for first in range(used):
        for a in aa:
            yield (first,) + a
    if used < m:
        for a in assignments(n - 1, m, used + 1):
            yield (used,) + a

rawDescription: Generating a list of repetitions regardless of the order


code: [x for n in getNeighbors(vertex) for x in getNeighbors(n)]

rawDescription: Concatenation of many lists in Python

description: Concatenation of many lists in Python


code: df = df.ix[~df.apply(np.round, args=[4]).duplicated()]

rawDescription: drop duplicates in Python Pandas DataFrame not removing duplicates

description: Drop duplicates in Python Pandas DataFrame not removing duplicates


code:
import datetime

now = datetime.datetime.now()
date_string = now.strftime('%Y-%m-%d')
print(date_string)

rawDescription: Converting date to string in Python

description: Converting date to string in Python


code:
import calendar

year = int(raw_input('Enter year: '))
month = int(raw_input('Enter month number: '))

print(calendar.monthrange(year, month)[1])

rawDescription: Python amount of days in a month with a given year and month?


code: saw2 = x[None,:].repeat(4,0).flatten()

rawDescription: How to rewrite the code which appends to lists with numpy arrays

description: Rewrite the code which appends to lists with numpy arrays


code:
Sample.objects.filter(date__year='2011',
                      date__month='01')

rawDescription: Django database query: How to filter objects by date range?


code:
def a(a,b,c):
    lcl = locals()
    print(lcl)
    d(**lcl)
    e = 123
    print(locals())
def d(**kwargs):
    print(kwargs)
a(1,2,3)

rawDescription: Python: put all function arguments into **kwargs automatically


code:
from collections import namedtuple
n = namedtuple('Person', ('name', 'gender', 'age'))
persons = (("Josh", "Male", 22), )
for person in persons:
    data.append(Person(person))

rawDescription: Data type to save a table

description: Data type to save a table


code:
def mk_foobar(*args):
    for a in args:
        print(a)
    print('bar')

class Foo(object):
    @property
    def foo(self):
        return 'foo'
    echo = partialmethod_with_descriptorargs(mk_foobar, foo)

Foo().echo()
class Child(object):
    def __init__(self, item):
        self.item = item
    def __get__(self, instance, objtype):
        return 'child argument was: %s' % self.item

class Bar(object):
    a = Child('b')
    echo = partialmethod_with_descriptorargs(mk_foobar, a)

Bar().echo()

rawDescription: How to access a class's property using a partialmethod?

description: Access a class's property using a partialmethod


code:
d = {}
for k, v in dict_a.items():
    if k in dict_b:
        val1, val2 = (v[0]+ dict_b[k][0]) / 2, (v[1] + dict_b[k][1]) / 2 # average sum of ele1 and ele2 in each value list
        d[k] = [val1, val2] # set new value to key
        del dict_b[k] # remove key
    else:
        d[k] = v # else just add the k,v

d.update(dict_b) # update with remainder of dict_b

rawDescription: Combine Dictionaries With average values for similar keys,Python


code:
with open(path, 'r+b') as f:
    with contextlib.closing(mmap.mmap(f.fileno(), access=mmap.ACCESS_WRITE)) as m:
        m[first_position] = first_new_byte
        m[other_position] = other_new_byte
        # ...

rawDescription: How do I edit an executable with python by address/offset/bytes, like in a hex editor?

description: Edit an executable with python by address/offset/bytes, like in a hex editor


code:
class User(BaseMixin, db.Model):
    __tablename__ = 'user'

    user_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    created_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP"))
    updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP"))

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

rawDescription: How to add a custom function/method in sqlalchemy model to do CRUD operations?

description: Add a custom function/method in sqlalchemy model to do CRUD operations


code:
from random import sample, choice
sample(randomnumbers, 5)
[choice(randomnumbers) for _ in range(5)]

rawDescription: how to generate 5 numbers from a list?

description: Generate 5 numbers from a list


code: [lst[i:j] for i, j in combinations(range(len(lst)+1), 2)]

rawDescription: python connected combinations of list items

description: Python connected combinations of list items


code:
type(sex1)
type(sex2)

rawDescription: Function definitions vs Lambda expression


code:
# get some uniformly sampled data, padded out a bit
colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
# sample the input colormap at our sample points
colors_rgba = cmap(colors_i)
# indices for color map
indices = np.linspace(0, 1., N+1)
# dict to pass to the LinearSegmentedColormap
cdict = {}
# loop over the colors
for ki,key in enumerate(('red','green','blue')):
    # in each color assemble a list that looks like
    #[...,
    # (indices[2], colors_rgba[1,ki], colors_rgba[2,ki]),
    # (indices[3], colors_rgba[2,ki], colors_rgba[3,ki]),
    # ....]
    cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in xrange(N+1) ]
    # The color for a number between [indices[2], indices[3]] are interpolated
    # between colors_rgba[2,ki] and colors_rgba[2,ki] which are the same
    # which is what gives you the discrete blocks.
# Construct and return colormap object.
return cols.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

rawDescription: modify discrete LinearSegmentedColormap

description: Modify discrete LinearSegmentedColormap


rawDescription: How do I maximize efficiency with numpy arrays?

description: Maximize efficiency with numpy arrays


code: unique_elements, indices = np.unique(data[:]['name'], return_index = True)

rawDescription: Filter numpy structured array based based on unique elements in one dimension


code:
class Foo:
    a = None
    @property
    def a(self):
        pass
    @a.setter
    def a(self, v):
        '''
        >>> 1 == 1
        False
        '''
        pass
Foo.a
Foo.a.__doc__ is None

rawDescription: python-2.7: doctests ignored in setter method of a class

description: Python-2.7: doctests ignored in setter method of a class


code:
history=[]
for n in range(100):
    history.append(copy.deepcopy(gal.time_stepper(.1)))

rawDescription: python over-writing my list elements

description: Python over-writing my list elements


code:
import pkgutil
package = pkgutil.get_loader("pip")
package.filename
package = pkgutil.get_loader("threading")
package.filename
package = pkgutil.get_loader("sqlalchemy.orm")
package.filename

rawDescription: Find path of module without importing in Python


code:
f = gcf()  # f = figure(n) if you know the figure number
f.set_size_inches(11.69,8.27)

rawDescription: Python: A4 size for a plot

description: Python: A4 size for a plot


rawDescription: Generalizing matrix transpose in numpy

description: Generalizing matrix transpose in numpy


rawDescription: Iterating Through Table Rows in Selenium (Python)


code: sorted(inputlist, key=lambda s: s[5:])

rawDescription: Sort from a certain position in a String


rawDescription: How do I make a variable accessible from another python script when accessed from modulename.main() method

description: Make a variable accessible from another python script when accessed from modulename.main() method


rawDescription: How can I access unknown objects at runtime - not their names

description: Access unknown objects at runtime - not their names


code:
dic = dict((x, 0) for x in lis)
dic

rawDescription: Most Pythonic Way to Build Dictionary From Single List


code:
len(odd)
len(even)

rawDescription: Count even and odd numbers and the totals (python)


code:
import csv
with open('temperature.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
        ...

rawDescription: Formatting values using header indexing with csv


code:
class Data:

    def __init__(self, data):
        self.data = data
        self.dimensions = None

    def get_dimensions(self):
        self.dimensions = (np.shape(self.data) if
            self.dimensions is None else
            self.dimensions)
        return self.dimensions

rawDescription: Python - Create shared class variable in class itself


code:
def pivotarray(df):
    users,i= np.unique(df['user'],return_inverse=True)
    item,j= np.unique(df['item'],return_inverse=True)
    a=zeros((len(users),len(item)),int)
    a[i,j]=df['rating']
    return a

rawDescription: How to aggregate the values of a DataFrame (and output a numpy array quickly)?

description: Aggregate the values of a DataFrame (and output a numpy array quickly)


code: x

rawDescription: Fast way to find index of array in array of arrays


rawDescription: Django help - how to get data from foreign keys


code: bs = sorted(set(d['b'] for d in lst))

rawDescription: Breaking a list in to parts by subject

description: Breaking a list in to parts by subject


code: print('Text: ABC\b\b\bXYZ')

rawDescription: Using \b in python 3

description: Using \b in python 3


code: print((a + 1), (b + 1), result)

rawDescription: compare lists in python

description: Compare lists in python


rawDescription: Call Python from C++ OpenCV 3.0

description: Call Python from C++ OpenCV 3.0


code:
def generate_cache_filename(instance, path, specname, extension):
    extension = '.jpg'
    return 'cache/images_upload/%s_%s%s' % (instance.pk, specname, extension)
# generate random string of 10 characters
def id_generator(size=10, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range(size))

def generate_random_filename(instance, filename):
    filename = id_generator()
    extension = '.jpg'
return 'images_upload/%s_%s%s' % (instance.pk, filename, extension)

class Model(models.Model):
    name = models.CharField(max_length=20)
    image_1 = ProcessedImageField([Adjust(contrast=1.2, sharpness=1.1), ResizeToFill(500, 370)], upload_to=generate_random_filename, format='JPEG', options={'quality': 90})
    thumbnail_1 = ImageSpec([Adjust(contrast=1.2, sharpness=1.1), ResizeToFill(83, 78)], image_field='image_1', cache_to=generate_cache_filename, format='JPEG', options={'quality': 90})

rawDescription: Imagekit - cache image not deleted after deleting original


code:
path = split_url.path
path.split('/')

rawDescription: parsing a url in python with changing part in it

description: Parsing a url in python with changing part in it


code:
import pexpect

py = pexpect.spawn('fst-mor NOUN.A')
py.expect('analyze>')
py.send('INPUT_A_STRING_HERE')
output = py.read()
py.close()

rawDescription: Calling multi-level commands/programs from python


code:
def int_str(val, keyspace):
    """ Turn a positive integer into a string. """
    assert val >= 0
    out = ""
    while val > 0:
        val, digit = divmod(val, len(keyspace))
        out += keyspace[digit]
    return out[::-1]

def str_int(val, keyspace):
    """ Turn a string into a positive integer. """
    out = 0
    for c in val:
        out = out * len(keyspace) + keyspace.index(c)
    return out

rawDescription: What is the best way to get a semi long unique id (non sequential) key for Database objects


code:
Hello
World

rawDescription: How does Python interpret its code?

description: How does Python interpret its code


code:
from matplotlib import dates as mPlotDATEs   # helper functions num2date()
#                                            #              and date2num()
#                                            #              to convert to/from.

rawDescription: Reading a time list and make a plot using matplotlib


rawDescription: Sort multiple lists simultaneously

description: Sort multiple lists simultaneously


code:
import tarfile
baz = tarfile.open('baz.tgz')
bar = tarfile.open(fileobj=baz.extractfile('bar.tgz'))
bar.extractfile('bar/baz.txt').read()

rawDescription: How to walk a tar.gz file that contains zip files without extraction

description: Walk a tar.gz file that contains zip files without extraction


rawDescription: How to search and export value with python and re?

description: Search and export value with python and re


code:
params = {'rate': distinct} #where distinct is distinct = kwargs.pop('distinct')
things = Thing.object.filter(**params)

rawDescription: kwargs in django - how to put distinct() into kwargs

description: Kwargs in django - how to put distinct() into kwargs


code: common

rawDescription: Efficiently find overlap of a lists of tuples


code:
from selenium import webdriver

mime_types = "application/pdf,application/vnd.adobe.xfdf,application/vnd.fdf,application/vnd.adobe.xdp+xml"

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 2)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.download.dir", "/home/aafanasiev/Downloads")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", mime_types)
fp.set_preference("plugin.disable_full_page_plugin_for_types", mime_types)
fp.set_preference("pdfjs.disabled", True)

browser = webdriver.Firefox(firefox_profile=fp)
browser.get("http://epaper.dinamalar.com/")

webobj_get_link = browser.find_element_by_id("liSavePdf")
webobj_get_object = webobj_get_link.find_element_by_tag_name("a")
webobj_get_object.click()

rawDescription: Selenium pdf automatic download not working


code:
print("First line\nSecond line")
print(repr("First line\nSecond line"))
print(repr(repr("First line\nSecond line")))

rawDescription: Python - nested __repr__ reverts newline to "\\n"


code: AdvisorFormSet=modelformset_factory( Advisor, form=AdvisorForm )

rawDescription: using modelformset_factory and placeholder

description: Using modelformset_factory and placeholder


code:
N = np.dot(M, M.T)
N[N > 0] = 1
N

rawDescription: Transforming a mapping matrix

description: Transforming a mapping matrix


code: np.add.at(A, ind, B[:N])

rawDescription: Numpy Slicing slow?

description: Numpy Slicing slow


code:
h1 = Heater()
log = DataLogger(h1)
log.start(60)
h1.set_power(10,100)
h1.turn_on()
sleep(10)
h1.turn_off()

rawDescription: Elegant way to add functionallity to previously defined functions


rawDescription: Using an item from a list as a new dictionary key


code: loggify(Working)

rawDescription: How to cast object in Python

description: Cast object in Python


code:
class Congressman(ndb.model):
    ...

rawDescription: How to save results from an api request to the Google Datastore?

description: Save results from an api request to the Google Datastore


rawDescription: Python : Get many list from a list

description: Python : Get many list from a list


code:
app = tornado.web.Application([
    (r'/jesse\.txt', MyFileHandler, {'path': '/path/to/foo.json'})
])

rawDescription: How can Tornado serve a single static file at an arbitrary location?


code:
result = [item for a_tuple in lot for item in a_tuple]
result

rawDescription: List comprehension interpretation order while turning list of tuples into a list


code:
cols = ['buying', 'maint', 'lug_boot', 'safety', 'class']
df[cols].apply(lambda x: pd.factorize(x)[0])

rawDescription: Encoding column labels in Pandas for machine learning


rawDescription: getting date fields from oracle in correct format using Python and cx-oracle

description: Getting date fields from oracle in correct format using Python and cx-oracle


code: ''.join('\\%o' % ord(c) for c in test)

rawDescription: How to replace r'\xb0' with r'\260'

description: Replace r'\xb0' with r'\260'


code:
['Poles', 'Magnet', '?', 'Battery']
['Charge', 'Ends', 'Magic', 'Metal']
Charge

rawDescription: Split a string by three delimiters, and adding them to different lists


code:
import requests
from bs4 import BeautifulSoup

d = {"ctl00$ctl13": "ctl00$ctl13|ctl00$MainContent$physicianSearchView$btnSearch",
     "ctl00$MainContent$physicianSearchView$txtLastName": "Train",
     'ctl00$MainContent$physicianSearchView$txtFirstName': "Anthony",
     'ctl00$MainContent$physicianSearchView$txtCity': "Calgary",
     "__VIEWSTATEENCRYPTED":"",
     'ctl00$MainContent$physicianSearchView$txtPostalCode': "",
     'ctl00$MainContent$physicianSearchView$rblPractice': "",
     'ctl00$MainContent$physicianSearchView$ddDiscipline': "",
     'ctl00$MainContent$physicianSearchView$rblGender': "Male",
     'ctl00$MainContent$physicianSearchView$txtPracticeInterests': "",
     'ctl00$MainContent$physicianSearchView$ddApprovals': "",
     'ctl00$MainContent$physicianSearchView$ddLanguage': "",
     "__EVENTTARGET": "ctl00$MainContent$physicianSearchView$btnSearch",
     "__EVENTARGUMENT": "",
     'ctl00$MainContent$physicianSearchView$hfPrefetchUrl': "http://service.cpsa.ca/OnlineService/OnlineService.svc/Services/GetAlbertaCities?name=",
     'ctl00$MainContent$physicianSearchView$hfRemoveUrl': "http://service.cpsa.ca/OnlineService/OnlineService.svc/Services/GetAlbertaCities?name=%QUERY",
     '__ASYNCPOST': 'true'}

h ={ "X-MicrosoftAjax":"Delta = true",
"X-Requested-With":"XMLHttpRequest",
     "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"
}

with requests.session() as s:
    r = s.get("http://search.cpsa.ca/PhysicianSearch",headers=h)
    soup = BeautifulSoup(r.content, "lxml")
    ev = soup.select("#__EVENTVALIDATION" )[0]["value"]
    vs = soup.select("#__VIEWSTATE")[0]["value"]
    vsg = soup.select("#__VIEWSTATEGENERATOR")[0]["value"]
    d["__EVENTVALIDATION"] = ev
    d["__VIEWSTATEGENERATOR"] = vsg
    d["__VIEWSTATE"] = vs
    r = requests.post('http://search.cpsa.ca/PhysicianSearch', data=d,headers=h)
    print(r.content)

rawDescription: python - POST request doesn't work

description: Python - POST request doesn't work


rawDescription: Dialog box handling in excel through python


code:
word = "first portion|middle|,end"
l = word.split('|')
result1 = l[0] + l[2]
result2 = l[1]
result1
result2

rawDescription: Python - Having a sub for loop with the same variable


code:
b=[[] for _ in xrange(10)]
b
b[0].append(0)
b

rawDescription: append value in ith list of list

description: Append value in ith list of list


code:
class Derived(Base):
    decorator = staticmethod(whatever)

rawDescription: What's the cleanest way to add a decorator from a derived class to its base class?


code:
def make_repl(n, ignore):
    def repl(match):
        if match.group(1) == ignore:
            return match.group(0)
        return match.group(1) + str(int(match.group(2)) + n)
    return repl

result = re.sub(r'(\w+\d+:)(\d+)', make_repl(10, 'Seq1:'), s)

rawDescription: Substitution of certain occurences of a string with another string in python


code:
str2 : 2
str4 : 2
str3 : 1
str1 : 0

rawDescription: Python get name in loop

description: Python get name in loop


code:
class GameRobotCommands(object):
    reset = 0x0
    turncenter = 0x1
    turnright = 0x2
    turnleft = 0x4
    standstill = 0x8
    moveforward = 0x10
    movebackward = 0x20
    utility1 = 0x40
    utility2 = 0x80

rawDescription: How can I read hexadecimal data with python?

description: Read hexadecimal data with python


code:
import mock
import unittest

import mylib

class TestMyLib(unittest.TestCase):
    @mock.patch('mylib.SomeObject')
    def test_mytest(self, mock_someobject):
        mock_instance = mock_someobject.return_value
        mock_instance.method_inside_someobject.side_effect = ['something']

        retval = mylib.method_to_test()

        mock_someobject.assert_called_with(arg1='foo', arg2='bar', arg3='baz')
        self.assertEqual(retval, 'something')

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

rawDescription: Python mock object instantiation

description: Python mock object instantiation


code:
def partial_k(f, k, seq):
    def wrapper(x):
        return f(*seq[:k], x, *seq[k:])
    return wrapper

rawDescription: Freezing all but one positional arguments


rawDescription: Templates in web.py

description: Templates in web.py


code:
import subprocess
proc = subprocess.Popen(['gedit', 'file.txt'])

rawDescription: Opening file from python

description: Opening file from python


code:
pivoted = df.pivot_table(index=['ElementHID'], columns=['ShellSurface'])
pivoted

rawDescription: Adding DataFrame groups as data columns

description: Adding DataFrame groups as data columns


code:
myArray
myArray.sum(axis=(0,1))
myArray.std(axis=(0,1))
np.einsum('ijk->k',myArray)

rawDescription: perform 2-d operation on each layer of a 3-d stack

description: Perform 2-d operation on each layer of a 3-d stack


code: url_for('find_user', user=user)

rawDescription: Flask multiple URL handlers process URLs partially


code:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
twenty-six
twenty-seven
twenty-eight
twenty-nine
thirty

rawDescription: how to extract specific lines from a data file

description: Extract specific lines from a data file


code:
import nltk

groucho_grammar = nltk.CFG.fromstring("""
S -> NP VP
PP -> P NP
NP -> Det N | Det N PP | 'I' | NUM N
VP -> V NP | VP PP
Det -> 'an' | 'my'
N -> 'elephant' | 'pajamas' | 'elephants'
V -> 'shot'
P -> 'in'
NUM -> '#NUM#'
""")

original_sent = 'I shot 333 elephants'.split()
sent = ['#NUM#' if i.isdigit() else i for i in original_sent]
numbers = [i for i in original_sent if i.isdigit()]

parser = nltk.ChartParser(groucho_grammar)
for tree in parser.parse(sent):
    treestr = str(tree)
    for n in numbers:
        treestr = treestr.replace('#NUM#', n, 1)
    print(treestr)

rawDescription: How to match integers in NLTK CFG?

description: Match integers in NLTK CFG


rawDescription: Python - "cannot perform reduce with flexible type" when trying to use numpy.mean


code:
timeit(lambda: truncate(StringIO('abc' * 1000)))
timeit(lambda: new(StringIO('abc' * 1000)))

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code:
[r[:1] + tuple(r[1].split())
 for r in re.findall(r"{% url '(\w+)'((?:\s+\w+)*) %}", inputtext)]

rawDescription: python 3.3 RE How to grab possible groups?

description: Python 3.3 RE How to grab possible groups


code: angleInDegrees = arctan(deltaY / deltaX) * 180 / PI

rawDescription: How to calculate the angle between a line and the horizontal axis?

description: Calculate the angle between a line and the horizontal axis


code: cmd="python script1.py "+i

rawDescription: Call same python script in for loop from another python script


code: 'foo\nb'

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


code: out = my_array[cond]

rawDescription: extracting specific rows of Nx3 array whereby each column satisfies condition

description: Extracting specific rows of Nx3 array whereby each column satisfies condition


code:
import unittest

class BaseDB(unittest.TestCase):
  def testFirstOperation(self):
    self.db.query("Foo")
  def testSecondOperation(self):
    self.db.query("Blah")

rawDescription: Running the same tests with different configurations


code:
A = list(itertools.ifilter(
          lambda x:sum(x)*2<=n,
          itertools.product([0, 1], repeat=n)))

rawDescription: Make all tuples with no more 1s than 0s

description: Make all tuples with no more 1s than 0s


code:
import marshal
bytes = marshal.dumps( eggs )

rawDescription: Possible to execute Python bytecode from a script?


code:
class foo:
    _instances = []

    def __init__(self, value):
        self.value = value
        foo._instances.append(self)

    def getvalues(self):
        return sum(instance.value for instance in foo._instances)

rawDescription: Python: reference to other instances of class objects


code:
with open('A.txt') as file_a:
    words = {line.strip() for line in file_a}

rawDescription: check whether a string is in a 2-GB list of strings in python

description: Check whether a string is in a 2-GB list of strings in python


code:
def search(self, search_key):
    hsh = self.hash_function(search_key)
    if self.slots[hsh] is None:
        return -1
    while hsh < self.capacity:
        if self.slots[hsh] == search_key:
            return hsh
        hsh += 1
    return -1

rawDescription: Python MyHashTable class: search method with linear probing


code:
from django.db import models

from annoying.fields import AutoOneToOneField

class UserProfile(models.Model):
    user = AutoOneToOneField('auth.user')
    follows = models.ManyToManyField('UserProfile', related_name='followed_by')

    def __unicode__(self):
        return self.user.username

rawDescription: Following users like twitter in Django, how would you do it?


code:
import csv

file_1_tuples = []

with open("file_1.csv") as fh:
    csv_reader = csv.reader ( fh )
    for row in csv_reader:
        file_1_tuples.append(  tuple(row)  )

with open("file_2.csv") as fh:
    csv_reader = csv.reader ( fh )
    for row in csv_reader:
        if tuple(row[0:3]) in file_1_tuples:
            print ( row[3:6] )

rawDescription: Compare entries in columns from CSV files and extract matched - python


code:
class MyFile():
    def __enter__(self):
        return self

    def __init__(self, path, *args):
        ''' store the path, but don't actually open the file '''
        self.path = path
        self.file_object = None
        self.args = args

    def write(self, s):
        ''' you open the file here, just before writing '''
        if not self.file_object:
            self.file_object = open(self.path, *self.args)
        self.file_object.write(self, s)

    def close(self):
        ''' close the file '''
        if self.file_object:
            self.file_object.close()

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.close()

rawDescription: Write a file to disk only when first content is written into it


code:
from collections import namedtuple
Object = namedtuple('Object', 'text ID')
objects = Object('foo', 1), Object('foo', 2), Object('bar', 4), Object('bar', 3)

rawDescription: Trying to remove duplicates from large list of objects, keep certain one


code:
from module import function
function(1)
function([2,3])

rawDescription: Changing a function implementation in Python


rawDescription: Python Simple Parse Tree Interpreter

description: Python Simple Parse Tree Interpreter


rawDescription: Share Y axis label

description: Share Y axis label


code:
line=u'abcش'
line.find(u'ش')

rawDescription: Finding the index of a UTF-8 character in a Python string


code:
import os

sc_clk_tck = os.sysconf_names['SC_CLK_TCK']
HZ = os.sysconf(sc_clk_tck)

rawDescription: Convert "jiffy" time

description: Convert "jiffy" time


code: f( modify_matrix(m1) )

rawDescription: Pythonic way to update a single element of a numpy matrix?


code:
def g():
    return 'pennyroyal tea'
f = intify(g)
f()
f.__int
g.__int

rawDescription: Why do list/dict attributes retain values outside decorators, but integer attribues do not?


code:
idx = gen.permutation(n_total)
train_idx, test_idx = idx[:n_train], idx[n_train:]

rawDescription: Cross-validation: finding row indices for a test set that aren't part of a training set


code:
@classmethod
def get_employee_count(cls):
    return cls.employeeCount

rawDescription: Class methods/instance methods in Python


code:
def parseActionThatDeletesTheParsedTokens(tokens):
    # ...
    # do something interesting with the tokens
    # ...

    # delete the contents of the parsed tokens
    del tokens[:]

rawDescription: How to discard pyparsing parseResults during parsing?

description: Discard pyparsing parseResults during parsing


code:
for i in [1, 2, 3]:
    print(i)

rawDescription: Trouble finding the 1000th prime using python


code:
item_type = context['item_type']
try:
    form_cls = ITEM_TYPE_MAP[item_type]
except KeyError:
    # invalid item_type. raise a meaningful error here
    raise
form = form_cls(request.POST)

rawDescription: How to instatiate a Django Form dynamically by string?

description: Instatiate a Django Form dynamically by string


rawDescription: How do I munge this pandas.read_csv result into the following format?

description: Munge this pandas.read_csv result into the following format


code:
class Empty(object):

    def __init__(self, **kwargs):
        object.__setattr__(self, '_obj', kwargs)

    def __getattribute__(self, name):
        obj = object.__getattribute__(self, '_obj')
        try:
            return obj[name]
        except KeyError:
            cls_name = object.__getattribute__(self, '__class__').__name__
            raise AttributeError(
                "'%(cls_name)s' object has no attribute '%(name)s'" % locals())

    def __setattr__(self, name, val):
        obj = object.__getattribute__(self, '_obj')
        obj[name] = val

    def __getitem__(self, key):
        return getattr(self, key)

    def __setitem__(self, key, val):
        return setattr(self, key, val)

rawDescription: Creating Truly Empty Types in Python

description: Creating Truly Empty Types in Python


code: weight.applymap(lambda x: d.get(x,x))

rawDescription: Replacing Names with Index From Separate File using Pandas


code: sorted(alpha_items, key=lambda x: -x[1])

rawDescription: how to sort a list of tuples with list[i][1] as key from biggest to smallest

description: Sort a list of tuples with list[i][1] as key from biggest to smallest


code:
def mod_heap_sorta(items, top_k=L):
    heap_store = items[:top_k]
    heapq.heapify(heap_store)
    remaining = itertools.islice(items, top_k, None)
    leftovers = [heapq.heappushpop(heap_store, item) for item in remaining]
    return heap_store + leftovers

rawDescription: Python performance: heaps

description: Python performance: heaps


code:
from functools import reduce
reduce(addfoo, foos, defaultdict(set))

rawDescription: using map or similar to update a dictionary when not using a class

description: Using map or similar to update a dictionary when not using a class


code:
def make_tree(self):
    # init widgets
    self.tgb = QGroupBox("[Tree Group Box Title]")
    self.main_layout.addWidget(self.tgb)

    tgb_layout = QVBoxLayout()
    self.tgb.setLayout(tgb_layout)

    view = QTreeView()
    tgb_layout.addWidget(view)

    ...

    debug_btn = QPushButton("DEBUG")
    tgb_layout.addWidget(debug_btn)

rawDescription: QTreeView not spanning parent width or height


code:
import sys
sys.path = ['../lib'] + sys.path

rawDescription: changing namespace of current python script (class with module name)

description: Changing namespace of current python script (class with module name)


code:
from random import random

class WeightedChoice(object):
    def __init__(self, weights):
        """Pick items with weighted probabilities.

            weights
                a sequence of tuples of item and it's weight.
        """
        self._total_weight = 0.
        self._item_levels = []
        for item, weight in weights:
            self._total_weight += weight
            self._item_levels.append((self._total_weight, item))

    def pick(self):
        pick = self._total_weight * random()
        for level, item in self._item_levels:
            if level >= pick:
                return item

rawDescription: How to select an item from a list with known percentages in Python

description: Select an item from a list with known percentages in Python


rawDescription: Python list traversal with gaps

description: Python list traversal with gaps


rawDescription: Cumulative addition whilst looping over a list


code:
from itertools import product
import random

class Deck(object):

    def __init__(self, ranks=None, suits=None):
        if ranks is None:
            ranks = range(2, 15)
        if suits is None:
            suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
##        self.deck = [Card(r, s) for r, s in product(ranks, suits)]
        self.deck = []
        for r in ranks:
            for s in suits:
                self.deck.append(Card(r, s))

    def deal(self, n):
        return random.sample(self.deck, n)

rawDescription: Python Simple Card Game to Learn Classes


code: [items[k:k+7] for k in range(0,105,7)]

rawDescription: Creating new lists with a consistent range of indexes from another list


code:
result = list(inner_join(listA, listB))
assert result == listC

rawDescription: How do I merge two lists of tuples based on a key?

description: Merge two lists of tuples based on a key


rawDescription: Variable creation within a program

description: Variable creation within a program


rawDescription: Using django exclude filter problem with empty m2m field


rawDescription: slicing tuples backwards - how to handle getting the first element?

description: Slicing tuples backwards - how to handle getting the first element


code: brands = {'Suzuki':['model_1', 'model_2'], 'Ferrari':['model_1', 'model_2']}

rawDescription: Good practice default values

description: Good practice default values


code: fOut.write(line.rstrip('\n') + ' | new position =' + str(newPosition))

rawDescription: Copy/write line on to another file with minor change on the line


code:
mean.shape = (mean.shape[0], 1)
A - mean

rawDescription: Remove mean from numpy matrix

description: Remove mean from numpy matrix


code:
parser.add_argument('-c', dest='action', action='store_const', const='exit')
args=parser.parse_args('-c --foo 123'.split())
if args.action=='exit':parser.print_usage()

rawDescription: Check for certain arguments and assign values to an arbitrary variable


code:
(False, False)
(False, True)
(True, False)
(True, True)

rawDescription: Creating a matrix of options using itertools


code:
import tkinter as ttk

#----------------------------------------------------------------------

def on_option_change(event):
    selected = step_type.get()

    if selected == "Kill":
        goal_label['text'] = "Required Kills"
    elif selected == "Explore":
       goal_label['text'] = "Location ID"
    elif selected == "Conversation":
       goal_label['text'] = "NPC ID"

    # show label and entry
    #goal_label.grid(column=1, row=17)
    #goal_entry.grid(column=2, row=17, sticky='E')

#----------------------------------------------------------------------

mainframe = ttk.Tk()

# Step Type

step_type = ttk.StringVar() # there is the rule: variable name lowercase with _
ttk.Label(mainframe, text="Step Type").grid(column=1, row=16)
type_entry = ttk.OptionMenu(mainframe, step_type, "Kill", "Explore" , "Conversation", command=on_option_change)
type_entry.grid(column=2, row=16, sticky='E')
step_type.set("Kill")

# Step Goal

step_goal = ttk.StringVar()
goal_label = ttk.Label(mainframe, text="Required Kills")
goal_label.grid(column=1, row=17)
goal_entry = ttk.Entry(mainframe, width=20, textvariable=step_goal)
goal_entry.grid(column=2, row=17, sticky='E')

# hide label and entry
#goal_label.grid_forget()
#goal_entry.grid_forget()

# --- star the engine ---

mainframe.mainloop()

rawDescription: Check OptionMenu selection and update GUI


rawDescription: Remove element from list without side-effect


code:
while len(numbList) < randAmount:
    numbList.append(random.randint(2,5))

rawDescription: Using a While loop to generate ints to append?


code: uuid.UUID(bytes=('81CMD_bOEeGbPwAjMtYnhg' + '==').replace('_', '/').decode('base64'))

rawDescription: Convert UUID 32-character hex string into a "YouTube-style" short id and back


code:
import urllib.request
page = 'http://bandcamp_website.com/'
# Gets HTML Code Of Page
html = urllib.request.urlopen(page).read()
# Splits the HTML into a list containing every line
html = html.split('\n')
files = []
# Iterates through the HTML line by line
for line in html:
    # Removes blank spaces at the beginning of every line
    while line.startswith(' ') or line.startswith(' '):
        line = line[-1]
    # Checks if the line has an audio tag
    if line.startswith('<audio'):
        # Splits the line remove the first part of the line [and separate link]
        line = line.split('src="')[1]
        # Gets the link into a single string
        line = line.split('"')[0]
        # Adds the link to the array containing the files to be downloaded
        files.append(line)
# Iterates through the links
for file in files:
    # Downloads file
    urllib.request.urlretrieve(file, filename='C:/directories/your_filename')

rawDescription: How to download audio from bandcamp in Python

description: Download audio from bandcamp in Python


rawDescription: Calculating mean of Pandas dataframe in iterations


code:
minutes = 135
'{:02d}:{:02d}'.format(*divmod(minutes, 60))

rawDescription: Converting minutes to HH:MM format in Python


code:
for state in states:
    score += penalty if state == bad else bonus

rawDescription: Python Ternary Style: Is this good or bad style?


rawDescription: How to prepend an element to a list in Mongoengine

description: Prepend an element to a list in Mongoengine


code:
def my_partial():
    my_function(x, y)

periodic_callback = PeriodicCallback(
    my_partial,
    10)

rawDescription: tornado PeriodicCallback: provide callback with arguments?

description: Tornado PeriodicCallback: provide callback with arguments


code: [x.strip("' ") for x in a.strip('()').split(',')]

rawDescription: using python extract string from a list of string

description: Using python extract string from a list of string


rawDescription: BS4 grabbing the contents of a tag with an unusual attribute


code: np.searchsorted(b, a, side='right') != np.searchsorted(b, a, side='left')

rawDescription: Find indices of large array if it contains values in smaller array


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

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


code:
fruits = {x.name : x for x in [Fruit('apple', 'red'), Fruit('banana', 'yellow')]}

print("An apple is %s" % fruits['apple'].color)

rawDescription: Accessing list of Python objects by object attribute


code:
data = self.cmd("r.out.gdal in=rdata out=geo{0}.tif".format(i))
self.dataOutTIF.setValue("geo{0}.tif".format(i))

rawDescription: insert variable values into a string in python

description: Insert variable values into a string in python


code: all_locs = Location.objects.all()

rawDescription: last record in django models database

description: Last record in django models database


code:
class Object(object):

    @synchronized
    def function_im_1(self):
        pass

    def function_im_2(self):
        with synchronized(self):
            pass

rawDescription: Possible to create a @synchronized decorator that's aware of a method's object?


rawDescription: Python compare list and store in new variable


code:
def get_majority(a):
    a = a.ravel()
    a = np.sort(a)
    diff = np.empty(len(a)+1, 'bool')
    diff[0] = True
    diff[-1] = True
    diff[1:-1] = a[1:] != a[:-1]
    where = np.where(diff)[0]
    counts = where[1:] - where[:-1]
    argmax = counts.argmax()
    uniq_a = a[diff[1:]]
    return uniq_a[argmax]

rawDescription: 'Tiling' a 2d array using numpy

description: 'Tiling' a 2d array using numpy


code:
db=MySQLdb.connect(
    host='mysql.server',
    user='<your_username>',
    passwd='<your_mysql_password>',
    db='<your_username>$<your_database_name>')

rawDescription: Pythonanywhere MySQL connection

description: Pythonanywhere MySQL connection


code: s.sendall("GET / HTTP/1.1\r\nHost: www.cnn.com\r\n\r\n")

rawDescription: python socket GET

description: Python socket GET


code:
from lxml import etree

xml = """<root foo="bar">
    <media:item>a</media:item>
    <abc:item>b</abc:item>
    <foo:item>c</foo:item>
    <item>d</item>
</root>"""
parser = etree.XMLParser(recover=True)
tree = etree.fromstring(xml, parser=parser)
tagname = "item"
#expression to match element undefined prefix
predicate1 = "contains(local-name(),':{0}')".format(tagname)
#expression to match element with properly defined prefix or with no prefix
predicate2 = "local-name()='{0}'".format(tagname)
elements = tree.xpath("//*[{0} or {1}]".format(predicate1, predicate2))
for e in elements:
    print(etree.tostring(e))

rawDescription: Parse xml node children list by tag with any prefix in python


code:
def reduceOutputListToPossibleMatches(outputList, detailsList):
    details = {}
    for detailsItem in detailsList:
        key = detailsItem[14]
        if key in details:
            details[key][30] = "1"
        else:
            details[key] = detailsItem

    for outputItem in outputList:
        key = outputItem[4]
        if key in details:
            yield details[key]

res = reduceOutputListToPossibleMatches(outputList, detailsList)
with open('somefile', 'w') as f:
    f.writelines(res)

rawDescription: Can Lists cope with a million items?

description: Can Lists cope with a million items


code:
with open('binary.txt',"rb",buffering=-1) as f:
    for line in f:
        for c in line:
            print(c)

rawDescription: Python: Read binary file into buffer as integer then Slice


code:
uvals[np.bincount(uind).argsort()[-4:]][::-1].tolist()

[8, 3, 2, 9]

rawDescription: get the first few items order by item's count

description: Get the first few items order by item's count


rawDescription: How to extract a floating number from a string in Python

description: Extract a floating number from a string in Python


code:
from operator import itemgetter
from functools import reduce
def compose(*functions):
    return reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
nest = compose(*[itemgetter(name) for name in reversed(lookup['customfield'])])
nest(data)

rawDescription: How to handle dictionary attributes at arbitrarily nested depths?

description: Handle dictionary attributes at arbitrarily nested depths


code: ans = eval(user_input, {'ans':ans,'sqrt':sqrt},{})

rawDescription: Using user defined variables/functions in eval [Python 3.4.2]?


code:
import random
s = {1, 2, 3, 4, 5}
random.choice(s)

rawDescription: How does Python implement random.choice() from a set?


code:
import ctypes
from ctypes import wintypes

ntdll = ctypes.WinDLL('ntdll')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

# WINAPI Definitions

PROCESS_VM_READ           = 0x0010
PROCESS_QUERY_INFORMATION = 0x0400

ERROR_INVALID_HANDLE = 0x0006
ERROR_PARTIAL_COPY   = 0x012B

PULONG = ctypes.POINTER(wintypes.ULONG)
ULONG_PTR = wintypes.LPVOID
SIZE_T = ctypes.c_size_t

def _check_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.ReadProcessMemory.errcheck = _check_bool
kernel32.ReadProcessMemory.argtypes = (
    wintypes.HANDLE,  # _In_  hProcess
    wintypes.LPCVOID, # _In_  lpBaseAddress
    wintypes.LPVOID,  # _Out_ lpBuffer
    SIZE_T,           # _In_  nSize
    ctypes.POINTER(SIZE_T))  # _Out_ lpNumberOfBytesRead

kernel32.CloseHandle.errcheck = _check_bool
kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)

kernel32.GetCurrentProcess.restype = wintypes.HANDLE
kernel32.GetCurrentProcess.argtypes = ()

kernel32.OpenProcess.errcheck = _check_bool
kernel32.OpenProcess.restype = wintypes.HANDLE
kernel32.OpenProcess.argtypes = (
   wintypes.DWORD, # _In_ dwDesiredAccess
   wintypes.BOOL,  # _In_ bInheritHandle
   wintypes.DWORD) # _In_ dwProcessId

class RemotePointer(ctypes._Pointer):
    def __getitem__(self, key):
        # TODO: slicing
        size = None
        if not isinstance(key, tuple):
            raise KeyError('must be (index, handle[, size])')
        if len(key) > 2:
            index, handle, size = key
        else:
            index, handle = key
        if isinstance(index, slice):
            raise TypeError('slicing is not supported')
        dtype = self._type_
        offset = ctypes.sizeof(dtype) * index
        address = PVOID.from_buffer(self).value + offset
        simple = issubclass(dtype, ctypes._SimpleCData)
        if simple and size is not None:
            if dtype._type_ == wintypes.WCHAR._type_:
                buf = (wintypes.WCHAR * (size // 2))()
            else:
                buf = (ctypes.c_char * size)()
        else:
            buf = dtype()
        nread = SIZE_T()
        kernel32.ReadProcessMemory(handle,
                                   address,
                                   ctypes.byref(buf),
                                   ctypes.sizeof(buf),
                                   ctypes.byref(nread))
        if simple:
            return buf.value
        return buf

    def __setitem__(self, key, value):
        # TODO: kernel32.WriteProcessMemory
        raise TypeError('remote pointers are read only')

    @property
    def contents(self):
        # a handle is required
        raise NotImplementedError

_remote_pointer_cache = {}
def RPOINTER(dtype):
    if dtype in _remote_pointer_cache:
        return _remote_pointer_cache[dtype]
    name = 'RP_%s' % dtype.__name__
    ptype = type(name, (RemotePointer,), {'_type_': dtype})
    _remote_pointer_cache[dtype] = ptype
    return ptype

# NTAPI Definitions

NTSTATUS = wintypes.LONG
PVOID = wintypes.LPVOID
RPWSTR = RPOINTER(wintypes.WCHAR)
PROCESSINFOCLASS = wintypes.ULONG

ProcessBasicInformation   = 0
ProcessDebugPort          = 7
ProcessWow64Information   = 26
ProcessImageFileName      = 27
ProcessBreakOnTermination = 29

STATUS_UNSUCCESSFUL         = NTSTATUS(0xC0000001)
STATUS_INFO_LENGTH_MISMATCH = NTSTATUS(0xC0000004).value
STATUS_INVALID_HANDLE       = NTSTATUS(0xC0000008).value
STATUS_OBJECT_TYPE_MISMATCH = NTSTATUS(0xC0000024).value

class UNICODE_STRING(ctypes.Structure):
    _fields_ = (('Length',        wintypes.USHORT),
                ('MaximumLength', wintypes.USHORT),
                ('Buffer',        RPWSTR))

class LIST_ENTRY(ctypes.Structure):
    pass

RPLIST_ENTRY = RPOINTER(LIST_ENTRY)

LIST_ENTRY._fields_ = (('Flink', RPLIST_ENTRY),
                       ('Blink', RPLIST_ENTRY))

class LDR_DATA_TABLE_ENTRY(ctypes.Structure):
    _fields_ = (('Reserved1',          PVOID * 2),
                ('InMemoryOrderLinks', LIST_ENTRY),
                ('Reserved2',          PVOID * 2),
                ('DllBase',            PVOID),
                ('EntryPoint',         PVOID),
                ('Reserved3',          PVOID),
                ('FullDllName',        UNICODE_STRING),
                ('Reserved4',          wintypes.BYTE * 8),
                ('Reserved5',          PVOID * 3),
                ('CheckSum',           PVOID),
                ('TimeDateStamp',      wintypes.ULONG))

RPLDR_DATA_TABLE_ENTRY = RPOINTER(LDR_DATA_TABLE_ENTRY)

class PEB_LDR_DATA(ctypes.Structure):
    _fields_ = (('Reserved1',               wintypes.BYTE * 8),
                ('Reserved2',               PVOID * 3),
                ('InMemoryOrderModuleList', LIST_ENTRY))

RPPEB_LDR_DATA = RPOINTER(PEB_LDR_DATA)

class RTL_USER_PROCESS_PARAMETERS(ctypes.Structure):
    _fields_ = (('Reserved1',     wintypes.BYTE * 16),
                ('Reserved2',     PVOID * 10),
                ('ImagePathName', UNICODE_STRING),
                ('CommandLine',   UNICODE_STRING))

RPRTL_USER_PROCESS_PARAMETERS = RPOINTER(RTL_USER_PROCESS_PARAMETERS)
PPS_POST_PROCESS_INIT_ROUTINE = PVOID

class PEB(ctypes.Structure):
    _fields_ = (('Reserved1',              wintypes.BYTE * 2),
                ('BeingDebugged',          wintypes.BYTE),
                ('Reserved2',              wintypes.BYTE * 1),
                ('Reserved3',              PVOID * 2),
                ('Ldr',                    RPPEB_LDR_DATA),
                ('ProcessParameters',      RPRTL_USER_PROCESS_PARAMETERS),
                ('Reserved4',              wintypes.BYTE * 104),
                ('Reserved5',              PVOID * 52),
                ('PostProcessInitRoutine', PPS_POST_PROCESS_INIT_ROUTINE),
                ('Reserved6',              wintypes.BYTE * 128),
                ('Reserved7',              PVOID * 1),
                ('SessionId',              wintypes.ULONG))

RPPEB = RPOINTER(PEB)

class PROCESS_BASIC_INFORMATION(ctypes.Structure):
    _fields_ = (('Reserved1',       PVOID),
                ('PebBaseAddress',  RPPEB),
                ('Reserved2',       PVOID * 2),
                ('UniqueProcessId', ULONG_PTR),
                ('Reserved3',       PVOID))

def NtError(status):
    import sys
    descr = 'NTSTATUS(%#08x) ' % (status % 2**32,)
    if status & 0xC0000000 == 0xC0000000:
        descr += '[Error]'
    elif status & 0x80000000 == 0x80000000:
        descr += '[Warning]'
    elif status & 0x40000000 == 0x40000000:
        descr += '[Information]'
    else:
        descr += '[Success]'
    if sys.version_info[:2] < (3, 3):
        return WindowsError(status, descr)
    return OSError(None, descr, None, status)

NtQueryInformationProcess = ntdll.NtQueryInformationProcess
NtQueryInformationProcess.restype = NTSTATUS
NtQueryInformationProcess.argtypes = (
    wintypes.HANDLE,  # _In_      ProcessHandle
    PROCESSINFOCLASS, # _In_      ProcessInformationClass
    PVOID,            # _Out_     ProcessInformation
    wintypes.ULONG,   # _In_      ProcessInformationLength
    PULONG)           # _Out_opt_ ReturnLength

class ProcessInformation(object):
    _close_handle = False
    _closed = False
    _module_names = None

    def __init__(self, process_id=None, handle=None):
        if process_id is None and handle is None:
            handle = kernel32.GetCurrentProcess()
        elif handle is None:
            handle = kernel32.OpenProcess(PROCESS_VM_READ |
                                          PROCESS_QUERY_INFORMATION,
                                          False, process_id)
            self._close_handle = True
        self._handle = handle
        self._query_info()
        if process_id is not None and self._process_id != process_id:
            raise NtError(STATUS_UNSUCCESSFUL)

    def __del__(self, CloseHandle=kernel32.CloseHandle):
        if self._close_handle and not self._closed:
            try:
                CloseHandle(self._handle)
            except WindowsError as e:
                if e.winerror != ERROR_INVALID_HANDLE:
                    raise
            self._closed = True

    def _query_info(self):
        info = PROCESS_BASIC_INFORMATION()
        handle = self._handle
        status = NtQueryInformationProcess(handle,
                                           ProcessBasicInformation,
                                           ctypes.byref(info),
                                           ctypes.sizeof(info),
                                           None)
        if status < 0:
            raise NtError(status)
        self._process_id = info.UniqueProcessId
        self._peb = peb = info.PebBaseAddress[0, handle]
        self._params = peb.ProcessParameters[0, handle]
        self._ldr = peb.Ldr[0, handle]

    def _modules_iter(self):
        headaddr = (PVOID.from_buffer(self._peb.Ldr).value +
                    PEB_LDR_DATA.InMemoryOrderModuleList.offset)
        offset = LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks.offset
        pentry = self._ldr.InMemoryOrderModuleList.Flink
        while pentry:
            pentry_void = PVOID.from_buffer_copy(pentry)
            if pentry_void.value == headaddr:
                break
            pentry_void.value -= offset
            pmod = RPLDR_DATA_TABLE_ENTRY.from_buffer(pentry_void)
            mod = pmod[0, self._handle]
            yield mod
            pentry = LIST_ENTRY.from_buffer(mod, offset).Flink

    def update_module_names(self):
        names = []
        for m in self._modules_iter():
            ustr = m.FullDllName
            name = ustr.Buffer[0, self._handle, ustr.Length]
            names.append(name)
        self._module_names = names

    @property
    def module_names(self):
        if self._module_names is None:
            self.update_module_names()
        return self._module_names

    @property
    def process_id(self):
        return self._process_id

    @property
    def session_id(self):
        return self._peb.SessionId

    @property
    def image_path(self):
        ustr = self._params.ImagePathName
        return ustr.Buffer[0, self._handle, ustr.Length]

    @property
    def command_line(self):
        ustr = self._params.CommandLine
        buf = ustr.Buffer[0, self._handle, ustr.Length]
        return buf

rawDescription: How to access the PEB of another process with python ctypes

description: Access the PEB of another process with python ctypes


code:
content = []
for feed in YahooContent.entries:
    content.append(feed.title + ": " + "\n" + feed.link + "\n" + feed.published)

return HttpResponse('\n'.join(content))

rawDescription: Displaying view function in Django

description: Displaying view function in Django


code: return render(request, 'analyzer/resultsfinal.html', {'results': results})

rawDescription: Getting count of elements sent to html in Django