code:
for params in get_params(some_stuff_here, and_another_stuff):
    param_one, param_two, param_three, param_four, param_five = params
    pass

rawDescription: proper formatting of python multiline [ for in ] statement

description: Proper formatting of python multiline [ for in ] statement


code:
Hello
World

rawDescription: How to insert a string on a specific line in a Sublime Text Plugin?

description: Insert a string on a specific line in a Sublime Text Plugin


code:
import string
values = dict()
for index, letter in enumerate(string.ascii_lowercase):
   values[letter] = index + 1

rawDescription: python: How do I assign values to letters?

description: Python: How do I assign values to letters


code: vargs={key:(float(v0),float(v1)) for key,v0,v1 in args.kwarg}

rawDescription: using a variable keyword for an optional argument name with python argparse

description: Using a variable keyword for an optional argument name with python argparse


code:
start = 'AUG'
stop = ('UAA', 'UGA', 'UAG')

rawDescription: Creating a List of Lists for Three Reading Frames


code: make_list = ArrayField(models.CharField(max_length=200), blank=True)

rawDescription: How to avoid brackets in SQL around Django custom database function call?

description: Avoid brackets in SQL around Django custom database function call


rawDescription: Python requests urlencode not working?

description: Python requests urlencode not working


rawDescription: print array in specific format

description: Print array in specific format


rawDescription: Numpy put array in Nth dimension

description: Numpy put array in Nth dimension


code:
g = lambda x:[lambda x:x*1, lambda x:x*x, lambda x:x*x*x, lambda x:42][x%4](x)
[g(x) for x in xrange(12)]

rawDescription: Python lambda in lambda

description: Python lambda in lambda


code:
import re
input_str = 'foo [[bar]] baz [[etc.]]'

rawDescription: Most pythonic way to delete text between two delimiters


rawDescription: iterating over lists finding standard deviation of each point

description: Iterating over lists finding standard deviation of each point


rawDescription: Vectorize mask of squared euclidean distance in Python


code:
values[1].append(4)
values
values[1][1][1].append(5)
values

rawDescription: Python:how to understand assignment and reference?


code: list_a, list_b, list_c = [[0 for k in range(10)] for i in range(3)]

rawDescription: Functioning of list values in Python

description: Functioning of list values in Python


code:
import textwrap

class Table:

    def __init__(self,
                 contents,
                 wrap,
                 wrapAtWordEnd = True,
                 colDelim = "|",
                 rowDelim = "-"):

        self.contents = contents
        self.wrap = wrap
        self.colDelim = colDelim
        self.wrapAtWordEnd = wrapAtWordEnd

        # Extra rowDelim characters where colDelim characters are
        p = len(self.colDelim) * (len(contents[0]) - 1)

        # Line gets too long for one concatenation
        self.rowDelim = self.colDelim
        self.rowDelim += rowDelim * (self.wrap * max([len(i) for i in l]) + p)
        self.rowDelim += self.colDelim + "\n"

    def withoutTextWrap(self):

        string = self.rowDelim

        for row in self.contents:
            maxWrap = (max([len(i) for i in row]) // self.wrap) + 1
            for r in range(maxWrap):
                string += self.colDelim
                for column in row:
                    start = r * self.wrap
                    end = (r + 1) * self.wrap
                    string += column[start : end].ljust(self.wrap)
                    string += self.colDelim
                string += "\n"
            string += self.rowDelim

        return string

    def withTextWrap(self):

        print(self.wrap)

        string = self.rowDelim

        # Restructure to get textwrap.wrap output for each cell
        l = [[textwrap.wrap(col, self.wrap) for col in row] for row in self.contents]

        for row in l:
            for n in range(max([len(i) for i in row])):
                string += self.colDelim
                for col in row:
                    if n < len(col):
                        string += col[n].ljust(self.wrap)
                    else:
                        string += " " * self.wrap
                    string += self.colDelim
                string += "\n"
            string += self.rowDelim

        return string

    def __str__(self):

        if self.wrapAtWordEnd:

            return self.withTextWrap()

        else:

            return self.withoutTextWrap()

if __name__ == "__main__":

    l = [["heading 1", "heading 2", "asdf"],
         ["some text", "some more text", "Lorem ipsum dolor sit amet."],
         ["lots and lots and lots and lots and lots of text", "some more text", "foo"]]

    table = Table(l, 20, True)

    print(table)

rawDescription: how to have multirow cells in Python table

description: Have multirow cells in Python table


code:
from django import template
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import re

register = template.Library()

@register.filter(name='twittify')
def twittify(tweet, autoescape=None):
    tweet = conditional_escape(tweet)
    user_pattern = re.compile('(\s|^)(@)(\w+)(\s|$)')
    tweet = user_pattern.sub('\1\2\3\4', tweet)
    return mark_safe(tweet)

twittify.needs_autoescape = True

rawDescription: Linking a @username in Django Template Variables


code:
class User:  # changed class name to make it clearer
    users = {}

    def __init__(self, name, list_a, list_b, list_c, list_d):  # added underscores to make list name easier to read
        self.name = name
        self.list_a = list_a
        self.list_b = list_b
        self.list_c = list_c
        self.list_d = list_d

    @classmethod  # the @classmethod is a preference for later sub-classes to have the ability to edit the list if need-be
    def create_new_users(cls):
        print("how many users do you want to create")
        x = int(input())
        for _ in range(x):
            name = input("Assign the users names")
            if name == '' or name.lower() == 'none':
                raise RuntimeError("name cannot be None or empty")
            new_user = cls(name, list_a=[], list_b=[], list_c=[], list_d=[])  # changed strings to lists
            cls.users[new_user.name] = new_user  # adds new_user to the dict using the user name as the key

    @classmethod
    def show_users(cls):
        for key in cls.users:
            print(key, cls.users[key])

    @classmethod
    def set_lists(cls):
        choice = input("select the user you intend on adding lists for")  # moved prompts into input()
        for elem in User.users:
            print(vars(User.users[choice]))
            decision2 = int(input("how many lists would you like to create?(up to 4)"))
            if decision2 == 1:
                name_string = input("what would you like the list to be named?")
                setattr(User.users['Ian'], 'list_a', name_string) # see below
                print("you have created 1 list, with the name:%s" %name_string)

rawDescription: Editing an attribute reffering to a list of classes


code:
import random
ar = [
    [[random.randint(1, 100)] for t in range(1, 5)]
    for i in range(1, 5)
]
for row in ar:
    print(row)

rawDescription: Random number grid 4 x 6 Python 3

description: Random number grid 4 x 6 Python 3


rawDescription: Python itertools.combinations continue from certain value?


rawDescription: trying to mask 2D numpy arrays based on values in one column

description: Trying to mask 2D numpy arrays based on values in one column


code:
@gen.engine
def async_fetch(url, method='GET', headers={}, body=None, callback=None):
    async_http_client = AsyncHTTPClient()
    http_request = HTTPRequest(url, method=method, headers=headers, body=body)
    http_response = yield client.fetch(http_request)
    if callback:
        callback(http_response)

class MyHandler(RequestHandler):
    @web.asynchronous
    @gen.engine
    def get():
        ...
        response = yield gen.Task(async_fetch, 'http://example.org')
        ...

rawDescription: How to make a wrapper that simplifies requests with tornado AsyncHTTPClient?

description: Make a wrapper that simplifies requests with tornado AsyncHTTPClient


code:
from celery import Celery
from datetime import timedelta

celery = Celery(__name__)
celery.config_from_object(__name__)

@celery.task
def say_hello():
    print('Hello, World!')

CELERYBEAT_SCHEDULE = {
    'every-second': {
        'task': 'example.say_hello',
        'schedule': timedelta(seconds=5),
    },
}

rawDescription: Print statement in Celery scheduled task doesn't appear in terminal


rawDescription: How to merge two columns together in Pandas

description: Merge two columns together in Pandas


code:
regex = re.compile(r"""
    \{START\}  # Match {START}
    (          # Match and capture the following:
     (?:       # Start of non-capturing group, used to match a single character
      (?!      # only if it's impossible to match the following:
       \{      # - a literal {
       (?:     # Inner non-capturing group, used for the following alternation:
        START  # - Either match the word START
       |       # or
        END    # - the word END
       )       # End of inner non-capturing group
       \}      # - a literal }
      )        # End of negative lookahead assertion
      .        # Match any single character
     )*        # Repeat as often as possible
    )          # End of capturing group 1
    \{END\}    # until {END} is matched.""",
    re.VERBOSE)

rawDescription: python regex to match all minimal strings between specified start and end tokens

description: Python regex to match all minimal strings between specified start and end tokens


code:
newdic = {key:[i*1000 if key != 'x' else i for i in val] for key,val in dic.items()}
newdic
newdic = {key:[i*1000 if key not in ('x','y') else i for i in val] for key,val in dic.items()}
newdic

rawDescription: looping over keys and values, process the key values and store them back another dictinory in Python

description: Looping over keys and values, process the key values and store them back another dictinory in Python


code:
class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

rawDescription: How to markup form fields with <div class='field_type'> in Django

description: Markup form fields with <div class='field_type'> in Django


code:
def find_indices(haystack, needle):
  return [i for i,x in enumerate(haystack) if needle == x]

def remove_at(xs, indices):
  return [x for i,x in enumerate(xs) if i not in indices]

rawDescription: Can I put a value in a y-series to prevent matplotlib plotting a value for that x-value?

description: Put a value in a y-series to prevent matplotlib plotting a value for that x-value


code:
@app.route('/create', methods=['GET', 'POST'])
def article_create():
    if 'email' not in session:
        return redirect(url_for('signin'))
    person = Person.query.filter_by(email=session['email']).first()
    name = person.firstname
    article = Article()
    form = ArticleCreateForm()
    form.person_name.data = person.firstname
    if form.validate_on_submit():
        form.populate_obj(article)
        db.session.add(article)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('create.html', form=form, person=person, name=name)

rawDescription: How to use hidden input in an html form with Python+Jinja2

description: Use hidden input in an html form with Python+Jinja2


code:
from timeit import timeit
timeit('7. ** i', setup='i = 5')
timeit('pow(7., i)', setup='i = 5')
timeit('math.pow(7, i)', setup='import math; i = 5')

rawDescription: Exponentials in python x.**y vs math.pow(x, y)


code:
model = SVC()
model.fit(X, y)

rawDescription: How to vectorize labeled bigrams with scikit learn?

description: Vectorize labeled bigrams with scikit learn


code:
test(1, 2, operator.lt)
test(1, 2, operator.gt)

rawDescription: Is there a way to swap between logical operators on the basis of some boolean?


code: df = pd.read_csv(StringIO.StringIO(d[1:]), header=None, parse_dates=[0])

rawDescription: How to get the mean over time value

description: Get the mean over time value


code:
import time
time.strptime('9:00 AM', '%I:%M %p')
time.strptime('9:00 PM', '%I:%M %p')

rawDescription: How to access meridiem of a time in Python?

description: Access meridiem of a time in Python


code:
info = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+city +','+ country +'&mode=json')
info.json()['coord']['lon']

rawDescription: How to extract information out of an api in python

description: Extract information out of an api in python


code:
import cb

class CB(cb.Callback):
    def __init__(self):
        super(CB, self).__init__()
    def call(self, x):
        print("Hello from CB!")
        print(x)

def foo(x):
    print("Hello from foo!")
    print(x)

class Bar:
    def __call__(self, x):
        print("Hello from Bar!")
        print(x)

o = cb.ObjWithPyCallback()
mycb=CB()
o.setCallback(mycb)
o.call()
o.setCallback(foo)
o.call()
o.setCallback(Bar())
o.call()

rawDescription: What Is The Cleanest Way to Call A Python Function From C++ with a SWIG Wrapped Object


code:
class Example(QWidget):
    my_signal = pyqtSignal(int)

rawDescription: PyQt proper use of emit() and pyqtSignal()


code:
for i in range(n):
    doSomething()

rawDescription: Transform a while loop with counter into a more pythonic code


code:
from . import art3d
from . import proj3d
from . import axis3d

rawDescription: How to update 3D arrow animation in matplotlib

description: Update 3D arrow animation in matplotlib


rawDescription: matrix array plotting opposite of what i want matplotlib

description: Matrix array plotting opposite of what i want matplotlib


code: proc = subprocess.Popen(['echo', os.path.expandvars('$MY_ENV_VAR')])

rawDescription: How to get PID via subprocess.Popen with custom environment variable?

description: Get PID via subprocess.Popen with custom environment variable


code: final_result =  [{key:dic_a[key]- dic_b[key]} for dic_a in a for dic_b in b for key in dic_a if key in dic_b]

rawDescription: Compare the keys of two dictionaries present inside two lists and subtracting their respective values


code:
import csv
with open('<csvfile>','r') as f:
    reader = csv.reader(f,skipinitialspace=True)
    words = next(reader)

rawDescription: Reading comma-separated words into pandas


code:
import string
import itertools
import random

initial_consonants = (set(string.ascii_lowercase) - set('aeiou')
                      # remove those easily confused with others
                      - set('qxc')
                      # add some crunchy clusters
                      | set(['bl', 'br', 'cl', 'cr', 'dr', 'fl',
                             'fr', 'gl', 'gr', 'pl', 'pr', 'sk',
                             'sl', 'sm', 'sn', 'sp', 'st', 'str',
                             'sw', 'tr'])
                      )

final_consonants = (set(string.ascii_lowercase) - set('aeiou')
                    # confusable
                    - set('qxcsj')
                    # crunchy clusters
                    | set(['ct', 'ft', 'mp', 'nd', 'ng', 'nk', 'nt',
                           'pt', 'sk', 'sp', 'ss', 'st'])
                    )

vowels = 'aeiou' # we'll keep this simple

# each syllable is consonant-vowel-consonant "pronounceable"
syllables = map(''.join, itertools.product(initial_consonants,
                                           vowels,
                                           final_consonants))

# you could trow in number combinations, maybe capitalized versions...

def gibberish(wordcount, wordlist=syllables):
    return ' '.join(random.sample(wordlist, wordcount))

rawDescription: Any Python password-generators that are readable and pronounceable?


code:
while True:
    try:
        num = int(input("Give me an integer between 1 and 100:"))
        if num > 100 or num < 1:
            print ("Sorry, that is not an integer between 1 and 100. Try again.")
            continue
    except ValueError:
        print ("Sorry, that is not an integer between 1 and 100. Try again.")
    else:
        print ("Thank you for your input")
        break

rawDescription: python try except format

description: Python try except format


code:
from operator import add, sub, mul, floordiv
from random import choice

tries = 10
maxn = 9
numbers = list(range(1, maxn+1))
ops = (('+', add), ('-', sub), ('*', mul), ('//', floordiv))

for i in range(tries):
    left = choice(numbers)
    right = choice(numbers)
    op = choice(ops)
    print("What is", left, op[0], right,"?")
    try:
        user = int(input("Answer here: "))
    except ValueError:
        user = None
    if user == op[1](left, right):
        print("Well done")
    else:
        print("No")

rawDescription: Accessing functions which have been placed in a list


code:
class PostListView(ListView):
    queryset = Post.objects.all().order_by("-date")[:4]
    template_name = "personal/index.html"

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        context['background_image'] = 'personal/img/home-bg.jpg'
        return context

rawDescription: Django pass parameter to web page via ListView class


code: [k for k,v in User._fields.iteritems() if v.required]

rawDescription: Get required fields from Document in mongoengine?


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

xy = np.random.random((5, 2))
text = ['A', 'B', 'C', 'D', 'E']

fig, ax = plt.subplots()
for (x,y), label in zip(xy, text):
    ax.text(x, y, label, ha='center', size=20)
plt.show()

rawDescription: Plot strings of text on Basemap in place of points in Python


code:
def a():
    print('a')

rawDescription: Can I add function references to a list, and iterate over this list calling each in succession?

description: Add function references to a list, and iterate over this list calling each in succession


code: datetime.date(year_int, month_int, _)

rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


rawDescription: How do I convert a list of tuples with sets to a dictionary?

description: Convert a list of tuples with sets to a dictionary


code:
Output
['Here is the First Paragraph.', 'Here is the second Paragraph.',
 'Paragraph Three."']

rawDescription: extracting paragraph in python using lxml

description: Extracting paragraph in python using lxml


code:
import pickle
t = open('/tmp/x.pickle', 'w+b')
pickle.dump(x, t)

rawDescription: getting the class path or name space of a class in python even if it is nested

description: Getting the class path or name space of a class in python even if it is nested


code:
import os
os.system("start /WAIT cmd /c ping google.com -t")

rawDescription: Python , trying to open a command

description: Python , trying to open a command


rawDescription: my matplotlib title gets cropped

description: My matplotlib title gets cropped


code:
class UiDialog(object):
    def setupUi(self, datadb):
        datadb.setObjectName("Dialog")
        datadb.resize(404, 304)
        datadb.setWindowTitle("Database results")
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(datadb.sizePolicy().hasHeightForWidth())
        datadb.setSizePolicy(sizePolicy)
        datadb.setMinimumSize(QtCore.QSize(404, 304))
        datadb.setMaximumSize(QtCore.QSize(404, 304))
        self.table = QtGui.QTableWidget(datadb)
        self.table.setGeometry(QtCore.QRect(2, 2, 400, 261))
        self.table.setObjectName("table")
        self.show = QtGui.QPushButton(datadb)
        self.show.setGeometry(QtCore.QRect(2, 270, 400, 31))
        self.show.setObjectName("show")
        self.show.setText("Show results")
        QtCore.QObject.connect(self.show, QtCore.SIGNAL("clicked()"), lambda: self.populate(datadb)) ### Using LAMBDA function to pass datadb object to the method
        #self.show.pressed.connect(lambda: self.populate(datadb)) ### Another syntax for the same operation
        QtCore.QMetaObject.connectSlotsByName(datadb)

    def populate(self, mainWindow):
        self.table.setRowCount(len(all_data))
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(['Number', 'Keys', 'Time', 'Tries'])
        for i, item in enumerate(all_data):
            number = QtGui.QTableWidgetItem(str(item[0]))
            keys = QtGui.QTableWidgetItem(item[1])
            time = QtGui.QTableWidgetItem(str(item[2]))
            tries = QtGui.QTableWidgetItem(str(item[3]))
            self.table.setItem(i, 0, number)
            self.table.setItem(i, 1, keys)
            self.table.setItem(i, 2, time)
            self.table.setItem(i, 3, tries)
        mainWindow.setWindowTitle("ANOTHER TITLE")

rawDescription: PyQT change dynamically a QMainWindow title


code:
[[u'Hello', u'Good', u'See'], [u'world!', u'morning', u'you!']]

[[u'Hello' u'world!']
 [u'Good' u'morning']
 [u'See' u'you!']]

rawDescription: Reading a Matlab's cell array saved as a v7.3 .mat file with H5py


rawDescription: Correct way to octal escape a UTF-8 character in Python


code: df['value'] + previous.cumsum()

rawDescription: Pandas create time series from day counts


rawDescription: Passing a math equation as an argument (numpy)


code:
parser.add_argument('-v', '--verbose', action='store_true',
    help='Increases messages being printed to stdout')

rawDescription: Using argparse to convert csv to xml in python


code:
from locale import *
setlocale(LC_NUMERIC, '') # set to your default locale; for me this is
# 'English_Canada.1252'. Or you could explicitly specify a locale in which floats
# are formatted the way that you describe, if that's not how your locale works :)
atof('123,456') # 123456.0
# To demonstrate, let's explicitly try a locale in which the comma is a
# decimal point:
setlocale(LC_NUMERIC, 'French_Canada.1252')
atof('123,456') # 123.456

rawDescription: How to convert an input number 34,6 to decimal form 34.6 in Python

description: Convert an input number 34,6 to decimal form 34.6 in Python


code:
# my_model.py
def V(m, k, x):
   return -m*x**2 + k*x**4

rawDescription: Python structuring - Do I really need a class?


code:
def replace(thelist, a, b):
    if not thelist:
        return []
    elif thelist[0] == a:
        return [b] + replace(thelist[1:], a, b)
    else:
        return [thelist[0]] + replace(thelist[1:], a, b)

rawDescription: Iterate a list using recursion

description: Iterate a list using recursion


code: reduce(lambda x, y: x[y], index, array)

rawDescription: Indexing into a nested array of arbitrary dimension?


code:
import csv
import datetime
import copy
from collections import defaultdict

with open(r"C:\Temp\test.csv") as i, open(r"C:\Temp\resuls.csv", "wb") as o:
    rdr, wrt = csv.reader(i), csv.writer(o)

    curr, currdate = defaultdict(lambda:[0, 0]), None
    for line in rdr:
        date, name = datetime.datetime.strptime(line[0], '%d/%m/%Y'), line[7]

        if date != currdate or not currdate:
            prev = copy.deepcopy(curr)
            currdate = date

        wrt.writerow(line + prev[name])

        curr[name][1] += 1
        if line[6] == "1": curr[name][0] += 1

rawDescription: Calculating number of occurrences and entering and appending them to csv


code:
patches, texts, autotexts = ax.pie(frac, colors=colors, labels=labels, autopct='%1.1f%%')
texts[0].set_fontsize(4)
plt.show()

rawDescription: How to set the labels size on a pie chart in python

description: Set the labels size on a pie chart in python


code:
df = DataFrame(dict(A=list(range(5)),B=list(range(5))))
df
store = pd.HDFStore('test.h5',mode='w')
store.append('df',df)

rawDescription: Selecting rows from an HDFStore by index using where


code:
#Vigenere Cipher
EncryptedMessage=""
Mode=""
Keywordcount = 0 #sets everything to 0

while Mode != "encrypt" and Mode != "decrypt":
    Mode = input('Do you want to encrypt or decrypt a message?')
    Mode = Mode.lower()

if Mode == "encrypt":
    Keyword=input('Please enter the keyword you want to use:')
    Message=input('Please eneter the message you wish to encrypt: ')
    Keywordlength = len(Keyword)
    for i in range(0, len(Message)):
        Messageencrypt = Message[i]
        Keywordencrypt = Keyword[Keywordcount]
        if Messageencrypt.isalpha():
            if Messageencrypt.isupper():
                Messageencrypt = ord(Messageencrypt)
                Keywordencrypt = Keywordencrypt.upper()
                Keywordencrypt = ord(Keywordencrypt) - 64
                CodedMessage = Messageencrypt + Keywordencrypt
                if CodedMessage > 90:
                    CodedMessage = CodedMessage - 26
                Encryptedletter = chr(CodedMessage)
            elif Messageencrypt.islower():
                Messageencrypt = ord(Messageencrypt)
                Keywordencrypt = Keywordencrypt.upper()
                Keywordencrypt = ord(Keywordencrypt) - 64
                CodedMessage = Messageencrypt + Keywordencrypt
                if CodedMessage > 122:
                    CodedMessage = CodedMessage - 26
            Encryptedletter = chr(CodedMessage)
        else:
            Encryptedletter = Messageencrypt
        EncryptedMessage = EncryptedMessage + Encryptedletter
        Keywordcount = Keywordcount + 1
        if Keywordcount >= Keywordlength:
            Keywordcount = 0
    print(EncryptedMessage)

if Mode == "decrypt":
    Keyword=input('Please enter the keyword you want to use:')
    Message=input('Please eneter the message you wish to decrypt: ')
    Keywordlength = len(Keyword)
    for i in range(0, len(Message)):
        Messageencrypt = Message[i]
        Keywordencrypt = Keyword[Keywordcount]
        if Messageencrypt.isalpha():
            if Messageencrypt.isupper():
                Messageencrypt = ord(Messageencrypt)
                Keywordencrypt = Keywordencrypt.upper()
                Keywordencrypt = ord(Keywordencrypt) - 64
                CodedMessage = Messageencrypt - Keywordencrypt
                if CodedMessage < 65:
                    CodedMessage = CodedMessage + 26
                Encryptedletter = chr(CodedMessage)
            elif Messageencrypt.islower():
                Messageencrypt = ord(Messageencrypt)
                Keywordencrypt = Keywordencrypt.upper()
                Keywordencrypt = ord(Keywordencrypt) - 64
                CodedMessage = Messageencrypt - Keywordencrypt
                if CodedMessage < 97:
                    CodedMessage = CodedMessage + 26
            Encryptedletter = chr(CodedMessage)
        else:
            Encryptedletter = Messageencrypt
        EncryptedMessage = EncryptedMessage + Encryptedletter
        Keywordcount = Keywordcount + 1
        if Keywordcount >= Keywordlength:
            Keywordcount = 0
    print(EncryptedMessage)

rawDescription: Can someone tell me why my encrpyt works but not my decrpyt? look at picture below


code:
for i in range(len(test) - 1, -1, -1):
    if test[i] not in ["C","D"]:
        del test[i]

rawDescription: How can I loop through a list of strings?

description: Loop through a list of strings


code:
i=[x for x in neigh(next,i) if x == curr[i]-orig[i]][0]
orig[i]

rawDescription: Finding the Maximum Route in a given input


code:
numbers = [1, 2, 3, 4]
digits = [str(number) for number in numbers]
digits
numeral = ''.join(digits)
numeral
number = int(numeral)
number

rawDescription: Convert an int list into an int number

description: Convert an int list into an int number


code:
import subprocess
import shlex
import threading

def worker():
    proc = subprocess.Popen(shlex.split('animate animation.gif'))
    proc.communicate()

t = threading.Thread(target = worker)
t.daemon = True
t.start()
# do other stuff in main process
t.join()

rawDescription: How to display an animated gif with Linux?

description: Display an animated gif with Linux


code:
def check_quarters(row):
   # if either Quarter or Last_Quarter is NaN, return False
   if (row['Quarter'] != row['Quarter']) or (row['Last_Quarter'] != row['Last_Quarter']):
      return False
   # check for valid combination when Quarter is Q2 Q3 or Q4
   if int(row['Quarter'][1:2]) - 1 == int(row['Last_Quarter'][1:2]):
      return True
   # check for valid combination when Quarter is Q1
   elif int(row['Quarter'][1:2]) == 1 and int(row['Last_Quarter'][1:2]) == 4:
      return True
   else:
      return False

rawDescription: Detect errant data over consecutive rows of a Python Pandas DataFrame


code:
def client_marshal(client):
    if client.email:
        return {'id' : fields.String,
                'name' : fields.String,
                'email' : fields.String}
    else:
        return {'id' : fields.String,
                'name' : fields.String}

rawDescription: Flask-RESTful - don't return object property instead of returning null


code: open(myfile, 'rb')

rawDescription: Python line read size in bytes

description: Python line read size in bytes


code:
for x in indices:
    print (x[0])

rawDescription: Accessing elements in a list of arrays in python


rawDescription: Python: transform a list of lists of tuples


code:
# coding: utf-8
import csv
import cStringIO
import codecs

class DictUnicodeWriter(object):

    def __init__(self, f, fieldnames, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.DictWriter(self.queue, fieldnames, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, D):
        self.writer.writerow({k:v.encode("utf-8") for k,v in D.items()})
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for D in rows:
            self.writerow(D)

    def writeheader(self):
        self.writer.writeheader()

D1 = {'name':u'马克','pinyin':u'Mǎkè'}
D2 = {'name':u'美国','pinyin':u'Měiguó'}
f = open('out.csv','wb')
f.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
w = DictUnicodeWriter(f,sorted(D.keys()))
w.writeheader()
w.writerows([D1,D2])
f.close()

rawDescription: Python DictWriter writing UTF-8 encoded CSV files


code:
import datetime
l = [datetime.datetime(2014, 1, 1, 0, 0), datetime.datetime(2015, 1, 1, 0, 0)]
sum(1 for d in l if d > datetime.datetime(2014, 2, 1, 0, 0))

rawDescription: Count by > DATE

description: Count by > DATE


code:
class ThreadPool(object):

    def __init__(self, size = 1, start=False):
        self.__poolEvent = Event()
        self.__runEvent = Event()
        self.__size = size
        self.__queue = Queue()
        self.__pool = []
        self.__destroyed = False

        if start:
            self.__runEvent.set()

rawDescription: SOLVED: Custom Python Thread Pool Synchrnoization


code:
import argparse
import numpy as np
if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-l','--list', help='list variables', action='store_true')
    parser.add_argument('filename')
    __args = parser.parse_args()
    data = np.load(__args.filename)
    locals().update(data)
    del parser, data, argparse, np
    if __args.list:
        print([k for k in locals() if not k.startswith('__')])
    del __args

rawDescription: IPython loading variables to workspace: can you think of a better solution than this?


code:
import matplotlib.pyplot as plt

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

ax.annotate("TESTING", xy=(.5, .5), xytext=(.5, .5),
           )

plt.show()

rawDescription: Matplotlib text transparency

description: Matplotlib text transparency


code: df

rawDescription: Pandas plot on 3 variables

description: Pandas plot on 3 variables


code:
sentence = "My screen is smashed"
sentence = "My screen is smashed and broken"
sentence = "My screen is broken"
sentence = "My phone is broken"

rawDescription: Search multiple keywords in string

description: Search multiple keywords in string


code:
col = 0 if value > y else 1
row = 0 if value > x else 1
fn = arr[row][col]

rawDescription: Select a function in a Pythonic way

description: Select a function in a Pythonic way


code:
from collections import defaultdict

processed = defaultdict(list)

for s in data:
    chr_, start, end = s.split(":")
    processed[chr_].append((int(start), int(end)))

rawDescription: Python - Overlapping Ranges - Determine unique positions


code:
['>gb|CP001618.1|:70731-70780 Beutenbergia cavernae DSM 12333,'
 'complete genome\n',
 'GCCCGAGTTCCCCGAACCGTGCCGAGGTAGTACTCCACGGGCGAGGGAGT\n',
 '\n']

rawDescription: How do I extract a sequence from a genome based on homologues with a sequence?

description: Extract a sequence from a genome based on homologues with a sequence


code:
array([[False, False,  True, False],
       [False, False,  True, False],
       [ True, False, False, False]], dtype=bool)

rawDescription: Find adjacent elements in a 2D numpy grid


code:
d2 = {3: 'three', 2:'LOL'}
dict(ChainMap(*ds))
dict(ChainMap(*reversed(ds)))

rawDescription: Dict merge in a dict comprehension

description: Dict merge in a dict comprehension


code: return (True, a, b)

rawDescription: Python return true - false and value

description: Python return true - false and value


code:
def isPDFfile(fname):
    if not os.path.isfile(fname):
        return False
    name, ext = os.path.splitext(fname)
    return ext.lower() == '.pdf'

rawDescription: How to distinguish a PDF file from other files?

description: Distinguish a PDF file from other files


code:
z = [[5,2,7],[8,1,5],[3,4,10]]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(z,extent=[3,6,6,9],interpolation='none')

plt.show()

rawDescription: How to set graph (and not figure !) size in matplotlib

description: Set graph (and not figure !) size in matplotlib


rawDescription: Multiprocessing in Python to process a list of parameters


code:
# -*- coding: utf-8 -*-
import re
import unicodedata
from functools import partial

NFKD = partial(unicodedata.normalize, 'NFKD')

def match(word, letters):
    word, letters = NFKD(word), map(NFKD, letters) # normalize
    return re.match(r"(?:%s)+$" % "|".join(map(re.escape, letters)), word)

words = [u"மரம்", u"மடம்", u"படம்", u"பாடம்"]
get_words = lambda letters: [w for w in words if match(w, letters)]

print(" ".join(get_words([u'ம', u'ப', u'ட', u'ம்'])))
# -> மடம் படம்
print(" ".join(get_words([u'ப', u'ம்', u'ட'])))
# -> படம்

rawDescription: Regex to get list of all words with specific letters (unicode graphemes)


code: first_num, first_arr, second_num, second_arr = generate_arrangements(data)

rawDescription: Unpack a given number of items in Python?


code:
def __init__ (self, fields):
    for attribute, value in fields.items():
        setattr(self, attribute, value)

rawDescription: Create class instance with unknown number of attributes


code:
for i in range(len(words)):
    if words[i] in word_list.keys():
        words[i] = word_list[words[i]]

rawDescription: Python string replacement

description: Python string replacement


code:
class Foo(object):
    def __init__(self):
        self._a = 2
        self.b = 2

    @property
    def a(self):
        self._a += 1
        return self._a - 1

rawDescription: Python: How to do extra stuff when a specific attribute of an object is accessed?


code:
class ShareObject:
    def __init__(self):
        self.data = None

    def get(self):
        return self.data

    def set(self, data):
        self.data = data

rawDescription: Using RLock inside shared object

description: Using RLock inside shared object


code:
import numpy as np

def sol0(M):
    return np.eye(M.shape[1]) * M[:,np.newaxis,:]

def sol1(M):
    b = np.zeros((M.shape[0], M.shape[1], M.shape[1]))
    diag = np.arange(M.shape[1])
    b[:, diag, diag] = M
    return b

rawDescription: Numpy: Fastest way of computing diagonal for each row of a 2d array


rawDescription: Passing variables to a function

description: Passing variables to a function


code: return tb, mobilityhelper

rawDescription: How to add a variable of a method of a class in aonther program in python?

description: Add a variable of a method of a class in aonther program in python


rawDescription: Regex pattern to stop only accept what's left on that line


code:
class UserProfileManager(models.Manager):
    def create_profile(self, user, role):
        profile = self.create(user=user, role=role)
        return profile

rawDescription: How to save data in models with oneToOne relationship

description: Save data in models with oneToOne relationship


code:
#sudoku game
from random import randint

#generate board
def build_board():
    board=[]
    for i in range(9):
        block=[[" "," "," "],
               [" "," "," "],
               [" "," "," "]]
        board.append(block)
    return board

##
## Ensure no other block in the same row has the value
##
def row_available(block, row, board, num):
    # Determine which of the main 3 rows this 3x3 block is at
    boardRow = int(block / 3);
    good = True
    for b in range(boardRow * 3, (boardRow * 3) + 3):
        if b != block:
            if num in board[b][row]:
                good = False
                break
    return good

##
## Ensure no other block in the same col has the value
##
def col_available(block, row, col, board, num):
    # Determine which of the main 3 columns this 3x3 block is at
    boardCol = block % 3;
    good = True
    for b in (boardCol, boardCol + 3, boardCol + 6):
        if b != block:
            if num == board[b][row][col]:
                good = False
                break
    return good

def fill_board(board):
    # to fill all numbers 1 through 9
    for num in range(1,10):
        # for each of the 9 3x3 blocks
        for block in range(len(board)):
            triedRow = [-1]
            foundSpot = False
            for i in range(3):
                row = -1
                while row in triedRow:
                    row = randint(0,2)
                triedRow.append(row)
                if " " in board[block][row] and row_available(block, row, board, num):
                    triedCol = [-1]
                    for j in range(3):
                        col = -1
                        while col in triedCol:
                            col = randint(0,2)
                        triedCol.append(col)
                        if " " == board[block][row][col] and col_available(block, row, col, board, num):
                            board[block][row][col] = num
                            foundSpot = True
                        if foundSpot:
                            break
                if foundSpot:
                    break
            if not foundSpot:
                print("Never Found a Spot for " + str(num) + " in block " + str(block))
    return board

#display board
def display(board):
    num=[]
    for i in board: #block level
        for subI in i: #row
            for subsubI in subI: #item
                num.append(subsubI)
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[0],num[1],num[2],num[9],num[10],num[11],num[18],num[19],num[20]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[3],num[4],num[5],num[12],num[13],num[14],num[21],num[22],num[23]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[6],num[7],num[8],num[15],num[16],num[17],num[24],num[25],num[26]))
    print("---------------------------------------")
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[27],num[28],num[29],num[36],num[37],num[38],num[45],num[46],num[47]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[30],num[31],num[32],num[39],num[40],num[41],num[48],num[49],num[50]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[33],num[34],num[35],num[42],num[43],num[44],num[51],num[52],num[53]))
    print("---------------------------------------")
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[54],num[55],num[56],num[63],num[64],num[65],num[72],num[73],num[74]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[57],num[58],num[59],num[66],num[67],num[68],num[75],num[76],num[77]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[60],num[61],num[62],num[69],num[70],num[71],num[78],num[79],num[80]))
    print("---------------------------------------")

#test
board=build_board()
board=fill_board(board)
display=display(board)

rawDescription: Trouble with sudoku game in python 3.3.4


rawDescription: How do you check if a string contains ONLY numbers - python

description: Check if a string contains ONLY numbers - python


rawDescription: Display a list with hyperlink in Python template


code:
def split_list(l, sep):
    i = 0
    try:
        while True:
            j = l.index(sep, i)
            yield l[i:j]
            i = j + 1
    except ValueError:
        yield l[i:]

rawDescription: Splitting a list in python

description: Splitting a list in python


code:
from datetime import datetime

input_date = '2015-11-16'
# convert string to datetime
from_date = datetime.strptime(input_date, '%Y-%m-%d').date()
posts = Post.objects.filter(
    created_time__year=from_date.year,
    created_time__month=from_date.month,
    created_time__day=from_date.day,
)

rawDescription: Filter objects with a datetime range (00:00 to 23:59:99) in Django


rawDescription: Convert string to nested structures like list


rawDescription: Pandas DataFrame.unstack() Changes Order of Row and Column Headers


code: words = list(chain(*[re.split(r'\s+', line) for line in lines]))

rawDescription: Return list of words from a list of lines with regexp


code:
def __init__(self):
    handlers = [
        (r"/", home.HomeHandler),
        (r"/products/list/([0-9]+)", product.ProductHandler)
        (r"/products/find/([0-9]+)", product.ProductHandler)
        (r"/products/copy/([0-9]+)", product.ProductHandler)
        (r"/products/(\w+)/(\w+)/(\w+)", product.ProductHandler)]

rawDescription: Python Tornado Request Handler Mapping

description: Python Tornado Request Handler Mapping


code: ssh [username]@[hostname]

rawDescription: Beginner advice on how to use FTP or SSH? (django)


code:
integrate(gaussian, (x,-oo,oo), conds='none')
integrate(gaussian, (x,-oo,oo), conds='separate')

rawDescription: Simplify conditional integrals in SymPy

description: Simplify conditional integrals in SymPy


code: field | language | message

rawDescription: Using keywords vs real phrases for translation


code:
import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay

nolectures = pd.date_range(start='2015-03-28',end='2015-04-12').union_many(
    [['2015-05-01'], pd.date_range(start='2015-11-09',end='2015-12-31')])
calendar = CustomBusinessDay(holidays=nolectures)
print(calendar.holidays)

rawDescription: How do I specify different date ranges for CustomBusinessDays holidays in Pandas?

description: Specify different date ranges for CustomBusinessDays holidays in Pandas


code:
result = [processing_funcs(subdata) for subdata in input_data]
result = np.array(result)

rawDescription: Numpy matrices - how to handle arbitrary size


rawDescription: Calculating time elapsed on a groupby object


code:
def iter_frames(filename):
    with open(filename, 'rb') as mjpeg_file:
        while True:
            frame_length_bytes = mjpeg_file.read(5)
            if len(frame_length_bytes) != 5:
                if frame_length_bytes:
                    raise ValueError('incomplete length')
                else:
                    break
            frame_length = int(frame_length_bytes)
            frame = mjpeg_file.read(frame_length)
            if len(frame) != frame_length:
                raise ValueError('incomplete frame data')
            if not (
                frame.startswith(b'\xff\xd8') and frame.endswith(b'\xff\xd9')
            ):
                raise ValueError('invalid jpeg')

            yield frame

def main():
    frames = iter_frames('Movie.mjpeg')
    frame = next(frames)
    with open('test.jpg', 'wb') as jpeg_file:
        jpeg_file.write(frame)

if __name__ == '__main__':
    main()

rawDescription: Printing a MJPEG frame

description: Printing a MJPEG frame


code:
def Print(self, age, name=None):
    if name is not None:
        print(name)
    print(age)

rawDescription: type function overloading in python

description: Type function overloading in python


code:
import csv
from itertools import izip_longest

with open('result.csv','wb') as out:
    keys = list_of_dict[0].keys()
    f1 = csv.DictWriter(out, keys)
    f1.writeheader()
    f1.writerows(dict(zip(keys, row)) for row in izip_longest(*list_of_dict[0].values()))

rawDescription: Write a list of dictionaries to csv where the dictionary values are lists


code:
fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "pepper"
if food_sought in fridge:
    print("I was able to find a something in our list of food: %s : %s" % (food_sought, fridge[food_sought]))
else:
    print("We couldn't find the food you were looking for")

rawDescription: trying to iterating over dictionary but when the element is not found, else statement is not called, last key is printed instead

description: Trying to iterating over dictionary but when the element is not found, else statement is not called, last key is printed instead


code:
def blanks():
    all_line_max = []
    while True:
        try:
            strline = input()
            if strline:
                z = maxspaces(strline)
                all_line_max.append(z)
                y = ' '.join(strline.split())
                print(y)
            if strline == 'END':
                break
        except Exception:
            break
    print(max(all_line_max))

rawDescription: Loop Issue with Local Variable

description: Loop Issue with Local Variable


code:
doc.xpath('.//ul[@class = "myclass"]/li/text()')
# out: ["blah","blah2"]

rawDescription: Get bulletted list in lxml

description: Get bulletted list in lxml


rawDescription: Kivy Gif animation runs too often

description: Kivy Gif animation runs too often


code:
from sklearn.utils import compute_class_weight
compute_class_weight('auto', [0, 1], [0, 1, 0])

rawDescription: How to get pos/neg instance counts for all nodes of a scikit-learn decision tree?

description: Get pos/neg instance counts for all nodes of a scikit-learn decision tree


code:
class SomeObject(object):
    def method_inside_someobject(self):
        return 'The real thing'

rawDescription: Python mock object instantiation

description: Python mock object instantiation


code:
import matplotlib
def add_labels(line):
    x,y=line.get_data()
    labels=map(','.join,zip(map(lambda s: '%g'%s,x),map(lambda s: '%g'%s,y)))
    map(matplotlib.pyplot.text,x,y,labels)

rawDescription: Data value at each marker

description: Data value at each marker


code:
def do_this():

    sql='select * from v$session where machine like abc'
    session=Popen(['sqlplus','-S','/ as sysdba'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    session.stdin.write(sql)
    stdout,stderr=session.communicate()
    stdout=stdout.strip().split('\n')

    if 'no rows selected' not in stdout:
        pool = multiprocessing.Pool()
        pool.map(kill_it, stdout) # blocking call until all are done
        pool.close()
        pool.join()

    return

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


code:
for line in reversed(list(open("filename"))):
    print(line.rstrip())

rawDescription: Read a file in reverse order using python


code:
import csv

lista = [u'Club',
         u'CLUB TENIS DE MESA PORTUENSE',
         u'Nombre Equipo',
         u'C.T.M. PORTUENSE',
         u'Telefono fijo',
         u'630970055',
         u'Telefono Movil',
         u'630970055', u'E_Mail', u'M.LOPEZ_70@HOTMAIL.COM', u'Local de Juego', u'INSTITUTO MAR DE CADIZ', u'Categoria', u'DIVISION HONOR ANDALUZA', u'Grupo', u'GRUPO 9', u'Delegado', u'SANCHEZ SANTANO, JOSE MARIA', u'*Dias de Juego', u'SABADO', u'*Hora de Juego', u'17:00']

header = []
row = []
for i, val in enumerate(lista):
    if i%2==0:
        header.append(val)
    else:
        row.append(val)

out = open('file.csv', 'w')

w = csv.writer(out, dialect='excel')
w.writerow(header)
w.writerow(row)
out.close()

rawDescription: Write a simple list into a new CSV file

description: Write a simple list into a new CSV file


code:
if __name__ == '__main__':
    sys.exit(main(sys.argv))

rawDescription: Why is signal.SIGTERM not dealt with properly in my main thread?


code: self.d_birthdate = datetime.strptime('6/8/1980', '%m/%d/%Y')

rawDescription: Python date object for MongoDB

description: Python date object for MongoDB


code:
l2 = [sorted(list(g), key=lambda x:x["sequence"])
      for k, g in itertools.groupby(sorted(l, key=lambda x:x["part"]),
                                    key=lambda x:x["part"])]

rawDescription: Python - List of dictionary to list of list of dictionary


code:
[{'db': 'database_1', 'threshold': 1},
 {'db': 'database_1', 'threshold': 2},
 {'db': 'database_1', 'threshold': 3},
 {'db': 'database_1', 'threshold': 4}]

rawDescription: Is there a Python test framework suitable to run simulations


code:
calls = ['admobapioauthcert', 'admobapinewsession', 'admobendusercamp']
filter(lambda x : x[1]>1 and len(x[0])>2,Counter(reduce(lambda x,y:x + y,reduce(lambda x,y: x+y, map(lambda z :map(lambda x : map(lambda g: z[g:x+1],range(len(z[:x+1]))),range(len(z))),calls)))).most_common())

rawDescription: Python finding most common pattern in list of strings


code:
a = np.arange(25)
a
a.reshape(5,5)

rawDescription: Create a matrix out of an array

description: Create a matrix out of an array


code:
import re
inputtext = '''\
{{cite web
|title=Testing
|url=Testing
|editor=Testing
}}
'''
re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', inputtext, flags=re.DOTALL)
re.sub(r'\{cite web.*?[\r\n]+.*?\}\}', lambda m: re.sub('\s*[\r\n]\s*', '', m.group(0)), inputtext, flags=re.DOTALL)

rawDescription: Python regex on wikitext template

description: Python regex on wikitext template


rawDescription: Dealing with wacky encodings in Python

description: Dealing with wacky encodings in Python


code:
cols = df.columns[df.columns.str.contains('X')]
df[cols] = df[cols].replace({'True': True, 'False': False})

rawDescription: Pandas read_csv dtype specify all columns but one


code:
r, xi = np.loadtxt("s.dat", skiprows=1, unpack=True)
keep = xi > 0
keep

rawDescription: Applying conditions to python lists

description: Applying conditions to python lists


code:
from itertools import islice

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

def func():
    it = iter(arr)
    for sli in iter(lambda: list(islice(it, 3)),[]):
        print(sli) # pass sli to function
        print(exit())

func()

rawDescription: Break from array and run another function in python


code:
def frange(start, stop, step):
    x = start
    while x < stop:
        yield x
        x += step

rawDescription: Python xrange with float

description: Python xrange with float


rawDescription: Python dictionary to equivalent pymongo statement


rawDescription: matplotlib problems plotting logged data and setting its x/y bounds

description: Matplotlib problems plotting logged data and setting its x/y bounds


code:
import numpy as np
import scipy.ndimage as nd

N = 1000
cords = np.random.randint(3, 7, (N, 3)) #np.array([[5,4,5],[5,4,3],[6,4,6]])
atoms = np.random.choice(list('HC'), N) #np.array([['C'],['H'],['C']])
atom_proj = {'H': np.array([[0,0,0,0,0],
                            [0,0,1,0,0],
                            [0,1,1,1,0],
                            [0,0,1,0,0],
                            [0,0,0,0,0]]),
             'C': np.array([[0,0,0,0,0,0,0],
                            [0,0,0,0,0,0,0],
                            [0,0,1,1,1,0,0],
                            [0,0,1,1,1,0,0],
                            [0,0,1,1,1,0,0],
                            [0,0,0,0,0,0,0],
                            [0,0,0,0,0,0,0]])}

def project_atom(cords, atoms, atom_proj):
    extruded = np.zeros((N, 10,10))
    extruded[range(N), cords[:,2], cords[:,0]] = 1
    grid = np.zeros((10,10))
    for atom, proj in atom_proj.iteritems():
        grid += nd.convolve(extruded[atoms.squeeze()==atom].sum(0), proj, mode='constant')
    return grid

def OP_simplified(cords, atoms, atom_proj):
    rads = {atom: (proj.shape[0] - 1)/2 for atom, proj in atom_proj.iteritems()}
    grid = np.zeros((10,10))
    for (x,y,z), atom in zip(cords, atoms):
        rad = rads[atom]
        grid[z-rad:z+rad+1, x-rad:x+rad+1] += atom_proj[atom]
    return grid

def OP(cords, atoms, atom_proj):
    grid = np.zeros((10,10))
    for values in zip(cords, atoms):
        atom_shape = np.shape(atom_proj[values[1][0]])
        rad = (atom_shape[0]-1)/2
        grid[values[0][2]-rad:values[0][2]+rad+1,values[0][0]-rad:values[0][0]+rad+1] += atom_proj[values[1][0]]
    return grid

rawDescription: Projecting Coordinates in Numpy array

description: Projecting Coordinates in Numpy array


code:
import json
inp = open('input.txt', 'r')
out = open('output.txt', 'w')
in_as_obj = json.load(inp)
json.dump(in_as_obj, out, ensure_ascii=False)

rawDescription: How can I replace Unicode characters with Turkish characters in a text file with Python

description: Replace Unicode characters with Turkish characters in a text file with Python


code:
import sched
import time

def print_something(x):
    print(x)

s = sched.scheduler()

s.enter(1, 0, print_something, ['first'])
s.enter(2, 0, print_something, ['second'])
s.run()

rawDescription: How to invoke a function at an exactly given time point in Python?

description: Invoke a function at an exactly given time point in Python


code: [(x,y) for (x,y) in zip(list1, list2) if x != y]

rawDescription: Zip without duplicate values in the resulting tuples


code: df.groupby(["TICKET_NUMBER", "ITEM"], sort=False, as_index=False)["TICKET_ROW"].first()

rawDescription: Pandas: filter unique values in groups

description: Pandas: filter unique values in groups


rawDescription: Counting same elements in an array and create dictionary


rawDescription: Check string by user-given regex

description: Check string by user-given regex


rawDescription: Appending to a Series dynamically

description: Appending to a Series dynamically


code: default_app().match({'PATH_INFO': path, 'REQUEST_METHOD': method})

rawDescription: bottle.py URL routing & reverse howto?

description: Bottle.py URL routing & reverse howto


code:
from shlex import split
from subprocess import Popen

p = Popen(split('ssh user@host "hohup PATH/XProgram >&- &"'))
p.communicate() # returns (None, None)

rawDescription: python subprocess run a remote process in background and immediately close the connection

description: Python subprocess run a remote process in background and immediately close the connection


code: min(b,z - c) - max(a, z - d) + 1

rawDescription: Sum of 2 elements from 2 ranges that will be one given number


code:
my_list = []
with open('Test.csv', 'r') as csvfile:
    for lines in csvfile:
        temp_lines = lines.strip().split(',')
        my_list.append(temp_lines)

print(my_list)

rawDescription: Get row index instead of columns in csv file


code:
a = np.arange(10)
b = a.reshape((5,2))
c = a[::2]
d = a[1::2]
e = a[0:1]
f = a[0:1]
f = f.reshape(())
share_memory(a,b)
share_memory(a,c)
share_memory(a,d)
share_memory(c,d)
share_memory(a,e)
share_memory(a,f)

rawDescription: Is there a way to check if NumPy arrays share the same data?


rawDescription: How to turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)

description: Turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)


code: xl = [item for item in xl if item not in yl]

rawDescription: getting the index while interating a list

description: Getting the index while interating a list


code: any((c in yourString) for c in badChars)  # extensionally equivalent, slower

rawDescription: Find which lines in a file contain certain characters


code:
AA = []
for row_index, rows_to_be_merged in itertools.groupby(A, lambda x: x[0]):
    AA.append([row_index] +
              [sum(rows) for rows in zip(*rows_to_be_merged)][1:])

rawDescription: python sorting array of XYZ coordinates in table matrix

description: Python sorting array of XYZ coordinates in table matrix


code:
p1 = call1()
p1 = call2()
p1 = call3()

rawDescription: Does method for plotting need return?

description: Does method for plotting need return


code: multiprocessing.map(lambda f: f(1), functions)

rawDescription: Multiprocessing pool 'apply_async' only seems to call function once


code: links = soup.findAll('tr')[5].findAll('a', href=re.compile("Company"))

rawDescription: Extracting 'a' tags containing specific substring with Python's BeautifulSoup


code:
def within(obj, func):
    return func(**obj.__dict__)

rawDescription: Is there a way to enter the class namespace in Python?


code:
while True:
    GPIO.output(26, GPIO.input(23))

rawDescription: How to code a through-beam sensor to detect LED using a Raspberry Pi?

description: Code a through-beam sensor to detect LED using a Raspberry Pi


rawDescription: Easier way to run Python program in Pdev console without typing commands?


code:
from setuptools import setup, find_packages

setup(
    name = "google killer",
    version = "0.1.0",
    url = 'http://example.com/',
    license = 'AGPL',
    description = 'best software ever',
    author = 'me',
    packages = find_packages('src'),
    package_dir = {'': 'src'},
    install_requires = ['numpy', 'scipy', 'sqlalchemy'],
)

rawDescription: best tool for building python distro with dependencies/resources

description: Best tool for building python distro with dependencies/resources


code: call_attrs(a, ['method1', 'method2', 'method3'])

rawDescription: Nested try statements in python?

description: Nested try statements in python


code:
sum_val = myArray.sum(axis=(0,1))

std_val = myArray.std(axis=(0,1))

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

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


code:
department = Department.objects.select_related('leader').get(pk=1)
print(department.leader.salary)

rawDescription: How can I make a django query-set that uses two classes?

description: Make a django query-set that uses two classes


code:
def dedup(lst):
    seen = set()
    result = []
    for item in lst:
        fs = frozenset(item)
        if fs not in seen:
            result.append(item)
            seen.add(fs)
    return result

rawDescription: Python list of tuples deduplication

description: Python list of tuples deduplication


code:
fb = type('fb',(object,),{'__init__':initer,
                              'link':linker,
                              'CLASSIES':0})

rawDescription: Local variable in each class - python timed loop


code:
plt.yticks([0.5,1.5,2.5], ["first", "second", "third"])
plt.xticks([0.5,1.5,2.5], ["first", "second", "third"], rotation='vertical')

rawDescription: Creating a correlation plot with matplotlib


code:
ax2 = ax1.twinx()
mn, mx = ax2.get_ylim()
ax2.set_ylim(mn*km3yearToSv, mx*km3yearToSv)
ax2.set_ylabel('Sv')

rawDescription: Plot single data with two Y axes (two units) in matplotlib


code:
#!/usr/bin/env python
from __future__ import unicode_literals

wrong_chars = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7'],
]
true_chars = 'abc'

table = {}
for keys, value in zip(wrong_chars, true_chars):
    table.update(dict.fromkeys(map(ord, keys), value))
print("123456789".translate(table))

rawDescription: Python - Replace list of characters with another list


code:
import MySQLdb as mdb
import sys

con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');

with con:

    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS \
        Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
    cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")

rawDescription: Saving information from URL to MySQL database


rawDescription: Get index of recently appended item

description: Get index of recently appended item


code:
obj.push(3)
"""adds number 3 to your stack"""

obj.pop()
"""returns last item from your stack that was inserted into it and deletes it from the stack (in this case 3)"""

obj.length()
"""returns length of your stack, now it is 0 but if we didn't perform obj.pop() that would be 1"""

rawDescription: python Queue used in the below code

description: Python Queue used in the below code


code:
base64_img = get_base_64()
return HttpResponse('<img alt="Embedded Image" src="data:image/jpeg;base64," % base64_img />')

rawDescription: how to output a Image in Django web page with PIL Image

description: Output a Image in Django web page with PIL Image


code:
import wx
import os.path

class MainWindow(wx.Frame):

    def __init__(self, parent, title, *args, **kwargs):
        super(MainWindow,self).__init__(parent, title = title, size = (800,600))
        #wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos =  wx.DefaultPosition, size = wx.Size( 800,608 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
        grid = wx.GridSizer( 2, 2, 0, 0 )

        self.filename = ""
        self.dirname = '.'
        #self.CreateInteriorWindowComponents()
        #self.CreateExteriorWindowComponents()

    def CreateInteriorWindowComponents(self):

        staticbox = wx.StaticBoxSizer( wx.StaticBox( self, wx.ID_ANY, u"Enter text" ), wx.VERTICAL )
        staticbox.Add( self.m_textCtrl1, 0, wx.ALL|wx.EXPAND, 5 )
        self.m_textCtrl1 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( -1,250 ), wx.TE_MULTILINE)
        self.m_textCtrl1.SetMaxLength(10000)

        self.Submit = wx.Button( self, wx.ID_ANY, u"Submit", wx.DefaultPosition, wx.DefaultSize, 0 )
        staticbox.Add( self.Submit, 0, wx.ALL, 5 )

    def CreateExteriorWindowComponents(self):
        ''' Create "exterior" window components, such as menu and status
            bar. '''
        self.CreateMenu()
        self.CreateStatusBar()
        self.SetTitle()

    def CreateMenu(self):
        fileMenu = wx.Menu()
        for id, label, helpText, handler in \
            [(wx.ID_ABOUT, '&About', 'Storyteller 1.0 -',
                self.OnAbout),
             (wx.ID_OPEN, '&Open', 'Open a new file', self.OnOpen),
             (wx.ID_SAVE, '&Save', 'Save the current file', self.OnSave),
             (wx.ID_SAVEAS, 'Save &As', 'Save the file under a different name',
                self.OnSaveAs),
             (None, None, None, None),
             (wx.ID_EXIT, 'E&xit', 'Terminate the program', self.OnExit)]:
            if id == None:
                fileMenu.AppendSeparator()
            else:
                item = fileMenu.Append(id, label, helpText)
                self.Bind(wx.EVT_MENU, handler, item)

        menuBar = wx.MenuBar()
        menuBar.Append(fileMenu, '&File') # Add the fileMenu to the MenuBar
        self.SetMenuBar(menuBar)  # Add the menuBar to the Frame

    def SetTitle(self):
        # MainWindow.SetTitle overrides wx.Frame.SetTitle, so we have to
        # call it using super:
        super(MainWindow, self).SetTitle('Editor %s'%self.filename)

    # Helper methods:

    def defaultFileDialogOptions(self):
        ''' Return a dictionary with file dialog options that can be
            used in both the save file dialog as well as in the open
            file dialog. '''
        return dict(message='Choose a file', defaultDir=self.dirname,
                    wildcard='*.*')

    def askUserForFilename(self, **dialogOptions):
        dialog = wx.FileDialog(self, **dialogOptions)
        if dialog.ShowModal() == wx.ID_OK:
            userProvidedFilename = True
            self.filename = dialog.GetFilename()
            self.dirname = dialog.GetDirectory()
            self.SetTitle() # Update the window title with the new filename
        else:
            userProvidedFilename = False
        dialog.Destroy()
        return userProvidedFilename

    # Event handlers:

    def OnAbout(self, event):
        dialog = wx.MessageDialog(self, 'A sample editor\n'
            'in wxPython', 'About Sample Editor', wx.OK)
        dialog.ShowModal()
        dialog.Destroy()

    def OnExit(self, event):
        self.Close()  # Close the main window.

    def OnSave(self, event):
        textfile = open(os.path.join(self.dirname, self.filename), 'w')
        textfile.write(self.control.GetValue())
        textfile.close()

    def OnOpen(self, event):
        if self.askUserForFilename(style=wx.OPEN,
                                   **self.defaultFileDialogOptions()):
            textfile = open(os.path.join(self.dirname, self.filename), 'r')
            self.control.SetValue(textfile.read())
            textfile.close()

    def OnSaveAs(self, event):
        if self.askUserForFilename(defaultFile=self.filename, style=wx.SAVE,
                                   **self.defaultFileDialogOptions()):
            self.OnSave(event)

app = wx.App()
frame = MainWindow(None, "test")
frame.Show()
app.MainLoop()

rawDescription: TypeError: __init__() takes at least 3 arguments (1 given)


code:
def insert_new_els(tree, child_tag, parent_tag, new_node_tag):
    to_replace = list(find_elements(tree, child_tag, parent_tag))
    for child, parent in to_replace:
        ix = list(parent).index(child)
        new_node = ET.Element(new_node_tag)
        parent.insert(ix, new_node)
        parent.remove(child)
        new_node.append(child)

rawDescription: Adding a parent tag to a nested structure with ElementTree (Python)


code: {{ list_item.text|truncatewords:t }}

rawDescription: How to use template within Django template?

description: Use template within Django template


code:
# access to /api/foo/?category=animal

class FooListView(generics.ListAPIView):
    model = Foo
    serializer_class = FooSerializer

    def get_queryset(self):
        qs = super(FooListView, self).get_queryset()
        category = self.request.query_params.get("category", None)
        if category:
            qs = qs.filter(category=category)
        return qs

rawDescription: How to add search parameters to GET request in Django REST Framework?

description: Add search parameters to GET request in Django REST Framework


code:
def get_item(response, path):
    return reduce(lambda x, y: x[y], path, response)

rawDescription: How to Create a Dynamic Path for Grabbing Variables from JSON in Python


code:
a = 'motor'
a.replace('moto', '')

rawDescription: Remove letters from sting

description: Remove letters from sting


code: Dictionary=dict(Arr)

rawDescription: How to implement associative array (not dictionary) in Python?

description: Implement associative array (not dictionary) in Python


code: np.vstack([np.hstack(conc[i:i+2,...]) for i in range(0,4,2)])

rawDescription: Double loops for "concatenation of subarrays in bigger array"


code:
fields = sorted(d)
stats = sorted(set().union(*d.values()))  # use d.itervalues() in Python 2

with open(res, 'w') as csvfile:
    w = csv.DictWriter(csvfile, delimiter='\t', fieldnames=['stats'] + fields)
    w.writerow({'stats': '#Global Statistics:'})
    w.writeheader()
    for stat in stats:
        # produce a dictionary mapping field name to specific statistic for
        # this row
        row = {k: v.get(stat, 0) for k, v in d.items()}
        row['stats'] = stat
        w.writerow(row)

rawDescription: print nested dict to tsv format file

description: Print nested dict to tsv format file


code: frame.bind('...', lambda event: callback2())

rawDescription: How can I prevent Tkinter from passing the event object in a binding? Is there any workaround to do this?

description: Prevent Tkinter from passing the event object in a binding? Is there any workaround to do this


rawDescription: 2 d interpolation with the arrays with different dimensions in python


code: new_d = {next((k for k in d.iterkeys() if k), u''): d['']}

rawDescription: Python nested dictionaries key,value swap


code:
sql = "SELECT devices.id, devices.names, devices.addresses,\
devices.charging, devices.covered, record_temperatures.time \
FROM devices \
WHERE devices.imei like '%0444258'";

rawDescription: SQL formatting examples for long queries in python for psycopg2 connections


code:
@contextlib.contextmanager
def awesome_open(path_or_file):
    if isinstance(path_or_file, basestring):
        f = file_to_close = open(path_or_file, 'rb')
    else:
        f = path_or_file
        file_to_close = None

    try:
        yield f
    finally:
        if file_to_close:
            file_to_close.close()

def awesome_parse(path_or_file):
    with awesome_open(path_or_file) as f:
        return do_stuff(f)

rawDescription: Python function that accepts file object or path


code:
url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$',
    CategorizedPostsView.as_view(paginate_by=3)),

rawDescription: How to use pagination in class-based generic views?

description: Use pagination in class-based generic views


code:
def collection_filter_row(catalogue_filtered, index_dict, collection):
    return collection[[index_dict[document_id]
                       for document_id
                       in catalogue_filtered.index.values.tolist()]]

rawDescription: Selecting rows from a sparse matrix based on the index of a panda dataframe


rawDescription: Specifying and saving a figure with exact size in pixels


rawDescription: offset one of matplotlib's legend items

description: Offset one of matplotlib's legend items


code:
import pymel.core as pm
pm.scriptEditorInfo(clearHistory=True)

rawDescription: How can I clear the Maya Script Editor programatically?

description: Clear the Maya Script Editor programatically


code:
for i in reversed(range(NumElements)):
    if not A[i]:
        del A[i], B[i], C[i], D[i]

rawDescription: remove all occurences of a given value in multiple arrays at once

description: Remove all occurences of a given value in multiple arrays at once


rawDescription: How do I delete the first part of a string in python

description: Delete the first part of a string in python


rawDescription: How can I import a string file into a list of lists?

description: Import a string file into a list of lists


code: "".join(map(unicode.strip, response.xpath("//font[b = 'Claim:']/following-sibling::text()").extract()))

rawDescription: How can I scrape tagless paragraph with Scrapy

description: Scrape tagless paragraph with Scrapy


code:
g="Canada's bananas analysis"
sub_string="ana"
[1 for i in range(0, len(g)-len(sub_string)) if g[i:i+len(sub_string)]==sub_string]

rawDescription: Counting instances a substring shows up

description: Counting instances a substring shows up


code:
tuple(x for pair in sorted(zip(urls[::2], urls[1::2]),
                           key=itemgetter(0), reverse=True)
      for x in pair)

rawDescription: Is there a way to sort custom objects in a custom way in Python?


code:
NumCols = 10
vars = [ 'x'+str(n) for n in xrange(1,NumCols+1) ]
coef = [1]*NumCols
cpx.linear_constraints.add(
        lin_expr= [cplex.SparsePair(ind = vars, val = coef)] ,
        senses=["L"],
        rhs=[constantValue] )

rawDescription: cplex python sum constraint

description: Cplex python sum constraint


code:
def func(*args):
   if len(args) == 3:
       start,stop,step=args
   elif len(args) == 2:
       start,stop = args
       step = None
   elif len(args) == 1:
       stop, = args  #Need the comma here.  Could write `stop = args[0]` instead ...
       step = start = None
   else:
       raise TypeError("Wrong number of arguments!")

rawDescription: How to implement optional first argument in Python (reproduce slice() behavior)

description: Implement optional first argument in Python (reproduce slice() behavior)


code: ''.join('{}{}'.format(key, val) for key, val in adict.items())

rawDescription: How to convert dictionary into string

description: Convert dictionary into string


rawDescription: Find Unique Dates in Numpy Datetime Array


code:
# print the numbers 0..1000 in random order
nums = list(range(1001))
random.shuffle(nums)      # shuffle list in-place
for num in nums:
    print(num)

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

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


code:
def cart(n, seq):
    import itertools
    b = 8
    write = file.write  # speed up lookup of method
    while b < n:
        n = n - 1
        for p in itertools.product(seq, repeat=n):
            write(''.join(p)+'\n')  # only call it once in loop

rawDescription: python itertools product slow is the write speed to a output file a bottleneck

description: Python itertools product slow is the write speed to a output file a bottleneck


code:
def get_total_seconds(td): return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6

get_total_seconds(down_time) / get_total_seconds(server_life_period)

rawDescription: Python 2.6.5: Divide timedelta with timedelta


rawDescription: Python Jinja2 post

description: Python Jinja2 post


rawDescription: How to construct query using the SQLAlchemy ORM

description: Construct query using the SQLAlchemy ORM


code:
sizeLimit = 4
range(sizeLimit-1, -1, -1)

rawDescription: Dynamic programming in Python

description: Dynamic programming in Python


code:
quality_val = 90
image.save(filename, 'JPEG', quality=quality_val)

rawDescription: How to adjust the quality of a resized image in Python Imaging Library?

description: Adjust the quality of a resized image in Python Imaging Library


rawDescription: Removing minimize/maximize buttons in Tkinter


code:
s = np.argsort(a)
a[s], b[s]

rawDescription: zip, sorted and pandas

description: Zip, sorted and pandas


rawDescription: Access Kinect Depth Data with Pykinect

description: Access Kinect Depth Data with Pykinect


code: print(card['ace of hearts'][0])

rawDescription: Assigning multiple values to a dictionary key- Python


code:
file.write(target + '\n')
file.write(genstr + '\n')

rawDescription: Outputting loop data to a text document in python


code: df['C'].iloc[::20] = some_function()

rawDescription: iterate over the rows , and control count i++

description: Iterate over the rows , and control count i++


rawDescription: reshaping ndarrays versus regular arrays in numpy?

description: Reshaping ndarrays versus regular arrays in numpy


code:
d = []
d.append(t)
d

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

description: Extract time and store in an Array/Structure


rawDescription: Avoid double typing class names in python


code:
res = re.findall('"(\w+)"', s)
i = iter(res)
dict(zip(*[i]*2))

rawDescription: Extracting data using regex in python

description: Extracting data using regex in python


code:
def doing_something():
   s = requests.session()
   # something here.....
   # notice we're returning 2 things
   return some_result, s

def calling_it():
   # there's also a syntax for 'unpacking' the result of calling the function
   some_result, s = doing_something()

rawDescription: python-requests keep session between function

description: Python-requests keep session between function


rawDescription: Python - Declare two variable with the same values at the same time


code:
wanted_stuff = []
for datas in datas:
    wanted_stuff.append(data[0:3]) #extracting chromatin name, start, end
# or as a list comprehension
#wanted_stuff = [data[:3] for data in datas]

rawDescription: Writing python chunking loops with reference to another txt


code: (label, subarr), mean = npi.group_by((largearray.flatten(), idx[0])).mean(idx[1:], axis=1)

rawDescription: Find center coordinates of regions in a 3d numpy array


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

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

# ... plot some stuff ...

ax.set_xticks(xi)
ax.set_yticks(yi)
ax.set_xticklabels(x)
ax.set_yticklabels(y)

plt.show()

rawDescription: python matplotlib : ploting 3d surface from string indexed arrays

description: Python matplotlib : ploting 3d surface from string indexed arrays


code:
import argparse
parser = argparse.ArgumentParser("Calculate something with a quantity commonly called lambda.")
parser.add_argument("-l", "--lambda",
    help="Defines the quantity called lambda",
    type=float, dest='lambda_', metavar='LAMBDA')
parser.print_help()
args = parser.parse_args(['--lambda', '4.2'])
args.lambda_

rawDescription: Python: How to escape 'lambda'

description: Python: How to escape 'lambda'


code:
import comtypes.client as cc
cc.GetModule("TaskbarLib.tlb")

rawDescription: Using Windows 7 taskbar features in PyQt


code:
f = open('file')

with f:
    print >> f, "Open"
    with f:
        print >> f, "Open"
    print >> f, "This errors, as the file is already closed"

rawDescription: Can I use a with statement on a file that already exists?

description: Use a with statement on a file that already exists


code:
def is_pali(s):
    if len(s) <= 1:
        return True
    else:
        return s[0] == s[-1] and is_pali(s[1:-1])

rawDescription: How to write a recursive function for palindromic primes?

description: Write a recursive function for palindromic primes


code:
from xml.etree import ElementTree

xml = ElementTree.parse("test.xml")

root = xml.getroot()

all = {}

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

rawDescription: python - Values not being pulled from XML

description: Python - Values not being pulled from XML


code: [ pers for pers in world if all([f(pers) for f in predicates]) ]

rawDescription: Dynamic list comprehension

description: Dynamic list comprehension


code:
from itertools import groupby
import matplotlib.pyplot as plt

data = [
    ('A', 12),
    ('A', 13),
    ('A', 15),
    ('A', 29),
    ('B', 23),
    ('B', 23),
    ('B', 23),
    ('C', 90),
    ('C', 83)
]

labels,ys = zip(*data)
xs = range(len(ys))

def centered(val, ln, empty=''):
    half = (ln - 1) // 2
    return (val if i==half else empty for i in xrange(ln))

def centered_labels(labels):
    return [v for val,grp in groupby(labels) for v in centered(val, len(list(grp)))]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xticklabels(centered_labels(labels))
ax.plot(xs, ys, 'b-', linewidth=3)

rawDescription: Joining neighbouring x-tics with numpy

description: Joining neighbouring x-tics with numpy


code:
class DictWrapper(object):
    def __init__(self, d):
        self.d = d
    def __getattr__(self, key):
        return self.d[key]

rawDescription: Is there any trick to "overload the dot operator"?


code: myListOfVectors

rawDescription: Sort list of vectors python

description: Sort list of vectors python


code:
import traceback
try:
    filename,line_number,function_name,text = traceback.extract_stack()[-2]
    print(filename,line_number,function_name,text)
except IndexError:
    pass

rawDescription: Is it possible to get "importing module" in "imported module" in Python?


rawDescription: How to count how many positions away an element is in a list?

description: Count how many positions away an element is in a list


code:
#!python2
import ctypes as c

class Record(c.Structure):
    _fields_ = [('x',c.c_int),('y',c.c_int)]

class db_obj(c.Structure):
    _fields_ = [('db_name',c.c_char * 50),
                ('db_guid',c.c_int),
                ('db_path',c.c_char * 100)]

dll = c.CDLL('x')

get_data_int = dll.get_data_int
get_data_int.argtypes = [c.POINTER(Record), c.POINTER(c.c_int)]
get_data_int.restype = None

get_data_string = dll.get_data_string
get_data_string.argtypes = [c.POINTER(Record), c.POINTER(c.c_char), c.c_size_t]
get_data_string.restype = None

get_database_running_status = dll.get_database_running_status
get_database_running_status.argtypes = [c.POINTER(db_obj), c.c_int8, c.POINTER(c.c_int8)]
get_database_running_status.restype = None

result = c.c_int()
rec = Record(5,7)
get_data_int(c.byref(rec),c.byref(result))
print(result.value)

result = c.create_string_buffer(50)
rec = Record(5,7)
get_data_string(c.byref(rec),result,c.sizeof(result))
print(result.value)

result = c.c_int8()
db = db_obj('database name',1234,'database path')
get_database_running_status(c.byref(db),7,c.byref(result))
print(result.value)

rawDescription: Working with ctypes return values

description: Working with ctypes return values


code:
import urllib
u = urllib.urlopen("http://www.google.com")
u.info().get("last-modified")

rawDescription: Good way (and/or platform-independent place) to cache data from web


code:
import os
theKeyword = 'KEYWORD'
directory = '.'
with open('output.csv', 'w') as out:
    for file in os.listdir(directory):
        if file.endswith(".log"):
            with open(file, 'r') as f:
                for line in f:
                    if theKeyword in line:
                        out.write(line)

rawDescription: Copy select lines from many text files and paste to new file


rawDescription: Python list slice

description: Python list slice


code:
y = MyClass()
y = 3
y = 5
y.previous_value() # will yield 3

rawDescription: How to design a python class which will behave like root classes

description: Design a python class which will behave like root classes


code:
from itertools import chain
list(chain.from_iterable(map(str.split, L)))

rawDescription: explode list to another list at space characters

description: Explode list to another list at space characters


code:
client = xmlrpclib.ServerProxy('http://user:password@blah.com/plone')
path = '/sites/ng/path/to/folder'
subdirs = path.split('/')[1:]
dir = client
for subdir in subdirs:
    if subdir in dir.objectIds():
        dir = dir[subdir]
    else:
        return False
return True

rawDescription: How to check if a folder exists by its complete path in Plone?

description: Check if a folder exists by its complete path in Plone


code:
def ifact(n):
    stack = []
    while True:
        if n==1:
            while stack:
                n *= stack.pop()
            break
        else:
            stack.append(n)
            n -= 1
    return n

rawDescription: Using a list to synthesize a stack for recursion in Python? Examples?


rawDescription: why is my function not always returning the correct list?

description: Why is my function not always returning the correct list


code:
from itertools import groupby
map(lambda x: next(x[1]),
    groupby(sorted(files,
                   key=lambda x: x['date'],
                   reverse=True),
         key=lambda x: datetime(x['date'].year, x['date'].month, x['date'].day)))

rawDescription: Python: Taking an array and break it into subarrays based on some criteria


rawDescription: Alternative to using 'in' with numpy.where()


code:
import io

with io.open('file.txt', encoding='utf_8_sig'):
    data = f.read()

rawDescription: Reading UTF-8 file returns unexpected chars


code:
def format_exponent(ax, axis='y'):

    # Change the ticklabel format to scientific format
    ax.ticklabel_format(axis=axis, style='sci', scilimits=(-2, 2))

    # Get the appropriate axis
    if axis == 'y':
        ax_axis = ax.yaxis
        x_pos = 0.0
        y_pos = 1.0
        horizontalalignment='left'
        verticalalignment='bottom'
    else:
        ax_axis = ax.xaxis
        x_pos = 1.0
        y_pos = -0.05
        horizontalalignment='right'
        verticalalignment='top'

    # Run plt.tight_layout() because otherwise the offset text doesn't update
    plt.tight_layout()
    ##### THIS IS A BUG
    ##### Well, at least it's sub-optimal because you might not
    ##### want to use tight_layout(). If anyone has a better way of
    ##### ensuring the offset text is updated appropriately
    ##### please comment!

    # Get the offset value
    offset = ax_axis.get_offset_text().get_text()

    if len(offset) > 0:
        # Get that exponent value and change it into latex format
        minus_sign = u'\u2212'
        expo = np.float(offset.replace(minus_sign, '-').split('e')[-1])
        offset_text = r'x$\mathregular{10^{%d}}$' %expo

        # Turn off the offset text that's calculated automatically
        ax_axis.offsetText.set_visible(False)

        # Add in a text box at the top of the y axis
        ax.text(x_pos, y_pos, offset_text, transform=ax.transAxes,
               horizontalalignment=horizontalalignment,
               verticalalignment=verticalalignment)
    return ax

rawDescription: Adjust exponent text after setting scientific limits on matplotlib axis


rawDescription: oneliner scramble program

description: Oneliner scramble program


code:
idx2 = df2.eval('columns >= 1')
idx2

rawDescription: What's the meaning of keyword 'columns' in pandas query method?


code:
params = {"filters": []}
req = scrapy.Request(url,
                     method='POST',
                     body=json.dumps(params),
                     headers={'X-Requested-With': 'XMLHttpRequest',
                              'Content-Type': 'application/json; charset=UTF-8'},
                     callback=self.parser2)

rawDescription: Scrapy simulate XHR request - returning 400


rawDescription: Python sorting a list of deeply nested dictionaries by value


code:
for r in np.arange(s.shape[0]):
    ix = indices[r]

    if indices[r]==0:
        s2[ix] = l[0]
        l[0] = np.nan
    elif indices[r]==l.shape[0]:
        s2[ix] = l[r-1]
        l[r-1] = np.nan
    else:
        width = 0

        while width<min([10,r]) and np.isnan(l[ix-width:ix+2+width].mean()):
            width += 1

        tmp = l[ix-width:ix+2+width]
        s2[r] = tmp[ np.abs(s[r]-tmp)==np.nanmin(np.abs(s[r]-tmp)) ][0]
        l[l==s2[r]] = np.nan

rawDescription: python: how to find a subset of one set that is closest to another

description: Python: how to find a subset of one set that is closest to another


code:
class PDFStore(ndb.Model):
  content = ndb.BlobProperty()

rawDescription: Getting a file with urlfetch and saving it to the Google datastore


rawDescription: making arrays/lists of selected items from a dictionary in python

description: Making arrays/lists of selected items from a dictionary in python


code: getattr(test, method)()

rawDescription: How do I access a object's method when the method's name is in a variable?

description: Access a object's method when the method's name is in a variable


rawDescription: python - looping through values in a string

description: Python - looping through values in a string


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

t = np.linspace(.2, 1.6 * np.pi)
x, y = np.cos(t), np.sin(t)

# Shuffle the points...
i = np.arange(t.size)
np.random.shuffle(i)
x, y = x[i], y[i]

fig, ax = plt.subplots()
ax.plot(x, y, color='lightblue')
ax.margins(0.05)
plt.show()

rawDescription: Numpy way to sort out a messy array for plotting


code:
import struct
data = '....' # same as above
struct.unpack('HHLQ', data) == (1, 2, 3, 4) # '>HHLQ' if data is htonl/htons-ed in sencding part.

rawDescription: Convert string data received from network packet to Structure


code:
import xapian
def index_url(database, url):
    text = strip_tags(get_page(url))
    doc = xapian.Document()

    # TermGenerator will split text into words
    # and then (because we set a stemmer) stem them
    # into terms and add them to the document
    termgenerator = xapian.TermGenerator()
    termgenerator.set_stemmer(xapian.Stem("en"))
    termgenerator.set_document(doc)
    termgenerator.index_text(text)

    # We want to be able to get at the URL easily
    doc.set_data(url)
    # And we want to ensure each URL only ends up in
    # the database once. Note that if your URLs are long
    # then this won't work; consult the FAQ on unique IDs
    # for more: http://trac.xapian.org/wiki/FAQ/UniqueIds
    idterm = 'Q' + url
    doc.add_boolean_term(idterm)
    db.replace_document(idterm, doc)

# then index an example URL
db = xapian.WritableDatabase("exampledb", xapian.DB_CREATE_OR_OPEN)

index_url(db, "http://stackoverflow.com/")

rawDescription: How to use xapian which returns a URL when indexing a web page

description: Use xapian which returns a URL when indexing a web page


code:
class Leaf:
    def __init__(self):
        self.leafimage = pygame.image.load('fallingleaf.jpg').convert()
        self.leafrect = self.leafimage.get_rect()
        xpos = random.randint(0, 640)
        self.leafrect.midtop = (xpos, 0)
    def move(self):
        self.leafrect = self.leafrect.move([0, 1])

rawDescription: How to duplicate objects in Python/Pygame?

description: Duplicate objects in Python/Pygame


code:
regex1 = re.compile(r'foobar')
regex2 = re.compile(r'bazquux')
# etc

rawDescription: Can I have anonymous function with "static" variables in Python?

description: Have anonymous function with "static" variables in Python


rawDescription: Pandas - Remove rows based on combinations of NaN values


code:
temp = Button(...)
temp.config(command=lambda j=i, button=temp: self.letterGuess(alpha[j], button))
temp.grid(...)

rawDescription: Sneaky way of disabling a button once it's been pressed?


rawDescription: Building a list with a parent-child dependency


code: items[0][1].extend(reversed(range(1, num + 1)))

rawDescription: Appending numbers into a list in reverse


rawDescription: Converting bytes to integer in Python

description: Converting bytes to integer in Python


code: nmail = nmail + line.rstrip(os.linesep),

rawDescription: Convert multiple lines to single line and store in a variable in python


code:
class MyList(list):
    def sort(self, key=None, reverse=None):
        if key is None:
            key = int
        return super().sort(key, reverse)

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

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


code:
import pandas as pd
df = pd.read_csv("grouped.csv", sep="[,\s]*")
df
g = df.groupby("name").describe()
g

rawDescription: Python - find average for columns with unique matching value in nested list


code:
for line in PriceList:
    Dict1[line[0]][line[1]] = line[2]

rawDescription: 'int' object has no attribute 'update' - dictionary within dictionary - python2.7


rawDescription: Text File Parsing with Python

description: Text File Parsing with Python


code:
list1 = [x for x in list1 if x[1] in zip(*list2)[1]]
list2 = [x for x in list2 if x[1] in zip(*list1)[1]]

rawDescription: Removing non-matching items from datasets


code:
import json
with open('<filename>') as f:
    data = json.load(f)

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

description: Import an array containing dictionary from a text file


code:
import dis
dis.dis(lambda: 'Hi' in x)
dis.dis(lambda: x.find('Hi') != -1)

rawDescription: Comparing efficiency of two substring searching methods in Python


code: META_MORE_RE = re.compile(r'^[ ]{4,}(?P<value>.*)')

rawDescription: How to check for key value metadata in markdown

description: Check for key value metadata in markdown


rawDescription: Parsing custom string

description: Parsing custom string


code:
parsed = dict(k.split("=", 1) for k in split if '=' in k)
parsed

rawDescription: how to separate string from unformed string

description: Separate string from unformed string


code:
args = parser.parse_args(['were', 'you'])
args.pattern
pattern = '|'.join(['(?:{})'.format(p) for p in args.pattern])
pattern

rawDescription: Take multiple patterns from cli. argparse Python3


code:
def delta_to_start_and_end(year, day_of_year):
    dt = date(year, 1, 1) + timedelta(days=(day_of_year - 1))

    def first_day(dt):
         return date(dt.year, dt.month, 1)
    def last_day(dt):
         days_in_month = calendar.monthrange(dt.year, dt.month)[1]
         return date(dt.year, dt.month, days_in_month)

    return (dt - first_day(dt)).days, (last_day(dt) - dt).days

rawDescription: Python: Date manipulation code

description: Python: Date manipulation code


code:
from functools import wraps
from flask import flash

def login_required(function_to_protect):
    @wraps(function_to_protect)
    def wrapper(*args, **kwargs):
        user_id = request.cookies.get('YourSessionCookie')
        if user_id:
            user = database.get(user_id)
            if user:
                # Success!
                return function_to_protect(*args, **kwargs)
            else:
                flash("Session exists, but user does not exist (anymore)")
                return redirect(url_for('login'))
        else:
            flash("Please log in")
            return redirect(url_for('login'))

rawDescription: Python Flask: keeping track of user sessions? How to get Session Cookie ID?


code:
import array
idlist = array.array('l')
with open(filename, "rb") as f:
    while True:
        try: idlist.fromfile(f, 2000)
        except EOFError: break
idtuple = tuple(idlist)

rawDescription: Reading a binary file in Python into a struct


code:
def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

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

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


code:
import numpy as np

def main():
    # Generate some random flow_direction and sediment_transport data...
    nrows, ncols = 1000, 1000
    flow_direction = 2 ** np.random.randint(0, 8, (nrows, ncols))
    sediment_transport = np.random.random((nrows, ncols))

    # Make sure all of the results return the same thing...
    test1 = vectorized(flow_direction, sediment_transport)
    test2 = iterate(flow_direction, sediment_transport)
    test3 = lookup(flow_direction, sediment_transport)
    assert np.allclose(test1, test2)
    assert np.allclose(test2, test3)

def vectorized(flow_direction, sediment_transport):
    elevation_change = np.zeros_like(sediment_transport)
    sediment_transport = np.pad(sediment_transport, 1, mode='constant')
    lookup = {32: (-1, -1),
              16:  (0, -1),
              8:   (1, -1),
              4:   (1,  0),
              64: (-1,  0),
              128:(-1,  1),
              1:   (0,  1),
              2:   (1,  1)}

    for value, (row, col) in lookup.iteritems():
        mask = flow_direction == value
        shifted = np.pad(mask, 1, mode='constant')
        shifted = np.roll(shifted, row, 0)
        shifted = np.roll(shifted, col, 1)
        elevation_change[mask] = sediment_transport[shifted]

    return elevation_change

def iterate(flow_direction, sediment_transport):
    elevation_change = np.zeros_like(sediment_transport)
    padded_transport = np.pad(sediment_transport, 1, mode='constant')

    for [i, j], flow in np.ndenumerate(flow_direction):
        r, c = i + 1, j + 1
        if flow == 32:
            elevation_change[i, j] = padded_transport[r - 1, c - 1]
        elif flow == 16:
            elevation_change[i, j] = padded_transport[r, c - 1]
        elif flow == 8:
            elevation_change[i, j] = padded_transport[r + 1, c - 1]
        elif flow == 4:
            elevation_change[i, j] = padded_transport[r + 1, c]
        elif flow == 64:
            elevation_change[i, j] = padded_transport[r - 1, c]
        elif flow == 128:
            elevation_change[i, j] = padded_transport[r - 1, c + 1]
        elif flow == 1:
            elevation_change[i, j] = padded_transport[r, c + 1]
        elif flow == 2:
            elevation_change[i, j] = padded_transport[r + 1, c + 1]
    return elevation_change

def lookup(flow_direction, sediment_transport):
    elevation_change = np.zeros_like(sediment_transport)
    nrows, ncols = flow_direction.shape
    lookup = {32: (-1, -1),
              16:  (0, -1),
              8:   (1, -1),
              4:   (1,  0),
              64: (-1,  0),
              128:(-1,  1),
              1:   (0,  1),
              2:   (1,  1)}

    for [i, j], flow in np.ndenumerate(flow_direction):
        dr, dc = lookup.get(flow, (0,0))
        r, c = i + dr, j + dc
        if not ((0 <= r < nrows) & (0 <= c < ncols)):
            elevation_change[i,j] = 0
        else:
            elevation_change[i,j] = sediment_transport[r, c]

    return elevation_change

if __name__ == '__main__':
    main()

rawDescription: Iterating through a numpy array and then indexing a value in another array


code:
import datetime
t1 = datetime.datetime(2013, 6, 6, 8, 30, 0)
t5 = datetime.datetime(2013, 6, 6, 10, 30, 0)
mytime = t5 - t1
mytime
mytime.total_seconds() // 60
divmod(mytime.total_seconds(), 60)

rawDescription: subtraction date - how to get result in minutes

description: Subtraction date - how to get result in minutes


rawDescription: How to create a numpy array from two lists of tuples, but only when the tuples are the same

description: Create a numpy array from two lists of tuples, but only when the tuples are the same