code:
from struct import *
mode = pack("h", 42) # 'h' == short

rawDescription: Creating Twisted TCP socket and sending test value


code:
doc = BeautifulSoup(html, 'lxml')
print(doc.prettify())
doc = BeautifulSoup(html, 'html5lib')
print(doc.prettify())

rawDescription: BeautifulSoup - proper way of dealing with self-closing tags


code:
def minimum(y,var):
    for y in var:
        w=(var[0],var[1],var[2],var[3],var[4])
        a= min(var[0],var[1],var[2],var[3],var[4])

    return a

def menu(x,var):
    if x == 1:
        make_table(var)
    if x == 2:
        y = raw_input("enter a row (as a number) or a column (as an uppercase letter)")
        if y in [ '1','2','3']:
            mini = minimum(y, var)
            print("Minimum is:", mini) # dont need this.
            print("Minimum is:", min(var)) # this should be all you really need.
    if x == 3:
        print ('bye')

menu(2,[1,2,3,4,5]) # calling the menu function

rawDescription: i have a list of number that come from function [1,2,3,4....] and i need to find min out of them in different function

description: I have a list of number that come from function [1,2,3,4....] and i need to find min out of them in different function


rawDescription: Regex: match two occurrences of the same unknown substring


code:
options, args = parser.parse_args()
option_dict = vars(options)

rawDescription: Python optparse Values Instance

description: Python optparse Values Instance


code:
#at time 20 generate a request event
import simpy
class TrainStation:
    def __init__(self,env):
        self.env= env
        self.request_event = env.event()
        self.request_receiver_process = env.process(self.receive_request())
        self.request_producer_process = env.process(self.produce_request())

    def produce_request(self):
        yield self.env.timeout(20)
        self.request_event.succeed()
        self.request_event = self.env.event()

    def receive_request(self):
        print("Waiting for request at time: {0}".format(env.now))
        yield self.request_event
        print("Request received at time: {0}".format(env.now))

env = simpy.Environment()
trainStation = TrainStation(env)
env.run()

rawDescription: How to schedule a request at a particular time?

description: Schedule a request at a particular time


code: ax1.text(.60, .06, r'Hello', transform=ax1.transAxes)

rawDescription: Text in legend for matplotlib plot

description: Text in legend for matplotlib plot


code:
def dragMoveEvent(self, event):
        super(SpecialTreeWidget, self).dragMoveEvent(event)
        mDropItem = self.itemAt(event.pos())
        if mDropItem:
            if mDropItem.scriptMenuData["drop"]:
                event.accept()
            else:
                event.ignore()
        else:
            event.accept()

rawDescription: PySide how to get a target on dropEvent

description: PySide how to get a target on dropEvent


code: ' '.join(A).replace(' C', '\nC')

rawDescription: Joining of strings in a list

description: Joining of strings in a list


code:
def GetCustomData(request):
    if request.method == 'POST':
        request.session['custom_date'] = ' '.join(
            request.POST['custom_date_day'],
            request.POST['custom_date_month'],
            request.POST['custom_date_year']
        )
    custom_date = request.session.setdefault('custom_date', '1 1 2015')
    date_reformat = datetime.datetime.strptime(custom_date, '%d %m %Y')
    chart_date = date_reformat.strftime('%-d %b %Y')
    return render(request, 'custom_results.html', {'cdate': chart_date})

rawDescription: python view not working after deploying django app

description: Python view not working after deploying django app


code:
import lxml.etree as ET

content = '''\
<Envelope xmlns="http://www.xxx.com/zzz/yyy">
  <Header>
    <Version>1</Version>
  </Header>
  <Buckets>
    some stuff
  </Buckets>
</Envelope>
'''
root = ET.fromstring(content)
print(root.xpath("./*[local-name()='Buckets']"))
# [<Element {http://www.xxx.com/zzz/yyy}Buckets at 0xb73a62ac>]

rawDescription: Wildcard namespaces in lxml

description: Wildcard namespaces in lxml


code:
class UserProfile(models.Model):
    user = OneToOneField(User, related_name="profile")
    # add profile fields here, e.g.,
    nickname = CharField(...)

# usage: no get_profile() needed. Just standard 1-to-1 reverse syntax!
nickname = request.user.profile.nickname

rawDescription: Get rid of get_profile() in a migration to Django 1.6


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

fig,ax = plt.subplots(1)

ax.plot(np.arange(5),np.arange(5),'bo-',label='plot1')
ax.errorbar(np.arange(5),np.arange(1,6),yerr=1,marker='s',color='g',label='errorbar')
ax.plot(np.arange(5),np.arange(2,7),'ro-',label='plot2')

handles,labels = ax.get_legend_handles_labels()

handles = [handles[0], handles[2], handles[1]]
labels = [labels[0], labels[2], labels[1]]

ax.legend(handles,labels,loc=2)
plt.show()

rawDescription: Order in legend plots python

description: Order in legend plots python


code: import foo

rawDescription: How to package a python program

description: Package a python program


code: df['WEEKDAY'] = ((pd.DatetimeIndex(df.index).dayofweek) // 5 == 1).astype(float)

rawDescription: Convert dataframe date row to a weekend / not weekend value


code:
import webapp2
import json

class MainPage(webapp2.RequestHandler):
    def post(self):
        self.response.out.write("This is a POST Request \n")
        req = self.request
        a = req.body
        b = json.loads(a)

        self.response.out.write(b)
        self.response.out.write(b['reg_id'])
        self.response.out.write(b['datetime'])
        self.response.out.write(type(b))

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

rawDescription: Python Google App Engine Receiving a string in stead of JSON object


code:
import csv
from itertools import izip

with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(izip(bins, frequencies))

rawDescription: How to write data from two lists into columns in a csv?

description: Write data from two lists into columns in a csv


code:
from sympy.plotting import plot_implicit
from sympy.parsing.sympy_parser import parse_expr

def ezplot(s):
    #Parse doesn't parse = sign so split
    lhs, rhs = s.replace("^","**").split("=")
    eqn_lhs = parse_expr(lhs)
    eqn_rhs = parse_expr(rhs)

    plot_implicit(eqn_lhs-eqn_rhs)

ezplot('x^2 + y^2 = y + 5')

rawDescription: Plot arbitrary 2-D function in python/pyplot like Matlab's Ezplot


rawDescription: Remove elements from list preceded by some specific element


code:
def allOneOf(items, ids):
    first = items[0]
    if first in ids and all(i==first for i in items):
        return first
    else:
        raise TypeError()

assert_all_zero_or_one = (lambda vector: allOneOf(vector, set([0,1])))

rawDescription: python: best way to verify conditions and raise Exception

description: Python: best way to verify conditions and raise Exception


code:
from itertools import count

def next_available(base):
    for ext in count(start=1):
        name = '{}.{:03d}'.format(base, ext)
        if not os.path.exists(name):
            return name

rawDescription: Elegant & short (pythonic) way to find the lowest unused number


code: re.findall(r'#\w+', data)

rawDescription: parsing strings with non alphanumeric characters in python

description: Parsing strings with non alphanumeric characters in python


code: re.split(r'\s(?=\w+:)', post)

rawDescription: python regex split string while keeping delimiter with value

description: Python regex split string while keeping delimiter with value


code:
class AboutRequestHandler(BaseHandler):
    """
    Handler to show the about page
    """

    def get(self):
        """ Returns a simple HTML form for about."""
        return self.render_template('about.html')

rawDescription: Google App Engine Boilerplate help - How does it direct templates to URL path


code:
class Client(Thread):

    def __init__(self, serv):
        Thread.__init__(self)
        self.serv = serv
        self.inq = Queue()   # declares a queue for the client

    def run(self):
        self.serv.inq.put(("Hi", self.inq))  # send a message, and pass along a response address
        resp = self.inq.get()    # get the response
        print("Got: ", resp)

class Server(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.inq = Queue()  # declare a queue for the server

    def run(self):
        while True:
            req = self.inq.get()   # get a message from input queue
            if not req:
                break
            msg, clientq = req    # parse the message
            # other processing
            clientq.put("From serv: " + msg)  #send back a response

rawDescription: Python , multithreading with Queue

description: Python , multithreading with Queue


code:
def create_image(width, height, path):
    img = QtGui.QImage(width, height, QtGui.QImage.Format_RGB32)
    img.fill(QtCore.Qt.red)
    img.save(path, 'JPG')

rawDescription: Procedurally Create-Generate a Raster Image with PyQt


code:
class applicant(admin.ModelAdmin):

    model = Job
    list_display = ('Job_Position')
    list_filter = ['Job_Position', 'Job_Posting__fkey']
    inlines = [jobs]

rawDescription: Django: add a list filter option to filter related models under parent model


code: items = Item.objects.filter(customer_items__customer=customer, customer_items__item_count__gt = 0)

rawDescription: Filter on ManyToManyField intermediate table fields


code:
import time
subprocess.call("pip install phpserialize &> /dev/null 2>&1", shell=True)
subprocess.call("pip install requests &> /dev/null  2>&1", shell=True)
subprocess.call("apt-get install git -y &> /dev/null 2>&1", shell=True)
time.sleep(5)
import phpserialize
import requests
from phpserialize import serialize
from phpserialize import unserialize

def checktext():
    text = raw_input("\n\n\nEnter your text:")
    return text

itext = checktext()

rawDescription: Python console output gets overwritten in Debian 6


code:
import sys
if sys.version_info[0] < 3:
    raise "Must be using Python 3"

rawDescription: Detect Python version at runtime

description: Detect Python version at runtime


code:
import numpy as np
from scipy.stats import truncnorm, norm

a_s = np.random.uniform(0, 1, size=100)
b_s = a_s + 0.2

cdf_start = norm.cdf(a_s)
cdf_stop = norm.cdf(b_s)
cdf_samples = np.random.uniform(0, 1, size=(100, 100))
cdf_samples *= (cdf_stop - cdf_start)[:, None]
cdf_samples +=  cdf_start[:, None]
truncnorm_samples = norm.ppf(cdf_samples)

rawDescription: Vectorised code for sampling from truncated normal distributions with different intervals


code:
for row in range(self._rows):
    for col in range(self._cols):
        ...
for row in range(self._rows):
    self._root_window.grid_rowconfigure(row, weight=1)
for col in range(self._cols):
    self._root_window.grid_columnconfigure(col, weight=1)

rawDescription: Tkinter canvas does not resize properly

description: Tkinter canvas does not resize properly


code:
# in your settings.py:
THUMBNAIL_BACKEND = 'path.to.MyThumbnailBackend'

#some module, in one of yours apps:
from sorl.thumbnail.base import ThumbnailBackend
from sorl.thumbnail.conf import settings
from sorl.thumbnail.helpers import tokey, serialize

class MyThumbnailBackend(ThumbnailBackend):
    def _get_thumbnail_filename(self, source, geometry_string, options):
        """
        Computes the destination filename.
        """
        key = tokey(source.key, geometry_string, serialize(options))
        # make some subdirs
        path = '%s/%s/%s' % (key[:2], key[2:4], key)
        return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path,
                            EXTENSIONS[options['format']])

rawDescription: How can change or override sorl-thumbnail cache path and add image with absolute path?


code:
class PickleableFile(object):
    def __init__(self, filename, mode='rb'):
        self.filename = filename
        self.mode = mode
        self.file = open(filename, mode)
    def __getstate__(self):
        state = dict(filename=self.filename, mode=self.mode,
                     closed=self.file.closed)
        if not self.file.closed:
            state['filepos'] = self.file.tell()
        return state
    def __setstate__(self, state):
        self.filename = state['filename']
        self.mode = state['mode']
        self.file = open(self.filename, self.mode)
        if state['closed']: self.file.close()
        else: self.file.seek(state['filepos'])
    def __getattr__(self, attr):
        return getattr(self.file, attr)

class WordWindowReader:
    def __init__(self, filenames, window_size):
        self.filenames = filenames
        self.window_size = window_size
        self.filenum = 0
        self.stream = None
        self.filepos = 0
        self.prevwords = []
        self.current_line = []

    def __iter__(self):
        return self

    def next(self):
        # Read through files until we have a non-empty current line.
        while not self.current_line:
            if self.stream is None:
                if self.filenum >= len(self.filenames):
                    raise StopIteration
                else:
                    self.stream = PickleableFile(self.filenames[self.filenum])
                    self.stream.seek(self.filepos)
                    self.prevwords = []
            line = self.stream.readline()
            self.filepos = self.stream.tell()
            if line == '':
                # End of file.
                self.stream = None
                self.filenum += 1
                self.filepos = 0
            else:
                # Reverse line so we can pop off words.
                self.current_line = line.split()[::-1]

        # Get the first word of the current line, and add it to
        # prevwords.  Truncate prevwords when necessary.
        word = self.current_line.pop()
        self.prevwords.append(word)
        if len(self.prevwords) > self.window_size:
            self.prevwords = self.prevwords[-self.window_size:]

        # If we have enough words, then return a word window;
        # otherwise, go on to the next word.
        if len(self.prevwords) == self.window_size:
            return self.prevwords
        else:
            return self.next()

rawDescription: Singleton python generator? Or, pickle a python generator?


code:
def setattr_deco(setattr_func):
    def setattr_wrapper(self, attr, value):
        if attr in self._descriptors:
            return object.__setattr__(self, attr, value)
        return setattr_func(self, attr, value)
    return setattr_wrapper

class MiscSetattr(type):
    def __new__(metacls, name, bases, dct):
        descriptors = set()
        for key, obj in dct.items():
            if key == "__setattr__":
                dct[key] = setattr_deco(obj)
            elif hasattr(obj, "__get__"):
                descriptors.add(key)
        dct["_descriptors"] = descriptors
        return type.__new__(metacls, name, bases, dct)

# and use MiscSetattr as metaclass for your classes

rawDescription: Using both __setattr__ and descriptors for a python class


code:
[...]
go = self.builder.get_object
self.window = go('window')
self.my_foobar = go('my_foobar')
[...]

rawDescription: Python + Glade + PyGObject. How can I get the value of two text fields at once?


code: chromo[gene1Pos], chromo[gene2Pos] = chromo[gene2Pos], chromo[gene1Pos]

rawDescription: Exchange position of 2 array elements in Python


code:
from subprocess import call
call(['someAppName', 'someArg'])

rawDescription: use Python to call a executable file and run commands of that file

description: Use Python to call a executable file and run commands of that file


code:
from sympy import I, solve
from sympy.abc import x, y
solve(x**4-1, x)

rawDescription: Equation solver in Python

description: Equation solver in Python


code:
from itertools import product
[''.join(i) for i in product(base_urls, to_append)]

rawDescription: Map an array to each item in another array? (Python)


rawDescription: Divide list and append the list to separate lists python


code:
import datetime
a = datetime.datetime(2012, 10, 15, 1, 0, 0)
a.time
a.time()

rawDescription: Comparing time in a datetime object python


code:
np.savetxt("foo.csv", x, delimiter=",", header="ID,AMOUNT",
           fmt="%i", comments='')

rawDescription: python numpy.savetxt header has extra character #

description: Python numpy.savetxt header has extra character #


rawDescription: How to delete a value from 'ValuesListQuerySet' in django?

description: Delete a value from 'ValuesListQuerySet' in django


code:
t = locals().copy()
for name, value in t.iteritems():
  setattr(module, name, value)

rawDescription: how to get variable's name?

description: Get variable's name


code:
from pydub import AudioSegment

sound1 = AudioSegment.from_mp3("/path/to/file1.mp3")
sound2 = AudioSegment.from_mp3("/path/to/file1.mp3")

# mix sound2 with sound1, starting at 5000ms into sound1)
output = sound1.overlay(sound2, position=5000)

# save the result
output.export("mixed_sounds.mp3", format="mp3")

rawDescription: How do I mix audio files using python?

description: Mix audio files using python


code:
import csv
writer = csv.writer(open("out.csv", "wb"), quoting=csv.QUOTE_NONE)
reader = csv.reader(open("in.csv", "rb"), skipinitialspace=True)
writer.writerows(reader)

rawDescription: Python CSV: Remove quotes from value

description: Python CSV: Remove quotes from value


code:
def on_done(self, Regex):
    self.window.set_layout({
        "cols": [0, 0.5, 1],
        "rows": [0.0, 0.33, 0.66, 1.0],
        "cells": [ [0, 0, 1, 3], [1, 0, 2, 1], [1, 1, 2, 2], [1, 2, 2, 3]]
            })
    # For each of the new groups call putHello (self.window.num_groups() = 4)
    for numGroup in range(self.window.num_groups()):
        # If the group is empty (has no views) then we create a new file (view) and insert the text hello
        if len(self.window.views_in_group(numGroup)) == 0:
            self.window.focus_group(numGroup) # Focus in group
            createdView = self.window.new_file() # New view in group
            createdView.run_command("insert",{"characters": "Hello"}) # Insert in created view

rawDescription: Insert text into view in sublime 3 api

description: Insert text into view in sublime 3 api


code:
class GenericFile: # general file class
    # bunch of methods here
    ...
    def insert(self, db):
        return db.insert_generic_file_object(self)

class SomeFileObject_A: # low level class for storing objects of kind SomeFileObject_A
    # bunch of methods here
    ...
    def insert(self, db):
        return db.insert_file_object_a(self)

class SomeFileObject_B: # low level cass for storing objects of kind SomeFileObject_A
    # bunch of methods here
    ...
    def insert(self, db):
        return db.insert_file_object_b(self)

class Database:
    def insert(self, obj):
        return obj.insert(self)

rawDescription: Is usage of isinstance is justified when calling different methods by passed object


code: result = string.replace("\\","")

rawDescription: how to replace back slash character with empty string in python

description: Replace back slash character with empty string in python


code:
class C(object):
  def __new__(cls, ref):
    if isinstance(ref, C):
      return ref
    else:
      return super(C, cls).__new__(cls)

  def __init__(self, ref):
    if self is not ref:
      self.x = ref

c1=C(7)
c2=C(13)
assert c1 is not c2
c3=C(c1)
assert c1 is c3

rawDescription: Identity after passing an immutable Python object to its constructor


code:
class Vector(object):
    """
    >>> Vector(angle, speed)  # initialize with angle and speed
    >>> Vector(x, y, speed)   # or initialize with x, y, and speed
    """
    def __init__(first, second, third=None):
        if third is None:
            angle, speed = first, second
        else:
            x, y, speed = first, second, third

rawDescription: How would I create a 2d vector object that could be initialized with an x and a y or an angle in degrees?


code:
def main():
    number = int(sys.argv[1])  # this line will fail if you pass an argument that's not an integer
    print(number)

if __name__ == "__main__":
    main()

rawDescription: How to send in command line arguments for a python file execution in command line?

description: Send in command line arguments for a python file execution in command line


code:
# put the frame in its parent
frame.pack()

# tell frame not to let its children control its size
frame.pack_propagate(0)

# put the textbox in the frame
textBox.pack()

rawDescription: tkinter's .pack_propagate() method

description: Tkinter's .pack_propagate() method


code:
element = browser.find_elements_by_css_selector('.tl-cell.tl-popularity')
text = element.get_attribute('data-tooltip')

rawDescription: Alter XPath to Extract Text Selenium

description: Alter XPath to Extract Text Selenium


code: metrospot['Postal Code'] = metrospot['Postal Code'].str.replace(" ","")

rawDescription: Pandas Column Value Replacement confusing behaviour.


code:
def __getattr__(self, tag):
    u"""Return the (first) child with the given tag name.  If no namespace
    is provided, the child will be looked up in the same one as self.
    """
    if is_special_method(tag):
        return object.__getattr__(self, tag)
    return _lookupChildOrRaise(self, tag)

rawDescription: dir(element) returns non-existing element. Trying to use getattr(element, ...) fails

description: Dir(element) returns non-existing element. Trying to use getattr(element, ...) fails


code:
import sublime, sublime_plugin
from subprocess import call

class TestCommand(sublime_plugin.ApplicationCommand):
    def __init__(self):
        super(TestCommand, self).__init__()
        #do your stuf here
        # call(["node", "app.js", "../User/"], Shell=true)
        call(["ping", "192.168.1.1"])

    def run(self, edit):
        pass

rawDescription: Sublime Text 2 API ability to run nodejs script on editor start


code:
from django.contrib import admin

class CustomerDataInline(admin.StackedInline):
    model = CustomerData

class CustomersAdmin(admin.ModelAdmin):
    inlines = [CustomerDataInline,]

admin.site.register(Customers, CustomersAdmin)

rawDescription: Using joined results for Django model with legacy database schema


code: data = pack('>i', len(arr)) + arr.tostring()

rawDescription: Using python's pack with arrays

description: Using python's pack with arrays


code:
for key in [key4, key5, key6, key7]:
    if mydict[key] == valueB:
        pass # do stuff here

rawDescription: Python: using only certain keys in a dictionary for a for-loop


code:
class HopBill(object):
   def __init__(self):
       self.hop_list = []
   def add(self, hop):
      self.hop_list.append(hop)
   def addnew(self, variety, aa, qty, time):
      hop = Hop(variety, aa, qty, time)
      self.add(hop)

rawDescription: Brain stuck on overloading, How can I do this like a pythonista?


code: list(g)

rawDescription: How to convert a namedtuple into a list of values and preserving the order of properties?

description: Convert a namedtuple into a list of values and preserving the order of properties


code:
class CombinedFormSet(BaseInlineFormSet):
    # Validate formset data here
    def clean(self):
        super(CombinedFormSet, self).clean()
        for form in self.forms:
            if not hasattr(form, 'cleaned_data'):
                continue

            data = self.cleaned_data
            valid = False
            for i in data:
                if i != {}:
                    if i['is_correct']:
                        valid = True

            if not valid:
                #TODO: translate admin?
                raise forms.ValidationError("A Question must have an answer.")

            # Always return the cleaned data, whether you have changed it or
            # not.
            return data

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 4
    formset = CombinedFormSet

rawDescription: How to use admin.TabularInline in a ModelForm

description: Use admin.TabularInline in a ModelForm


code:
import matplotlib.pyplot as plt

plt.figure()
plt.axvline(x=0.2)
plt.axvline(x=0.5)
plt.show()

rawDescription: How to add a line parallel to y axis in matplotlib?

description: Add a line parallel to y axis in matplotlib


rawDescription: Python: retrieve values after index in each column of table


code:
# define your base directory
# It will be `absolute/path/to/demo3`
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'
# define where your static files will be collected
# It will be `absolute/path/to/demo3/static`
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# keep it empty for the moment
STATICFILES_DIRS = (
)

rawDescription: STATIC_ROOT setup in Django 1.8

description: STATIC_ROOT setup in Django 1.8


rawDescription: Get XPath of parent

description: Get XPath of parent


code:
num = input("Please enter an integer: ")
try:
    num = int(num)
except ValueError:
    print("Error,", num, "is not a number.")

rawDescription: converting logic tests into try statements (python3)

description: Converting logic tests into try statements (python3)


code:
l = [1, 2, 1, 10, 2, 1, 3, 10]
exclusions = [1, 2]
[el if el not in exclusions else 0 for el in l]

rawDescription: How to make denial of the list of items?

description: Make denial of the list of items


code:
from collections import defaultdict

time=[1,2,3,3]
cf=[100,500,1000,-500]

result = defaultdict(int)

for num,i in enumerate(time):
    result[i] += cf[num]

time2 = list(result.keys())
cf2 = list(result.values())

rawDescription: Creating a net cash flow

description: Creating a net cash flow


code:
@property
def last_readings(self):
    sub = object_session(self) \
           .query(Reading.value, Reading.value_type.label('value_type')) \
           .filter(Reading.sensor_id == self.id) \
           .order_by(Reading.timestamp.desc()).subquery()
    return object_session(self).query(sub).group_by(sub.c.value_type)

rawDescription: Get latest Reading value of each type for a Sensor in SQLAlchemy


code:
for word in file:
    if isinstance(word, int):
        ...
    elif isinstance(word, list):
        ...
    elif isinstance(word, tuple):
        ...
    elif isinstance(word, str):
        ...

rawDescription: how to check str int list and tuple?

description: Check str int list and tuple


code:
def f(s, n):
    return ' '.join(s.split()[:n])

rawDescription: How do I trim the number of words in Python?

description: Trim the number of words in Python


code:
import zipfile, zlib, binascii, struct
class BufferedZipFile(zipfile.ZipFile):
    def writebuffered(self, zipinfo, buffer):
        zinfo = zipinfo

        zinfo.file_size = file_size = 0
        zinfo.flag_bits = 0x00
        zinfo.header_offset = self.fp.tell()

        self._writecheck(zinfo)
        self._didModify = True

        zinfo.CRC = CRC = 0
        zinfo.compress_size = compress_size = 0
        self.fp.write(zinfo.FileHeader())
        if zinfo.compress_type == zipfile.ZIP_DEFLATED:
            cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
        else:
            cmpr = None

        while True:
            buf = buffer.read(1024 * 8)
            if not buf:
                break

            file_size = file_size + len(buf)
            CRC = binascii.crc32(buf, CRC) & 0xffffffff
            if cmpr:
                buf = cmpr.compress(buf)
                compress_size = compress_size + len(buf)

            self.fp.write(buf)

        if cmpr:
            buf = cmpr.flush()
            compress_size = compress_size + len(buf)
            self.fp.write(buf)
            zinfo.compress_size = compress_size
        else:
            zinfo.compress_size = file_size

        zinfo.CRC = CRC
        zinfo.file_size = file_size

        position = self.fp.tell()
        self.fp.seek(zinfo.header_offset + 14, 0)
        self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size))
        self.fp.seek(position, 0)
        self.filelist.append(zinfo)
        self.NameToInfo[zinfo.filename] = zinfo

rawDescription: Create a zip file from a generator in Python?


code:
tags = ['x', 'y']
events = events = Event.objects.all()
for tag in tags:
    events = events.filter(tags__name=tag)

rawDescription: How to filter the events based on the tags entered?

description: Filter the events based on the tags entered


code:
def create_cert():
    cert = crypto.X509()
    cert.set_serial_number(serial_no)
    cert.gmtime_adj_notBefore(notBeforeVal)
    cert.gmtime_adj_notAfter(notAfterVal)
    cert.set_issuer(caCert.get_subject())
    cert.set_subject(deviceCsr.get_subject())
    cert.set_pubkey(deviceCsr.get_pubkey())
    cert.sign(CAprivatekey, digest)
    return cert

rawDescription: Sign CSR from client using CA root certificate in python


code:
m0 = scipy.sparse.csc_matrix([1])
m0.getformat()
m1 = scipy.sparse.csr_matrix([1])
m1.getformat()

rawDescription: Checking if a scipy sparse matrix is CSC or CSR


code:
from lxml import etree

parser = etree.XMLParser(remove_comments=False)
tree = etree.parse('input.xml', parser=parser)
# or alternatively set the parser as default:
# etree.set_default_parser(parser)

rawDescription: How to prevent xml.ElementTree fromstring from dropping commentnode

description: Prevent xml.ElementTree fromstring from dropping commentnode


code:
for aa in amminoacids:
    if distance(aa,referenceAA) == referenceDistance:
        aaCandidates.append(aa)

if not aaCandidates:
    return 'some default choice'

luckyAA = choice(aaCandidates)
return luckyAA

rawDescription: how to handle an empty list, python3

description: Handle an empty list, python3


rawDescription: payroll program, need help simply a patterned event, new to python

description: Payroll program, need help simply a patterned event, new to python


code: set(x**2 for x in range(5))

rawDescription: How to add generator elements to a set() without a loop?

description: Add generator elements to a set() without a loop


rawDescription: Print the concatenation of the digits of two numbers in Python


code: min(my_list, key=lambda x: x[0])

rawDescription: Python, min among first objects in lists


code:
C1 = Cookie.SimpleCookie()
C1["emailAddress"] = self.request.get('emailAddress')
C2 = Cookie.SimpleCookie()
C2["secretCode"] = self.request.get('secretCode')
C2["secretCode"]["path"] = "/"
self.response.headers.add_header("Set-Cookie", C1.output(header=''))
self.response.headers.add_header("Set-Cookie", C2.output(header=''))

rawDescription: GAE: Setting multiple cookies (or a multi-value cookie) with SimpleCookie


code:
def solve(m, y):
    v = [0 for i in xrange(len(m))]
    for i in xrange(len(m)):
        v[i] = (y[i] - v.dotProduct(m[i]))/float(m[i][i])

    return v

rawDescription: Forward substitution of lower triangular matrix. How?


code:
simple_url_re = re.compile(r'^(https?)?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)$', re.IGNORECASE)

if simple_url_re.match(text) or simple_url_2_re.match(text):
    raise ValidationError

rawDescription: Django - Filter URL in texts

description: Django - Filter URL in texts


code:
x = b.map(func1, b)
y = b.map(func2, b)
compute(x.frequencies(), b.frequencies())

rawDescription: When are generators converted to lists in Dask?


code:
df
df['Time'] = df.index.asi8
dist = df.diff().fillna(0.)
dist['Dist'] = np.sqrt(dist.X**2 + dist.Y**2)
dist['Speed'] = dist.Dist / (dist.Time / 1e9)
dist

rawDescription: Calculate speed from timestamped positions in Pandas.DataFrame


code:
jsonstring = open('myfile.json').read()
data = eval(jsonstring)

rawDescription: Parse json file with ironpython 2.5

description: Parse json file with ironpython 2.5


code:
if len(x) > len(set(x)):
   pass # do something

rawDescription: Checking if all elements in a list are unique


code:
while True:
    if io.input(door_pin):
        print("DOOR Open!")
        while io.input(door_pin):
            pass # do nothing - the door is still open
    # now continue doing whatever you want after the door is closed again

rawDescription: Python while loop, pause while not, continue again when true?


code:
p = subprocess.Popen(["./pmm"], shell=False, stdout=subprocess.PIPE)
output = p.stdout.read()

rawDescription: Executing a command and storing its output in a variable


code:
lst = [ch for ch in "HELLOMYQUESTION"]
print(' '.join([j + " " * (len(str(i+1)) - 1)  for i,j in enumerate(lst)]))
print(' '.join([str(i+1) for i,j in enumerate(lst)]))

rawDescription: How can I print the iterations of the elements of a list just beneath them in a nice format

description: Print the iterations of the elements of a list just beneath them in a nice format


code:
def plot_func (name):
    global subseq
    print('\n')
    for i in range(len(seq)):
        subseq = seq[0:i+1]

rawDescription: Unable to pass list to this Python function when using timeit


code:
Section = [('1', '1.1', '1.2'), ('1', '2', '2.2', '3'), ('1', '1.2', '3.2', '3.5')]
Page = [('1', '1', '3'), ('1', '2', '2', '2'), ('1', '2', '3', '5')]
Titles = [('General', 'Info', 'Titles'), ('More', 'Info', 'Section', 'Here'), ('Another', 'List', 'Of', 'Strings')]

# Flat a list of tuples into a list
l1 = [item for sublist in Section for item in sublist]
l2 = [item for sublist in Page for item in sublist]
l3 = [item for sublist in Titles for item in sublist]

# Python2, `zip` returns a list of tuples
#result = zip(*sorted(zip(l1, l2, l3), key=lambda x:float(x[0])))

# Python3, `zip` returns an iterator of tuples
result = list(zip(*sorted(zip(l1, l2, l3), key=lambda x:float(x[0]))))

print(result)
# Output
[   ('1', '1', '1', '1.1', '1.2', '1.2', '2', '2.2', '3', '3.2', '3.5'),
    ('1', '1', '1', '1', '3', '2', '2', '2', '2', '3', '5'),
    ('General', 'More', 'Another', 'Info', 'Titles', 'List', 'Info', 'Section', 'Here', 'Of', 'Strings')]

rawDescription: Combing 2D list of tuples and then sorting them in Python


code:
import re

preg = re.compile(r'^((?P<leading_currency>\S+) +)?'
                  r'(?P<value>[-\d\.,]+)'
                  r'( +(?P<trailing_currency>\S+))?$')
bunch = "$ 148.69\n" \
        "€ 148.69\n" \
        "€ 148,69\n" \
        "148,69 €\n" \
        "₹ 148.69\n" \
        "Rs 148.69\n" \
        "RM 148.69"

def parse_currency(line):
    match = preg.match(line)
    if match:
        currency = match.group('leading_currency') \
                   or match.group('trailing_currency')
        val_str = match.group('value')
        dec_sep = '.' if val_str.rfind('.') > val_str.rfind(',') else ','
        int_part, float_part = val_str.rsplit(dec_sep, 1)
        def norm(number_string):
            return ''.join(c for c in number_string if c.isdigit())
        value = float('{}.{}'.format(norm(int_part), norm(float_part)))
        return currency, value

for line in bunch.splitlines():
    print(parse_currency(line))

rawDescription: How can I convert from string to currency when the format is not known?

description: Convert from string to currency when the format is not known


code:
file_1='file1.txt'
file_2='file2.txt'

my_string = 'word'

for line_1 in [l.rstrip() for l in open(file_1)]:
    with open(line_1+'.txt', 'a') as my_file:
        for line_2 in open(file_2):
            line_2_split = line_2.split(' ')
            if line_1 == line_2_split[0][3:]:
                if my_string in line_2:
                    my_file.write(line_2_split[2] + '\n')

rawDescription: How to use strings from one text file to search another, and create a new text file with columns from another?

description: Use strings from one text file to search another, and create a new text file with columns from another


code:
def otherfunction(a):
    ...

...
mass_of_rider_kg = float(input('input mass of rider in kilograms:'))
a = mass_of_rider_kg
while a < mass_of_rider_kg+16:
     a = a + 4
     otherfunction(a)

rawDescription: How to use loop outputs in another function

description: Use loop outputs in another function


code:
def f(x, y): pass
f(print(1), print(2))

rawDescription: How to prove that parameter evaluation is "left to right" in python

description: Prove that parameter evaluation is "left to right" in python


code:
pq.put((1, "some data"))
pq.put((2, "some lower priority data"))

rawDescription: Adding Items into Priority Queue

description: Adding Items into Priority Queue


code:
import unittest
import datetime
from mock import patch

class SomeTestCase(unittest.TestCase):
    def setUp(self):
        self.time = datetime.datetime(2012, 5, 18)
        class fakedatetime(datetime.datetime):
            @classmethod
            def now(cls):
                return self.time
        patcher = patch('datetime.datetime', fakedatetime)
        self.addCleanup(patcher.stop)
        patcher.start()

    def test_something(self):
        self.assertEqual(datetime.datetime.now(), datetime.datetime(2012, 5, 18))
        self.time = datetime.datetime(2012, 5, 20)
        self.assertEqual(datetime.datetime.now(), datetime.datetime(2012, 5, 20))

rawDescription: Simulating the passing of time in unittesting


code:
#!/usr/bin/env python
"""
pipreqs.py: run ``pip install`` iteratively over a requirements file.
"""
def main(argv):
    try:
        filename = argv.pop(0)
    except IndexError:
        print("usage: pipreqs.py REQ_FILE [PIP_ARGS]")
    else:
        import pip
        retcode = 0
        with open(filename, 'r') as f:
            for line in f:
                pipcode = pip.main(['install', line.strip()] + argv)
                retcode = retcode or pipcode
        return retcode
if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv[1:]))

rawDescription: Pip Install -r continue past installs that fail


code: ''.join(chr(int(x)) for x in oldString)

rawDescription: How to convert a Python string representing bytes into actual bytes?

description: Convert a Python string representing bytes into actual bytes


code:
google = oauth.remote_app('google',
                      base_url='https://www.google.com/accounts/',
                      authorize_url='https://accounts.google.com/o/oauth2/auth',
                      request_token_url=None,
                      request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email',
                                            'response_type': 'code',
                                            'hd':'domain.com'},
                      access_token_url='https://accounts.google.com/o/oauth2/token',
                      access_token_method='POST',
                      access_token_params={'grant_type': 'authorization_code'},
                      consumer_key=GOOGLE_CLIENT_ID,
                      consumer_secret=GOOGLE_CLIENT_SECRET)

rawDescription: Google Oauth2.0 with Python: How do I limit access to a specific domain?


rawDescription: Python relative path simplifier

description: Python relative path simplifier


code:
baseMatch = re.compile('123A[A-Z]{6}')
baseMatch.findall('123AABCDEFxyz123AAABCDExyz')
['123AABCDEF', '123AAABCDE']

rawDescription: Python Re, need a list of matches

description: Python Re, need a list of matches


code:
xmin = min(XdS)
ymax = max(YdS)
zmin = min(ZdS)
length_of_array = len(XdS)
xmin_array = [xmin] * length_of_array
ymax_array = [ymax] * length_of_array
zmin_array = [zmin] * length_of_array
fig=plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(XdS,YdS,ZdS,zdir='z', c='r')
ax.plot(XdS,YdS,zmin_array, zdir='z', c='g')
ax.plot(xmin_array, YdS, ZdS, 'y')
ax.plot(XdS,ymax_array,ZdS,'b')
ax.set_xlabel('XKSM (Saturn Radii)')
ax.set_ylabel('YKSM (Saturn Radii)')
ax.set_zlabel('ZKSM (Saturn Radii)')
plt.show()

rawDescription: Matplotlib 2d Plot on Faces of 3d Plot

description: Matplotlib 2d Plot on Faces of 3d Plot


code:
import cookielib
import urllib2
cookiejar= cookielib.LWPCookieJar()
opener= urllib2.build_opener( urllib2.HTTPCookieProcessor(cookiejar) )
opener.urlopen(...)

rawDescription: Enabling cookies with urllib

description: Enabling cookies with urllib


code: ''.join(random.choice(string.lowercase) for x in range(X))

rawDescription: How do I generate a random string (of length X, a-z only) in Python?

description: Generate a random string (of length X, a-z only) in Python


code:
app.add_url_rule('/example', view_func = example.Index.as_view('example_index'))
app.add_url_rule('/example/<string:example_key>', view_func = example.Show.as_view('example_show'), methods=['GET'])

rawDescription: Flask route query parameter

description: Flask route query parameter


code:
import matplotlib.pyplot as plt

plt.plot(range(10), rasterized=True)
plt.savefig('test.pdf')

rawDescription: matplotlib bitmap plot with vector text

description: Matplotlib bitmap plot with vector text


code:
def print_dict(d):
    new = {}
    for k, v in d.iteritems():
        if isinstance(v, dict):
            v = print_dict(v)
        new[k.replace('.', '-')] = v
    return new

rawDescription: Python recursively replace character in keys of nested dictionary?


rawDescription: How to require X before Y in regex?

description: Require X before Y in regex


code:
## Cell one
"""
A cell is everything between two commands starting with '##'
"""
a = 3
b = 4
print('The answer is ' + str(a+b))

## Cell two

print('Hello World')

rawDescription: Cell mode in Python editors

description: Cell mode in Python editors


code:
import clr
clr.AddReference("MyAssembly")
import MyGlobalClass

rawDescription: How do I import non namespaced types into IronPython?

description: Import non namespaced types into IronPython


rawDescription: How to keep track of unique ranges in a 2D list of ranges?

description: Keep track of unique ranges in a 2D list of ranges


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

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker = 'o', c = data[:, 2], s = data[:, 3]*1500,
    cmap = plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy = (x, y), xytext = (-20, 20),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

plt.show()

rawDescription: Matplotlib: How to put individual tags for a scatter plot


code: df_b.County = [c.strip() for c in df_b.County]

rawDescription: Pandas merge returning empty dataframe

description: Pandas merge returning empty dataframe


code:
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import datetime
c = pdc.Constants()
p = pdt.Calendar(c)
for text in ('january 6, 2011', '4 days ago', '12 hours ago'):
    date=datetime.datetime(*p.parse(text)[0][:6])
    # print(date.isoformat())
    # 2011-01-06T09:00:18
    # 2011-01-02T09:00:18
    # 2011-01-05T21:00:18
    print(date.strftime('%Y%m%dT%H%M%S'))
    # 20110106T090208
    # 20110102T090208
    # 20110105T210208

rawDescription: Python: Convert Relative Date String to Absolute Date Stamp


rawDescription: Efficient way to construct datetime64 and pandas time series?


code:
import unittest

class Base: pass
class Derived1(Base): pass

class BaseTest(object):
    cls = None

    def setUp(self):
        self.instance = self.cls()

    def test_Method1(self):
        print("run test_Method1, cls={}".format(self.cls))

class TestParent(BaseTest, unittest.TestCase):
    cls = Base

class TestDerived1(BaseTest, unittest.TestCase):
    cls = Derived1

unittest.main()

rawDescription: How use Python unittest to test a class hierarchy?


code:
import sys
sys.byteorder

rawDescription: What's the most Pythonic way of determining endianness?


code:
from tkinter import *
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

root = Tk()

frame = Frame(root)
frame.pack()
fig = Figure(figsize=(16,8))
p = fig.add_subplot(1,1,1)
p.plot([1,2,3],[1,2,3])
canvas = FigureCanvasTkAgg(fig, frame)
canvas.show()
canvas.get_tk_widget().pack(fill='both', expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, frame)
toolbar.update()
canvas._tkcanvas.pack(fill='both', expand=True)

def pick(event):
    p.hlines(event.ydata, event.xdata-0.009, event.xdata+0.009,
             colors='red', linestyle='solid')
    canvas.show()

fig.canvas.mpl_connect('button_press_event', pick)

root.mainloop()

rawDescription: Plot hlines in embedded graph?

description: Plot hlines in embedded graph


code:
import dateutil.parser
from pytz import timezone
from_date = "2014/05/06 17:07"
from_date = dateutil.parser.parse(from_date)
from_date = timezone('Asia/Kuwait').localize(from_date).astimezone(timezone('UTC'))
from_date
from_date.strftime("%b %d %Y %H:%M:%S" )

rawDescription: Time conversion using pytz isn't accurate


code:
class MessageBox(wx.Dialog):
    def __init__(self, parent, title):
        wx.Dialog.__init__(self, parent, title=title)
        text = wx.TextCtrl(self, style=wx.TE_READONLY|wx.BORDER_NONE)
        text.SetValue("Hi hi hi")
        text.SetBackgroundColour(wx.SystemSettings.GetColour(4))
        self.ShowModal()
        self.Destroy()

rawDescription: Select and copy text from dialog in wxPython


code:
import collections

val_map = collections.defaultdict(list)
for k,v in myRackDict.items():
    val_map[v].append(k)

rawDescription: Return all keys with the same value in a dictionary


code:
def filter_data(data, predicate=lambda k, v: True):
    for d in data:
         for k, v in d.items():
               if predicate(k, v):
                    yield d

test_data = [{"key1":"value1", "key2":"value2"}, {"key1":"blabla"}, {"key1":"value1", "eh":"uh"}]
list(filter_data(test_data, lambda k, v: k == "key1" and v == "value1"))
# [{'key2': 'value2', 'key1': 'value1'}, {'key1': 'value1', 'eh': 'uh'}]

rawDescription: Filtering dictionaries and creating sub-dictionaries based on keys/values in Python?


code:
import numpy as np
list_of_lists=[[1,2,3],[4,5,2],[3,2,4]]
weights = [10, 2, 5.5]
(np.array(list_of_lists) * np.array(weights)[:, None]).tolist()

rawDescription: Applying different weights to multiple lists grouped in list of lists - Python


code:
# Store x and y coordinates as column vectors
xcoord = np.array([[459, 450]]).T
ycoord = np.array([[467, 466]]).T

# Run contour detection code
contours, hierarchy = cv2.findContours(mask2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

coordinate_list = []

# Go through each contour...
for contour in contours:
    rect = cv2.minAreaRect(contour)
    points = cv2.cv.BoxPoints(rect)
    points = np.int0(points)

    # Check to see if any rectangle points are in our lists
    if np.any(np.logical_and(xcoords == points[:,0], ycoords == points[:,1])):
        continue

    coordinate_list.append(points)

rawDescription: Filter out minimum area rectangles - Python OpenCV


code:
co = webdriver.ChromeOptions()
co.add_argument("--user-data-dir=userdir")
browser = webdriver.Chrome(chrome_options = co)

rawDescription: Getting or Manipulating all cookies in Selenium Webdriver


code:
seekbar.connect("value-changed", control_changed, label)
seekbar.connect("notify::fraction", fraction_changed, label)

rawDescription: How to handle back and forward buttons in the hildon.Seekbar?

description: Handle back and forward buttons in the hildon.Seekbar


code:
import itertools
sum(a[i][j] - b[k][l] for i, j, k, l in itertools.product(range(1, 100), repeat=4))

rawDescription: Python : summation over all permutations


code:
from collections import Counter

def calc_percentiles(cnts_dict, percentiles_to_calc=range(101)):
    """Returns [(percentile, value)] with nearest rank percentiles.
    Percentile 0: <min_value>, 100: <max_value>.
    cnts_dict: { <value>: <count> }
    percentiles_to_calc: iterable for percentiles to calculate; 0 <= ~ <= 100
    """
    assert all(0 <= p <= 100 for p in percentiles_to_calc)
    percentiles = []
    num = sum(cnts_dict.values())
    cnts = sorted(cnts_dict.items())
    curr_cnts_pos = 0  # current position in cnts
    curr_pos = cnts[0][1]  # sum of freqs up to current_cnts_pos
    for p in sorted(percentiles_to_calc):
        if p < 100:
            percentile_pos = p / 100.0 * num
            while curr_pos <= percentile_pos and curr_cnts_pos < len(cnts):
                curr_cnts_pos += 1
                curr_pos += cnts[curr_cnts_pos][1]
            percentiles.append((p, cnts[curr_cnts_pos][0]))
        else:
            percentiles.append((p, cnts[-1][0]))  # we could add a small value
    return percentiles

cnts_dict = Counter()
for segment in segment_iterator:
    cnts_dict += Counter(segment)

percentiles = calc_percentiles(cnts_dict)

rawDescription: percentiles from counts of values

description: Percentiles from counts of values


code:
class Foo(object):
    @property
    def x(self):
        return 4

    # If the class statement stopped here, Foo.x would have a __get__ method
    # that calls the x function we just defined, and its __set__ and __delete__
    # methods would raise errors.

    @x.setter
    def x(self, value):
        pass

    # If the class statement stopped here, Foo.x would have usable __get__ and
    # __set__ methods, and its __delete__ method would raise an error.

    @x.deleter
    def x(self):
        pass

# Now Foo.x has usable __get__, __set__, and __delete__ methods.

bar = Foo()
bar.x      # Calls __get__
bar.x = 4  # Calls __set__
del bar.x  # Calls __delete__

rawDescription: what magic methods does @property touch

description: What magic methods does @property touch


code:
from collections import Counter

counts = Counter(tup[index_of_path] for tup in some_list)

some_list = [tup for tup in some_list if counts[tup[index_of_path]] == 1]

rawDescription: Modify the list that is being iterated in python


code: df['C'] = df.A > df.B

rawDescription: How do you add a calculated column to a pandas dataframe using set-based logic?

description: Add a calculated column to a pandas dataframe using set-based logic


code:
left_col = []
right_col = []
for tr in soup.find_all('tr'):
    tds = tr.find_all('td')
    left, right = tds[0], tds[1:]
    assert('prodSpecAtribute' in left['class'])
    left_col.append(left)
    right_col.append(combine_columns(right))

rawDescription: Parsing rows of information from html using python


code: some_var = 'default' if other_var is None else other_var

rawDescription: Avoid 0 and others to count as False

description: Avoid 0 and others to count as False


code:
with open("info.txt", "r") as read:
    lines = []
    for item in read:
        row = item.split()
        row[:2] = map(int, row[:2])
        lines.append(row)

rawDescription: Python: read from file into list

description: Python: read from file into list


rawDescription: Remove duplicates and finding unique sublists


code:
def new_getDuplicateList(oldlist):
    # find duplicate elements
    newlist = []
    duplicate = set()
    a_to_b = {}
    for elements in oldlist:
        a = elements[0]
        b = elements[1]
        if a in duplicate:
            newlist.append(a)
        else:
            if a in a_to_b.keys():
                if not b in a_to_b[a]:
                    a_to_b[a].append(b)
                    duplicate.add(a)
                    extension = [a for i in a_to_b[a]]
                    newlist.extend(extension)
                else:
                    a_to_b[a].append(b)
            else:
                a_to_b[a] = [b]

    return newlist

rawDescription: How can I filter duplicate rows efficiently in Python?

description: Filter duplicate rows efficiently in Python


code: del L[:]

rawDescription: Clearing a list

description: Clearing a list


code: csv.reader(fh, delimiter='|')

rawDescription: python reading csv files comma issue

description: Python reading csv files comma issue


code:
with open('myFile.txt', 'r+') as word_bank:
    new_lines = []
    for line in word_bank:
        new_line = []
        for word in line.strip().split():
            if 'go' in word:
                new_line.append('boat')
            else:
                new_line.append(word)
        new_lines.append('%s\n' % ' '.join(new_line))
    word_bank.truncate(0)
    word_bank.seek(0)
    word_bank.writelines(new_lines)

rawDescription: Replace the whole string if it contains specific letters/character


rawDescription: showPage interferes with laterPages template in reportlab

description: ShowPage interferes with laterPages template in reportlab


code:
s = {'abcd', 'abdd', 'acdd'}
r = [el for el in s if re.search('ab.d', el)]
r

rawDescription: Query a set with an regex

description: Query a set with an regex


code:
from collections import Counter
counter = Counter('hellooo i am a potato!!!!!')
counter.most_common(2)

rawDescription: Performance of python list count method

description: Performance of python list count method


code:
with open(input_path, 'r') as infile, open(output_path, 'w') as outfile:
  for line in infile:
    line_name, line_id = line.split(':')
    line_name = line_name.strip().replace(' ', '_')
    print('{} = ["{}"]'.format(line_name, line_id.strip()))

rawDescription: convert a text file into a list of variables

description: Convert a text file into a list of variables


code:
from minimock import TraceTracker, Mock, mock
import unittest

import pysvn

from code_under_test import VersionControl

class TestVersionControl(unittest.TestCase):

    def test_init(self):

        mock_svn = Mock(name='svn_client')
        mock('pysvn.Client', returns=mock_svn)

        vc = VersionControl()

        self.assertEqual(vc.svn, mock_svn)

    def test_list_calls_svn_list_and_returns_urls(self):

        tracker = TraceTracker()
        test_url = 'a test_url'
        mock_data = [
            ({'path': 'first result excluded'}, None),
            ({'path': 'url2'}, None),
            ({'path': 'url3', 'info': 'not in result'}, None),
            ({'path': 'url4'}, None),
        ]

        vc = VersionControl()
        mock('vc.svn.list', returns=mock_data, tracker=tracker)

        response = vc.list(test_url)
        self.assertEqual(['url2', 'url3', 'url4'], response)
        self.assertTrue("Called vc.svn.list('a test_url')" in tracker.dump())

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

rawDescription: How to mock pysvn

description: Mock pysvn


code:
ui = MainWindow()
ui.setupUi(mainwindow)
ui.widget.setAttribute(QtCore.Qt.WA_StyledBackground, True)

rawDescription: PySide: QWidget does not draw background color


code:
res = [ "{}\t{}\n".format(x,y)
          for (x,y) in zip(datacolumn[0::2], datacolumn[1::2])]

rawDescription: group element by two python list

description: Group element by two python list


code:
import wx.grid

class UserView(wx.Panel):
        def __init__(self, parent, ID):
            wx.Panel.__init__(self, parent, ID)
            self.sizer = wx.BoxSizer(wx.VERTICAL)

            self.gridPnl = wx.Panel(self,-1)
            self.gridPnlSizer = wx.BoxSizer(wx.HORIZONTAL)

            #Grid that show current users
            self.newGrid = wx.grid.Grid(self.gridPnl)
            self.newGrid.CreateGrid(6,3)
            self.newGrid.SetColLabelValue(0, "ID")
            self.newGrid.SetColLabelValue(1, "Username")
            self.newGrid.SetColLabelValue(2, "Password")

            #Start out showing this Grid until the Add button or Edit button is clicked
            self.newGrid.Show()

            self.userEntryPnl = wx.Panel(self,-1)
            self.userEntryPnlSizer = wx.BoxSizer(wx.VERTICAL)

            self.userlbl = wx.StaticText(self.userEntryPnl, label='Username')
            self.userTxt = wx.TextCtrl(self.userEntryPnl, size=(140,-1))
            self.userTxt.SetModified(True)
            self.userTxt.SetEditable(True)
            self.passlbl = wx.StaticText(self.userEntryPnl, label='Password')
            self.passTxt = wx.TextCtrl(self.userEntryPnl, size=(140,-1))
            self.passTxt.SetModified(True)
            self.passTxt.SetEditable(True)

            self.userEntryPnlSizer.AddStretchSpacer()
            self.userEntryPnlSizer.Add(self.userlbl,0,wx.ALL|wx.ALIGN_CENTER)
            self.userEntryPnlSizer.AddSpacer(10)
            self.userEntryPnlSizer.Add(self.userTxt,0,wx.ALL|wx.ALIGN_CENTER)
            self.userEntryPnlSizer.AddSpacer(10)
            self.userEntryPnlSizer.Add(self.passlbl,0,wx.ALL|wx.ALIGN_CENTER)
            self.userEntryPnlSizer.AddSpacer(10)
            self.userEntryPnlSizer.Add(self.passTxt,0,wx.ALL|wx.ALIGN_CENTER)
            self.userEntryPnlSizer.AddStretchSpacer()

            self.userEntryPnl.SetAutoLayout(True)
            self.userEntryPnl.SetSizer(self.userEntryPnlSizer)
            self.userEntryPnlSizer.Fit(self.userEntryPnl)

            #start out hiding this panel until Add button or Edit button is clicked
            self.userEntryPnl.Hide()

            self.gridPnlSizer.AddStretchSpacer()
            self.gridPnlSizer.Add(self.newGrid,0,wx.EXPAND)
            self.gridPnlSizer.Add(self.userEntryPnl,0,wx.EXPAND)
            self.gridPnlSizer.AddStretchSpacer()

            self.gridPnl.SetAutoLayout(True)
            self.gridPnl.SetSizer(self.gridPnlSizer)
            self.gridPnlSizer.Fit(self.gridPnl)

            self.bottomBtnsPnl = wx.Panel(self,-1)
            self.bottomSizer = wx.BoxSizer(wx.HORIZONTAL)

            self.AddBtn = wx.Button(self.bottomBtnsPnl, label='Add')
            self.EditBtn = wx.Button(self.bottomBtnsPnl, label='Edit')
            self.DeleteBtn = wx.Button(self.bottomBtnsPnl, label='Delete')
            self.SaveBtn = wx.Button(self.bottomBtnsPnl, label='Save')

            self.AddBtn.Show()
            self.EditBtn.Show()
            self.DeleteBtn.Show()
            self.SaveBtn.Hide()

            self.Bind(wx.EVT_BUTTON, self.addBtnEnt, self.AddBtn)
            self.Bind(wx.EVT_BUTTON, self.editBtnEnt, self.EditBtn)
            self.Bind(wx.EVT_BUTTON, self.deleteBtnEnt, self.DeleteBtn)
            self.Bind(wx.EVT_BUTTON, self.saveBtnEnt, self.SaveBtn)

            self.bottomSizer.AddStretchSpacer()
            self.bottomSizer.Add(self.AddBtn,0,wx.EXPAND)
            self.bottomSizer.AddSpacer(10)
            self.bottomSizer.Add(self.EditBtn,0,wx.EXPAND)
            self.bottomSizer.AddSpacer(10)
            self.bottomSizer.Add(self.DeleteBtn,0,wx.EXPAND)
            self.bottomSizer.AddSpacer(10)
            self.bottomSizer.Add(self.SaveBtn,0,wx.ALL|wx.ALIGN_CENTER)
            self.bottomSizer.AddSpacer(10)
            self.bottomSizer.AddStretchSpacer()

            self.bottomBtnsPnl.SetAutoLayout(True)
            self.bottomBtnsPnl.SetSizer(self.bottomSizer)
            self.bottomSizer.Fit(self.bottomBtnsPnl)

            self.sizer.AddSpacer(10)
            self.sizer.Add(self.gridPnl,0,wx.EXPAND)
            self.sizer.AddSpacer(10)
            self.sizer.Add(self.userEntryPnl,0,wx.EXPAND)
            self.sizer.AddSpacer(10)
            self.sizer.Add(self.bottomBtnsPnl,0,wx.EXPAND)
            self.sizer.AddSpacer(10)

            self.SetAutoLayout(True)
            self.SetSizer(self.sizer)
            self.sizer.Fit(self)

        def addBtnEnt(self,e):
            self.gridPnl.Hide()
            self.AddBtn.Hide()
            self.EditBtn.Hide()
            self.DeleteBtn.Hide()
            self.SaveBtn.Show()
            self.userEntryPnl.Show()
            self.userEntryPnl.Layout()
            self.bottomBtnsPnl.Layout()
            self.Layout()

        def editBtnEnt(self,e):
            self.gridPnl.Hide()
            self.AddBtn.Hide()
            self.EditBtn.Hide()
            self.DeleteBtn.Hide()
            self.SaveBtn.Show()
            self.userEntryPnl.Show()
            self.userEntryPnl.Layout()
            self.Layout()

        def deleteBtnEnt(self,e):
            print("Delete clicked")

        def saveBtnEnt(self,e):
            self.userEntryPnl.Hide()
            self.SaveBtn.Hide()
            self.gridPnl.Show()
            self.AddBtn.Show()
            self.EditBtn.Show()
            self.DeleteBtn.Show()
            self.gridPnl.Layout()
            self.Layout()

rawDescription: wxPython Hide() and Show() Changes Panel Alignment

description: WxPython Hide() and Show() Changes Panel Alignment


rawDescription: PyODBC + Pandas + Parameterization

description: PyODBC + Pandas + Parameterization


code:
category = Category.objects.get(pk=10)
products = category.product_set.all()  # note that this is a queryset

rawDescription: Fetching data from Many to Many relationship (intermediate table)


code:
def find_character(target_table, character):
    for row in range(len(target_table)):
        for column in range(len(target_table[row])):
            if target_table[row][column] == character:
                return row,column

rawDescription: How to return the row and column from a table in python?

description: Return the row and column from a table in python


code:
dataframe = read_csv(csvio, header=5, index_col=None, parse_dates=True)
dataframe
dataframe.head()

rawDescription: Downloading treasury data with Pandas read_csv


code: return redirect('/auth/login')

rawDescription: Django / From redirect_to to RedirectView


code:
import subprocess

fd = open(filename, 'r')
subprocess.Popen(['mysql', '-u', username, '-p{}'.format(password), '-h', hostname, database], stdin=fd).wait()

rawDescription: Source large MySQL dump with Python script


code:
import Tkinter as tk

class App:
    def __init__(self):
        self.root = tk.Tk()
        tk.Label(self.root, text="main window").pack()
        self.t = tk.Toplevel()
        tk.Label(self.t, text="tool window").pack()
        self.root.bind("<Unmap>", self.OnUnmap)
        self.root.bind("<Map>", self.OnMap)
        self.root.mainloop()

    def OnMap(self, event):
        # show the tool window
        self.t.wm_deiconify()

    def OnUnmap(self, event):
        # withdraw the tool window
        self.t.wm_withdraw()

if __name__ == "__main__":
    app=App()

rawDescription: Running a command on Window minimization in Tkinter


code:
import re

results = [('uid=alex,class=zenth', {'age': ['12'], 'uidnumber': ['12AC']}), ('uid=beth,class=nenth', {'age': ['22'], 'uidnumber': ['13SD']})]

c = re.compile('uid=(?P<uid>.+?),')

uid_val_list = [c.search(result[0]).group('uid') for result in results]
print(uid_val_list)

rawDescription: Python : array tuple extraction

description: Python : array tuple extraction


code:
pattern = r"\w.\d{3}\-\w+.(jpg|Jpg|JPG)"

for filename in FileList:
    if displaymatch(re.match(pattern, filename)) is None:
        os.rename(filename, "P." + str("{0:0=3d}".format(num)) + "-" + filename)
        num+= 1

rawDescription: Python Regular Expression pattern

description: Python Regular Expression pattern


code:
def stringReceived(self, data):
    getattr(self, "stringReceived_{}".format(self.state))(data)

def stringReceived_authenticate(self, data):
    if self.auth_ok(data):
       self.state = 'normal'
    else:
       self.transport.loseConnection()

def stringReceived_normal(self, data):
    self.do_stuff(data)

rawDescription: How to separate two different phases of a protocol in Twisted?

description: Separate two different phases of a protocol in Twisted


code:
class JobDefinitionsAllInOneView(mixins.UpdateModelMixin,
                                 mixins.DestroyModelMixin,
                                 mixins.ListModelMixin,
                                 mixins.CreateModelMixin,
                                 generics.GenericAPIView):

    queryset = JobDefinitions.objects.all()
    serializer_class = JobDefinitionsSerializer

    def get_object(self):
        job_def_id = self.request.query_params.get('job-def-id', None)
        if job_def_id is not None:
            self.kwargs['pk'] = job_def_id
        return super(JobDefinitionsAllInOneView, self).get_object()

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

    def get(self, request, *args, **kwargs):
        job_def_id = self.request.query_params.get('job-def-id', None)
        if job_def_id is not None:
            # return the details
            return self.retrieve(request, *args, **kwargs)
        else:
            # return a list
            return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        return self.partial_update(self, request, *args, **kwargs)
    def delete(self, request, *args, **kwargs):
        return self.destroy(self, request, *args, **kwargs)

rawDescription: Django REST Framework : update() based on query string parameter


code: rows.exclude(lambda r: r.id == some_id)

rawDescription: How to remove row from rows object, not from database?

description: Remove row from rows object, not from database


code:
type(g1.date).__name__ == "datetime"
type(Greeting.date).__name__ == "DateTimeProperty"

rawDescription: Why does this gae example use a class method?


code:
from playhouse.shortcuts import cast

...
my_field = tgt.attrs.NumberMissingOriginalIntrons
r = r.where((cast(my_field, 'float') <= 0.5 * cast(my_field, 'float') - 0.5))

rawDescription: peewee multiplying integer fields by floats for linear expression - replaces numbers between 0 and 1 with 0

description: Peewee multiplying integer fields by floats for linear expression - replaces numbers between 0 and 1 with 0


code:
chunk_len = 100
split_char = ';'
delim = ("~||~")
d = ";"
f = open(filename, "r")
text = f.read()
f.close()
lines = text.split(';')
for lines_idx, line in enumerate(lines):
    line = line + d  #NEW LINE ADDED HERE
    length = len(line)
    if length > chunk_len:
        chunks = [line[idx:idx+chunk_len]for idx in range(0,length,chunk_len)]
        lines[lines_idx] = delim.join(chunks)
new_text = delim.join(lines)
f = open(outputfile, 'w')
f.write(new_text)
f.close()

rawDescription: Python Split removing delimiters?

description: Python Split removing delimiters


code:
class App:
    def __init__(self, root):
        self.start = 0
        self.root = root
        self.sb = tk.Scrollbar(orient="vertical")
        text = tk.Text(root, width=40, height=20, yscrollcommand=self.sb.set)
        self.sb.config(command=text.yview)
        self.sb.pack(side="right",fill="y")
        text.pack(side="top", fill="both", expand=True)
        self.chkbuttons = [tk.Checkbutton(text="checkbutton %s" % i,padx=0,pady=0,bd=0)
                          for i in range(30)]
        for cb in self.chkbuttons:
            text.window_create("end", window=cb)
            text.insert("end", "\n")
            cb.bind("<Button-1>", self.selectstart)
            cb.bind("<Shift-Button-1>", self.selectrange)

    def selectstart(self, event):
        self.start = self.chkbuttons.index(event.widget)

    def selectrange(self, event):
        start = self.start
        end = self.chkbuttons.index(event.widget)
        sl = slice(min(start, end)+1, max(start, end))
        for cb in self.chkbuttons[sl]:
            cb.toggle()
        self.start = end

if __name__ == '__main__':
    root = tk.Tk()
    app = App(root)
    root.mainloop()

rawDescription: How to select multiple checkboxes with SHIFT in tkinter?

description: Select multiple checkboxes with SHIFT in tkinter


rawDescription: Recognizing newline characters in Python


code:
# import section
from pyuca import Collator

# Calling Collator() takes some seconds so you should create it as reusable variable.
c = Collator()

# ...

# main part:
author_list = sorted(Author.objects.all(), key=lambda x: (c.sort_key(x.lastname), c.sort_key(x.firstname)))

rawDescription: Django, SQLite - Accurate ordering of strings with accented letters


code:
import fileinput

output = None
for line in fileinput.input():
    line2 = line.strip()
    if line2.startswith('<'):
        output = open(line2[1:].split(';')[0], 'w')
    elif line2 == 'END':
        output.close()
        output = None
    elif output:
        output.write(line)

rawDescription: Python log parser

description: Python log parser


code:
import tkinter as tk

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        for i in range(1,11):
            label = tk.Label(self, text="This is item #%s" % i,
                             borderwidth=2, relief="groove")
            label.pack(side="top", fill="both", expand=True, padx=2, pady=1)

app = ExampleApp()
app.mainloop()

rawDescription: Tkinter - expand widget in python 3.2

description: Tkinter - expand widget in python 3.2


code:
def vowelcheck(variable):
    if variable[0] == "a" or variable[0] == "e" or variable[0] == "i" or variable[0] == "o" or variable[0] == "u":
        variable = "an " + variable
    else:
        variable = "a " + variable
    return variable

noun1, noun2, noun3 = (vowelcheck(noun1), vowelcheck(noun2), vowelcheck(noun3))

rawDescription: Function used to check if a variable's string starts with vowel?


code:
class SmokeTests():

    def suite(self): #Function stores all the modules to be tested
        modules_to_test = ('external_sanity', 'internal_sanity')
        alltests = unittest.TestSuite()
        for module in map(__import__, modules_to_test):
            alltests.addTest(unittest.findTestCases(module))
        return alltests
if __name__ == '__main__':
    Smoke = SmokeTests()
    unittest.main(defaultTest='Smoke.suite')

rawDescription: Run unittest in a Class

description: Run unittest in a Class


code:
df
df.plot(kind='barh', stacked=True)

rawDescription: plotting stacked barplots on a panda data frame

description: Plotting stacked barplots on a panda data frame


code:
class FakeFile:
    def read(self, size=0):
        return ''

rawDescription: uploading empty file to ftp with psuedo-file

description: Uploading empty file to ftp with psuedo-file


code: eval(data)

rawDescription: python data array string convert to list

description: Python data array string convert to list


code:
with open('input.dat') as handle:
    data = asarray([[x == 'T' for x in line.strip().split()]
                    for line in handle],
                   dtype=bool)

rawDescription: how to read in boolean data file in Python with asarray function of numpy

description: Read in boolean data file in Python with asarray function of numpy


code:
def replaceWord(old, new, astr):
   return astr.replace(old, new)

rawDescription: How to use .replace in python?

description: Use .replace in python


code:
def dobin(n):
  digs = []
  s = ''
  if n<0:
    s = '-'
    n = -n
  while True:
    digs.append(str(n % 2))
    n /= 2
    if not n: break
  if s: digs.append(s)
  digs.reverse()
  return ''.join(digs)

rawDescription: how change int to binary. on python 2.5

description: How change int to binary. on python 2.5


code:
op = lambda a, b: a + b
result = op(5, 7)
result

rawDescription: Python - is it possible to set a variable to an operator?


code:
import time

localtime   = time.localtime()
timeString  = time.strftime("%Y%m%d%H%M%S", localtime)

# is DST in effect?
timezone    = -(time.altzone if localtime.tm_isdst else time.timezone)
timeString += "Z" if timezone == 0 else "+" if timezone > 0 else "-"
timeString += time.strftime("%H'%M'", time.gmtime(abs(timezone)))

rawDescription: Python: date, time formatting

description: Python: date, time formatting


code:
if id not in ids:
    return False, None

if not cycles:
    self.d_types[2] += 1
    return False, 2

if not gs:
    self.d_types[3] += 1
    return False, 3

if sch_date not in gs:
    self.d_types[1] += 1
    return False, 1

if dp not in gs[sch_date]:
    self.d_types[4] += 1
    return False, 4

return True, None

rawDescription: python call function on short circuit

description: Python call function on short circuit


code:
import logging
logging.basicConfig(level=logging.INFO)
#logging.getLogger('suds.client').setLevel(logging.DEBUG)
#logging.getLogger('suds.transport').setLevel(logging.DEBUG)
#logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)
#logging.getLogger('suds.wsdl').setLevel(logging.DEBUG)

from suds.client import Client
from suds.xsd.doctor import ImportDoctor, Import
from suds.transport.https import HttpAuthenticated

class MyTransport(HttpAuthenticated):
  def __init__(self,*args,**kwargs):
    HttpAuthenticated.__init__(self,*args,**kwargs)
    self.last_headers = None
  def send(self,request):
    result = HttpAuthenticated.send(self,request)
    self.last_headers = result.headers
    return result

doctor = ImportDoctor(Import('http://schemas.xmlsoap.org/soap/encoding/'))
svc_url  = 'https://server/Service?wsdl'
svc_user = 'username'
svc_pass = 'password'

client = Client(svc_url,doctor=doctor,transport=MyTransport())
# For some reason I can't be bothered to investigate, setting the username and password in
# client kwargs doesn't pass them to the custom transport:
client.set_options(location=svc_url.partition('?')[0],username=svc_user,password=svc_pass)
# call a method
client.service.SomeMethod()
# look at headers
client.options.transport.last_headers

rawDescription: How to get the response headers from a suds request

description: Get the response headers from a suds request


code:
pos_io_tagged = map(lambda word, pos_tag, io_tag:
    (word, pos_tag, io_tag), zip(zip(words, pos_tags), io_tags))

rawDescription: Python 2 vs 3: Lambda Operator

description: Python 2 vs 3: Lambda Operator


code:
import itertools

s = 'this is a string'

words = s.split()
for t in itertools.product(range(len('01')), repeat=len(words)-1):
    print(''.join([words[i]+t[i]*' ' for i in range(len(t))])+words[-1])

rawDescription: Python Join String to Produce Combinations For All Words in String


code:
import operator
for key, value in sorted(my_dict.items(), key=operator.itemgetter(1)):
    print("Officer '{1}', '{2}' with '{0}' ate '{3}' with '{4}' and '{5}'.".format(key, *value))

rawDescription: sorting printed output from a dictionary of lists with index 0 of the list alphabetized

description: Sorting printed output from a dictionary of lists with index 0 of the list alphabetized


code:
from random import randint
import random

number_of_lists = randint(0,1000)

random_data = []
for number in xrange(0,number_of_lists):
    list_length=randint(0,1000)
    random_data.append(random.sample(range(1, 100000), list_length))

rawDescription: Create Python list of list with random numbers and lengths


code:
def reformat(filename):
    mydict = dict()
    feature = ''
    for line in filename:
        m = re.search("\AFeature",line[0])
        if m:
            feature = line[0]
            mydict[feature] = (line[1:-1])
        else:
            mydict[feature].append(line[0])
print(mydict)

rawDescription: Python: restructure an ordered text file via dictionary


code: plt.plot(x, y, 'r-', alpha=0.7)

rawDescription: Matplotlib transparent line plots

description: Matplotlib transparent line plots


code:
class CommentForm(CommentDetailsForm):
    email = forms.EmailField(label=_("E-mail address"), required=False)

    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['field_to_add_placeholder_to'].widget.attrs['placeholder'] = "your placeholder"

rawDescription: Django: Add a placeholder text to default comment textarea field


rawDescription: How to convert pandas' DataFrame to DataFrame or LabeledPoint in Spark?

description: Convert pandas' DataFrame to DataFrame or LabeledPoint in Spark


code:
import os
import readline
os.environ['PYTHONINSPECT'] = '1'

rawDescription: Friendly line editing with `PYTHONINSPECT`


rawDescription: Extract elements of an N-dimensionnal array within a list in Python


code:
my_speed=np.ones(shape=(no,no))

fig = plt.figure(2)
ax = fig.add_subplot(1,1,1)

# my_speed=np.log10(my_speed)
img = ax.imshow(my_speed, interpolation='bilinear', cmap=cm.jet,
                norm=mpl.colors.LogNorm())
fig.colorbar(img)

rawDescription: How do I add a colorbar with log data in an image/matrix

description: Add a colorbar with log data in an image/matrix


rawDescription: Python with scikit-image to invert colors Back and white


code:
from mock import patch
...
@patch('mymodel_module.os.remove')
def test_my_method(self, mocked_remove):
    call_my_model_method()
    self.assertTrue(mocked_remove.called)

rawDescription: Write test for views containing os.remove in django


code:
from django.db.models import Sum
total_points = Player.objects.aggregate(Sum('points'))['points__sum']
num_matches = Match.objects.count()
average_points_per_match = total_points / num_matches

rawDescription: Count average points per 'Match' in Python Django


code:
import  pandas as pd

df = pd.read_csv("http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ&render=download")

print(df)

rawDescription: Return data from URL with Python

description: Return data from URL with Python


code:
r.table("accounts").map(lambda account:
    account.merge({
        "conversations": r.table("conversations").filter(lambda conversation:
            conversation["to"].contains(account["id"])).coerce_to("array").map(lambda conversation:
            conversation.merge({
                "to": conversation["to"].map(lambda account:
                    r.table("accounts").get(account)).pluck(["id", "name",]).coerce_to("array"),
                "messages": r.table("messages").filter(lambda message:
                    message["conversation"] == conversation["id"]).coerce_to("array").map(lambda message:
                    message.merge({
                        "from": r.table("accounts").get(message["from"]).pluck(["id", "name",]),
                        "readers": r.table("message_readers").filter(lambda message_reader:
                            message["id"] == message_reader["message"]).coerce_to("array").order_by(r.desc("created_on")),
                    })).order_by(r.desc("created_on"))
            })).order_by(r.desc("modified_on"))
    })).order_by("id").run(db_connection)

rawDescription: RethinkDB: How to do recursive joins on three tables?


code:
def connected_components(self,SWTImage):
    width=SWTImage.shape[1]
    heigth=SWTImage.shape[0]
    G=nx.Graph()
    row_loc=np.zeros(SWTImage.shape[0]*SWTImage.shape[1])

    for y in xrange(1,heigth):
        for x in xrange(1,width):
            currentPix=SWTImage.item(y,x)
            if currentPix>0:
                left=x-1
                up=y-1
                rigth=x+1

                leftPix=SWTImage.item(y,left)
                if(leftPix>0 and (leftPix/currentPix<=3.0 or currentPix/leftPix<=3.0)):
                    G.add_edge(y*width+x,y*width+left)
                    row_loc.itemset((y*width+left),y)

                leftUpPix=SWTImage.item(up,left)
                if(leftUpPix>0 and (leftUpPix/currentPix<=3.0 or currentPix/leftUpPix<=3.0)):
                    G.add_edge(y*width+x,up*width+left)
                    row_loc.itemset((up*width+left),up)

                upPix=SWTImage.item(up,x)
                if(upPix>0 and (upPix/currentPix<=3.0 or currentPix/upPix<=3.0)):
                    G.add_edge(y*width+x,up*width+x)
                    row_loc.itemset((up*width+x),up)

                if(rigth<width):
                    rightUpPix=SWTImage.item(up,rigth)
                    if (rightUpPix>0 and (rightUpPix/currentPix<=3.0 or currentPix/rightUpPix<=3.0)):
                        G.add_edge(y*width+x,up*width+rigth)
                        row_loc.itemset(up*width+rigth,up)

                row_loc.itemset((y*width+x),y)

    components=nx.algorithms.components.connected_components(G)
    return components,row_loc

rawDescription: find connected component labeling based on some condition

description: Find connected component labeling based on some condition


code:
import socket

host = ''
port = 1010

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
    databytes = conn.recv(1024)
    if not databytes: break
    data = databytes.decode('utf-8')
    print("Recieved: "+(data))
    if data == "dodo":  # moved to before the `input` call
        print("hejhej")
    response = input("Reply: ")
    if response == "exit":
        break
    conn.sendall(response.encode('utf-8'))
conn.close()

rawDescription: i got problems with making a python socket server recive commands from an python socket client

description: I got problems with making a python socket server recive commands from an python socket client


rawDescription: average numpy array but retain shape

description: Average numpy array but retain shape


code:
def new_response_subscriber(event):
    request = event.request
    response = event.response

    if "api" == request.environ['HTTP_HOST'].split('.')[0]:
        if 'Set-Cookie' in response.headers:
            del response.headers['Set-Cookie']

rawDescription: In Pyramid, how can prevent cookies from being set in certain responses?


code:
Session.query(Item, deliver, sell, stock).from_statement("""
SELECT     Item.id,
    Item.description,
    deliver.del_amount,
    sell.sell_amount ,
    deliver.del_amount - sell.sell_amount as stock
from item
join (
    select Deliveryitem.Item_id as del_id,
    sum(DeliveryItem.amount) as del_amount
    from  Deliveryitem group by DeliveryItem.item_id

) deliver on deliver.del_id = item.id
 join (
    SELECT LineItem.Item_id as sell_id,
    sum(LineItem.amount) as sell_amount
    from  LineItem  group by LineItem.item_id
) sell on sell.sell_id=item.id
""")

rawDescription: How to convert SQL statement into correct SQLAlchemy expression

description: Convert SQL statement into correct SQLAlchemy expression


code:
args = [    imagemagick,
            filename + "_b.bmp",
            filename + "_w.bmp",
            "-alpha", "off", "( ... )", "-composite",
            filename + ".png" ]

rawDescription: How not to quote argument in subprocess?

description: How not to quote argument in subprocess


rawDescription: Python, sort a list of dicts by an arbitrary order


code:
copy = {outer_key: {inner_key: newd.get(inner_key, inner_dict[inner_key]) for inner_key in inner_dict} for outer_key,inner_dict in data.items()}
copy
data

rawDescription: copy complex dictionary structure

description: Copy complex dictionary structure


rawDescription: add an item into sublist as value inside a dictionary

description: Add an item into sublist as value inside a dictionary


code:
ax1 = df.plot(x=['TIME'], y=['Column A'], kind='bar', color='r', legend=False)
ax1.set_ylabel("Label A")
ax2 = ax1.twinx()
ax2.plot(df['Column B'].values, linestyle='-', marker='o', linewidth=2.0, color ='b', label="test2")
ax2.set_ylabel("Label B")

lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines1 + lines2, labels1 + labels2, loc=0)

rawDescription: Using Pandas DF and Matplotlib to plot primary(bar) and secondary(line) axis but legends to be shown together..?


code:
#!/usr/bin/python

appendToFile = open("appendedFile", "r")
sortToFile = open("sortedFile", "w")

for line in sorted(appendToFile, key = str.lower):
    sortToFile.write(line)

rawDescription: Quickly alphabetize a large file via python


code:
#Create a 2d lists with the smaller lists containing the rgb values and append lists of lists
def horizontal_flip(self):
    if int(self.columns) > 1000:
        return "ERROR!! Number of columns is larger than what can be held in a buffer."
    else:
        temp_list = []
        for b in range(int(self.row)):
            column_list = []
            column_list += self.pixels[0:int(self.columns) * 3]
            self.pixels = self.pixels[int(self.columns) * 3 : ]
            temp_list.append(column_list)
        #print temp_list
        new_list = []
        for i in range(int(len(temp_list))):
            new_list.append (temp_list[i][0])
            new_list.append (temp_list[i][1])
            new_list.append (temp_list[i][2])
            temp_list[i] = temp_list[i][::-1]

rawDescription: Classes in Python

description: Classes in Python


code:
MIDDLEWARE_CLASSES = (
    '...',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    '...',
)

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.RemoteUserBackend',
)

rawDescription: Django Grab Apache User

description: Django Grab Apache User


code:
import json
import requests
from OpenSSL import crypto

P12_CERT_FILE = 'C:/Users/mryan/Documents/Code/SampleApps/bundle.p12'
p12_cert = crypto.load_pkcs12(open(P12_CERT_FILE).read(), 'passphrase')
pem_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, p12_cert.get_certificate())

# remove PEM header, footer, and new lines to produce raw cert data
raw_data = ''.join(pem_cert.split('\n')[1:-2])
cert_data = json.dumps({'RawData': raw_data})
result = requests.post(apiRoot + "/Accounts/" + accId + "/certs", data=cert_data)

rawDescription: Reading an X509 Certificate in Python

description: Reading an X509 Certificate in Python


code:
def __init__(self,form):

# Lots of your code is duplicated here, so I'm just highlighting the main parts

    button1 = Button(form, text='Button1', command = self.addchat)
    self.textbox = textbox1 # to make it accessible outside your __init__
    self.textarea = textarea1 # see above

    form.bind("<Return>", lambda x: self.addchat())
    # this is the magic that makes your enter key do something

def addchat(self):
    txt = self.textbox.get()
    # gets everything in your textbox
    self.textarea.insert(END,"\n"+txt)
    # tosses txt into textarea on a new line after the end
    self.textbox.delete(0,END) # deletes your textbox text

rawDescription: Tkinter. Press Enter in Entry box. Append to Text box. How?


code:
plt.plot(R,P,color='0.2',lw=1.5, zorder=1)
plt.scatter(R,P,s=150,color=c, zorder=2)

rawDescription: How to plot the lines first and points last in matplotlib

description: Plot the lines first and points last in matplotlib


code:
import math

# read the phone numbers from file
with open('phone.txt', 'r') as f:
    progs = f.read().splitlines()

folders = input( "How many folders for perfix {0} : ".format(name))
# calculate how many folders a number is in
# therefore use the highest possible number (e.g. if folders is 8 use 3)
num = int(math.ceil(float(folders)/len(progs)))

# loop through the number of folders to create
for i in xrange(folders):
    # create folder
    pathname = os.path.join(fullPath, str(i+1))
    os.mkdir( pathname )

    # create file
    filename = os.path.join(pathname, 'number.txt')
    with open(filename, 'w') as f:
        f.write(progs[i/num])

rawDescription: Python copy a string for specified number of times


code:
def guess_tab(text):
    count = 0
    for line in text.split("\n"):
        indents = line[:len(line)-len(line.lstrip())]
        if "\t" in indents:
            count += 1
    if count > 5:
        return True
    else:
        return False

def buffer_active(arg):
    editor.setBackSpaceUnIndents(True)
    use_tab = guess_tab(editor.getText())
    editor.setUseTabs(use_tab)
    sys.stderr.write( "setUseTabs %s\n" % use_tab )

notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED])
notepad.callback(buffer_active, [NOTIFICATION.BUFFERACTIVATED])

rawDescription: Notepad++ Automatic Detection of Python Tabs or Spaces


rawDescription: xpath on authenticated page in Python

description: Xpath on authenticated page in Python


code:
hstack((arange(10) for _ in range(10)))
vstack((arange(10) for _ in range(10)))

rawDescription: Combining multiple numpy arrays into one


code:
ttk.Style().configure("RB.TButton", background='black')
ttk_btn = ttk.Button(text="ttk_Sample", style="RB.TButton")

rawDescription: Remove grey borders from ttk.Button

description: Remove grey borders from ttk.Button


code: y = [sum(x[:i+1]) for i in range(len(x))]

rawDescription: Sum consecutive numbers in a list. Python


code:
def read_large_txt(path, delimiter=None, dtype=None):
    with open(path) as f:
        nrows = sum(1 for line in f)
        f.seek(0)
        ncols = len(f.next().split(delimiter))
        out = np.empty((nrows, ncols), dtype=dtype)
        f.seek(0)
        for i, line in enumerate(f):
            out[i] = line.split(delimiter)
    return out

rawDescription: why numpy narray read from file consumes so much memory?

description: Why numpy narray read from file consumes so much memory


code: [x + 'y' for x in lis]

rawDescription: Changing list of strings using python 2x


code:
import sys

from Foundation import NSString, NSAutoreleasePool

def fs_normalize(path):
    _pool = NSAutoreleasePool.alloc().init()
    normalized_path = NSString.fileSystemRepresentation(path)
    upath = unicode(normalized_path, sys.getfilesystemencoding() or 'utf8')
    return upath

if __name__ == '__main__':
    e = u'\xe9'
    j = u'\ufa1b'
    e_expected = u'e\u0301'

    assert fs_normalize(e) == e_expected
    assert fs_normalize(j) == j

rawDescription: How to convert path to Mac OS X path, the almost-NFD normal form?

description: Convert path to Mac OS X path, the almost-NFD normal form


code:
REQUIRE_EMAIL_VALIDATION_TO = Setting('REQUIRE_EMAIL_VALIDATION_TO', [], USERS_SET, dict(
label = _("Require email validation to..."),
help_text = _("Which actions in this site, users without a valid email will be prevented from doing."),
widget=CheckboxSelectMultiple(attrs={"checked":"checked"}),
choices=(("ask", _("ask questions")), ("answer", _("provide answers")), ("comment", _("make comments")), ("flag", _("report posts"))),
required=False,
))

rawDescription: python mechanize brakes the content of TextareaControl

description: Python mechanize brakes the content of TextareaControl


code:
open('deleteme', 'w').write('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
f = open('deleteme', 'r+')
f.read()
f.seek(0)
f.truncate()
f.write('bbb')
f.close()
open('deleteme').read()

rawDescription: Reading a file and then overwriting it in Python


rawDescription: List of cols to list of rows

description: List of cols to list of rows


rawDescription: VIM: How to access the redo-register

description: VIM: How to access the redo-register


code:
s = ["John", "Bertha", "Janna", "Daniel", "Emma"]
def change(s, a, b):
    s[b], s[a] = s[a], s[b]
change(s, 2, 4)
s

rawDescription: function that changes the position of 2 elements in a list

description: Function that changes the position of 2 elements in a list


code:
import paramiko

host='hostname'

# Make the connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host)

# Somehting like this to run the command:
stdin, stdout, stderr = ssh.exec_command("command --arg 1 --arg 2")

# Close connection
ssh.close()

rawDescription: How to use python to get result from remote terminal

description: Use python to get result from remote terminal


rawDescription: How Do I Remove A Vowel From String

description: How Do I Remove A Vowel From String


code:
import pyximport; pyximport.install()
import helloworld

rawDescription: What is pyximport and how should I use it?


code:
import argparse

class TwoOrSeven(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if len(values) not in (2,7):
            raise argparse.ArgumentTypeError('Not a valid number of args (2 or 7)')
        try:
            values = values[2], values[5]
        except IndexError:
            values = values[0]
        setattr(namespace, self.dest, values)
parser = argparse.ArgumentParser()
parser.add_argument('args', metavar='arg', action=TwoOrSeven, nargs='+',
    help='Must be supplied 2 or 7 arguments')

args = parser.parse_args('1 2 3 4 5 6 7'.split())
print(args)
# Namespace(args=('3', '6'))
args = parser.parse_args('1 2'.split())
print(args)
# Namespace(args='1')
args = parser.parse_args('1 2 3 4 5 6'.split())
# argparse.ArgumentTypeError: Not a valid number of args (2 or 7)

rawDescription: Python argparse: How to get simple parsing behavior?


code:
for item in my_list:
    # First time you see an item create an empty list
    if item not in my_dict:
        my_dict[item] = []
    # Otherwise, add the item to the list
    else:
        my_dict[item].append( item )

rawDescription: Create new dictionary into list

description: Create new dictionary into list


code:
listY = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = set()
for listX in listY:
    for x in listX:
        result.add(x)

rawDescription: What does this line of Python code mean?

description: What does this line of Python code mean


rawDescription: Regular expression group capture with multiple matches


code:
from models import *

class SlotInline(admin.StackedInline):
    model = Slot

class MatchupAdmin(admin.ModelAdmin):
    model = Matchup
    inlines = [SlotInline]

admin.site.register(Matchup, MatchupAdmin)

rawDescription: Inline Forms in Django 1.1 Admin Panel

description: Inline Forms in Django 1.1 Admin Panel


code:
import os

# Get a list of all files under the current directory
flist = []
for root, dirs, files in os.walk('.'):
    flist += [os.path.join(root, f) for f in files]

# Go over each file and see if it contains the string foo
want = 'foo'
targets = []
for path in flist:
    with open(path) as df:
        data = df.read()
    if want in data:
        targets.append(path)
# The targets list now contains the paths of all the files that contain foo.

rawDescription: Python: How can I open and read files in a directory that do not have a file extension (Windows)?


code:
import re
s = "djdjfksjlfsdk (600m 36.57) fhksjhfhsdhfkjhks"
m = re.findall(r'(?<=\()\d+|\d+[.:]\d+(?=\))', s, re.M)
m

rawDescription: alternative to encased capturing groups in python

description: Alternative to encased capturing groups in python


code:
def is_prime(x):
    if x < 2: ##because negative numbers, 0 and 1 are not prime##
            return False
    elif x == 2:
            return True
    else:
        for n in range(2, x):
            if x % n == 0:
                return False
    return True

rawDescription: My is_prime function fails on 9, and I don't know why?


rawDescription: Regarding an instance of simulating the functionality of 2D arrays in Python


code: re.search(r'\bthis is\b', 'I think this isnt right')

rawDescription: Python: sub string search

description: Python: sub string search


code:
str1 = 'caars'
str2 = 'rats'
set(str1) == set(str2)
str3 = 'racs'
set(str1) == set(str3)

rawDescription: Checking if two strings contain the same characters, not considering their frequencies


code:
d = defaultdict(int)
for lst in lists:
   d[len(lst)] += 1

rawDescription: How to get statistic of a list of lists in python?

description: Get statistic of a list of lists in python


code:
factors = {"factor 1" : "10 minutes",
"factor 2" : "2 minutes",
"factor 3" : "8 minutes",
"factor 4" : "20 minutes",
"factor 5" : "7 minutes"
}

wantedTime = 19;
String_1={}
String_2={}
total = 0
for k,v in factors.items():## or factors.iteritems()
    time = int(v.split(" ")[0])
    if total+time <= wantedTime:
        total +=time
        String_1[k]=v
    else:
        String_2[k]=v

rawDescription: dividing list in python based on variable

description: Dividing list in python based on variable


code:
driver = webdriver.PhantomJS("./phantomjs") # path to phantomjs binary
driver.get("https://ps.rsd.edu/public/")

elem = driver.find_element_by_name("account")
elem.send_keys("Username")
elem2 = driver.find_element_by_name("pw")
elem2.send_keys("Password")
elem.send_keys(Keys.RETURN)

driver.quit()

rawDescription: Using Selenium in the background

description: Using Selenium in the background


code:
Code
import Image, ImageDraw # PIL modules

withlines = Image.open('withgrid.jpg')
nolines   = Image.open('nogrid.jpg')

def findlines(image):
    w,h, = image.size
    s = w*h
    im = image.point(lambda i: 255 * (i < 60))   # threshold
    d = im.getdata()      # faster than per-pixel operations

    linecolumns = []

    for col in range(w):
        black = sum( (d[x] for x in range(col, s, w)) )//255
        if black > 450:
            linecolumns += [col]

    # return an image showing the detected lines
    im2 = image.convert('RGB')
    draw = ImageDraw.Draw(im2)
    for col in linecolumns:
        draw.line( (col,0,col,h-1), fill='#f00', width = 1)

    return im2

findlines(withlines).show()
findlines(nolines).show()

rawDescription: Categorize different images

description: Categorize different images


code:
card = raw_input("Enter your credit card number here: ")
digit_sum = 0

for i, digit in enumerate(reversed(card)):
    n = int(digit)

    if i % 2 == 0:
        digit_sum += n
    elif i >= 5:
        digit_sum += n * 2 - 9
    else:
        digit_sum += n * 2

if digit_sum % 10 == 0:
    print("Card is valid!")
else:
    print("Card is invalid!")

rawDescription: Is this the most efficient way to write the Luhn algorithm in Python?


code:
exec("""
def _f():
    print('B')
    return
    print('C')
_f()
""")

rawDescription: Python - early return from exec

description: Python - early return from exec


code: yaml.dump(d,  width=20, default_flow_style=False)

rawDescription: How do I write a YAML file using a dictionary with long keys and values?

description: Write a YAML file using a dictionary with long keys and values


code: import posixpath

rawDescription: Is there any way I can specify the platform for os.path?


code:
for e in xs:
   myDict.setdefault(val(e), []).append(e)

rawDescription: Efficiently adding elements to a list in python


code:
class Demo:
    def __init__(self):
       self.__snooze_time = None
       self.window = gtk.Window()
       self.window.connect("destroy", gtk.main_quit)
       self.button = gtk.Button(stock = gtk.STOCK_SAVE)

       self.button.connect("clicked", self.run, window, snooze_time_entry)
    def run(self, widget, event, data):
       try:
          self.__snooze_time = int(data.get_text())
       except ValueError:
          snooze_time = 5

rawDescription: Accessing return value of function passed directly into another in Python


code: newlist = oldlist[::-1]

rawDescription: Best way to create a "reversed" list in Python?

description: Create a "reversed" list in Python


code:
mList = myObj.objects.all()
for my_obj in mList:
    my_obj.user = uDict.get(my_obj.C)

rawDescription: How to combine a QuerySet and a Dictionary in Django Template?

description: Combine a QuerySet and a Dictionary in Django Template


code:
ar = np.zeros((512,256),dtype=np.uint16)

# there should be something here to fill ar

xs = np.arange(ar.shape[0])
ys = np.arange(ar.shape[1])

check = (0 < ar) & (ar < 1000)
ind = np.where( check )
xlist = xs[ ind[0] ]
ylist = ys[ ind[1] ]
zlist = ar[ check ]

rawDescription: Python: process array faster

description: Python: process array faster