code:
import uuid
uuid.uuid4().int & (1<<64)-1
uuid.uuid4().int & (1<<64)-1

rawDescription: How to generate unique 64 bits integers from Python?

description: Generate unique 64 bits integers from Python


code:
def check(string):
    m = p.match(string)
    if m:
        lower, upper = m.groups()
        if upper in ("*", "-1"):
            return True
        else:
            return int(lower) <= int(upper)
    else:
        return False

rawDescription: Pattern for multiplicity in python

description: Pattern for multiplicity in python


code:
df2 = df.pivot_table(index='week', columns='year', values='value')
df2['max'] = df2.max(axis=1)
df2['min'] = df2.min(axis=1)

rawDescription: Issue with merging time series variables to create new DataFrame with arbitrary index


code:
instance_groups = []
instance_groups.append(InstanceGroup(
    num_instances=1,
    role="MASTER",
    type="m1.small",
    market="ON_DEMAND",
    name="Main node"))
instance_groups.append(InstanceGroup(
    num_instances=2,
    role="CORE",
    type="m1.small",
    market="ON_DEMAND",
    name="Worker nodes"))
instance_groups.append(InstanceGroup(
    num_instances=2,
    role="TASK",
    type="m1.small",
    market="SPOT",
    name="My cheap spot nodes",
    bidprice="0.002"))

rawDescription: How to launch and configure an EMR cluster using boto

description: Launch and configure an EMR cluster using boto


rawDescription: Any better algorithm possible here?

description: Any better algorithm possible here


code:
import numpy
from StringIO import StringIO

a = StringIO("""family\tid\tmum\tdad\trs1\trs2\trs3\trs4\trs5\trs6\trs7\trs8\trs9\trs10\trs11\trs12
1\t1\t4\t6\tA T\tA A\tT T\tC C\tG G\tA T\tA G\tA A\tG A\tT A\tG G\tC C
2\t2\t7\t9\tT A\tG A\tC T\tC T\tG A\tT T\tA A\tA C\tG G\tT A\tC C\tC T
3\t3\t2\t8\tT T\tG G\tC T\tC T\tG G\tA T\tA G\tA C\tG G\tT T\tC C\tC C
4\t4\t5\t1\tA A\tA A\tT T\tC C\tG A\tT T\tA A\tA A\tG A\tT A\tG C\tC T""")

dt = 'int,int,int,int,S3,S3,S3,S3,S3,S3,S3,S3,S3,S3,S3,S3'
A = numpy.genfromtxt(a, delimiter='\t', names=True, dtype=dt)

rawDescription: Numpy: order array as other array - by string order


code:
import time
from datetime import timedelta

def get_seconds(item):
    try:
        x = time.strptime(item, '%H hrs %M min %S sec')
    except ValueError:
        try:
            x = time.strptime(item, '%M min %S sec')
        except ValueError:
            x = time.strptime(item, '%S sec')
    return timedelta(hours=x.tm_hour, minutes=x.tm_min, seconds=x.tm_sec).total_seconds()

l = [
    "2 hrs 5 min 15 sec",
    "8 min 4 sec",
    "2 sec"
]

for item in l:
    print(get_seconds(item))

rawDescription: Python: change "- hrs - min - sec' string into minutes decimal


code:
user_links_count = Link.objects.filter(user=request.user).count()
render(request, "addurl.html", {'form': form, linkscount: user_links_count})

rawDescription: Django 1.6: How to print the number of objects a user uploaded?


rawDescription: Sorting list of tuples by first element of each tuple - Python 2.7


rawDescription: Combining 2-d arrays to form a 3-d array


code: {'key': key, 'value': value.values()}

rawDescription: Get data from dict by using for-loop in Python


code:
import Queue
sentinel = object()
root = tkinter.Tk()

...
def run(self, url):
    outqueue = Queue.Queue()
    thr = threading.Thread(target=self.run_tests, args=(url, outqueue))
    thr.start()
    root.after(250, self.update, outqueue)

rawDescription: Run thread from Tkinter and wait until it's finished


code:
class PostIcon(models.Model):
    post = models.ForeignKey(Post)
    icon = models.ForeignKey(Icon)
    count =  models.IntegerField()

rawDescription: Way to allow for duplicate many-to-many entries in Python/Django


code:
def main():
    root = tk.Tk()
    app = Application(master=root)
    Work_Module.progress_bar = progress_bar
    app.mainloop()

rawDescription: Tkinter: Update widget from different module


code:
def c(df):
    return df.groupby('id').apply(lambda x: pd.Series(dict(new_col1=(x['foo'].notnull()).sum(),new_col2=np.in1d(x['bar'],'P').sum(),new_col3=np.in1d(x['bar'],'C').sum(),new_col4=(np.in1d(x['Status'],['Approved, not yet paid']) & np.in1d(x['Current_Status'],['Approved, paid'])).sum(),new_col5=(np.in1d(x['Status'],['Approved, not yet paid']) & np.in1d(x['Current_Status'],['Approved, not yet paid'])).sum(),new_col6=(np.in1d(x['Status'],['Approved, paid']) & np.in1d(x['Current_Status'],['Approved, paid'])).sum(),)))

def d(df):
    return df.groupby('id').apply(lambda x: pd.Series(dict(new_col1=(x['foo'] != np.nan).sum(),new_col2=(x['bar'] == 'P').sum(),new_col3=(x['bar'] == 'C').sum(),new_col4=((x['Status']=='Approved, not yet paid') & (x['Current_Status']=='Approved, paid')).sum(),new_col5=((x['Status']=='Approved, not yet paid') & (x['Current_Status']=='Approved, not yet paid')).sum(),new_col6=((x['Status']=='Approved, paid') & (x['Current_Status']=='Approved, paid')).sum())))

rawDescription: Pandas, long processing time of groupby and comparisons


code:
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_http_methods

from datetime import datetime

@require_http_methods(['POST'])
def textbook(request):
    uisbn = request.POST.get('uisbn')
    # I'm assuming all of this is correct
    ltextbook = get_object_or_404(Textbook, isbn=uisbn)
    if ltextbook:
        text = ltextbook[0]
        wishlists = Wishlist.objects.filter(textbook=text)
        listings = Posting.objects.filter(textbook=text)
        new = Wishlist(textbook=text, user=request.user, wish_date=datetime.now())
        new.save()
        new_created = True
    else:
        new_created = False

    data = {
        'new_created': new_created
    }
    return JsonResponse(data)

rawDescription: Django post on click with jquery not getting a response


code:
env = Environment()

# h:
x = env.Program("hello1", "hello1.c")
y = env.Program("hello2", "hello2.c")
env.Alias("h", [x,y])
# equivalently: env.alias("h", ["hello1", "hello2"])

# h3
y = env.Program("hello3", "hello3.c")
env.Alias("h3", y)

Default(None)

rawDescription: Dividing SConstruct code into set of aliases; no code called by default


code: real_fun = getattr(generator, 'getCmd')

rawDescription: How to get data from SNMP with python?

description: Get data from SNMP with python


code:
# Create a value-to-symbol table.
VA2SY = dict(map(reversed, SY2VA.items()))

# Take a integer and base to convert to.
# Create an array to store the digits in.
# While the integer is not zero:
#     Divide the integer by the base to:
#         (1) Find the "last" digit in your number (value).
#         (2) Store remaining number not "chopped" (integer).
#     Save the digit in your storage array.
# Return your joined digits after putting them in the right order.

def int2str(integer, base):
    array = []
    while integer:
        integer, value = divmod(integer, base)
        array.append(VA2SY[value])
    return ''.join(reversed(array))

rawDescription: Python - Homework - Converting Any Base to Any Base


code:
data = ['xyz-1.23.35.10.2.rpm', 'xyz-linux-version-90-12-13-689.tar.gz', 'xyz-xyz-xyz-13.23.789.0-xyz-xyz.rpm']

versions = [version_from(filename) for filename in data]

rawDescription: extract a pattern from different string in Python

description: Extract a pattern from different string in Python


rawDescription: Copy a layer from an image to another

description: Copy a layer from an image to another


rawDescription: grouping dictionary with list values

description: Grouping dictionary with list values


code:
import random
import string

size = 100000
seq = [random.choice(string.ascii_letters) for x in range(size)]

rawDescription: Implementing the Alon-Matias-Szegedy Algorithm For The Second Moment Stream Approximation


code: divergence = sum(sum(V * np.log(V/WH) - V + WH)) # equation (3)

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code:
http = Httplib2Transport()
client = Client(url,transport=http)

rawDescription: Set useragent on Client __init__ (Python suds)


rawDescription: Remove string quotes from array in Python


code:
def ndm(*args):
    return [x[(None,)*i+(slice(None),)+(None,)*(len(args)-i-1)] for i, x in enumerate(args)]

x2,y2,z2  = ndm(xaxis,yaxis,zaxis)
result3 = func2(x2,y2,z2)

rawDescription: numpy - evaluate function on a grid of points

description: Numpy - evaluate function on a grid of points


code:
def __init__(self, initial_balance):
        """Creates an account with the given balance."""
        self.money = initial_balance
        self.penalty = 0

rawDescription: Bank account Classes. How to make it more powerful/efficient? (OOP)


code:
class Product(models.Model):
    price = models.FloatField()
    description = models.TextField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    details = generic.GenericForeignKey('content_type', 'object_id')

class Jacket(models.Model):
    size = models.PositiveIntegerField()
    color = models.CharField(max_length=25)

rawDescription: How to write dynamic Django models?

description: Write dynamic Django models


code:
r = requests.head('http://resus.org.au/?wpfb_dl=17')
pprint(dict(r.headers))
r = requests.head('http://www.mndaust.asn.au/Documents/Information-resources/MND-Aspects-of-care-for-the-primary-health-care-te.aspx')
pprint(dict(r.headers))

rawDescription: How to test if a link target is a pdf file if the link does not contain .pdf

description: Test if a link target is a pdf file if the link does not contain .pdf


rawDescription: Explain the code function in call by object


code:
files = [
    ('up', ('aa.png', open('aa.png', 'rb'), 'image/png')),
    ('exp', (None, 'python', None)),
    ('ptext', (None, 'text', None)),
    ('board', (None, 'Pictures', None)),
]

r = requests.post(url, files=files, cookies=cookie)

rawDescription: How to arrange the order of data and file using requests to post multipart/form-data?

description: Arrange the order of data and file using requests to post multipart/form-data


code:
# Split matrix and add last row.
sub_matrix = MATRIX[:(n / 2)] + [tail]

rawDescription: Numbers in a Matrix

description: Numbers in a Matrix


code:
my_tuple = ([],[])
for x in a_list:
   my_tuple[isinstance(x,basestring)].append(x)

rawDescription: How to divide a tuple into two in pythonic way

description: Divide a tuple into two in pythonic way


code: filename = message.split()[1]

rawDescription: Take data from socket connection and split it


rawDescription: How to convert a nested list into a one-dimensional list in Python?

description: Convert a nested list into a one-dimensional list in Python


code:
if req.method == 'GET':
    # Handle the request
    if reg.args.get('name'):
        name = req.args['name']
        self.log.debug('Got request for name=%s' % name)

rawDescription: Trac plugin with support for HTTP get parameters


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(source)
allTags = soup.findAll(True)
[tag.name for tag in allTags ]
[u'em', u'label']

rawDescription: Match HTML tags in two strings using regex in Python


code:
test = True
a = 23
b = 42
a,b = (1,b) if test else (a,1)
print (a,b)

rawDescription: Switch between assignments to different variables in python? With ternary operator?


code: numLetters = len(string)

rawDescription: Count letters in string python

description: Count letters in string python


code:
thelist = [[elem.strip(" '") for elem in line.split(',')]
           for line in open('file.txt', 'r')]

rawDescription: Strip outside quotes from text when writing to list in Python


rawDescription: If I have got content of line 2 I want to get content of line 9. How to do?


code:
http_user = 'DOMAIN\\USER'
http_pass = 'PASS'

rawDescription: NTLM authentication with Scrapy for web scraping


rawDescription: Transform string into dictionary (with additional constraints)


code: self.insert(key, root=tmp.left)

rawDescription: Python recursion and return statements

description: Python recursion and return statements


rawDescription: Remove final slash and number in a string in Python


code:
#!/bin/sh
#
# This should normally be placed in the ${SITE_ROOT}/.env
#
# DEPLOYMENT DO NOT MODIFY THESE..
SECRET_KEY='XXXSECRETKEY'

rawDescription: Pycharm: set environment variable for run manage.py Task


code:
strange_sort("1 2 3".split())
strange_sort("1 2 10 3".split())
strange_sort("1 2 10 3 bear".split())
strange_sort("2 1 bear 10 3".split())
strange_sort("2 1 zebra 10 3 bear".split())
strange_sort("20 zebra 12 bear".split())
strange_sort("20 zebra 12 bear 3".split())

rawDescription: How to sort and keep the integrity of the list?

description: Sort and keep the integrity of the list


code:
user_input = raw_input().split() # tokenize
fname, *args = user_input #This use of *args syntax is not available prior to Py3
if hasattr(shell, fname):
    func = getattr(shell, fname)
    result = func(*args) #The *args syntax here is available back to at least 2.6
else:
    print('That function is not defined.')

rawDescription: exposing the inner methods of a class, and using them

description: Exposing the inner methods of a class, and using them


code:
buf = StringIO.StringIO(x)
for line in buf:
            if line is not None:
                    timm = re.search('time>(.*?)</time', line, re.S)
                    if timm is not None:
                            kmlTrack += ("          <when>"+ timm.group(1)+"</when>\n")
                            checkSumA =+ 1
buf = StringIO.StringIO(x)
for line in buf:
            if line is not None:
                    lat = re.search('lat="(.*?)" lo', line, re.S)
                    lon = re.search('lon="(.*?)"><ele>', line, re.S)
                    ele = re.search('<ele>(.*?)</ele>', line, re.S)
                    if lat is not None:
                            kmlTrack += ("          <gx:coord>"+ lon.group(1) + " " + lat.group(1) + " " + ele.group(1) + "</gx:coord>\n")
                            checkSumB =+ 1
if checkSumA == checkSumB:
            #put a footer on
            kmlTrack += """     </gx:Track></Placemark></Document></kml>"""
else:
            print ("checksum error")
            return None

with open("Realbush2.kml", "a") as myfile:
            myfile.write(kmlTrack)
return ("succsesful .kml file-write completed in :" + str(c.seconds) + " seconds.")

rawDescription: successively take values between two sub-strings and temporarily store it before writing them in a different order withhin a python fileread

description: Successively take values between two sub-strings and temporarily store it before writing them in a different order withhin a python fileread


code: pd.concat(next_n_asof(df1.A, t, 4) for t in df2.index)

rawDescription: How can I slice a timeseries dataframe in Pandas based on multiple conditions?

description: Slice a timeseries dataframe in Pandas based on multiple conditions


code:
soup = BeautifulSoup(html, 'lxml')

all_links = []
links = soup.find_all('a', {'class': ['btn', 'btn-gray']})
for link in links:
    if 'More Info' in link.text:
        all_links.append(link['href'])  # Save href only, for example.

rawDescription: Beautiful soup - capture all links with a certain class or text


code: MyModalView(background_color=(0, 0, 0, 0))

rawDescription: Kivy Disable background fading on popup open


code:
import configparser

config = configparser.ConfigParser()
config._interpolation = configparser.ExtendedInterpolation()
config.read(encoding='utf-8', filenames=['path to file/config.ini'])

smtp = config['SMTP.CONFIG']
db = config['DB.CONFIG']
mail = config['APP.CONFIG']

rawDescription: How to add your app specific settings in pyramid rest framework?

description: Add your app specific settings in pyramid rest framework


code:
def PrintFrom(c,s):
    count = 0
    for item in s:
        if item == c:
           count +=1
        if count > 0: # indented to be inside of for-loop
           print (item)

rawDescription: Python - Print all items in a string from first instance of item onwards


code: objects = C.objects.get(user=user)

rawDescription: Generic object "ownership" in Django

description: Generic object "ownership" in Django


rawDescription: Python - How can I change bytes in a file


code:
def dictfetchall(cursor):
    """Returns all rows from a cursor as a list of dicts"""
    desc = cursor.description
    return [dict(itertools.izip([col[0] for col in desc], row))
            for row in cursor.fetchall()]

rawDescription: how to get all mysql tuple result and convert to json

description: Get all mysql tuple result and convert to json


code:
from datetime import datetime
from pytz import timezone, utc

_utc = utc
dte = "2002-08-22T10:00:00Z"
utc = datetime.strptime(dte, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_utc)
coun_to_tz = {'Europe/Helsinki': 'Finland', 'Asia/Thimphu': 'Bhutan', 'Australia/Currie': 'Australia', 'Pacific/Niue': 'Niue', 'Asia/Dili': 'Timor-Leste', 'Europe/Kiev': 'Ukraine', 'Indian/Mahe': 'Seychelles', 'Asia/Kathmandu': 'Nepal', 'Asia/Aden': 'Yemen', 'Europe/Malta': 'Malta', 'Pacific/Noumea': 'New Caledonia', 'America/Bahia_Banderas': 'Mexico', 'Africa/Ceuta': 'Spain', 'Europe/Uzhgorod': 'Ukraine', 'Asia/Hebron': 'Palestine, State of', 'America/Indiana/Knox': 'United States', 'Europe/Kaliningrad': 'Russian Federation', 'America/Chicago': 'United States', 'Asia/Amman': 'Jordan', 'Europe/Isle_of_Man': 'Isle of Man', 'America/Guadeloupe': 'Guadeloupe', 'Europe/Copenhagen': 'Denmark', 'Indian/Maldives': 'Maldives', 'Pacific/Bougainville': 'Papua New Guinea', 'Africa/Banjul': 'Gambia', 'America/Cuiaba': 'Brazil', 'Pacific/Wake': 'United States Minor Outlying Islands', 'Antarctica/Mawson': 'Antarctica', 'America/Noronha': 'Brazil', 'America/Indiana/Tell_City': 'United States', 'America/Inuvik': 'Canada', 'Africa/Niamey': 'Niger', 'Africa/Juba': 'South Sudan', 'Atlantic/Reykjavik': 'Iceland', 'America/Curacao': 'Curaçao', 'Africa/Porto-Novo': 'Benin', 'Africa/Brazzaville': 'Congo', 'Atlantic/South_Georgia': 'South Georgia and the South Sandwich Islands', 'Asia/Baku': 'Azerbaijan', 'America/Detroit': 'United States', 'America/Monterrey': 'Mexico', 'America/Grenada': 'Grenada', 'Australia/Perth': 'Australia', 'Asia/Magadan': 'Russian Federation', 'Pacific/Fiji': 'Fiji', 'Pacific/Honolulu': 'United States', 'America/Thule': 'Greenland', 'America/Guyana': 'Guyana', 'America/Grand_Turk': 'Turks and Caicos Islands', 'America/Indiana/Petersburg': 'United States', 'Antarctica/Rothera': 'Antarctica', 'Europe/Vatican': 'Holy See (Vatican City State)', 'America/Cambridge_Bay': 'Canada', 'America/Marigot': 'Saint Martin (French part)', 'Africa/Sao_Tome': 'Sao Tome and Principe', 'Pacific/Palau': 'Palau', 'Asia/Gaza': 'Palestine, State of', 'America/Tortola': 'Virgin Islands, British', 'Asia/Yakutsk': 'Russian Federation', 'America/Argentina/Catamarca': 'Argentina', 'Pacific/Norfolk': 'Norfolk Island', 'America/Paramaribo': 'Suriname', 'Asia/Aqtobe': 'Kazakhstan', 'America/Anguilla': 'Anguilla', 'Africa/Douala': 'Cameroon', 'Asia/Chita': 'Russian Federation', 'Asia/Riyadh': 'Saudi Arabia', 'Africa/Mbabane': 'Swaziland', 'America/Argentina/San_Juan': 'Argentina', 'Europe/London': 'United Kingdom', 'Australia/Brisbane': 'Australia', 'Asia/Urumqi': 'China', 'America/Asuncion': 'Paraguay', 'America/Regina': 'Canada', 'Asia/Qyzylorda': 'Kazakhstan', 'Africa/Kigali': 'Rwanda', 'Africa/Dakar': 'Senegal', 'Asia/Jerusalem': 'Israel', 'Asia/Ashgabat': 'Turkmenistan', 'Asia/Kuala_Lumpur': 'Malaysia', 'Africa/Maputo': 'Mozambique', 'America/Glace_Bay': 'Canada', 'Africa/Malabo': 'Equatorial Guinea', 'Europe/Jersey': 'Jersey', 'America/Rankin_Inlet': 'Canada', 'America/Fortaleza': 'Brazil', 'Europe/Luxembourg': 'Luxembourg', 'Asia/Taipei': 'Taiwan, Province of China', 'Europe/Bratislava': 'Slovakia', 'Asia/Pontianak': 'Indonesia', 'Pacific/Chuuk': 'Micronesia, Federated States of', 'Indian/Chagos': 'British Indian Ocean Territory', 'America/Cayman': 'Cayman Islands', 'Atlantic/Madeira': 'Portugal', 'Africa/El_Aaiun': 'Western Sahara', 'America/Indiana/Winamac': 'United States', 'America/St_Kitts': 'Saint Kitts and Nevis', 'Asia/Tbilisi': 'Georgia', 'America/Yellowknife': 'Canada', 'Atlantic/St_Helena': 'Saint Helena, Ascension and Tristan da Cunha', 'Asia/Novokuznetsk': 'Russian Federation', 'Africa/Libreville': 'Gabon', 'Europe/Brussels': 'Belgium', 'America/Guatemala': 'Guatemala', 'Europe/Simferopol': 'Russian Federation', 'Europe/Vaduz': 'Liechtenstein', 'Africa/Harare': 'Zimbabwe', 'America/Goose_Bay': 'Canada', 'America/Indiana/Indianapolis': 'United States', 'Africa/Cairo': 'Egypt', 'Asia/Bishkek': 'Kyrgyzstan', 'Asia/Sakhalin': 'Russian Federation', 'Asia/Nicosia': 'Cyprus', 'America/St_Thomas': 'Virgin Islands, U.S.', 'Europe/Sarajevo': 'Bosnia and Herzegovina', 'Pacific/Johnston': 'United States Minor Outlying Islands', 'Atlantic/Cape_Verde': 'Cape Verde', 'America/Tegucigalpa': 'Honduras', 'Australia/Eucla': 'Australia', 'Pacific/Tahiti': 'French Polynesia', 'Africa/Tripoli': 'Libya', 'Australia/Sydney': 'Australia', 'America/Kentucky/Monticello': 'United States', 'Antarctica/Palmer': 'Antarctica', 'Asia/Tokyo': 'Japan', 'Asia/Baghdad': 'Iraq', 'America/Dawson_Creek': 'Canada', 'America/Bogota': 'Colombia', 'Pacific/Chatham': 'New Zealand', 'America/Scoresbysund': 'Greenland', 'Pacific/Pitcairn': 'Pitcairn', 'Europe/Madrid': 'Spain', 'America/Ojinaga': 'Mexico', 'America/Campo_Grande': 'Brazil', 'America/Lima': 'Peru', 'America/Metlakatla': 'United States', 'America/Boise': 'United States', 'Atlantic/Bermuda': 'Bermuda', 'America/Kralendijk': 'Bonaire, Sint Eustatius and Saba', 'America/Edmonton': 'Canada', 'Asia/Kabul': 'Afghanistan', 'America/Maceio': 'Brazil', 'Europe/Stockholm': 'Sweden', 'Asia/Oral': 'Kazakhstan', 'Pacific/Efate': 'Vanuatu', 'Europe/Athens': 'Greece', 'Europe/Rome': 'Italy', 'America/St_Lucia': 'Saint Lucia', 'Africa/Addis_Ababa': 'Ethiopia', 'Asia/Aqtau': 'Kazakhstan', 'America/Indiana/Marengo': 'United States', 'America/Port_of_Spain': 'Trinidad and Tobago', 'Africa/Lubumbashi': 'Congo, the Democratic Republic of the', 'America/Moncton': 'Canada', 'Africa/Bangui': 'Central African Republic', 'Asia/Samarkand': 'Uzbekistan', 'America/Cayenne': 'French Guiana', 'Europe/Zurich': 'Switzerland', 'America/Adak': 'United States', 'America/Argentina/San_Luis': 'Argentina', 'America/Mexico_City': 'Mexico', 'Australia/Lindeman': 'Australia', 'Pacific/Funafuti': 'Tuvalu', 'Asia/Jayapura': 'Indonesia', 'Pacific/Saipan': 'Northern Mariana Islands', 'America/Santo_Domingo': 'Dominican Republic', 'Africa/Freetown': 'Sierra Leone', 'America/Aruba': 'Aruba', 'Asia/Yekaterinburg': 'Russian Federation', 'Europe/Ljubljana': 'Slovenia', 'America/Iqaluit': 'Canada', 'America/Caracas': 'Venezuela, Bolivarian Republic of', 'Europe/Zaporozhye': 'Ukraine', 'Indian/Christmas': 'Christmas Island', 'Asia/Krasnoyarsk': 'Russian Federation', 'America/Los_Angeles': 'United States', 'America/St_Vincent': 'Saint Vincent and the Grenadines', 'Europe/Prague': 'Czech Republic', 'Africa/Monrovia': 'Liberia', 'Africa/Gaborone': 'Botswana', 'America/Cancun': 'Mexico', 'Pacific/Wallis': 'Wallis and Futuna', 'Asia/Qatar': 'Qatar', 'Asia/Bahrain': 'Bahrain', 'America/Boa_Vista': 'Brazil', 'America/Santa_Isabel': 'Mexico', 'Antarctica/Macquarie': 'Australia', 'America/Eirunepe': 'Brazil', 'America/Guayaquil': 'Ecuador', 'Africa/Accra': 'Ghana', 'America/Matamoros': 'Mexico', 'Africa/Conakry': 'Guinea', 'America/Araguaina': 'Brazil', 'Pacific/Gambier': 'French Polynesia', 'America/Puerto_Rico': 'Puerto Rico', 'America/Halifax': 'Canada', 'Asia/Pyongyang': "Korea, Democratic People's Republic of", 'America/Miquelon': 'Saint Pierre and Miquelon', 'Africa/Maseru': 'Lesotho', 'America/Thunder_Bay': 'Canada', 'Europe/Dublin': 'Ireland', 'Europe/Moscow': 'Russian Federation', 'Pacific/Pago_Pago': 'American Samoa', 'America/New_York': 'United States', 'Africa/Kampala': 'Uganda', 'Africa/Mogadishu': 'Somalia', 'Africa/Blantyre': 'Malawi', 'America/Argentina/Mendoza': 'Argentina', 'Europe/Sofia': 'Bulgaria', 'America/Nome': 'United States', 'Indian/Mayotte': 'Mayotte', 'Europe/Warsaw': 'Poland', 'Asia/Almaty': 'Kazakhstan', 'Pacific/Apia': 'Samoa', 'America/Kentucky/Louisville': 'United States', 'America/Winnipeg': 'Canada', 'America/Nipigon': 'Canada', 'Pacific/Nauru': 'Nauru', 'Asia/Seoul': 'Korea, Republic of', 'America/Menominee': 'United States', 'America/Argentina/Cordoba': 'Argentina', 'America/Rainy_River': 'Canada', 'Pacific/Majuro': 'Marshall Islands', 'America/Porto_Velho': 'Brazil', 'Asia/Vientiane': "Lao People's Democratic Republic", 'Europe/Guernsey': 'Guernsey', 'America/North_Dakota/Center': 'United States', 'Africa/Lusaka': 'Zambia', 'Pacific/Kwajalein': 'Marshall Islands', 'America/Port-au-Prince': 'Haiti', 'Europe/Vilnius': 'Lithuania', 'Europe/Vienna': 'Austria', 'Asia/Manila': 'Philippines', 'Africa/Djibouti': 'Djibouti', 'Asia/Jakarta': 'Indonesia', 'Africa/Windhoek': 'Namibia', 'Asia/Macau': 'Macao', 'Africa/Kinshasa': 'Congo, the Democratic Republic of the', 'America/Swift_Current': 'Canada', 'Africa/Lome': 'Togo', 'Asia/Vladivostok': 'Russian Federation', 'America/Belize': 'Belize', 'Europe/Amsterdam': 'Netherlands', 'Africa/Nouakchott': 'Mauritania', 'Asia/Singapore': 'Singapore', 'Europe/Riga': 'Latvia', 'Europe/Berlin': 'Germany', 'Africa/Lagos': 'Nigeria', 'Australia/Broken_Hill': 'Australia', 'America/Pangnirtung': 'Canada', 'Asia/Omsk': 'Russian Federation', 'Europe/Tallinn': 'Estonia', 'Africa/Bujumbura': 'Burundi', 'America/Managua': 'Nicaragua', 'Africa/Bissau': 'Guinea-Bissau', 'Europe/Paris': 'France', 'Asia/Rangoon': 'Myanmar', 'Europe/Chisinau': 'Moldova, Republic of', 'Asia/Irkutsk': 'Russian Federation', 'Asia/Hovd': 'Mongolia', 'America/Antigua': 'Antigua and Barbuda', 'America/Rio_Branco': 'Brazil', 'Asia/Srednekolymsk': 'Russian Federation', 'America/Belem': 'Brazil', 'America/Santarem': 'Brazil', 'America/Danmarkshavn': 'Greenland', 'Pacific/Kiritimati': 'Kiribati', 'America/Panama': 'Panama', 'America/Bahia': 'Brazil', 'Asia/Yerevan': 'Armenia', 'America/Indiana/Vevay': 'United States', 'America/Lower_Princes': 'Sint Maarten (Dutch part)', 'Africa/Asmara': 'Eritrea', 'America/Argentina/Ushuaia': 'Argentina', 'Atlantic/Canary': 'Spain', 'Asia/Phnom_Penh': 'Cambodia', 'America/Mazatlan': 'Mexico', 'America/Argentina/Tucuman': 'Argentina', 'Antarctica/Davis': 'Antarctica', 'America/Argentina/La_Rioja': 'Argentina', 'Pacific/Port_Moresby': 'Papua New Guinea', 'Asia/Muscat': 'Oman', 'Pacific/Enderbury': 'Kiribati', 'America/Havana': 'Cuba', 'America/Argentina/Jujuy': 'Argentina', 'Europe/San_Marino': 'San Marino', 'Asia/Kuwait': 'Kuwait', 'Pacific/Fakaofo': 'Tokelau', 'America/North_Dakota/Beulah': 'United States', 'America/Dominica': 'Dominica', 'Antarctica/DumontDUrville': 'Antarctica', 'Atlantic/Stanley': 'Falkland Islands (Malvinas)', 'Asia/Tehran': 'Iran, Islamic Republic of', 'Asia/Dushanbe': 'Tajikistan', 'Asia/Bangkok': 'Thailand', 'Africa/Ouagadougou': 'Burkina Faso', 'America/Sao_Paulo': 'Brazil', 'Australia/Lord_Howe': 'Australia', 'Antarctica/Syowa': 'Antarctica', 'Europe/Oslo': 'Norway', 'Asia/Tashkent': 'Uzbekistan', 'America/Phoenix': 'United States', 'Antarctica/Vostok': 'Antarctica', 'Europe/Istanbul': 'Turkey', 'Asia/Khandyga': 'Russian Federation', 'Pacific/Tarawa': 'Kiribati', 'Australia/Hobart': 'Australia', 'Pacific/Easter': 'Chile', 'Europe/Monaco': 'Monaco', 'America/Juneau': 'United States', 'Europe/Skopje': 'Macedonia, the Former Yugoslav Republic of', 'Australia/Darwin': 'Australia', 'America/Sitka': 'United States', 'America/Denver': 'United States', 'Asia/Kuching': 'Malaysia', 'Asia/Makassar': 'Indonesia', 'America/Hermosillo': 'Mexico', 'Asia/Hong_Kong': 'Hong Kong', 'Asia/Kolkata': 'India', 'Asia/Brunei': 'Brunei Darussalam', 'Asia/Anadyr': 'Russian Federation', 'Pacific/Rarotonga': 'Cook Islands', 'America/La_Paz': 'Bolivia, Plurinational State of', 'America/Martinique': 'Martinique', 'America/North_Dakota/New_Salem': 'United States', 'America/St_Barthelemy': 'Saint Barthélemy', 'Europe/Samara': 'Russian Federation', 'Asia/Dubai': 'United Arab Emirates', 'Africa/Johannesburg': 'South Africa', 'America/Blanc-Sablon': 'Canada', 'Indian/Comoro': 'Comoros', 'Asia/Kamchatka': 'Russian Federation', 'Asia/Ulaanbaatar': 'Mongolia', 'America/St_Johns': 'Canada', 'Europe/Bucharest': 'Romania', 'Pacific/Auckland': 'New Zealand', 'Africa/Luanda': 'Angola', 'Africa/Algiers': 'Algeria', 'Asia/Shanghai': 'China', 'America/Creston': 'Canada', 'America/Argentina/Salta': 'Argentina', 'America/Nassau': 'Bahamas', 'America/Dawson': 'Canada', 'America/Yakutat': 'United States', 'Antarctica/Casey': 'Antarctica', 'Europe/Podgorica': 'Montenegro', 'America/Manaus': 'Brazil', 'America/Atikokan': 'Canada', 'America/Recife': 'Brazil', 'Africa/Bamako': 'Mali', 'America/Vancouver': 'Canada', 'Indian/Kerguelen': 'French Southern Territories', 'Indian/Mauritius': 'Mauritius', 'Europe/Mariehamn': 'Åland Islands', 'Europe/Lisbon': 'Portugal', 'Antarctica/Troll': 'Antarctica', 'Europe/Budapest': 'Hungary', 'America/Argentina/Rio_Gallegos': 'Argentina', 'Australia/Melbourne': 'Australia', 'Europe/Belgrade': 'Serbia', 'Asia/Ust-Nera': 'Russian Federation', 'Pacific/Tongatapu': 'Tonga', 'Pacific/Pohnpei': 'Micronesia, Federated States of', 'Europe/Zagreb': 'Croatia', 'Asia/Karachi': 'Pakistan', 'Africa/Tunis': 'Tunisia', 'America/Merida': 'Mexico', 'Europe/Tirane': 'Albania', 'America/Anchorage': 'United States', 'Europe/Busingen': 'Germany', 'America/Montevideo': 'Uruguay', 'America/El_Salvador': 'El Salvador', 'Europe/Volgograd': 'Russian Federation', 'Pacific/Kosrae': 'Micronesia, Federated States of', 'Africa/Khartoum': 'Sudan', 'America/Santiago': 'Chile', 'Europe/Andorra': 'Andorra', 'Atlantic/Azores': 'Portugal', 'Europe/Minsk': 'Belarus', 'Asia/Colombo': 'Sri Lanka', 'Asia/Dhaka': 'Bangladesh', 'Pacific/Guadalcanal': 'Solomon Islands', 'Asia/Choibalsan': 'Mongolia', 'America/Argentina/Buenos_Aires': 'Argentina', 'Arctic/Longyearbyen': 'Svalbard and Jan Mayen', 'America/Chihuahua': 'Mexico', 'Indian/Cocos': 'Cocos (Keeling) Islands', 'Australia/Adelaide': 'Australia', 'Pacific/Midway': 'United States Minor Outlying Islands', 'Pacific/Guam': 'Guam', 'Africa/Casablanca': 'Morocco', 'Africa/Abidjan': "Côte d'Ivoire", 'Indian/Reunion': 'Réunion', 'Europe/Gibraltar': 'Gibraltar', 'America/Tijuana': 'Mexico', 'Asia/Ho_Chi_Minh': 'Viet Nam', 'Africa/Ndjamena': 'Chad', 'America/Montserrat': 'Montserrat', 'America/Resolute': 'Canada', 'Pacific/Marquesas': 'French Polynesia', 'Pacific/Galapagos': 'Ecuador', 'Atlantic/Faroe': 'Faroe Islands', 'America/Costa_Rica': 'Costa Rica', 'Asia/Beirut': 'Lebanon', 'America/Whitehorse': 'Canada', 'Africa/Nairobi': 'Kenya', 'Africa/Dar_es_Salaam': 'Tanzania, United Republic of', 'America/Godthab': 'Greenland', 'Asia/Damascus': 'Syrian Arab Republic', 'America/Toronto': 'Canada', 'America/Indiana/Vincennes': 'United States', 'Antarctica/McMurdo': 'Antarctica', 'Indian/Antananarivo': 'Madagascar', 'America/Jamaica': 'Jamaica', 'America/Barbados': 'Barbados', 'Asia/Novosibirsk': 'Russian Federation'}

for _tz, coun in coun_to_tz.items():
    tz = timezone(_tz)
    dt = utc.astimezone(tz)
    if str(dt.time()) == "10:00:00":
         print(dt.strftime("%A %B %d at %I:%M:%S%p in {}".format(coun)))

rawDescription: Translating timestamp to Human Readable format


code: second="".join(re.findall(r'\d+',line))#extract second position numbers

rawDescription: How to extract characters and numbers from every line of a file?

description: Extract characters and numbers from every line of a file


code:
joined = df1.groupby(['cnpj','num_doc']).sum() \
            .join(df2.groupby(['cnpj','num_doc']).sum()) \
            .fillna(0)

rawDescription: How can I get the difference between the conditional sum of values from 2 dataframes?

description: Get the difference between the conditional sum of values from 2 dataframes


code:
with mock.patch('socket.socket') as mock_socket:
    mock_socket.return_value.recv.return_value = some_data
    t = TCPSocket()
    t.connect('example.com', 12345)  # t.sock is a mock object, not a Socket
self.assertEqual(t.recv_bytes(), whatever_you_expect)
t.sock.connect.assert_called_with(('example.com', 12345))

rawDescription: How to mock a socket object via the mock library

description: Mock a socket object via the mock library


code:
import pygame
import random

red = [255,0,0]
green = [0,255,0]
blue = [0,0,255]
white = [255,255,255]
black = [0,0,0]
UP = [0,-1]
DOWN = [0,1]
LEFT = [-1,0]
RIGHT = [1,0]
NOTMOVING = [0,0]
#constants end
#classes
class collidable:
    x = 0
    y = 0
    w = 0
    h = 0
    rect = pygame.Rect(x,y,w,h)
    color = [0,0,0]
    def __init__(self,x,y,w,h,color):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.color = color
        self.rect = pygame.Rect(x,y,w,h)
    def draw(self):
        pygame.draw.rect(screen,self.color,[self.x,self.y,self.w,self.h],6)

class player:
    x = 0
    y = 0
    speed = 0
    rect = pygame.Rect(x,y,20,20)
    def __init__(self,x,y,speed):
        self.x = x
        self.y = y
        self.speed = speed
        self.rect = pygame.Rect(self.x,self.y,20,20)
    def draw(self):
        if player_moving==LEFT:
                pygame.draw.polygon(screen,black,[(self.x-10,self.y),(self.x+10,self.y-10),(self.x+10,self.y+10)])
        elif player_moving==RIGHT:
            pygame.draw.polygon(screen,black,[(self.x+10,self.y),(self.x-10,self.y-10),(self.x-10,self.y+10)])
        elif player_moving==UP:
            pygame.draw.polygon(screen,black,[(self.x,self.y-10),(self.x+10,self.y+10),(self.x-10,self.y+10)])
        elif player_moving==DOWN:
            pygame.draw.polygon(screen,black,[(self.x,self.y+10),(self.x+10,self.y-10),(self.x-10,self.y-10)])
        else:
            pygame.draw.rect(screen,black,pygame.Rect(self.x-10,self.y-10,20,20),6)
    def setpos(self,x,y):
        self.x = x
        self.y = y
    def move(self,direction):
        self.x = self.x + direction[0]*self.speed
        self.y = self.y + direction[1]*self.speed
        self.rect = pygame.Rect(self.x,self.y,20,20)
#classes end

#globals
pygame.init()
screenSize = [800,600]
screenBGColor = white
screen=pygame.display.set_mode(screenSize)
pygame.display.set_caption("Move the Block")
player = player(screenSize[0]/2,screenSize[1]/2,9)
collidables = []
clock=pygame.time.Clock()
for i in range(10):
    collidables.append(collidable(random.randrange(0,screenSize[0]),random.randrange(0,screenSize[1]),random.randrange(10,200),random.randrange(10,200),blue))

running = True
#globals end
player_moving = NOTMOVING
#functions
def render():
    screen.fill(screenBGColor)
    clock.tick(60)
    player.draw()
    for c in collidables:
        c.draw()
    pygame.display.flip()
def tick(player_moving):                                           #----------------HERE
    for c in collidables:
        if player.rect.colliderect(c.rect):
            player_moving = NOTMOVING
            print("hit"+str(c.rect)+" with "+str(player.rect))
    player.move(player_moving)

#functions end

#main loop
while running==True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running = False
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LEFT:
                player_moving = LEFT
            if event.key==pygame.K_RIGHT:
                player_moving = RIGHT
            if event.key==pygame.K_UP:
                player_moving = UP
            if event.key==pygame.K_DOWN:
                player_moving = DOWN
        else:
            player_moving = NOTMOVING
    tick(player_moving)
    render()
#main loop end

pygame.quit()

rawDescription: (Python + pygame) collision detection with rects


code:
import csv
import sys

# your data
data = {'name1':[{'AA':2,'GG':3,'CF':10}], 'name2':[{'AA':4, 'GG':9,'CF':5,'GT':1}]}
topleft = 'titles' # whatever you want the leftmost column header to be

# identify the column headers, and put them in alphabetical order (or some other order, if you'd prefer that)
headers = sorted(set(key
                     for row in data.values()
                     for key in row[0]))

# open a csv writer - this one writes to sys.stdout for interactive convenience
writer = csv.writer(sys.stdout, delimiter='\t')

# write the headers
writer.writerow([topleft] + headers)

for key in data:
    # construct each row
    row = [key] # row header
    for header in headers:
        row.append(data[key][0].get(header, 0)) # use 0 if a given header is absent in a given row
    writer.writerow(row) # write the row

rawDescription: Best Way to Convert a Dictionary of Dictionaries into a tab file


code:
genes.sort(key=lambda t: (t[1], t[2]))
genes

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


rawDescription: How to ignore SIGKILL or force a process into 'D' sleep state?

description: Ignore SIGKILL or force a process into 'D' sleep state


code:
for item in data:
    parts[item['TYPE']].update(item)

rawDescription: Unpacking a list of dictionaries based on key matches in Python


rawDescription: Numpy: Assignment and Indexing as Matlab


code:
from lxml import etree

tree = etree.XML('''
<root>
<AdditionalAttribute name="Version Notes" value="This Item was released indirectly as a result of releasing Item 10X9061-11 to In Design." dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Change Number" value="BCV2386079506" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Version Shared" value="No" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Effective Version Shared" value="No" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Material Effectivity Date" value="2016-03-15T08:52:33-08:00" dataType="String"></AdditionalAttribute>

<AdditionalAttribute name="Internal Version Identifier" value="UCV261KSBQGBPYF6" dataType="String"></AdditionalAttribute>
<AdditionalAttribute name="Item Creation Date" value="2016-03-01T09:08:14-08:00" dataType="String"></AdditionalAttribute>
</root>
''')

elements = tree.xpath('//AdditionalAttribute[@name="Internal Version Identifier"]')
assert len(elements) == 1
assert elements[0].attrib["value"] == 'UCV261KSBQGBPYF6'

rawDescription: lxml - Access value of meta tag on element

description: Lxml - Access value of meta tag on element


code: Contact.id < 5

rawDescription: how to deal with multiple arguments in a dictionary construct when query in sqlalchemy?

description: Deal with multiple arguments in a dictionary construct when query in sqlalchemy


rawDescription: How is the Decimal Class Immutable?

description: How is the Decimal Class Immutable


code:
import re
line = 'some dummy text ValueName:     123456 some dummy text'
m = re.findall(r'ValueName:\s+([0-9]+)',line)
m

rawDescription: Python Extract Values of varying length from Text Files


code:
# Import several GUI libraries.
import tkinter.ttk
import tkinter.filedialog
import tkinter.messagebox

# Import other needed modules.
import queue
import _thread
import operator

################################################################################

class AffinityLoop:

    "Restricts code execution to thread that instance was created on."

    __slots__ = '__action', '__thread'

    def __init__(self):
        "Initialize AffinityLoop with job queue and thread identity."
        self.__action = queue.Queue()
        self.__thread = _thread.get_ident()

    def run(self, func, *args, **keywords):
        "Run function on creating thread and return result."
        if _thread.get_ident() == self.__thread:
            self.__run_jobs()
            return func(*args, **keywords)
        else:
            job = self.__Job(func, args, keywords)
            self.__action.put_nowait(job)
            return job.result

    def __run_jobs(self):
        "Run all pending jobs currently in the job queue."
        while not self.__action.empty():
            job = self.__action.get_nowait()
            job.execute()

    ########################################################################

    class __Job:

        "Store information to run a job at a later time."

        __slots__ = ('__func', '__args', '__keywords',
                     '__error', '__mutex', '__value')

        def __init__(self, func, args, keywords):
            "Initialize the job's info and ready for execution."
            self.__func = func
            self.__args = args
            self.__keywords = keywords
            self.__error = False
            self.__mutex = _thread.allocate_lock()
            self.__mutex.acquire()

        def execute(self):
            "Run the job, store any error, and return to sender."
            try:
                self.__value = self.__func(*self.__args, **self.__keywords)
            except Exception as error:
                self.__error = True
                self.__value = error
            self.__mutex.release()

        @property
        def result(self):
            "Return execution result or raise an error."
            self.__mutex.acquire()
            if self.__error:
                raise self.__value
            return self.__value

################################################################################

class _ThreadSafe:

    "Create a thread-safe GUI class for safe cross-threaded calls."

    ROOT = tkinter.Tk

    def __init__(self, master=None, *args, **keywords):
        "Initialize a thread-safe wrapper around a GUI base class."
        if master is None:
            if self.BASE is not self.ROOT:
                raise ValueError('Widget must have a master!')
            self.__job = AffinityLoop() # Use Affinity() if it does not break.
            self.__schedule(self.__initialize, *args, **keywords)
        else:
            self.master = master
            self.__job = master.__job
            self.__schedule(self.__initialize, master, *args, **keywords)

    def __initialize(self, *args, **keywords):
        "Delegate instance creation to later time if necessary."
        self.__obj = self.BASE(*args, **keywords)

    ########################################################################

    # Provide a framework for delaying method execution when needed.

    def __schedule(self, *args, **keywords):
        "Schedule execution of a method till later if necessary."
        return self.__job.run(self.__run, *args, **keywords)

    @classmethod
    def __run(cls, func, *args, **keywords):
        "Execute the function after converting the arguments."
        args = tuple(cls.unwrap(i) for i in args)
        keywords = dict((k, cls.unwrap(v)) for k, v in keywords.items())
        return func(*args, **keywords)

    @staticmethod
    def unwrap(obj):
        "Unpack inner objects wrapped by _ThreadSafe instances."
        return obj.__obj if isinstance(obj, _ThreadSafe) else obj

    ########################################################################

    # Allow access to and manipulation of wrapped instance's settings.

    def __getitem__(self, key):
        "Get a configuration option from the underlying object."
        return self.__schedule(operator.getitem, self, key)

    def __setitem__(self, key, value):
        "Set a configuration option on the underlying object."
        return self.__schedule(operator.setitem, self, key, value)

    ########################################################################

    # Create attribute proxies for methods and allow their execution.

    def __getattr__(self, name):
        "Create a requested attribute and return cached result."
        attr = self.__Attr(self.__callback, (name,))
        setattr(self, name, attr)
        return attr

    def __callback(self, path, *args, **keywords):
        "Schedule execution of named method from attribute proxy."
        return self.__schedule(self.__method, path, *args, **keywords)

    def __method(self, path, *args, **keywords):
        "Extract a method and run it with the provided arguments."
        method = self.__obj
        for name in path:
            method = getattr(method, name)
        return method(*args, **keywords)

    ########################################################################

    class __Attr:

        "Save an attribute's name and wait for execution."

        __slots__ = '__callback', '__path'

        def __init__(self, callback, path):
            "Initialize proxy with callback and method path."
            self.__callback = callback
            self.__path = path

        def __call__(self, *args, **keywords):
            "Run a known method with the given arguments."
            return self.__callback(self.__path, *args, **keywords)

        def __getattr__(self, name):
            "Generate a proxy object for a sub-attribute."
            if name in {'__func__', '__name__'}:
                # Hack for the "tkinter.__init__.Misc._register" method.
                raise AttributeError('This is not a real method!')
            return self.__class__(self.__callback, self.__path + (name,))

################################################################################

# Provide thread-safe classes to be used from tkinter.

class Tk(_ThreadSafe): BASE = tkinter.Tk
class Frame(_ThreadSafe): BASE = tkinter.ttk.Frame
class Button(_ThreadSafe): BASE = tkinter.ttk.Button
class Entry(_ThreadSafe): BASE = tkinter.ttk.Entry
class Progressbar(_ThreadSafe): BASE = tkinter.ttk.Progressbar
class Treeview(_ThreadSafe): BASE = tkinter.ttk.Treeview
class Scrollbar(_ThreadSafe): BASE = tkinter.ttk.Scrollbar
class Sizegrip(_ThreadSafe): BASE = tkinter.ttk.Sizegrip
class Menu(_ThreadSafe): BASE = tkinter.Menu
class Directory(_ThreadSafe): BASE = tkinter.filedialog.Directory
class Message(_ThreadSafe): BASE = tkinter.messagebox.Message

rawDescription: Updating a TKinter GUI from a multiprocessing calculation


code: (df[cols] > 0).all(axis=1)

rawDescription: making new column in pandas dataframes based on filter

description: Making new column in pandas dataframes based on filter


code:
with open(filename, 'rb') as fileobj:
    for chunk in iter(lambda: fileobj.read(4), ''):
        integer_value = struct.unpack('<I', chunk)[0]

rawDescription: Reading 4 byte integers from binary file in Python


rawDescription: Generating pdf-latex with python script

description: Generating pdf-latex with python script


rawDescription: Use regex to parse parameter line with whitespace in parameters but without quotes


rawDescription: ast.literal_eval not working (python string of list to list)

description: Ast.literal_eval not working (python string of list to list)


code:
sample_dict = {'key1': {'key1': 'value_of_interest'}}
val = sample_dict.recursive_get('key1', None)

rawDescription: In Python, why isn't there a built in function to find a key in a nested dictionary?


code: from flask import g

rawDescription: Keeping an object over the lifetime of a request in Flask


code: rnaSequences = []

rawDescription: Python/Multiprocessing : Processes does not seem to start


code:
api = []
for i in xrange(5,51):
    ip = "192.168.0.%d" % (i)
    api.append(xmlrpclib.ServerProxy("http://user:pass@" + ip))

rawDescription: Referencing range of IP addresses

description: Referencing range of IP addresses


code:
class Hex(IntMathMixin, int):
    def __repr__(self):
         return "0x%x"%self
    __str__=__repr__

rawDescription: subclassing int to attain a Hex representation

description: Subclassing int to attain a Hex representation


code: print(cities["cityname"])

rawDescription: Creating a list of lists using append function


code:
exp_A = A - max_A
np.exp(exp_A, out=exp_A)

rawDescription: numerically stable way to multiply log probability matrices in numpy

description: Numerically stable way to multiply log probability matrices in numpy


code: ['Name1' 'Name3' 'Name4' 'Name5']

rawDescription: Python: comparing columns in numpy

description: Python: comparing columns in numpy


code: filter(lambda obj: obj.value == 1, [a, b])

rawDescription: Get class instance where a certain property has a certain value


rawDescription: Writing an XML header with LXML

description: Writing an XML header with LXML


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

dates = []
for year in range(2012, 2014):
    for month in range(1, 12):
        dates.append(dt.datetime(year=year, month=month, day=1))

y = [10, 180, 153, 80, 11, 92, 201, 74, 24]
plt.plot(dates[:9], y)
plt.show()

rawDescription: Setting the x axis as time (years, months) for a set of values


code: x.append('single item')

rawDescription: Python - Neaten this append/extend conditional


code: s.combine(s2, lambda x, y: len(x.intersection(y)))

rawDescription: Count size of rolling intersection in pandas


code:
next(names)
next(names)
next(names)

rawDescription: How would i go about automatic name generation


code:
def create_id_generator():
    """Returns an id generator."""
    i = 0
    while True:
        yield i
        i += 1

rawDescription: Python best practices for functions

description: Python best practices for functions


code:
from collections import defaultdict, Counter
jobsdict = defaultdict(lambda: defaultdict(Counter))
jobsdict['US']['TX']['1234'] += 1

rawDescription: Inserting values to nested dictionaries

description: Inserting values to nested dictionaries


code:
ax.fill_between(bincenters, 0, N, interpolate=True,
                where=((bincenters>=np.percentile(bincenters, 10)) &
                       (bincenters<=np.percentile(bincenters, 90))))

rawDescription: Filling under histogram until exact point with fill_between python


code:
class MyModel(Model):
    data = CharField(primary_key=True)

rawDescription: Peewee: change "Id" field with another name


code:
from yourapp import create_app
if __name__ == '__main__':
    logger = MyProcess()
    app = create_app(logger)
    app.run()

rawDescription: Pass another object to the main flask application


code:
with open("/tmp/LostShots/LostShots.txt", "r") as input_file:
    with open('results.txt', 'w') as output_file:

        for line in input_file:
            if "Lost" in line:
                output_file.write(line)

rawDescription: Search text file and save result to another text file


rawDescription: Switching between Anaconda and Anaconda3


code: shelf = the_function_you_want()

rawDescription: Supporting the "with open" syntax without using contextlib.closing()


rawDescription: How to combine two lists in a non standard way in Python

description: Combine two lists in a non standard way in Python


code:
root = Tk()
#...
canvas = Canvas(root)
#...
#endof canvas
root = Tk()
#...
app = Application(root)

rawDescription: I cant get the canvas to work how i wanted it to


code:
class z(base):
    def __init__(self, zz):
        self.zz = zz
        self.context = context

context = 'abc'
Z = z(26)

rawDescription: How to share common context between classes?

description: Share common context between classes


code:
import subprocess
import os
subprocess.call([os.environ.get('SHELL', '/bin/sh'), '-i'])

rawDescription: How can I exec an interactive shell from Jython?

description: Exec an interactive shell from Jython


code:
import requests
line_cnt=0
r = requests.get('http://127.0.0.1/some_path/small.csv',stream=True)
for i in r.iter_lines():
    if i.strip():
        line_cnt +=1
print (line_cnt)

rawDescription: Read info from hyperlink located remotely (know that by hyperlink it will be csv file, but can't find general approach)


code:
@it.should('do something')
@mock.patch('datetime.date')
@mock.patch('datetime.time')
def test_1(date, time, case):
    pass

@mock.patch('datetime.time')
@mock.patch('datetime.date')
@it.should('do something')
def test_2(case, date, time):
    pass

rawDescription: Use mock.patch decorators with nose2 Such DSL


code:
inner_style = {'color': 'r', 'lw': 5, 'ls':'--'}
outer_style = {'color': 'r', 'lw': 1, 'ls':'-'}

x = np.linspace(0, 2*np.pi, 1024)
y = np.sin(x)

low = np.pi / 2
high = 3*np.pi / 2

fig, ax = plt.subplots()

lower, mid, upper, vl_low, vl_high, hsp = split_plot(ax, x, y, low, high, inner_style, outer_style)
plt.show()

rawDescription: Using Python 2.7 and matplotlib, how do I create a 2D Line using two different styles?


code:
def r(lst):
    return range(len(lst))

rawDescription: Short for 'for i in range(1,len(a)):' in python


code:
inp = raw_input('Enter input: ')
ints = map(int, inp.split(','))

rawDescription: Feed user input directly into an int array PYTHON


rawDescription: Child thread doesn`t really spawn or has some issue in python?


code: route_best = max(route1, route2)

rawDescription: Python logic - how do I code the maximum weight for two roads that have a variety of maximum weight values?


rawDescription: How to read in metadata (with tags) from a text file using Python

description: Read in metadata (with tags) from a text file using Python


rawDescription: Binary data with pyserial(python serial port)


rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
import subprocess
p = subprocess.Popen("your command goes here", stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()

rawDescription: Handle result of os.system

description: Handle result of os.system


list: Hello World

rawDescription: HTML tags within JSON (in Python)

description: HTML tags within JSON (in Python)


code:
@app.route('/phototags/<int:id>')
def phototags(id=None):
    photo =  Photo.query.get(id)
    return render_template(
        'phototags.html',
        title='PhotoTags',
        message='Your application description page.',
        photo = photo
    )

rawDescription: Flask SQLalchemy - many to many - show photo with all tags (or blog with all posts etc)


code:
test = '/home/user/file.txt'
print(list(split_paths(test)))

['/', 'home', 'user', 'file.txt']

rawDescription: How do I flatten nested lists of lists in python?

description: Flatten nested lists of lists in python


code:
import my_dict
print(my_dict.dict2[2])
# Output: val2

rawDescription: Outputting a dictionary to file exactly as defined in variable


code:
T = BST( )
for x in [5,3,7,2,4,6,8]:
    T.insert(x)
print(T.root.inOrder())
print(T.root.preOrder())
print(T.root.postOrder())

rawDescription: Output BST in Nested Form

description: Output BST in Nested Form


code: c_tilde = SR.var('c_tilde', latex_name=r'\widetilde{c}')

rawDescription: How to render a variable with a tilde on Latex with Sagetex

description: Render a variable with a tilde on Latex with Sagetex


code:
def unravel (data):
    d = {}
    for k, v in data.items():
        if isinstance(v, dict):
            d.update(unravel(v))
        else:
            d[k] = v
    return d

rawDescription: Convert dict with mixed values to flat dict


code:
def anti_vowel(text):
    words = []
    for character in text:
        if not (character.lower() in vowels or character.upper() in vowels):
            words.append(character)
    return ''.join(words)

rawDescription: pop() function not functioning right in a for loop

description: Pop() function not functioning right in a for loop


code:
import re

re_id = re.compile("id (\d+)")
re_ip = re.compile("192\.168\.45\.28\.(\d+)")
with open("test.txt", "r") as f:
    for line in f:
        match = re.findall(re_id,line)
        if match:
            print("************ %s" % match.group(1))
        match = re.findall(re_ip,line)
        if match:
            print(match.group(1))

rawDescription: Locate multiple keywords in lines using Python


code:
...
url(r'/flash/(?P<movie>.+)$', 'myapp.views.my_view'),
...

rawDescription: Convert param into python?

description: Convert param into python


code:
dictionary = {'foo': 42, 'bar': 38, 'baz': 20}
[v for k, v in sorted(dictionary.iteritems())]
[dictionary[k] for k in sorted(dictionary)]

rawDescription: python : list of dictionary values by alphabetical order of keys

description: Python : list of dictionary values by alphabetical order of keys


code:
url(r'^register/(?P<success_url>[\w\/]+)/$',
    register,
    { 'backend': 'registration.backends.default.DefaultBackend' },
    name='registration_register'),

rawDescription: Django: How to write the reverse function for the following


rawDescription: Matplotlib - change automatic axis range


rawDescription: Inheriting context variables inside custom template tags


code:
import re
numslist = []
with open("filename.txt") as f:
    for line in f:
        if "form" in line:
            nums = re.findall('\d+', line)
            numslist.extend(nums)

rawDescription: Extracting digits in line and storing them to list in Python


code: subdfs = [subdf for key, subdf in grouped]

rawDescription: pandas quick way to break dataframe by timeindex

description: Pandas quick way to break dataframe by timeindex


code:
def pan(self):
    NavigationToolbar2TkAgg.pan(self)
    self.mode = "I'm panning!" #<--- whatever you want to replace "pan/zoom" goes here
    self.set_message(self.mode)

def zoom(self):
    NavigationToolbar2TkAgg.zoom(self)
    self.mode = "I'm zooming!" #<--- whatever you want to replace "zoom rect" goes here
    self.set_message(self.mode)

rawDescription: Matplotlib/Tkinter - customizing toolbar tooltips


code: c and c == d or True

rawDescription: What does this python expression mean

description: What does this python expression mean


code:
regex = re.compile(r'((iphone|games|mac)(\s*(iphone|games|mac))*)', re.I)
regex.sub(r'<em>\1</em>', sentence)

rawDescription: How do I add tags to certain strings in python using re.sub?

description: Add tags to certain strings in python using re.sub


rawDescription: computing rolling averages by integer days in pandas

description: Computing rolling averages by integer days in pandas


code:
def addition(x, y):
    return x + y

rawDescription: re-naming data frame output given input parameter to class in python

description: Re-naming data frame output given input parameter to class in python


code:
def f():
    a = []
    def g():
        a.append(1)
        return len(a)
    return g

rawDescription: How can data remain persistent across multiple calls of decorated function?


code:
def set(d, key, value):
    dd = d
    keys = key.split('.')
    latest = keys.pop()
    for k in keys:
        dd = dd.setdefault(k, {})
    dd.setdefault(latest, value)

d = {}
set(d, 'a.b.c', 'X')
set(d, 'a.b.d', 'Y')
print(d)

rawDescription: Set a value deep in a dict dynamically

description: Set a value deep in a dict dynamically


code:
data = zip(*data)
data = [x for x in data if any(x)]
data = zip(*data)

rawDescription: How do I remove an empty column in a two dimensional list in python?

description: Remove an empty column in a two dimensional list in python


code: tests = Test.objects.filter(metadata__key=key, metadata__value=value)

rawDescription: Django Filter by Multiple Foreign Key Properties


rawDescription: Splitting unicode string

description: Splitting unicode string


code:
import numpy
from matplotlib import gridspec
import matplotlib.pyplot as plt

def do_plot_1(ax):
    ax.plot([0.25, 0.5, 0.75], [0.25, 0.5, 0.75], 'k-')

def do_plot_2(ax):
    ax.plot([0.25, 0.5, 0.75], [0.25, 0.5, 0.75], 'g--')

fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=3, ncols=1, height_ratios=[2, 1, 2])

for n in range(3):
    ax = fig.add_subplot(gs[n])
    if n == 1:
        do_plot_1(ax)
    else:
        do_plot_2(ax)

fig.tight_layout()

rawDescription: matplotlib subplot2grid doesn't display correctly

description: Matplotlib subplot2grid doesn't display correctly


rawDescription: Comparing elements in a numpy array, finding pairs, how to deal with edges/corners


code: brightness = sum([R,G,B])/3 ##0 is dark (black) and 255 is bright (white)

rawDescription: python -- measuring pixel brightness

description: Python -- measuring pixel brightness


code:
def tuple_func(n):
    S = [1, 2]
    T = [0, 1]
    if n < 0:
        return(None, None)
    if 0 >= n < 2:
        return(S[n], T[n])
    for n in range(2, n + 1):
        S.append(2 * S[n - 1] + S[n - 2] + 4 * T[n - 1])
        T.append(S[n - 1] + T[n - 1])
    return(S[n], T[n])

rawDescription: python programming help for equation

description: Python programming help for equation


code: key_whose_count_is_10 = rev[10]

rawDescription: Python Counter: print key whose count is x


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

import sys, getopt
import urllib
import simplejson

OPTIONS = ("m:", ["min="])

def print_usage():
    s = "usage: " + sys.argv[0] + " "
    for o in OPTIONS[0]:
        if o != ":" : s += "[-" + o + "] "
    print(s + "query_string\n")

def search(query, index, offset, min_count, quiet=False, rs=[]):
    url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&start=%s" % (query, offset)
    result = urllib.urlopen(url)
    json = simplejson.loads(result.read())
    status = json["responseStatus"]
    if status == 200:
        results = json["responseData"]["results"]
        cursor = json["responseData"]["cursor"]
        pages = cursor["pages"]
        for r in results:
            i = results.index(r) + (index -1) * len(results) + 1
            u = r["unescapedUrl"]
            rs.append(u)
            if not quiet:
                print("%3d. %s" % (i, u))
        next_index  = None
        next_offset = None
        for p in pages:
            if p["label"] == index:
                i = pages.index(p)
                if i < len(pages) - 1:
                    next_index  = pages[i+1]["label"]
                    next_offset = pages[i+1]["start"]
                break
        if next_index != None and next_offset != None:
            if int(next_offset) < min_count:
                search(query, next_index, next_offset, min_count, quiet, rs)
    return rs

def main():
    min_count = 64
    try:
        opts, args = getopt.getopt(sys.argv[1:], *OPTIONS)
        for opt, arg in opts:
            if opt in ("-m", "--min"):
                min_count = int(arg)
        assert len(args) > 0
    except:
        print_usage()
        sys.exit(1)
    qs = " ".join(args)
    query = urllib.urlencode({"q" : qs})
    search(query, 1, "0", min_count)

if __name__ == "__main__":
    main()

rawDescription: get the first 10 google results using googleapi

description: Get the first 10 google results using googleapi


code:
import random
def mutate(string, mutation, threshold):
    dna = list(string)
    for index, char in enumerate(dna):
        if char in mutation:
            if random.random() < threshold:
                dna[index] = mutation[char]

    return ''.join(dna)

rawDescription: Using Random Module to Administer DNA Mutations


code:
class A(object):
    def __init__(self, y):
        self.x = 2
        self.y = y

class B(A):
    def __init__(self, y, z):
        super().__init__(y)  # equivalent to: A.__init__(self, y)
        self.z = z

b = B(3, 4)
# b's x is 2, b's y is 3 (both set by A.__init__, the last one was passed by B), and b's z is 4 (set by B.__init__)

rawDescription: Would I be able to separate variables into another class but keep the usage the same?


code:
print('Type > ', end='')
sys.stdout.flush()

rawDescription: Python3: Using "select.select" with print(str, end=' ')


code:
def count():
    sys.stdout = StatusWriter()
    i = 0
    def step():
        nonlocal i
        statusbar.config(text="{} of {}".format(i, 50))
        i += 1
        if i == 50:
            sys.stdout = sys.__stdout__
        else:
            root.after(100, step)
    root.after(100, step)

rawDescription: Using sys.stdout.write("\r...") in tkinter


code:
while 1:
    f = open('manual_mode','r')
    val = f.read()
    f.close()
    if val == '1':
        break

rawDescription: terminate python while loop in php

description: Terminate python while loop in php


code: timeit.timeit("''.join(c for c in t if c not in l)", 'from __main__ import inputtext as t; import string; l = set(string.letters)')

rawDescription: how to Ignore characters other than [a-z][A-Z]

description: Ignore characters other than [a-z][A-Z]


rawDescription: Isolating/manipulating data in a pandas Dataframe


code:
def your_view(request):
    config_file = request.registry.settings['config_file']

rawDescription: How do I access ${buildout:directory} from Python code?

description: Access ${buildout:directory} from Python code


code:
class MyThrough(MyModel.m2m.through):
    class Meta:
        proxy = True
    def __unicode__(self):
        return "My New Unicode"

class MyInline(admin.TabularInline):
    model = MyThrough

rawDescription: Django: Friendlier header for StackedInline for auto generated through model?


rawDescription: Python: how to extract the content of a column in a table


code:
import PIL
from PIL import Image
from matplotlib import pyplot as plt

im = Image.open('./color_gradient.png')
w, h = im.size
colors = im.getcolors(w*h)

def hexencode(rgb):
    r=rgb[0]
    g=rgb[1]
    b=rgb[2]
    return '#%02x%02x%02x' % (r,g,b)

for idx, c in enumerate(colors):
    plt.bar(idx, c[0], color=hexencode(c[1]))

plt.show()

rawDescription: Plot image color histogram using matplotlib


code: df1[df1.groupby(['a','b'])['c'].transform(lambda x: len(x) > 2).astype(bool)]

rawDescription: How to delete minority rows from a pandas data frame?

description: Delete minority rows from a pandas data frame


rawDescription: replacing part of the string in python 2.7

description: Replacing part of the string in python 2.7


code: t, p = ttest_ind(a, b, equal_var=False)

rawDescription: Perform 2 sample t-test

description: Perform 2 sample t-test


code:
if db == "mysql": # or whatever your real logic is
    import mysql_db as db_util
elif db == "postgres":
    import postgres_db as db_util

import some_helper_module

some_helper_module.db_util = db_util # explicitly add to another namespace

#...

rawDescription: Python import as global name not defined


code:
base = '4E00'
chr(int(base, 16))
(br'\u' + base.encode('ascii')).decode('unicode_escape')

rawDescription: Python3: Creating a string with an unescaped backslash


code:
uwsgi.opt['foo']
'bar'

rawDescription: Pass command line parameters to uwsgi script


code: from animals import Dog as Scooby

rawDescription: Python 3 Assume Module Namsepace

description: Python 3 Assume Module Namsepace


code:
busdef = (busname("bus1") + busname("bus2") +
            integer("linenum") +
            decimaltable("pf qf pl ql".split()))

rawDescription: How should I organise my functions with pyparsing?


code:
import random
c = Currencies()
vars(c)
[v for attr, v in vars(c).items() if len(attr) == 8 and attr[3:5] == 'To']
random.choice([v for attr, v in vars(c).items() if len(attr) == 8 and attr[3:5] == 'To'])

rawDescription: Get random element from attributes in an object


code:
import datetime

start_time = 9 # per user input
end_time = 10 # per user input
divisions = 4 # per user input

total_minutes = (end_time-start_time)*60
increment = total_minutes // divisions

minutes = [start_time*60]
while minutes[-1] < end_time*60:
    # < end_time*60 - increment to exclude end_time from result
    minutes.append(minutes[-1] + increment)

times = [datetime.time(c//60,c%60) for c in minutes]
# [09:00:00,
#  09:15:00,
#  09:30:00,
#  09:45:00,
#  10:00:00]

rawDescription: Python Time Math

description: Python Time Math


code:
lines_of_text = [
    (12345, 1312,  'Teso', 'Billy',  'Jones'),
    (12344, 30000, 'Test', 'John M', 'Smith')
]

for mytuple in lines_of_text:
    name = '{}, {}'.format(mytuple[4], mytuple[3])
    value = '£' + str(mytuple[1])
    print('{name:<20} {id:>8} {test:<12} {value:>8}'.format(
        name=name, id=mytuple[0], test=mytuple[2], value=value)
    )

rawDescription: Python String Padding

description: Python String Padding


code: pd.Series(range(10)).clip(2, 3)

rawDescription: Why np.clip(pd.Series(range(10)), 2,3) returns a Series?


code:
self.tab1.a.sigClicked.connect(self.pointChanged)

def pointChanged(self, points):
    tab2.points_from_tab1_a = tab1.a

rawDescription: Passing changing data from tab to tab

description: Passing changing data from tab to tab


code:
import subprocess
import threading

def kill_this(procs, hard=False):
    """kill the Popen processes in the list"""

    for proc in procs:
        if hard:
            proc.kill()
        else:
            proc.terminate()

class A(threading.Thread):
    """Runs tor and firefox, with graceful termination in 10 seconds and
    a hard kill in 20 seconds as needed"""

    def __init__(self):
        Thread.__init__(self)

    def run(self):
        # create processes
        tor = subprocess.Popen(['tor'])
        firefox = subprocess.Popen(['firefox'])

        # setup timers to kill 'em
        soft = threading.Timer(10, kill_this, ((tor, firefox), False))
        hard = threading.Timer(20, kill_this, ((tor, firefox), True))

        # wait for process exit
        tor.wait()
        firefox.wait()

        soft.cancel()
        hard.cancel()

rawDescription: How to kill a process within a thread in python?

description: Kill a process within a thread in python


code:
import weakref

def super_simple_decorator(method):
    instance = weakref.ref(method.__self__)
    func = method.__func__
    def f(*args, **kwds):
        self = instance()  # can return None
        return func(self, *args, **kwds)
    return f

rawDescription: Python classes with decorated methods and __del__ defined do not get garbage collected: how do I uncouple the decorated method?


rawDescription: Need help to read a file in python

description: Need help to read a file in python


code:
#Read page data as a string
pageData = sock.read()
#set p as regular expression
p = re.compile('(?<=line1=)(.*)(?=;)')
#find all instances of regular expression in pageData
parsed = p.findall(pageData)
#evaluate list as python code => turn into list in python
newParsed = eval(parsed[0])

rawDescription: How can I parse Javascript variables using python?

description: Parse Javascript variables using python


code:
begin=input("Welcome!\n"
            "When you would like to try out\n"
            "Python Mad Libs Program, Prototype000,"
            "press the enter/return key.")

print("\nInitializing befuddlement...")

import random
sentenceCap=35
sentenceBottom=25
numOfSentences=random.randint(sentenceBottom,sentenceCap)

tempstore=[" "]*numOfSentences
irregplrls={'child':'children','ox':'oxen','moose':'moose'}

def testforoo(x):
    return any(x[j]=='oo'.lower() for j in range(0,len(x)))

def pluralize(x):
    if x in irregplrls:
        return irregplrls[x]

    if x[-1]=="y":
        return x[:-1]+"ies"
    elif x[-2:]=="us":
        return x[:-2]+"i"
    elif x[-1] in 'sx':
        return x+"es"
    elif x[-2:] in ('ch','sh'):
        return x+"es"
    elif 'f'==x[-1] or x[-2]:
        if 'f'==x[-1]:
            return x[:-1] + 'ves'
        elif 'f'==x[-2]:
            return x[:-2]+"ves"
    elif any(x[j]=='oo'.lower() for j in range(0,len(x))):
        return x[:testforoo(x)-2]+'ee'+x[testforoo(x):]
    else:
        return x+'s'

print("\nRetrieving craploads of words...")

verb=["moves","jumps", "hides","sniffs","gazes","sneezes","calls"]
noun=["rabbit","dog","cat","otter","seal","elephant","fox",'baby','moose','octopus']
adjec=["happy","angry","cute","enormous","elegant","annoying"]
adver=["merrily","frustratedly","incoherently","morosely","peppily",'exuberantly']
endpunct=[".","!"]

print("\nSimulating human grammar-speak...\n")

for i000 in range(0,numOfSentences):
    v=random.choice(verb)
    n=random.choice(noun)
    adj=random.choice(adjec)
    adv=random.choice(adver)
    pun=random.choice(endpunct)
    askinput=random.randint(0,round(numOfSentences/5))
    whichinput=random.randint(0,3)
    if askinput==0:
        if whichinput==0:
            n=input("Please input a noun. ")
        elif whichinput==1:
            v=input("Please input a verb. ")
        elif whichinput==2:
            adj=input("Please input an adjective. ")
        elif whichinput==3:
            adv=input("Please input an adverb. ")
    templates=["The %s %s %s %s%s" % (adj,n,v,adv,pun),
               "%s %s %s %s%s" % (adj,pluralize(n),v[:len(v)-1],adv,pun)]
    final = random.choice(templates)
    final=final[0].upper() + final[1:]
    tempstore[i000]=final
    print('numOfSentences==',numOfSentences,i000)

print("\nProducing proof of illiteracy...\n")

print ('\n'.join(tempstore))

rawDescription: Python 3.3.3 TypeError : Can't convert 'NoneType' object to str implicitly


code:
vars(p)
p.__dict__

rawDescription: How to get a dict from scrapy item?

description: Get a dict from scrapy item


code:
df = pd.DataFrame([1,1,1,1], index=pd.date_range('1/1/2013',periods=4))
target_zero_row = df.index.get_loc('2013-01-04')
df.reset_index(drop=True, inplace=True)
df.index = df.index + (-target_zero_row)
df

rawDescription: How to reindex a dataframe specifying center

description: Reindex a dataframe specifying center


rawDescription: Speeding up column conversions

description: Speeding up column conversions


code:
from test import test
testObj = test()
testObj.quicktest(...)

rawDescription: Access function from within scripts and from commandline


code:
import re
li = []
b = open ('file_sample.txt','w')
with open ('file_sam.txt') as f:
    for i in open ('file_sam.txt','r'):
        a =  [re.sub('.*\\\\','',i).rstrip('\n') for i in i.split('D:')]
        b.write(''.join(a) + '\n')
b.close()

rawDescription: How to remove a directory path from a text file

description: Remove a directory path from a text file


code:
@app.route('/activate', methods=['POST'])
@validate_json
@validate_schema('activate_schema')
def activate():
    input = request.json

rawDescription: Flask: Decorator to verify JSON and JSON Schema


code:
import numpy as np
np.random.seed(1)

N = 10
a = np.random.randint(1, 1000, (2, 2, 3))
check_tuple = np.random.randint(1, 1000, N)

def using_in1d(a):
    idx = np.in1d(a[:,:,1], check_tuple)
    idx=idx.reshape(a[:,:,1].shape)
    a[idx,1] = a[idx,0] * 2
    return a

def using_in(a):
    idx = np.zeros(a[:,:,0].shape,dtype=bool)
    for n in check_tuple:
        idx |= a[:,:,1]==n
    a[idx,1] = a[idx,0]*2
    return a

assert np.allclose(using_in1d(a),using_in(a))

rawDescription: Numpy: checking if an element in a multidimensional array is in a tuple


code:
d = {}
for i in listofdict:
   d[i.pop('name')] = i

rawDescription: Elegant way to transform a list of dict into a dict of dicts


code:
# -*- coding: utf-8 -*-
from collections import defaultdict, Counter
import string
import pandas as pd

# prepare translate table, which will remove all punctuations and digits
chars2remove = list(string.punctuation + string.digits)
transl_tab = str.maketrans(dict(zip(chars2remove, list(' ' * len(chars2remove)))))
# replace 'carriage return' and 'new line' characters with spaces
transl_tab[10] = ' '
transl_tab[13] = ' '

def tokenize(s):
    return s.translate(transl_tab).lower().split()

chunksize = 100
fn = r'D:\temp\.data\ows-sample.txt'

#
# read `Day` and `Text` columns from the source CSV file
#

# not-chunked version
#df = pd.read_csv(fn, usecols=['Text','Day'])

# "chunked" version - will prepare a list of "reduced" DFs,
# containing word counts in the form: "{'we': 1, 'stand': 1, 'and': 1}"
dfs = []
for df in pd.read_csv(fn, usecols=['Text','Day'], chunksize=chunksize):
    # group DF by date and count words for each unique day, summing up counters
    dfs.append(df.assign(count=df['Text']
                                 .apply(lambda x: Counter(tokenize(x))))
                 .groupby('Day', as_index=False)['count'].sum()
    )

# convert sets of {'word1': count, 'word2': count} into columns
tmp = (pd.concat(dfs, ignore_index=True)
         .set_index('Day')['count']
         .apply(pd.Series)
         .reset_index()
)
tmp['Day'] = pd.to_datetime(tmp['Day'])

# free up memory
del dfs

# transform (melt) columns into desired columns: [Day, word, number]]
rslt = (pd.melt(tmp, id_vars='Day', var_name='word', value_name='number')
          .fillna(0)
)

# delete temporary DF from memory
del tmp

# save results as HDF5 file
rslt.to_hdf('d:/temp/.data/twit_words.h5', 'twit_words', mode='a',
            format='t', complib='zlib', complevel=4)

# save results as CSV file
rslt.to_csv('d:/temp/.data/twit_words.csv.gz', index=False,
            encoding='utf_8', compression='gzip')

rawDescription: # pandas DataFrame ValueError: Shape of passed values is (1, 3), indices imply (3, 3)


code:
class Attribute():
  AttributesMemberName =  "__attributes__"
  _debug =                False

  def __call__(self, func):
    # inherit attributes and append myself or create a new attributes list
    if (func.__dict__.__contains__(Attribute.AttributesMemberName)):
      func.__dict__[Attribute.AttributesMemberName].append(self)
    else:
      func.__setattr__(Attribute.AttributesMemberName, [self])
    return func

  def __str__(self):
    return self.__name__

  @classmethod
  def GetAttributes(self, method):
    if method.__dict__.__contains__(Attribute.AttributesMemberName):
      attributes = method.__dict__[Attribute.AttributesMemberName]
      if isinstance(attributes, list):
        return [attribute for attribute in attributes if isinstance(attribute, self)]
    return list()

rawDescription: Is it possible to implement .NET-like attributes in Python?


code:
if number >= 0 or number <= 100:
    if number >= 0:
        print("Positive")
    if number <= 100:
        print("<= 100")
else:
    print("x < 0 or x > 100")

rawDescription: Python 3 else for all previous ifs

description: Python 3 else for all previous ifs


rawDescription: How to convert numpy object array into str/unicode array?

description: Convert numpy object array into str/unicode array


code:
import M2Crypto
key = M2Crypto.RSA.new_pub_key((
    M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hex(e)[2:])),
    M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hex(n)[2:])),
    ))

rawDescription: M2Crypto - import keys from non-standard file?


code:
class Entry(models.Model):
    weekdays = models.PositiveIntegerField(choices=WEEKDAYS)

rawDescription: Representing a multi-select field for weekdays in a Django model


code: [x+y for x,y in zip(ListA, ListB)]

rawDescription: Python - Merge two lists with a simultaneous concatenation


code:
import re
from pprint import pprint
from collections import defaultdict

def build_tree(codes):
    """Build the tree from a list of codes (strings)"""

    # tree is a dictionary that maps each code to a list of codes of children.
    tree = defaultdict(list)
    roots = []
    for code in codes:
        if '000000' in code:
            tree[code] = []
            roots.append(code)
        else:
            nonzero = re.search(r'[1-9]0*$', code).start()
            parent = code[:nonzero] + '0' + code[1 + nonzero:]
            tree[parent].append(code)

    # sort children (optional)
    for v in tree.values():
        v.sort()

    # convert original dictionary to one in the desired form.
    def convert(old_parent):
        result = {}
        result['code'] = old_parent
        if len(tree[old_parent]) > 0:
            result['children'] = [convert(c) for c in tree[old_parent]]
        return result

    return [convert(root) for root in roots]

codes = ["01000000", "01100000", "01110000", "01111000", "01111100", "01111110",
         "01111111", "01111112", "01111113", "01111114", "01111115", "01111120",
         "01111121", "01111122", "01111123", "01111124", "01111130", "01111131",
         "01111132", "01111133", "01111134", "01111140", "01111141", "01111142",
         "01111143", "01111144"]

pprint(build_tree(codes))

rawDescription: Sorting 10k data set to the dict by child basis


code:
import xml.etree.ElementTree as ET
import copy

s = """<a>
   <b>
    <c>World</c>
   </b>
 </a>"""

file = ET.fromstring(s)
b = file.find("b")
for c in file.findall(".//c"):
    dupe = copy.deepcopy(c) #copy <c> node
    b.append(dupe) #insert the new node

print(ET.tostring(file))

rawDescription: How can I duplicate an xml element using Python?

description: Duplicate an xml element using Python


code:
from pyspark.ml.feature import RegexTokenizer

tokenizer = RegexTokenizer(
    inputCol="sentence", outputCol="words", pattern="\\W+")
tokenized = tokenizer.transform(df)

rawDescription: "normalize" dataframe of sentences into larger dataframe of words


code:
strs="4.00"
float(strs)
format(float(strs),".2f")
"{0:.2f}".format(float(strs))

rawDescription: Suggestions for parsing these data and rounding numbers


code: mylist = [sublist for sublist in oldlist if sublist]

rawDescription: dealing with an empty list inside a list

description: Dealing with an empty list inside a list


code:
broken_items = []
for ct in ContentType.objects.all():
    broken_items.extend(
        Generic.objects
        .filter(content_type=ct)
        .exclude(pk__in=ct.model_class.objects.all())
        .values_list('pk', flat=True))

rawDescription: Filter non-existing GenericForeignKey objects in Django queryset


code:
def matPlotSelected(self, qStandardItems):

    selModel = self.selectionModel()
    model = self.model()

    for item in qStandardItems:
        idx = model.indexFromItem(item)
        selModel.select(idx, selModel.Select)

rawDescription: QTableView item selection based on a QStandardItem data attribute


code:
soup_jazz = BeautifulSoup(page)
with open("jazz.csv", 'w') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow([u'Year Won', u'Category'])
    for year_cell in soup_jazz.find_all('td', class_='views-field-year'):
        year = year_cell and year_cell.text.strip().encode('utf8')
        if not year:
            continue
        category = next((e for e in year_cell.next_siblings
                         if getattr(e, 'name') == 'td' and
                            'views-field-category-code' in e.attrs.get('class', [])),
                        None)
        category = category and category.text.strip().encode('utf8')
        if year and category:
            csv_writer.writerow([year, category])

rawDescription: scraping site to move data to multiple csv columns

description: Scraping site to move data to multiple csv columns


code:
import base64
raw_data = base64.b64decode(data)
byting = GLib.Bytes(raw_data)
inputing = Gio.MemoryInputStream.new_from_bytes(byting)
image = GdkPixbuf.Pixbuf.new_from_data(inputing)
image_show_2.set_from_pixbuf(image)

rawDescription: Load image from base64 encoded image in Gtk3+


code:
from bs4 import BeautifulSoup, SoupStrainer # pip install beautifulsoup4

player_links = SoupStrainer('a', 'playerLink')
soup = BeautifulSoup(html, parse_only=player_links)
names = [a.get_text().strip()
         for a in soup.find_all(player_links) if 'subtab' not in a.attrs]
print(names)
# -> ['Russell, Addison', 'Vargas, Jason']

rawDescription: Parse 'a' tags based on attribute using Python and BeautifulSoup


code:
from os import chdir
chdir("C:/myOtherWork")

rawDescription: Python: changing IDLE's path in WIN7

description: Python: changing IDLE's path in WIN7


code: a.sort(key=lambda row:(row[0], row[2], row[3]))

rawDescription: Array Grouping and Identify in python

description: Array Grouping and Identify in python


code:
class Foo(object):
    def __init__(self, r, c):
        self.r = r
        self.c = c

    @property
    def cell(self):
        return var[self.r][self.c]

    @cell.setter
    def cell(self, val):
        var[self.r][self.c] = val

rawDescription: How to make two classes sharing a same attribute?

description: Make two classes sharing a same attribute


code: Object.getOwnPropertyNames({a: 10, b: 2});

rawDescription: How to find hidden properties/methods in Javascript objects?

description: Find hidden properties/methods in Javascript objects


code:
from datetime import datetime
import numpy
numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
numpy.__version__

rawDescription: Converting between datetime, Timestamp and datetime64


code:
from numpy.core.umath_tests import matrix_multiply
X = np.random.normal(size=(10,5,3))
Y = np.random.normal(size=(10,3,5))
Z1 = matrix_multiply(X,Y)
Z2 = np.array([np.dot(X[k],Y[k]) for k in range(10)])
np.allclose(Z1,Z2)  # <== returns True

rawDescription: find the dot product of sub-arrays in numpy

description: Find the dot product of sub-arrays in numpy


code:
header_text = soup.find(text=re.compile("Model Type "))
value = header_cell.find_next('tr').select('td:nth-of-type(3)')[0].get_text()

rawDescription: Using BeautifulSoup to pick up text in table, on webpages


code:
types = ['Small', 'Medium','Large']
print('Types: '+ types)
while True:
    ...

rawDescription: Best way to select from a list

description: Select from a list


code:
from collections import Counter
a = [10, 10, 10, 20, 20, 20, 30]
c = Counter(a)
# Counter({10: 3, 20: 3, 30: 1})

rawDescription: Python: Convert this list into dictionary


code:
import json

# p as path, gc as google analytics credentials
with open('/Path/To/Your/JSON/Goes/Here/google_analytics_accounts.json') as p:
    gc = json.load(p)
    p.close()

rawDescription: Pandas google analytics API - how to switch account?


rawDescription: Add two instances of my class

description: Add two instances of my class


code:
# a.py
print('hello world')

# b.py
print('goodbye world')
import a

rawDescription: Can I import a built-in module twice in both my script and custom module

description: Import a built-in module twice in both my script and custom module


code:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
b = np.array([[False,True,False],[True,False,False],[False,False,True]])
a[b]

rawDescription: Numpy selecting specific column index per row by using a list of indexes


code:
# m.py

__all__ = [
    "A_CONSTANT",
    "SomeClass",
]

A_CONSTANT = "foo"

class SomeClass: pass

rawDescription: Accessing the __all__ list of the parent module of a class instance


rawDescription: finding the number of grey levels

description: Finding the number of grey levels


rawDescription: How to evaluate the sum of values within array blocks

description: Evaluate the sum of values within array blocks


code: A.sum(axis=0, skipna=True)

rawDescription: Improving performance of operations on a NumPy array


code:
def newFunction(self, abc):
    self.abc = abc
    return self.abc

rawDescription: Adding functions from other files to a Python class


code:
class ThingForm(models.ModelForm):
  class Meta:
    model = Thing

  def __init__(self, *args, **kwargs):
    super(ThingForm, self).__init__(*args, **kwargs)
    self.fields['verb'].empty_label = None

rawDescription: Customize/remove Django select box blank option


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans, vq
from scipy.spatial.distance import cdist
data=np.array([   5,    1,  100,  102,    3,    4,  999, 1001,    5,    1,    2,    150,  180,  175,  898, 1012])
centroid,_ = kmeans(data, 3)
idx,_ = vq(data, centroid)
X=data.reshape(len(data),1)
Y=centroid.reshape(len(centroid),1)
D_k = cdist( X, Y, metric='euclidean' )
colors = ['red', 'green', 'blue']
pId=range(0,(len(data)-1))
cIdx = [np.argmin(D) for D in D_k]
dist = [np.min(D) for D in D_k]
r=np.vstack((data,dist)).T
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
mark=['^','o','>']
for i, ((x,y), kls) in enumerate(zip(r, cIdx)):
    ax.plot(r[i,0],r[i,1],color=colors[kls],marker=mark[kls])
    ax.annotate(str(i), xy=(x,y), xytext=(0.5,0.5), textcoords='offset points',
                 size=8,color=colors[kls])

ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel('Data')
ax.set_ylabel('Distance')
plt.show()

rawDescription: Ordered colored plot after clustering using python


code: seq = [SomeRandomObject() for i in range(100)]

rawDescription: Make python create a new object

description: Make python create a new object


code:
import os
if os.name != "posix":
    from win32com.shell import shellcon, shell
    homedir = "{}\\".format(shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0))
else:
    homedir = "{}/".format(os.path.expanduser("~"))

rawDescription: How to store variables/preferences in Python for later use

description: Store variables/preferences in Python for later use


rawDescription: Easiest way to create a scrollable area using wxPython?


code:
from multiprocessing import Process
import time

def f(name):
    print('hello', name)
    time.sleep(10)

def d(name):
    print('test2', name)
    time.sleep(10)

if __name__ == '__main__':
    p1 = Process(target=f, args=('bob',))
    p2 = Process(target=d, args=('alice',))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

rawDescription: Python multiple loops at the same time

description: Python multiple loops at the same time


code: url = base_url + link['href']

rawDescription: Making a vector from unformatted elements in Python


code:
import networkx as nx
G = nx.read_gml('t.gml')
G.node

rawDescription: Extracting data from a GML file

description: Extracting data from a GML file


code:
import sqlite3
from datetime import *

totalTime = datetime.now()
connection = sqlite3.connect('website.db', isolation_level=None)

sql = 'BEGIN IMMEDIATE TRANSACTION'
print(sql)
connection.execute(sql)

sql = 'INSERT INTO "Event" ("description", "date", "ip", "classtype") VALUES (?, ?, ?, ?)'
args = ('Sample event!', '2016-03-08 23:05:15.066742', '0.0.0.0', 'Event')
print(sql)
print(args)
connection.execute(sql, args)

sql = 'COMMIT'
print(sql)
connection.execute(sql)

totalTime = datetime.now() - totalTime
print(totalTime)

rawDescription: PonyORM, SQLite performance

description: PonyORM, SQLite performance


code: columns = row.split(',')

rawDescription: How to split string into collumn

description: Split string into collumn


code:
DEFAULT = object()
def foo(param=DEFAULT):
    if param is DEFAULT:
        ...

rawDescription: Python: how to check whether optional function parameter is set


code: merged = underlying.merge(options, left_on='0', right_on='0')

rawDescription: Merging two dataframes in pandas without column names (new to pandas)


code:
dfs = []

data = """\
num  a
101  0
102  1
103  0
104  0
105  1
106  1
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

data = """\
num  b
101  1
103  1
104  0
105  0
107  1
108  1
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

data = """\
num  c
102  0
103  0
104  1
105  1
106  1
107  1
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

data = """\
num  d
101  1
102  0
103  1
104  1
106  0
107  0
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

rawDescription: Merge of more than 2 python pandas data frames


code:
def enumerate_recursive(iter, base=()):
    for index, item in enumerate(iter):
        if isinstance(item, basestring):
            yield (base + (index,)), item
        else:
            for pair in enumerate_recursive(item, (base + (index,))):
                yield pair

def grep_index(filt, iter):
    return (index for index, text in iter if filt in text)

rawDescription: Grep multi-layered iterable for strings that match (Python)


code: any(item.startswith('C') for item in seto)

rawDescription: How can I tell if a string pattern exists within any element of a set in Python?

description: Tell if a string pattern exists within any element of a set in Python


code: frame.FieldOutput(name='works', description='this is a vector', type=VECTOR).addData(position=INTEGRATION_POINT, instance=grout_instance, labels=elementLabels, data=elementData)

rawDescription: Replacing State variable names in odb with python


rawDescription: Changing column headers after plotting table using Qt4


code:
df['arg-sort'] = df.groupby(level='A')['C'].apply(pd.Series.argsort)
f = lambda obj: obj.iloc[obj.loc[::-1, 'arg-sort'], :]
df.groupby(level='A', group_keys=False).apply(f)

rawDescription: Sorting a multi-index while respecting its index structure


code: employees2 = [line for line in employees if line[1] == "Professor"]

rawDescription: Trying to filter a list to bring back lines with a specific word


rawDescription: Django ManyToManyField in action

description: Django ManyToManyField in action


code:
output = "\"\\u001b[H\\u001b[2J\\r\\nPROCESS1       : process not running\\r\\n \\r\\nPROCESS2       : process running\\r\\nT\""
output.split('\\r\\n', maxsplit=1)[-1]

rawDescription: Unicode - Just print the string

description: Unicode - Just print the string


code:
class Event:
  def __init__(self, start_time, end_time):
    self.start_time = start_time
    self.end_time = end_time

  def __lt__(self,):
    pass

rawDescription: Schedule datetime intervals via different skipping methods


code:
if x not in my_queue:
    my_queue.put(x)

rawDescription: Check if element is already in a Queue

description: Check if element is already in a Queue


code: return tuple(parts)

rawDescription: Delete unusable characters or data in archive with python


code:
def get_odds(items):
    new_list = []
    for item in items:
        if item % 2 == 1:
            new_list.append(item)
    return new_list

rawDescription: Checking odd numbers python

description: Checking odd numbers python


rawDescription: In Python/OpenCV is there a way to quickly scroll through frames of a video, allowing the user to select the start and end frame to be processed?


code:
from ctypes import *
cmax = cdll.LoadLibrary('./test.dll').max
cmax.argtypes = [c_int, c_int] # arguments types
cmax.restype = c_int           # return type, or None if void
cmax(4, 7)

rawDescription: How to call C++ functions of a class from a Python

description: Call C++ functions of a class from a Python


rawDescription: How to round an RGB value to the closest web safe value with PIL (Python Imaging Library)?

description: Round an RGB value to the closest web safe value with PIL (Python Imaging Library)


code:
'''
Created on Apr 23, 2016

@author: billal begueradj
'''
from tkinter import *
class BlackjackTable:
    def __init__(self,numPlayers):
        self.numPlayers=numPlayers
        self.tableWindow=Tk()
        self.bettedE=False
        self.bettedS=False
        self.bettedW=False
        self.suitWindow()
    def suitWindow(self):
        self.tableWindow.title("Blackjack Table")
        self.tableWindow.config(bg="dark green")

        self.EHandEntry=Entry(self.tableWindow,fg="white",bg="dark green",width=10)
        self.EHandEntry.grid(row=5,column=9)

        self.EHandSubmit=Button(self.tableWindow,text="Bet",fg="white",padx=15,pady=5,command=self.betE,bg="dark green",activebackground="dark green",activeforeground="white")
        self.EHandSubmit.grid(row=5,column=10)

        self.SHandEntry=Entry(self.tableWindow,fg="white",bg="dark green",width=10)
        self.SHandEntry.grid(row=8,column=6)

        self.SHandSubmit=Button(self.tableWindow,text="Bet",fg="white",padx=15,pady=5,command=self.betST,bg="dark green",activebackground="dark green",activeforeground="white")
        self.SHandSubmit.grid(row=8,column=7)
        self.WHandEntry=Entry(self.tableWindow,fg="white",bg="dark green",width=10)
        self.WHandEntry.grid(row=5,column=3)

        self.WHandSubmit=Button(self.tableWindow,text="Bet",fg="white",padx=15,pady=5,command=self.betW,bg="dark green",activebackground="dark green",activeforeground="white")
        self.WHandSubmit.grid(row=5,column=4)
    def betE(self):
        print("betE")
        self.bettedE=True
        self.EHandSubmit.destroy()
        self.EHandEntry.destroy()

    def betST(self):
        print("betST")
        self.bettedS=True
        self.SHandSubmit.destroy()
        self.SHandEntry.destroy()

    def betW(self):
        print("betW")
        self.bettedW=True
        self.WHandSubmit.destroy()
        self.WHandEntry.destroy()

gui=BlackjackTable(3)
mainloop()

rawDescription: destroy() not destroying on repeats

description: Destroy() not destroying on repeats


code:
items = (layout.itemAt(i) for i in range(layout.count()))
for w in items:
   doSomething(w)

rawDescription: Loop over widgets in PyQt Layout

description: Loop over widgets in PyQt Layout


code:
def check_sudoku(n):
    return not any(n[0][i] == n[s][i] for i in range(len(n)) for s in range(1, len(n)))

rawDescription: why doesnt this double loop work?

description: Why doesnt this double loop work


code:
import re

re.split('(?<=>)\s+(?=<)', line)

rawDescription: splitting line in python

description: Splitting line in python


code:
#!/usr/bin/env python
from datetime import datetime
import pandas as pd

print(pd.read_csv(
    'input.txt', sep=r'\s+', parse_dates=[[0, 1, 2]],
    date_parser=lambda *columns: datetime(2005, *map(int, columns)),
    index_col=0))

rawDescription: Pandas: create timestamp from 3 columns: Month, Day, Hour


rawDescription: Execute a function randomly

description: Execute a function randomly


rawDescription: Weighted random from int list

description: Weighted random from int list


code:
exl_set = set()
exl_set.add(a.node)
exl_set.add(b.node)

rawDescription: What is the best practice to add tuples to a set?


rawDescription: split list by certain repeated index value

description: Split list by certain repeated index value


code:
intval = 42
strVal = "The value of intVal is %d" % (intVal)

rawDescription: Passing argument to python which is half "<direct string>" and half value of a variable


code: (lambda result: print(result) if result else None)(function_call(params))

rawDescription: Alternatives for 3 lines of java-like code?


code:
def urlopen(url, data=None, timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
    ...
    return _opener.open(url, data, timeout)

rawDescription: how do i set a timeout value for python's mechanize?

description: Set a timeout value for python's mechanize


code:
for item in s.split(' '):
    n = random.randint(0,1)
    if '[name]' in item:
        misspelled_list.append(item)
    elif n == 1:
        misspelled_list.append(misspeller(item))
    else:
        misspelled_list.append(item)

rawDescription: Place random character in string if not a certain word


code:
for b in range(length_spread):
    data = read_spread[b].rstrip('\n')
    splitted = data.split(',')
    plot_id = splitted[1]  # Can keep it as a string

    filename = 'plot_id_' + plot_id + '.file_extension'
    spreadsheet = some_open_method(filename, option='append')
    spreadsheet.writelines('%s\n\n\n\n\n' % splitted)
    spreadsheet.close_method()

rawDescription: Iterate through a loop to change a conditional statement, python


code:
Overlap = (M * T.transpose() > 0)  # track T overlaps mask M
Connected = (Overlap * Overlap.tranpose() > 0) # Connected masks
Density[mask_idx] = numpy.take(T, nonzero(Overlap[mask_idx, :])[0], axis=0).sum(axis=0)

rawDescription: More efficient way to count intersections?


code:
initial_time = 12.0
w += initial_time - min(w)

rawDescription: Matplotlib axis tickmarker alteration

description: Matplotlib axis tickmarker alteration