code:
import win32com.client

adoConnection = win32com.client.Dispatch('ADODB.Connection')
adoCommand = win32com.client.Dispatch('ADODB.Command')
adoRecordset = win32com.client.Dispatch('ADODB.Recordset')

adoConnection.Provider = 'ADSDSOObject'
adoConnection.Properties('User ID').Value = 'user'
adoConnection.Properties('Password').Value = 'password'
adoConnection.Properties('Encrypt Password').Value = True
adoConnection.Properties('ADSI Flag').Value = 1
adoConnection.Open('Active Directory Provider')

adoCommand.ActiveConnection = adoConnection
adoCommand.Properties('Page Size').Value = 1000

ldap = '''\
SELECT cn, mail
From 'LDAP://CN=Configuration,DC=abc,DC=com'
WHERE legacyExchangeDN = '/o=abc/ou=first administrative group/cn=configuration/cn=servers/cn=myserver/cn=microsoft public mdb'
'''

adoCommand.CommandText = ldap
adoRecordset.Open(adoCommand)
while not adoRecordset.EOF:
    print('{} {}'.format(adoRecordset('cn'), adoRecordset('mail')))
    adoRecordset.MoveNext()
adoRecordset.Close()

adoConnection.Close()

rawDescription: LDAP query with exchange object

description: LDAP query with exchange object


code:
# code

if __name__ == "__main__": exec("""

# main code

#""")

rawDescription: Terminate importation of module non-fatally?


code:
s1 = '\xd1\x98\xd1\x83\xd0\xbd'
s2 = u'\xd1\x98\xd1\x83\xd0\xbd'

s1 = s1.decode('unicode-escape')

rawDescription: Convert unicode string to string

description: Convert unicode string to string


code:
def in_language(word):
    if word in ('AB', 'C'):
        return True
    if len(word) < 3: #The only valid words with 2 or less letters are AB and C
        return False
    if word[0] == 'A' and word[-1] == 'B' and in_language(word[1:-1]):
        return True
    else:
        for i, letter in enumerate(word):
            if letter == 'C' and in_language(word[:i]) and in_language(word[i+1:]):
                return True
    return False

rawDescription: Python - Determine if a word is in this language or not


code:
def my_func():
    return {'key1': val1,
            'key2': val2,
            'key3': val3,
            'key4': val4,
           }

rawDescription: python syntax while using dict

description: Python syntax while using dict


code:
filter = Q(a=True)
filter = filter & Q(b=True)
filter.children
filter.children.pop()
filter.children

rawDescription: Popping a query from django Q query?

description: Popping a query from django Q query


code:
from graph_tool.all import *

g = Graph()

vals = [("a","b"), ("b","c"), ("c","d"), ("d","b"), ("c","e")]

vertexes_names = g.new_vertex_property("string")
vertexes = {}
for start, stop in vals:
    if start not in vertexes:
        vertexes[start] = g.add_vertex()
        vertexes_names[vertexes[start]] = start
    if stop not in vertexes:
        vertexes[stop] = g.add_vertex()
        vertexes_names[vertexes[stop]] = stop
    g.add_edge(vertexes[start], vertexes[stop])

graph_tool.stats.remove_parallel_edges(g)
graph_draw(g, vertex_text=vertexes_names, vertex_font_size=18, output="output.png")

rawDescription: Convert python dictionary to flowchart

description: Convert python dictionary to flowchart


code:
from xml.dom import minidom
import xml.etree.ElementTree as ET

tree = ET.parse('/tmp/input.xml').getroot()
namespaces = {'gml': 'http://www.opengis.net/gml', 'ogr':'http://ogr.maptools.org/'}
for child in tree.findall('gml:featureMember', namespaces=namespaces):
    if len(child.find('ogr:TZwards', namespaces=namespaces)):
        name = child.find('ogr:TZwards', namespaces=namespaces).find('ogr:Region_Nam', namespaces=namespaces).text
        if name != 'TARGET':
            tree.remove(child)

out = ET.ElementTree(tree)
out.write("/tmp/out.xml")

rawDescription: Remove XML node if childnode's childnode contains specific value


code:
import imp
my_module = imp.load_source('my_module', '.test.py')

rawDescription: Import with dot name in python

description: Import with dot name in python


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

a = 0.11768 #is it in m/s^2? I've used m/s^2...
v=[] #velocity at a given time ‹
x = np.arange(0, 100, 1)    # 0 to 100 seconds
for i in x: # ‹
    v.append(i*a) #read it as a*t, in fact is t...use i*a*3.6 if you want km/h ‹
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,v,)
plt.plot(x, v)
plt.ylabel(r'Velocity $(m/sec )$') #note if you want km/h use v.append(i*a*3.6) above
plt.xlabel(r'Time $(sec)$')
plt.show()

rawDescription: Calculating next y using previous y element using numpy


code:
if main_catalog.objects.filter(catalog__id=pk).exists():
    pass
else:
    Catalog.objects.filter(pk=pk).delete()

rawDescription: Do not delete if there is a FK dependency to obj


code:
txt ="it's tail was big"
txt.replace("'s", '').split()

rawDescription: Stripping 's (apostrophe s) from a string


code:
def list_animals(request_id, response, exception):
    if exception is not None:
        # Do something with the exception.
        pass
    else:
        # Do something with the response.
        pass

def list_farmers(request_id, response, exception):
    if exception is not None:
        # Do something with the exception.
        pass
    else:
        # Do something with the response.
        pass

service_ = authHandler.CreateService('drive', 'v2', creds)

batch = BatchHttpRequest()

batch.add(service_.changes().list(), list_animals)
batch.add(service_.changes().list(), list_farmers)
batch.execute(http=authHandler.getHttp(creds))

rawDescription: Is there a way to make batched calls using the Drive SDK?


code:
from django import forms

class VerificationAdminForm(forms.ModelForm):
    class Meta:
        model = Verification

    def clean_asset_code(self):
        asset_code = self.cleaned_data['asset_code']
        if Verification.objects.filter(asset_code=asset_code).exists():
            raise forms.ValidationError("This asset code already exist.")
        return asset_code

class VerificationAdmin(admin.ModelAdmin):
    form = VerificationAdminForm

rawDescription: How to prevent duplicate entries in model from django admin

description: Prevent duplicate entries in model from django admin


code:
class Foo(object):
    _close_on_exit = False

    def __init__(self, file_to_process):
        if isinstance(file_to_process, str):
            self._underlying_stream = open(file_to_process, "rb") # it's the path to a file
            self._close_on_exit = True
        elif isinstance(file_to_process, io.IOBase):
            self._underlying_stream = file_to_process # its the file itself
        else:
             raise TypeError()

    def __exit__(self, exc_type, exc_value, traceback):
        if self._close_on_exit:
            self._underlying_stream.close()

rawDescription: Should I close a stream (file-like object) passed into my object in the context manager __exit__() function?


code:
with open('output.txt', 'w') as stdout_file:
    robot.run('test.txt', stdout=stdout_file)

rawDescription: redirect robot output from robot.run in python

description: Redirect robot output from robot.run in python


code:
from PySide.QtGui import *

class MyEditor(QHBoxLayout):
    def __init__(self):
        super(MyEditor, self).__init__()
        self.add_buttons()
        self.add_editor()

    def add_buttons(self):
        self.buttons_layout = QVBoxLayout()
        self.addLayout(self.buttons_layout)
        self.b1 = QPushButton('1')
        self.b2 = QPushButton('2')
        for b in (self.b1, self.b2):
            self.buttons_layout.addWidget(b)

    def add_editor(self):
        self.editor = QTextEdit()
        self.addWidget(self.editor)

    def set_focus(self):
        self.editor.setFocus()

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.editor = MyEditor()
        self.setLayout(self.editor)
        self.editor.set_focus()
        self.show()

app = QApplication([])
window = Window()
app.exec_()

rawDescription: Qt trough PySide: QTextEdit doesn't get focus on window creation if there is a button in the window


rawDescription: How to split a word into letters in Python

description: Split a word into letters in Python


code:
for i in self.ids_string:
    for j in range(1, 32):
        if hasattr(i, "hours%s" % j):
            a = getattr(i, "hours%s" % j)
            setattr(i, "hours%s" %j, ftohhmm(a))

rawDescription: Updating table fields

description: Updating table fields


code:
for row in reader:
    id1 = ids.setdefault(row[0], len(ids))

rawDescription: Pythonic way to increment and assign ids from dictionary


code:
import pandas as pd
from numpy.random import rand, randint

df = pd.DataFrame(rand(100, 1), columns=['value'])

cut1 = randint(2,47)
cut2 = randint(52, 97)
df.ix[:cut1, 'class']='A'
df.ix[cut1+1:cut2, 'class']='B'
df.ix[cut2+1:, 'class'] = 'C'

dfg = df.groupby('class')

counts = [len(v) for k, v in dfg]
total = float(sum(counts))
cases = len(counts)

widths = [c/total for c in counts]

cax = df.boxplot(column='value', by='class', widths=widths)
cax.set_xticklabels(['%s\n$n$=%d'%(k, len(v)) for k, v in dfg])

rawDescription: Is there a good way to display sample size on grouped boxplots using Python Matplotlib


code:
class Visitor(models.Model):
    name = models.CharField(max_length=30)

class Meeting(model.Model):
    title = models.CharField(max_length=30)
    time = models.TimeField(blank=False, null=False)
    date = models.DateField(blank=False, null=False)
    attendance = models.ManyToManyField(Visitor, through='Attendant')

class Attendant(models.Model):
    visitors = models.ForeignKey(Visitor)
    meeting = models.ForeignKey(Meeting)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

rawDescription: How to add a timestamp to a ManyToMany record

description: Add a timestamp to a ManyToMany record


code:
import multiprocessing as mp

def foo(x):
    return x * x

if __name__ == '__main__':
    result = []
    pool = mp.Pool()
    for i in range(100):
        pool.apply_async(foo, args=(i, ), callback=result.append)
    pool.close()
    pool.join()
    print(result)
    # [0, 1, 4, 9, 16, ... 9409, 9604, 9801]

rawDescription: How to append return value of function into list in Pool?

description: Append return value of function into list in Pool


code:
if __name__ == '__main__':
    import main_module

rawDescription: Process subclass can't run in windows

description: Process subclass can't run in windows


rawDescription: Possible to specify csv delimiter for writing?


code:
import datetime
ist_time = datetime.utcnow() + datetime.timedelta(hours=5, minutes = 30)
# Turn this into a time object (no day information).
ist_time = ist_time.time()
if datetime.time(9, 55) <= ist_time <= datetime.time(16, 1):
   ...

rawDescription: call function between time intervals

description: Call function between time intervals


code:
def pid_running(pid):
    import ctypes
    kernel32 = ctypes.windll.kernel32
    SYNCHRONIZE = 0x100000

    process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
    if process != 0:
        kernel32.CloseHandle(process)
        return True
    else:
        return False

rawDescription: Check if PID exists on Windows with Python without requiring libraries


code:
txt=cv.create_text(..., text="OUT")
...
def enter_lambda(canvasID, textID):
    return lambda event:on_enter(event,canvasID, textID)
def leave_lambda(canvasID, textID):
    return lambda event:on_leave(event,canvasID, textID)
...
cv.bind("<Enter>", enter_lambda(canvasID, txt))
cv.bind("<Leave>", leave_lambda(canvasID, txt))
...
def on_enter(event,canvasID, txt):
    cv = event.widget
    cv.itemconfigure(txt, text="IN %s" % canvasID)

def on_leave(event,canvasID, txt):
    cv = event.widget
    cv.itemconfigure(txt, text="OUT %s" % canvasID)

rawDescription: How to make tkinter canvas text variable in function

description: Make tkinter canvas text variable in function


rawDescription: parse string of numbers with +/- signs and keep signs

description: Parse string of numbers with +/- signs and keep signs


code:
ALLOWED = ('color', 'size', 'model')
kwargs = dict(
    (key, value)
    for key, value in request.GET.items()
    if key in ALLOWED
)
query.filter(**kwargs)

rawDescription: Good practices for a flexible search page - Django


code:
"CREATE {} WITH REPLICATION = \
    {{ 'class' : '{}', 'replication_factor' : {}  }};".format('a','b','c')

rawDescription: 'CREATE' in Python String causing KeyError with " 'class' "


code:
import csv

# load the csv file
rows = [r for r in csv.reader(file('sample.csv','r'))]

# order preservation list
preserve_order = []

# track the schedule from the hosting team's point of view
hosting_teams = {}

# change the wanted column here
wanted_column = 3

for row in rows:
    # strip out the double quotes
    row = [c.replace('"','') for c in row]

    the_host = row[2]
    the_order = row[0]

    preserve_order.append(the_order)

    # create a dictionary with a unique set of visiting teams
    host_schedule = hosting_teams.setdefault(the_host,set([]))

    # add the team visit
    visiting_team = row[wanted_column]
    host_schedule.add((visiting_team,the_order))

output = []
for hosting_team,host_schedule in hosting_teams.items():
    for visiting_team,the_order in host_schedule:
        output.append([the_order,"Result",hosting_team,visiting_team])

output.sort(key=lambda x:preserve_order.index(x[0]))

csv.writer(file('output.csv','wb')).writerows(output)

rawDescription: Loop through .csv files with conditions in different columns


code:
import urllib2
from bs4 import BeautifulSoup

url = "www.theurlyouwanttoscrape.com"
html = urllib2.urlopen(url)

soup = BeautifulSoup(html)

img_src = soup.find('img', {'id':'main_image'})['src']

rawDescription: When scraping image url src, get data:image/jpeg;base64


code:
import pandas as pd
from glob import glob as gg

data = pd.DataFrame()
names = ['state', 'gender', 'year', 'name', 'count']

for f in gg('*.txt'):
    tmp = pd.read_csv(f,columns=names)

    data = pd.concat([data,tmp],axis=0,ignore_index=True)

rawDescription: Python read in multiple .txt files and row bind using pandas


code:
re.sub("([A-Z][a-z]*\s)SpA", "\\1", "Billboard Bill SpA")
'Billboard Bill '

rawDescription: Difference between re.sub and re.findall


code:
def __gt__(self, circle2):
    return self.r > circle2.r

rawDescription: "Enabling" comparison for classes

description: "Enabling" comparison for classes


code:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,

    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },

        'request_format': {
            'format': '%(levelname)s %(asctime)s %(module)s %(remote_addr)s %(username)s %(request_method)s '
            '%(path_info)s %(server_protocol)s" %(http_user_agent)s '
            '%(message)s',
        },
    },

    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },

       # Add an unbound RequestFilter.
       'request': {
           '()': 'django_requestlogging.logging_filters.RequestFilter',
       },
    },

    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },

        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
            'stream': sys.stdout
        },

        'rainbow': {
            "level": "DEBUG",
            "class": "rainbow_logging_handler.RainbowLoggingHandler",
            "stream": sys.stderr
        },

        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filters': ['request'],
            'filename': 'logs/django.log',
            'formatter': 'request_format',
        },

        'sentry': {
            'level': 'WARN',
            'class': PRODUCTION and 'raven.contrib.django.raven_compat.handlers.SentryHandler' or 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },

        'django.db.backends': {
            'handlers': [],
            'level': 'ERROR',
            'propagate': True,
        },

        'sqlalchemy': {
            'level': 'ERROR',
            'propagate': False,
        },

        'py.warnings': {
            'level': 'ERROR',
            'propagate': False,
        },

        '': {
            'level': PRODUCTION and 'WARN' or 'DEBUG',
            'handlers': [PRODUCTION and 'sentry' or 'rainbow', 'file'],
        },

    }
}

rawDescription: Ignoring log messages from third party packages in Python


code: np.equal(a, None)

rawDescription: creating a boolean array which compares numpy elements to None

description: Creating a boolean array which compares numpy elements to None


code:
def get_closest_rects(rect_list, click_pos):
  return filter(lambda r: r.left <= click_pos[0] <= r.right or r.top <= click_pos[1] <= r.bottom, rect_list)

rawDescription: How can I get a list from min() method in python?

description: Get a list from min() method in python


code:
images = self.driver.find_elements_by_tag_name('img')
for image in images:
    src = image.get_attribute("src")
    if src:
        urllib.urlretrieve(src)

rawDescription: How to download ALL the pictures of a webpage and save them in their original names?

description: Download ALL the pictures of a webpage and save them in their original names


code:
class _JobTableReader(_TableReader):
  """A TableReader that reads from a completed job."""

  def __init__(self, local_apiclient, project_id, job_id):
    self.job_id = job_id
    self.project_id = project_id
    self._apiclient = local_apiclient

  def ReadSchemaAndRows(self, max_rows=None):
    """Read at most max_rows rows from a table and the schema.

    Args:
      max_rows: maximum number of rows to return.

    Raises:
      BigqueryInterfaceError: when bigquery returns something unexpected.

    Returns:
      A tuple where the first item is the list of fields and the
      second item a list of rows.
    """
    page_token = None
    rows = []
    schema = {}
    max_rows = max_rows if max_rows is not None else sys.maxint
    while len(rows) < max_rows:
      (more_rows, page_token, total_rows, current_schema) = self._ReadOnePage(
          max_rows=max_rows - len(rows),
          page_token=page_token)
      if not schema and current_schema:
        schema = current_schema.get('fields', {})

      max_rows = min(max_rows, total_rows)
      for row in more_rows:
        rows.append([entry.get('v', '') for entry in row.get('f', [])])
      if not page_token and len(rows) != max_rows:
          raise BigqueryInterfaceError(
            'PageToken missing for %r' % (self,))
      if not more_rows and len(rows) != max_rows:
        raise BigqueryInterfaceError(
            'Not enough rows returned by server for %r' % (self,))
    return (schema, rows)

  def _ReadOnePage(self, max_rows, page_token=None):
    data = self._apiclient.jobs().getQueryResults(
        maxResults=max_rows,
        pageToken=page_token,
        # Sets the timeout to 0 because we assume the table is already ready.
        timeoutMs=0,
        projectId=self.project_id,
        jobId=self.job_id).execute()
    if not data['jobComplete']:
      raise BigqueryError('Job %s is not done' % (self,))
    page_token = data.get('pageToken', None)
    total_rows = int(data['totalRows'])
    schema = data.get('schema', None)
    rows = data.get('rows', [])
    return (rows, page_token, total_rows, schema)

rawDescription: Google BigQuery Incomplete Query Replies on Odd Attempts


rawDescription: IP address conversion using Python

description: IP address conversion using Python


code:
requests_mock = mocker.replace("requests")
session_mock = mocker.mock()
requests_mock.Session()
mocker.result(session_mock)

rawDescription: mocker won't mock requests session

description: Mocker won't mock requests session


rawDescription: Vectorized format function for Pandas series


code: pgettext_lazy(u'context', u'title')

rawDescription: pgettext not showing the untranslated value in django admin

description: Pgettext not showing the untranslated value in django admin


code:
ys = np.piecewise(
        xs,
        [(xs >= segments[i]) & (xs <= segments[i+1]) for i in range(len(segments)-1)],
        funcs)

rawDescription: Numpy piecewise of arbitrary length

description: Numpy piecewise of arbitrary length


code:
my_asyncore_obj = SomeAsyncoreObj()
asyncore.loop(map=my_asyncore_obj._map)

rawDescription: Starting an INDIVIDUAL instance of a subclass from asynchat


code:
import csv
import collections

occurences = collections.Counter()
grundformen = collections.defaultdict(list)

with open("material-2.csv", mode='r', newline='', encoding="utf-8") as material:
    reader = [ln for ln in csv.reader(material, delimiter='\t', quotechar="\t") if ln]
    for line in reader:
        occurences[line[5]] += 1
        grundformen[line[5]].append(line[2])
    list_of_occurences = list(map(list, occurences.most_common()))
    for elem in list_of_occurences:
        elem.append(grundformen[elem[0]][0])

print(occurences)

rawDescription: My for-Loop isn't working as intended

description: My for-Loop isn't working as intended


code:
# This layer bit is for balls colliding with other balls
# I'm only guessing that you want this though.
ball_layer = 1
# This layer bit is for things that collide with red balls only.
red_ball_layer = 2
# This layer bit is for things that collide with blue balls only.
blue_ball_layer = 4

# Bitwise OR the layer bits together
red_ball_shape.layers = ball_layer | red_ball_layer
blue_ball_shape.layers = ball_layer | blue_ball_layer

# Lower border should collide with red only
upper_border_shape.layers = red_ball_layer

#Upper border with blue balls only
lower_border_shape.layers = blue_ball_layer

rawDescription: Pymunk (chipmunk) - how to turn off physics/collisions temporarily for concrete object


code:
exercises = [
    {"Upper_body" : True, "Lower_body" : False, "Core" : False,'routine': "4 x 8 reps arm curl, 4 x 8 reps chest press, 4 x 8 reps shoulder press"},
    {"Upper_body" : True, "Lower_body" : False, "Core" : False,'routine':"4 x 8 reps squats, 4 x 8 reps leg press, 20 x lunges"},
    {"Upper_body" : True, "Lower_body" : False, "Core" : True,'routine':"4 x 8 reps arm curl, 4 x 8 reps chest press, 4 x 8 reps shoulder press, 20 min plank"}
             ]

def yes_no(question):
    answer = input(question).lower()
    if answer=='yes':
        ans=True
    else:
        ans=False
    return(ans)

client = { "Upper_body"  : yes_no("Do you want to exercise the upper body? "),
     "Lower_body" : yes_no("Do you want to exercise the lower body? "),
     "Core" : yes_no("Do you want to exercise the core muscle group? ")}

for exercise in exercises:
    if exercise["Upper_body"] == client["Upper_body"] and exercise["Lower_body"] == client["Lower_body"] and exercise["Core"] == client["Core"]:
        print(exercise["routine"])

rawDescription: Comparing values in dictionaries in Python and returning a value


rawDescription: Calculating percentile ranks of the last element of each column in a dataframe in Python


code:
query1 = pyes.MultiMatchQuery(self.FIELDS_SEARCH, query_string, operator='and')

typequery = pyes.QueryStringQuery(query="type_value",default_field="type")

combinequery = pyes.BoolQuery(must=[query1, typequery])

searchquery = pyes.Search(query=combinequery,filter=filters, fields=self.RESPONSE_FIELDS, size=num, index_boost=1)

rawDescription: Django ElasticSearch / pyes : How to search with two filters?


code:
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
    NeuralNetworkBase.__init__(self, numberOfInputers, numberOfHiddenNeurons, numberOfOutputs)
    self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))
    self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))

rawDescription: How do derived class constructors work in python?


code:
scores = [1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5]
from collections import Counter
score_counts = Counter(scores)
score_counts
import pandas as pd
pd.DataFrame.from_dict(score_counts, orient='index')

rawDescription: Python: Creating a 2-column dataframe from list and a computation on the list


code:
with open('file.txt') as f, open('out.txt', 'w') as f2:
    state = 1
    for line in f:
        if line == 'Middle Value\n':
            state = 2
            continue  # unless there's something to do upon entering the state
        elif line == 'Last Value\n':  # might want to just test for blank line `\n'
            state = 3
            continue  # unless there's something to do upon entering the state

        # otherwise process to line based on the current value of "state"
        if state == 1:      # before 'Middle Value' has been seen
            pass
        elif state == 2:    # after 'Middle Value' has been seen
            pass
        else:               # after 'Last Value' (or a blank line after
            pass            # 'Middle Value') has been seen

rawDescription: Is there a way to use "for loop" in the specific range with strings?


code:
import os
basedir = 'C:/Test'
for fn in os.listdir(basedir):
  if not os.path.isdir(os.path.join(basedir, fn)):
    continue # Not a directory
  if ',' in fn:
    continue # Already in the correct form
  if ' ' not in fn:
    continue # Invalid format
  firstname,_,surname = fn.rpartition(' ')
  os.rename(os.path.join(basedir, fn),
            os.path.join(basedir, surname + ', ' + firstname))

rawDescription: How to change folder names in python?

description: Change folder names in python


code:
spans = soup.find_all('span', attrs={"class":u"reviewCount"})
for span in spans:
    a = span.find('a')
    match = re.search(r'Reviews\-(.*?)\-City', a.get('href'))
    if match:
        print(match.group(1))

rawDescription: Find string between two sets of string (python / urllib2 / beautiful soup)


code:
frame = Frame(root, bd=2, relief=SUNKEN)

scrollbar = Scrollbar(frame)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(frame, bd=0, yscrollcommand=scrollbar.set)
listbox.pack()

scrollbar.config(command=listbox.yview)

frame.pack() #or others...

rawDescription: User interface optimization when using pack


rawDescription: Sorting Pandas dataframe data within Groupby groups


code:
routes_in = (
  ('/user', '/login'),
)

routes_out = (
  ('/user', '/'),
)

rawDescription: How to hide sub-directories in the url with web2py

description: Hide sub-directories in the url with web2py


code:
result = []
seen = set()
for obj in objects:
    if obj.field1 not in seen:
        seen.add(obj.field1)
        result.append(obj)

rawDescription: Python- Use set on a List of objects <class 'xyz.models.abc'>


code:
cmd_data = {cmd.id: cmd.value for cmd in cmd.cmd_list}
for rsp in rsp.rsp_list:
    if rsp.common.id in cmd_data:
        rsp.common.value.CopyFrom(cmd_data[rsp.common.id])

rawDescription: Update values in one list with values from another


code:
myDataString = "var1=value1&var2=value2&var3=value3"
mySplitData = myDataString.split('&')

import collections
myDict = collections.defaultdict(list)

for value in mySplitData:
    splitValue = value.split('=')
    myDict[splitValue[0]]

rawDescription: Most efficient way of sending a string with multiple variables as POST data using urllib


code:
import datetime
import pytz
import hashlib
now = datetime.datetime.now(pytz.timezone('Asia/Singapore')).isoformat()
later = datetime.datetime.now(pytz.timezone('Asia/Singapore')).isoformat()
m1 = hashlib.md5()
m2 = hashlib.md5()
m1.update(now)
m2.update(later)
m1.digest() == m2.digest()

rawDescription: Keep change to different hash md5

description: Keep change to different hash md5


code:
from itertools import groupby

xlist.sort(key=lambda x: (x["id"], x["day"], x["name"]))  # or use sorted()
unique_xlist = []

for k, g in groupby(xlist, lambda x: (x["id"], x["day"])):
    unique_xlist.append({"id": k[0], "day": k[1], "name": [i["name"] for i in g]})

rawDescription: Create unique dictionaries for two keys in a list of dictionaries


code: type(object) #gives you the type

rawDescription: How do I see what the "type" of an object is, in Python?

description: See what the "type" of an object is, in Python


code: result = tuple(itertools.izip_longest(l, (x[1] for x in f for y in range(x[0])), fillvalue='None'))

rawDescription: Python: Make new tuple by attaching info from existing list


code:
import random
cutoff = .2 # (random draws between 0 and 1, so .2 would yield a 20% sample.)
with open(myfile) as f1:
    with open(output,'w') as f2:
        for i,line in enumerate(f1):
            if random.random() < cutoff:
                f2.write(line)

rawDescription: Using has function for sampling large data set


code:
q = forms.CharField(label='search',
                    widget=forms.TextInput(attrs={'placeholder': 'Search'}))

rawDescription: How do I add a placeholder on a CharField in Django?

description: Add a placeholder on a CharField in Django


code:
import re

fin = open('snp.txt','r').readlines()
l = [ re.match('.*(\(.*?\))',line).group(1) for line in fin]
l = [ '%d %f\n'%eval(i) for i in l]

with open('o.txt','w') as fout:
    fout.writelines(l)
    fout.close()

rawDescription: Reading numbers from a .txt file

description: Reading numbers from a .txt file


code:
df = df.set_index('Time')
df.resample('5min', how='ohlc')

rawDescription: pandas dataframe group by uneven timestamp

description: Pandas dataframe group by uneven timestamp


code:
import grab, requests, urllib

root_url = 'https://e-okul.meb.gov.tr/'
g = grab.Grab()
g.go(root_url)
e = g.doc.select('//*[@id="image1"]')
captcha_url = root_url + e.attr('src')
resp = g.go(captcha_url)
localFile = open('captcha.jpg', 'wb')
localFile.write(resp.body)
localFile.close()

rawDescription: What's wrong with the logic of this captcha?


code:
from tkinter import *
from math import sin, cos, pi
master = Tk()

def update_canvas(*args):
    number_of_people = people_size_var.get() #gets scale's value
    DisplayFrame.delete("all") #deletes every content from canvas

    a = 350
    b = 140
    ellipsePoints = [(a * cos(theta), b * sin(theta))
                     for theta in (pi*2 * i/number_of_people for i in range(number_of_people))]

    for i in range(number_of_people-1):
        Bonds = DisplayFrame.create_line(ellipsePoints[i][0]+355+(node_size/2), ellipsePoints[i][1]+155+(node_size/2),
                                 ellipsePoints[i+1][0]+355+(node_size/2), ellipsePoints[i+1][1] +155+(node_size/2),
                                 width=2, fill="black")

    for i in range(number_of_people):
        People = DisplayFrame.create_oval(ellipsePoints[i][0]+355, ellipsePoints[i][1]+155,
                                 ellipsePoints[i][0]+355 + node_size, ellipsePoints[i][1] + 155 + node_size,
                                 fill="yellow", outline="black", width=2)

people_size_var = IntVar()
PeopleSize = Scale(master, from_=1, to=50, bd=3, length=320, variable=people_size_var)
PeopleSize.grid(row=0, column=0, padx=10, pady=5)
people_size_var.set(20)
PeopleSize.config(highlightbackground="white")

node_size = 5

DisplayFrame = Canvas(master, bg="white", width=725, height=320)
DisplayFrame.grid(row=0, columnspan=7, column=1, sticky='W', padx=5, pady=5)

people_size_var.trace("w", update_canvas)

master.mainloop()

rawDescription: Why doesn't the GUI update even with trace and a callback function?


rawDescription: Python, get base64-encoded MD5 hash of an image object


code:
a = numpy.arange(12).reshape(4,3)
a
a.strides
b = numpy.lib.stride_tricks.as_strided(a, shape=(4, 4), strides=(24, 8))
b

rawDescription: Appending large amount of data to a tables (HDF5) database where database.numcols != newdata.numcols?


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.page_source

rawDescription: How to get the entire web page source using selenium-webdriver in python

description: Get the entire web page source using selenium-webdriver in python


code:
class MyModelAdmin(admin.ModelAdmin):
    list_display = ['field_1', 'field_2', ...]

admin.site.register(MyModel, MyModelAdmin)

rawDescription: django admin need full table

description: Django admin need full table


code:
plt.plot(np.linspace(-10, 10), np.linspace(-10, 10))
plt.gca().tick_params('x', length=20, width=2, which='major')

xTicks = plt.xticks([-5,-4,-3,-2,-1,0,1,2,3,4,5])

xTicks_cld = xTicks[0][0].get_children()
xTicks[0][0].get_children()[0].set_color('g')
#change the color of the 1st bottom tick

xTicks[0][0].get_children()[1].set_color('r')
#change the color of the 1st top tick

xTicks[0][-1].get_children()[0].set_color('b')
#change the color of the last bottom tick

xTicks[0][5]._apply_params(color='r')
#change the color of the ticks of x=0, both top and bottom xaxis.

rawDescription: Matplotlib set individual tick style

description: Matplotlib set individual tick style


code:
import Cookie
def set_unicode_cookie(response, key, value):
  c = Cookie.SimpleCookie()
  c[key] = value.encode('unicode-escape')
  c[key]["expires"] = "Sun, 31-May-2020 23:59:59 GMT"
  c[key]["path"] = "/"
  response.headers.add_header('Set-Cookie', c[key].OutputString())

def get_unicode_cookie(request, key, defult_value):
  def unescape(s):
    m = re.match(r'^"(.*)"$', s)
    s = m.group(1) if m else s
    return s.replace("\\\\", "\\")
  if request.cookies.has_key(key):
    return unescape(request.cookies[key]).decode('unicode-escape')
  else:
    return default_value

rawDescription: An universal way to set unicode cookies in Python


code:
latex_documents = [
   ('index', 'Kaskady.tex', u'Kaskady  Documentation',
    u'Author', 'manual'),
   ('profile', 'profiles.tex', u'Wyznaczanie profili',
    u'Author', 'howto'),
]

rawDescription: Any way to generate multiple different pdfs from single sphinx configuration


rawDescription: how to insert a column to a list of lists in python

description: Insert a column to a list of lists in python


code:
import sqlite3, os

in_memory = sqlite3.connect(':memory:')
# do stuff

con = sqlite3.connect('existing_db.db')
con.execute('drop table stocks')
for line in in_memory.iterdump():
    con.execute(line)

rawDescription: Python SQLite cache in memory

description: Python SQLite cache in memory


code:
vars = {}
for x in config_list['entry']:
    vars[x] = StringVar()
    entry = ttk.Entry(mainframe_entry, textvariable=vars[x])
    entry.grid()

rawDescription: Dynamic Widget creation based of configparser file


code:
from subprocess import Popen, PIPE

scpt = '''
    on run {x, y}
        return x + y
    end run'''
args = ['2', '2']

p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print (p.returncode, stdout, stderr)

rawDescription: How do I embed an AppleScript in in a Python script?

description: Embed an AppleScript in in a Python script


code:
from nltk.tokenize import WordPunctTokenizer
from nltk.corpus import wordnet

my_list_of_strings = []  # populate list before using

wpt = WordPunctTokenizer()
only_recognized_words = []

for s in my_list_of_strings:
    tokens = wpt.tokenize(s)
    if tokens:  # check if empty string
        for t in tokens:
            if wordnet.synsets(t):
                only_recognized_words.append(t)  # only keep recognized words

rawDescription: NLTK WordNet Lemmatizer - How to remove the unknown words?


code:
from lxml import etree

root = etree.fromstring(xml)

for node in root.iter("graph"):
  #To get the namespaces of the direct children
  namespaces = [child.namespace for child in node]

  #To get the tags of the direct children
  tags = [child.tag for child in node]

  #To get the text of the direct children
  texts = [child.text for child in node]

rawDescription: I just want direct children of an XML element, not all descendents


code:
def adj_hdi(row):
    hdi = row['HDI']
    if hdi>.5:
        return hdi
    else:
        return 0
mydataframe['ADJ_HDI'] = mydataframe.apply(lambda row: adj_hdi(row), axis = 1)

rawDescription: Adding a column in Pandas while editing the values


code:
df = pd.DataFrame([[1,2],[2,4]], columns=['1stcol', '2ndcol'])
df.columns
df.columns[0]
df['1stcol'].name

rawDescription: Extract a column name from a Pandas column index


code:
inv = cursor.fetchone()[0]
remote_inv = cursor.fetchone()[0]
diff = remote_inv - inv
diff_minutes = diff.total_seconds() / 60

rawDescription: How to get hour difference between two date variables in python

description: Get hour difference between two date variables in python


code:
from tkinter import *
from PIL import ImageTk, Image

def image_resize(imageFile):
    width = 500
    height = 300
    image = Image.open(imageFile)
    im2 = image.resize((width,height), Image.ANTIALIAS)
    return im2

def show_image():
    label_originalimage ['image'] = image_tk

root = Tk()
filename = './Pictures/Space/AP923487321702.jpg'
image_resize = image_resize(filename)
image_tk = ImageTk.PhotoImage(image_resize)

label_originalimage = Label(root)
label_originalimage.pack()

button_open = Button(root, text='Open Image', command=show_image)
button_open.pack()

root.mainloop()

rawDescription: Cannot construct tkinter.PhotoImage from PIL Image


code:
source_file = open("file.txt", "r")
file_data = list(source_file.read())
source_file.close()
file_data.insert(position, data)
open("file.txt", "wb").write(file_data)

rawDescription: Python writing in files from a specific line


code:
from wtforms import Form
from wtforms.fields import StringField

class User(object):
    first_name = ""
    last_name = ""

class UpdateForm(Form):
    first_name = StringField()
    last_name = StringField()

data = {'first_name':'EDITED'}

form = UpdateForm(obj=Struct(**data))

# this is for the purpose of creating
# an existing user. We assume you are
# considering getting this out of a db
user = User()
user.first_name = 'OLD First name'
user.last_name = 'OLD Last name'

if form.data.get('first_name'):
    user.first_name = form.data.get('first_name')

if form.data.get('last_name'):
    user.last_name = form.data.get('last_name')

rawDescription: Bind only modified form data to a class

description: Bind only modified form data to a class


code:
import gtk
import pango

class TextBuffer(gtk.TextBuffer):
    def __init__(self):
        gtk.TextBuffer.__init__(self)
        self.connect_after('insert-text', self.text_inserted)
        # A list to hold our active tags
        self.tags_on = []
        # Our Bold tag.
        self.tag_bold = self.create_tag("bold", weight=pango.WEIGHT_BOLD)

    def get_iter_position(self):
        return self.get_iter_at_mark(self.get_insert())

    def make_bold(self):
        ''' add "bold" to our active tags list '''
        if 'bold' in self.tags_on:
            del self.tags_on[self.tags_on.index('bold')]
        else:
            self.tags_on.append('bold')

    def text_inserted(self, buffer, iter, text, length):
        # A text was inserted in the buffer. If there are ny tags in self.tags_on,   apply them
        if self.tags_on:
            # This sets the iter back N characters
            iter.backward_chars(length)
            # And this applies tag from iter to end of buffer
            self.apply_tag_by_name('bold', self.get_iter_position(), iter)

def main():
    window = gtk.Window()
    window.connect('destroy', lambda _: gtk.main_quit())
    window.resize(300, 300)
    tb = TextBuffer()
    tv = gtk.TextView(buffer=tb)

    accel = gtk.AccelGroup()
    accel.connect_group(gtk.keysyms.b,
                        gtk.gdk.CONTROL_MASK,gtk.ACCEL_LOCKED,
                        lambda a,b,c,d: tb.make_bold())
    window.add_accel_group(accel)
    window.add(tv)
    window.show_all()
    gtk.main()

if __name__ == '__main__':
    main()

rawDescription: Inserting bold characaters in pyGTK's TextView/TextBuffer


code:
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.menu = None

    def mousePressEvent(self, event):
        menu = QMenu()
        self.menu = menu
        menu.installEventFilter(self)
        self.quit_action = menu.addAction("Close")
        self.add_action = menu.addAction("Add action")
        menu.exec_(self.mapToGlobal(event.pos()))

    def eventFilter(self, obj, event):
        print(obj, self.menu)
        if obj == self.menu:
            if event.type() == QEvent.MouseButtonRelease:
                action = self.menu.actionAt(event.pos())
                if action:
                    if action == self.quit_action:
                        return False
                    elif action == self.add_action:
                        self.menu.addAction("New action")
                        self.menu.exec_()
                        return True
        return False

rawDescription: prevent PyQt's QActions from automatic triggers

description: Prevent PyQt's QActions from automatic triggers


code:
labels,num=label(image, return_num=True)
for i in range(num):
    area[i]=size(np.where(labels==i)[1])

rawDescription: Calculating just a specific property in regionprops python


code:
lis = ['aka', 'this is a good day', 'a pretty dog']
stopwords = ['a', 'dog']
stop = set(stopwords)
[' '.join(j for j in i.split(' ') if j not in stop) for i in lis]

rawDescription: python process multiple string at the same time

description: Python process multiple string at the same time


code:
from fabric.api import run, env
from fabric.context_managers import cd

env.use_ssh_config = True

def list_files():
    with cd('/tmp'):
        run('ls')

rawDescription: How to set the working directory for a Fabric task?

description: Set the working directory for a Fabric task


code:
lines =open("S011_PCR_ABCDEF-AnnotatedVDJAlignments.fasta", "r").read().splitlines()
manualintervf = open("NoDregion.txt", "w")
goodlines = open("withDregion.txt", "w")

d_before = 4
d_after = 3
d_flag = [0] * len(lines)

for i, line in enumerate(lines):
    if "No D" in line:
        dstart = max(i-d_before, 0)
        dend = min(i+d_after, len(lines))
        for j in range(dstart, dend):
          d_flag[j] = 1

for i, line in enumerate(lines):
    if d_flag[i] == 1:
        manualintervf.write(line+"\n")
    else:
        goodlines.write(line+"\n")

rawDescription: write lines to file and remove python

description: Write lines to file and remove python


code:
import matplotlib.pyplot as plt
import pandas as pd

# Some sample data
df = pd.DataFrame({'C' : [4,5,6,7], 'S' : [10,20,30,40],'R' : [100,50,-30,-50]})

fig=plt.figure()
plt.title('Title')

ax1 = df.R.plot(style='b', label='Suc. Rate')
ax1.set_ylabel('Success Rate / Coherence')

ax2 = df.C.plot(style='r', label='Coherence')

ax3 = df.S.plot(secondary_y=True, style='g', label='Size')
ax3.set_ylabel('Lexicon Size')

handles,labels = [],[]
for ax in fig.axes:
    for h,l in zip(*ax.get_legend_handles_labels()):
        handles.append(h)
        labels.append(l)

plt.legend(handles,labels)

plt.show()

rawDescription: Pyplot: single legend when plotting on secondary y-axis


code:
import importlib

module_list = ["TCA1","TCA2","TCA3","TCA15"]

g = globals()
for lib in module_list:
    g[lib] = importlib.import_module('{0}.{0}'.format(lib))

rawDescription: Is it possible to import multiple files with a loop in python?


code:
print("Copying... ", end="", flush=True)
shutil.copytree(src, dest)
print("DONE")

rawDescription: print() does not print until copytree() has finished

description: Print() does not print until copytree() has finished


code:
df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
df
df.dtypes
g = df.columns.to_series().groupby(df.dtypes).groups
g
{k.name: v for k, v in g.items()}

rawDescription: get list of pandas dataframe columns based on data type

description: Get list of pandas dataframe columns based on data type


code:
import sys
# from PyQt4.QtCore import *
# from PyQt4.QtGui import *

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class ComboDelegate(QItemDelegate):
    editorItems=['Combo_Zero', 'Combo_One','Combo_Two']
    height = 25
    width = 200
    def createEditor(self, parent, option, index):
        editor = QListWidget(parent)
        # editor.addItems(self.editorItems)
        # editor.setEditable(True)
        editor.currentItemChanged.connect(self.currentItemChanged)
        return editor

    def setEditorData(self,editor,index):
        z = 0
        for item in self.editorItems:
            ai = QListWidgetItem(item)
            editor.addItem(ai)
            if item == index.data():
                editor.setCurrentItem(editor.item(z))
            z += 1
        editor.setGeometry(0,index.row()*self.height,self.width,self.height*len(self.editorItems))

    def setModelData(self, editor, model, index):
        editorIndex=editor.currentIndex()
        text=editor.currentItem().text()
        model.setData(index, text)
        # print '\t\t\t ...setModelData() 1', text

    @pyqtSlot()
    def currentItemChanged(self):
        self.commitData.emit(self.sender())

class MyModel(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items=['Data_Item01','Data_Item02','Data_Item03']

    def rowCount(self, parent=QModelIndex()):
        return len(self.items)
    def columnCount(self, parent=QModelIndex()):
        return 1

    def data(self, index, role):
        if not index.isValid(): return QVariant()

        row=index.row()
        item=self.items[row]

        if row>len(self.items): return QVariant()

        if role == Qt.DisplayRole:
            # print ' << >> MyModel.data() returning ...', item
            return QVariant(item)

    def flags(self, index):
        return Qt.ItemIsEditable | Qt.ItemIsEnabled

    def setData(self, index, text):
        self.items[index.row()]=text

if __name__ == '__main__':
    app = QApplication(sys.argv)

    model = MyModel()
    tableView = QTableView()
    tableView.setModel(model)

    delegate = ComboDelegate()

    tableView.setItemDelegate(delegate)
    for i in range(0,tableView.model().rowCount()):
        tableView.setRowHeight(i,tableView.itemDelegate().height)
    for i in range(0,tableView.model().columnCount()):
        tableView.setColumnWidth(i,tableView.itemDelegate().width)

    tableView.show()
    sys.exit(app.exec_())

rawDescription: How to use QComboBox as delegate with QTableView

description: Use QComboBox as delegate with QTableView


code:
tree = Phylo.read("GSCGT000003.xml", "phyloxml")

for clade in tree.find_clades(name=True):
    # This changes the clade name to only the first four chars
    clade.name = clade.name[:4]

# At this point all clade names has been changed in-place
Phylo.write(tree, "GSCGT000003_modified.xml", "phyloxml")

rawDescription: Phyloxml: find and replace in a file

description: Phyloxml: find and replace in a file


rawDescription: How to pass two parameters into lambda functions in map

description: Pass two parameters into lambda functions in map


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

import urllib

class MyOpener(urllib.FancyURLopener):
    version = "App/1.7" #doesn't work
    version = "Mozilla/4.0 (MSIE 6.0; Windows NT 5.0)2011-03-10 15:38:34" #works

def textToSpeech(text, languageCode='en'):
    url = "http://translate.google.com/translate_tts?tl=%s&q=%s" % (languageCode, urllib.quote(text))
    myopener = MyOpener()
    return myopener.open(url, 'rb').read()

open('urllib.mp3', 'wb').write(textToSpeech('vår', 'no'))

rawDescription: Google App Engine UrlFetch - problem with urls with special characters in them


code:
import wx

def set_frame_display(frame, display_index):
    display = wx.Display(display_index)
    x, y, w, h = display.GetGeometry()
    frame.SetPosition((x, y))

def main():
    app = wx.PySimpleApp()
    count = wx.Display_GetCount()
    for index in range(count):
        frame = wx.Frame(None, -1, 'Display %d of %d' % (index + 1, count))
        set_frame_display(frame, index)
        frame.Center()
        frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: How can I choose the default wx.Display in wxpython?

description: Choose the default wx.Display in wxpython


code:
someXML = lxml.etree.XML(someString)
if ns is None:
      ns = {"m": someXML.tag.split("}")[0][1:]}
someid = someXML.xpath('.//m:ImportantThing//m:ID', namespaces=ns)

rawDescription: How to tell lxml.etree.tostring(element) not to write namespaces in python?

description: Tell lxml.etree.tostring(element) not to write namespaces in python


code:
for file in filenames:
    with open(base_path+file, 'rb') as fp:
        img = MIMEImage(fp.read())
    img.add_header('Content-Disposition', "attachment; filename= %s" % file)
    msg.attach(img)

rawDescription: how can I customize file name in python MIMEImage?

description: Customize file name in python MIMEImage


code:
ast.literal_eval("{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}")['session_id']
z = ast.literal_eval("{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}")
isinstance(z, dict)

rawDescription: Extract python objects from a string

description: Extract python objects from a string


rawDescription: why this x path brings just one value?

description: Why this x path brings just one value


code:
isinstance("foo", str) #Use basestring in py2.x
isinstance([1, 2, 3], list)

rawDescription: If Statement - Is this a string?

description: If Statement - Is this a string


code:
def eventDetector(x):                                    # 1
    x_arr = pd.Series(x['X_COOR'].values.copy())
    y_arr = pd.Series(x['Y_COOR'].values.copy())
    print('For x returned: %s for y: %s' % (x_arr.values, y_arr.values))
    for x, y in zip(x_arr, y_arr):                       # 2
        1+1
        print('Here are the x: %s and y: %s' % (x, y))
    return x                                             # 3

rawDescription: Pandas .apply() subfunction is changing main dataframe


rawDescription: Trouble resampling data in Pandas

description: Trouble resampling data in Pandas


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

my_data = np.genfromtxt('data.txt', delimiter=' ', skiprows=0)
X = my_data[:, 0]
Y = my_data[:, 1]
Z = my_data[:, 2]

d = {
    0: {'label': 'x0'},
    1: {'label': 'x1'}
}

for val, kwargs in d.items():
    mask = X == val
    y, z = Y[mask], Z[mask]

    plt.plot(y, z, **kwargs)

plt.legend()

plt.show()

rawDescription: Drawing 3D points on a 2D plot reading values from a file


code:
import numpy as np
from scipy.sparse import csr_matrix

def parse_sparse_vector(line):
    tokens = line.split()
    indexes = []
    values = []
    for token in tokens:
        index, value = token.split(':')
        index = int(index)
        value = int(value)
        indexes.append(index)
        values.append(value)
    return csr_matrix((values, ([0] * len(indexes), indexes)))

v = parse_sparse_vector(line1)
w = parse_sparse_vector(line2)
dist = v - w
# avoiding a cast to dense matrix:
np.sqrt(dist.dot(dist.T).sum())
## result is 39.038442591886273

rawDescription: Euclidian Distance of Two (Non-traditional) Vectors in Python


code:
# in the views.py
if form.is_valid():
    new_example = form.save(commit=False)
    if not form.cleaned_data['comment']:
      new_example.comment = ""
      new_example.save()

rawDescription: How to allow submission of empty string in django forms?

description: Allow submission of empty string in django forms


code:
D = dict((title, rank) for rank, title in enumerate(albums_yesterday))
for rank, title in enumerate(albums_today):
    D[title] = D[title] - rank

rawDescription: Fast algorithm to calculate delta of two list


code:
from postapp.models import posts
from comment_app.models import comment
class Comment_Admin_Form(admin.ModelAdmin):
    def get_post_title(self,obj):
        return posts.objects.get(id=obj.post_id).title
    get_post_title.short_description = 'post title'

model = Comment
list_display = ('get_post_title',)

admin.site.register(comment,Comment_Admin_Form)

rawDescription: how to access to django model from within admin

description: Access to django model from within admin


code:
from matplotlib import pyplot as plt
color_cycle = plt.rcParams['axes.color_cycle']
color_cycle

rawDescription: matplotlib: default color cycle from style

description: Matplotlib: default color cycle from style


code:
import string
"abc".translate(string.maketrans("abc", "def")) # => "def"

rawDescription: Character Translation using Python (like the tr command)


code: edate = date(datetime.today().year,  datetime.today().month,  datetime.today().day)

rawDescription: Today's Date in pandas with specific format - python 2.7


rawDescription: Repeated transient-socket connections - memory leak risk?


code:
from pandas import Series
s=Series([-25,0,70])

import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.add_subplot(111)
ax.set_ylabel('percentage')
ax.spines['bottom'].set_position('zero')       # x-axis where y=0
#ax.spines['bottom'].set_position('center')     # x-axis at center (not necessarily y=0)
#ax.spines['bottom'].set_position(('data', 50)) # x-axis where y=50
ax.spines['top'].set_color('none')             # hide top axis
ax.spines['right'].set_color('none')           # hide right axis

s.plot(ylim=(-100,100))

rawDescription: Easy way to set the position of x-axis in pandas?


rawDescription: re.search string in python

description: Re.search string in python


code:
f1 = open('filename','w')
f2 = open('filename', 'r')
f1.write('test string')
f1.flush()
f2.read()

rawDescription: Reading and writing a file using two file objects in Python 3.x


code:
class DjangoPony(models.Model):
    name = models.TextField()
    color = models.TextField()

class RevisionControlledValue(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User)
    value = models.TextField()
    field = models.CharField(max_length=20)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

rawDescription: Good way for a Revision Controllled Model? - Django


code:
calcsize ('Bq')
calcsize('=Bq')

rawDescription: Python struct.pack()/calcsize()

description: Python struct.pack()/calcsize()


code:
import numpy as np
a = np.arange(12).reshape((4, 3))
b = np.arange(15).reshape((5, 3))
diff = a[np.newaxis, :, :] - b[:, np.newaxis, :]
diff.shape
# (5, 4, 3)

rawDescription: 2D ndarray: row-wise operations

description: 2D ndarray: row-wise operations


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.scene = QtGui.QGraphicsScene(self)
        self.scene.addPixmap(QtGui.QPixmap('image.jpg'))
        self.scene.installEventFilter(self)
        self.view = QtGui.QGraphicsView(self)
        self.view.setScene(self.scene)
        self.label = QtGui.QLabel(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.view)
        layout.addWidget(self.label)

    def eventFilter(self, source, event):
        if (source is self.scene and
            event.type() == QtCore.QEvent.GraphicsSceneMouseRelease and
            event.button() == QtCore.Qt.LeftButton):
            pos = event.scenePos()
            self.label.setText('x=%0.01f,y=%0.01f' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: QMouseEvent, received unexpected type

description: QMouseEvent, received unexpected type


code:
def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return imap(next, imap(itemgetter(1), groupby(iterable, key)))

rawDescription: Python filter over a function with two arguments?


code:
import os
import glob

files = list(glob.glob(os.path.join(directory,'*.*')))

rawDescription: How to create a list from filenames in a user specified directory in python

description: Create a list from filenames in a user specified directory in python


code:
matches = []
def match_found(m):
    # append the match start position to the matches array
    matches.append(m.end(0))

editor.research('pattern', match_found)

matches[0]  #should now contain the index of the *end* of the first match

rawDescription: Getting line of a search term - Python Script for Notepad++


rawDescription: Designating a font in Tkinter?

description: Designating a font in Tkinter


code:
from django.db.models import Q
list_countries = Country.objects.filter(~Q(country_name='')).values_list('country_name', flat=True).distinct()

rawDescription: Empty values retrieved with values_list

description: Empty values retrieved with values_list


code:
numbers =  [78, 89, 56]
all ([81 > x for x in numbers])

rawDescription: How to use conditionals with lists

description: Use conditionals with lists


code:
document_to_be_searched = "blabla bla bla."
numOfOcur = document_to_be_searched.count("bl")

rawDescription: python: non-regex equiv of re.findall

description: Python: non-regex equiv of re.findall


code: app.secret_key = os.urandom(32)

rawDescription: How to I delete all Flask sessions?

description: I delete all Flask sessions


code:
from lxml import etree

nsmap = {
    'xmlns': 'http://www.openarchives.org/OAI/2.0/',
    'dc': 'http://purl.org/dc/elements/1.1/',
    'dct': 'http://purl.org/dc/terms/',
    'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
ns = [
    'dc:identifier[@xsi:type]',
    'dc:title',
    'dc:description',
    'dc:subject',
    'dc:type',
    'dct:educationLevel'
]
tree = etree.parse(file)
xpath = '|'.join('.//xmlns:record//{}'.format(n) for n in ns)
for items in tree.xpath(xpath, namespaces=nsmap):
    print(items)

rawDescription: how to loop through list in etree.findall()

description: Loop through list in etree.findall()


code:
import re
websites = re.findall(r'(\S+[.]com)', text)
# ['maangobar22.com', 'myapplesite22.com', 'berrymine22.com']

rawDescription: Regular expression to search only websites names from random text


code:
for i in range(1,3):
    exec('f' + str(i) + '.show_grayscale()')
    exec('f' + str(i) + '.add_colorbar()')
    exec('f' + str(i) + '.frame.set_linewidth(0.75)')

rawDescription: Using a for loop to make multiple Python APLpy subplots


code:
Parent.options = dict(
    option1='value1',
    option2='value2',
)

Child.options = dict(Parent.options,
    option2='value2a',
    option3='value3',
)

rawDescription: A neat way of extending a class attribute in subclasses


code:
from bson.binary import Binary

obj = BloomFilter()
serialized = obj.__dict__.copy()
serialized['bitarray'] = Binary(obj.bitarray.tobytes())

rawDescription: Saving bitarrays in MongoDB

description: Saving bitarrays in MongoDB


code:
import copy
from mock import MagicMock

class CopyArgsMagicMock(MagicMock):
    """
    Overrides MagicMock so that we store copies of arguments passed into calls to the
    mock object, instead of storing references to the original argument objects.
    """

    def _mock_call(_mock_self, *args, **kwargs):
        args_copy = copy.deepcopy(args)
        kwargs_copy = copy.deepcopy(kwargs)
        return super(CopyArgsMagicMock, self)._mock_call(*args_copy, **kwargs_copy)

rawDescription: Python mock method call arguments display the last state of a list


code:
import pandas as pd
df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]])
df['key'] = 0
ser = pd.DataFrame({'data': [13,14,15], 'key': [0] * 3})

result = pd.merge(df, ser, on = 'key').drop('key', axis = 1)

rawDescription: Merging a dataframe with a Series

description: Merging a dataframe with a Series


code:
ax1 = axes()
ax2 = ax1.twinx()

x = np.arange(100)
y1 = np.random.rand(100)
y2 = np.random.rand(100)

ax1.plot(x,y1,'-r')
ax1.set_ylim(-1,1)
ax2.fill_between(x,0,y2,color='b',alpha=0.5)
ax2.set_ylim(0,2)

ax1.set_ylabel('Red')
ax2.set_ylabel('Blue')

rawDescription: Plotting subplots with secondary continuous y-axis across all subplots


code:
with open(file, 'r') as indata:
    lines = indata.readlines()
menu = dict()
for i in xrange(0, len(lines), 3):
    name = lines[i].rstrip('\n')
    ingredients = lines[i+1].rstrip('\n').split('/')
    f = Foodset(name)
    f.setIngredients(ingredients)
    menu[name] = f

rawDescription: Python: Read multiple lines from a file and make instances stored in an dictionary


code:
keyVal= r'Software\Microsoft\Windows\CurrentVersion\Policies'
key2change= OpenKey(HKEY_CURRENT_USER, keyVal,0,KEY_ALL_ACCESS)
CreateKey(key2change,keyVal+"\System", 0, KEY_ALL_ACCESS)

key2change= OpenKey(HKEY_CURRENT_USER, keyVal+"\System",0,KEY_ALL_ACCESS)
SetValueEx(key2change, "Wallpaper",0,REG_SZ, "D:\\test.jpg")
SetValueEx(key2change, "WallpaperStyle",0,REG_SZ, "2")

rawDescription: _winreg CreateKey function in Python doesn't work


code:
import tkinter as tk

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.score = 0

        self.buttonDic = {
        'Brown Rice':0,
        'Banzai Veg':0,
        'Red Cabbage':0,
        'Black Beans':0
        }

        aFrame = self.aFrame = tk.Frame(self)
        aFrame.grid()

        for key in self.buttonDic:
            self.buttonDic[key] = tk.IntVar()
            aCheckButton = tk.Checkbutton(aFrame, text=key,
                                            variable=self.buttonDic[key])
            aCheckButton.grid(sticky='w')

        submitButton = tk.Button(aFrame, text="Submit",
                                        command=self.query_checkbuttons)
        submitButton.grid()

        self.trueList = ['Brown Rice', 'Black Beans']

    def query_checkbuttons(self):
        for key, value in self.buttonDic.items():
            state = value.get()
            if state != 0:
                if key in self.trueList:
                    self.score += 1
                else:
                    self.score -= 1
                self.buttonDic[key].set(0)
        self.result_screen()

    def result_screen(self):
        self.aFrame.grid_forget()
        self.rFrame = tk.Frame(self)
        self.rFrame.grid()
        self.scoreText = tk.Text(self.rFrame, width=20, height=1)
        self.scoreText.grid()
        self.scoreText.insert('end', self.score)
        self.after(3000, func=self.go_back)

    def go_back(self):
        self.score = 0
        self.rFrame.destroy()
        self.aFrame.grid()

gui = GUI()
gui.mainloop()

rawDescription: Python 3.2 tkinter create a results frame to display output


rawDescription: Handling IRI in Django

description: Handling IRI in Django


code:
import Tkinter as tk

class UpdateLabel(tk.Label):
  def __init__(self, *args, **kwargs):
    tk.Label.__init__(self, *args, **kwargs)
    self._count = 0

  def update_text(self):
    self.config(text=str(self._count))
    self._count += 1
    self.after(2000, self.update_text)

root = tk.Tk()
label = UpdateLabel(root)
label.pack()
label.update_text()
root.mainloop()

rawDescription: How to use looping in Tkinter

description: Use looping in Tkinter


code:
# mock dictionary because I dont have your image
tags = {}
tags['GPS GPSLatitude'] =  [33, 51, 2191/100]
tags['GPS GPSLatitudeRef'] = 'S'
tags['GPS GPSLongitude'] = [151, 13, 1173/100]
tags['GPS GPSLongitudeRef'] = 'E'

out = []
wantedtags = ('GPS GPSLatitude', 'GPS GPSLatitudeRef', 'GPS GPSLongitude', 'GPS GPSLongitudeRef')

for tag in wantedtags:
    try:
        val = tags[tag]
        if isinstance(val, list):
            out.extend(map(str, val))
        else:
            out.append(val)
    except KeyError:
        print('Key %s does not exists' % tag)

print(out)

rawDescription: How can I make python code cleaner, optimized, and efficient?

description: Make python code cleaner, optimized, and efficient


code:
def get_capslock_state():
    import ctypes
    hllDll = ctypes.WinDLL ("User32.dll")
    VK_CAPITAL = 0x14
    return hllDll.GetKeyState(VK_CAPITAL)

rawDescription: Python 3.x - Getting the state of caps-lock/num-lock/scroll-lock on Windows


rawDescription: python 3 threading single statement?

description: Python 3 threading single statement


code:
import csv

with open('company_inf1.csv','rb') as csvfile, open('out.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    writer.writerow(['id','name', 'date','indus','nike', 'paid', 'abbr'])
    reader = csv.reader(csvfile)
    reader.next() # skip header
    for id, (name, date, industry, nike1, nike2, nike3, paid, abbreviation) in enumerate(reader):
        nike = '([{0},{1},{2}])'.format(nike1, nike2, nike3)
        writer.writerow([id, name, date, industry, nike, paid, abbreviation])

rawDescription: merge the 3 cells data into one and write to another csv

description: Merge the 3 cells data into one and write to another csv


code:
from django.core.files.base import ContentFile

def rotateLeft(request,id):
    myModel = myModel.objects.get(pk=id)

    original_photo = StringIO.StringIO(myModel.file.read())
    rotated_photo = StringIO.StringIO()

    image = Image.open(original_photo)
    image = image.rotate(-90)
    image.save(rotated_photo, 'JPEG')

    myModel.file.save(image.file.path, ContentFile(rotated_photo.getvalue()))
    myModel.save()

    return render(request, '...',{...})

rawDescription: Django - Rotate image and save

description: Django - Rotate image and save


code:
text = '   foo\nbar      spam'
'\n'.join(' '.join(line.split()) for line in text.split('\n'))

rawDescription: How to strip double spaces and leave new lines? Python

description: Strip double spaces and leave new lines? Python


text: how now brown cow

rawDescription: How to query Elasticsearch to boost by specific field

description: Query Elasticsearch to boost by specific field


code: list(itertools.takewhile(lambda x: sum(x) < 20 and x[0] > 3, some_generator()))

rawDescription: Python itertools—takewhile(): multiple predicates


code:
import pandas
sample = pandas.DataFrame([[645382311, 12324234234], [645382311, -2434234242], [645382312, 32536365654], [645382312, 12324234234]], columns=['userid', 'code'])
# Add a column of True values
sample['value'] = True
# Pivot to boolean presence matrix and remove MultiIndex
presence = sample.pivot(index='userid', columns='code').fillna(False)['value']
# Perform desired boolean tests
case1 = (presence[12324234234] | presence[-2434234242]) & ~(presence[32536365654])
case2 = (presence[12324234234] & presence[-2434234242]) | ~(presence[32536365654])

rawDescription: Run logical Expressions against pandas dataframe


code:
soup = BeautifulSoup('1CONTENTS_HERE')
soup.find('span').span.next_sibling

rawDescription: How to detach a tag using BeautifulSoup in Python?

description: Detach a tag using BeautifulSoup in Python


rawDescription: How to get the content of a Html page in Python

description: Get the content of a Html page in Python


code:
counter=0
for element in string:
    counter+=bool(function(element))
    yield counter

rawDescription: Is there any way to shorten this Python generator expression?


code:
pathh='/home/pooja/Desktop/'      #set the base path
fo = open("/home/pooja/Desktop/xml.txt")
for i in range(len(count)):     #use len(count)
    file = fo.readline()
    file = file.strip()          #use strip()
    find_root_tags(pathh+file,str1,i) #base path+file
    mylist.append((file,count[i]))   #using 'list' as a variable name is not good

rawDescription: Error: file i/o in python

description: Error: file i/o in python


code:
#!/usr/bin/env python

import math
import numpy as np
import scipy
import scipy.misc
import scipy.ndimage.interpolation
import subprocess

src=scipy.misc.imread("ji80w.png")

size=256
frames=50

for frame in xrange(0,frames):

    # Image pixel co-ordinates
    px=np.arange(-1.0,1.0,2.0/size)+1.0/size
    py=np.arange(-1.0,1.0,2.0/size)+1.0/size
    hx,hy=scipy.meshgrid(px,py)

    # Compute z of sphere hit position, if pixel's ray hits
    r2=hx*hx+hy*hy
    hit=(r2<=1.0)
    hz=np.where(
        hit,
        -np.sqrt(1.0-np.where(hit,r2,0.0)),
        np.NaN
        )

    # Some spin and tilt to make things interesting
    spin=2.0*np.pi*(frame+0.5)/frames
    cs=math.cos(spin)
    ss=math.sin(spin)
    ms=np.array([[cs,0.0,ss],[0.0,1.0,0.0],[-ss,0.0,cs]])

    tilt=0.125*np.pi*math.sin(2.0*spin)
    ct=math.cos(tilt)
    st=math.sin(tilt)
    mt=np.array([[1.0,0.0,0.0],[0.0,ct,st],[0.0,-st,ct]])

    # Rotate the hit points
    xyz=np.dstack([hx,hy,hz])
    xyz=np.tensordot(xyz,mt,axes=([2],[1]))
    xyz=np.tensordot(xyz,ms,axes=([2],[1]))
    x=xyz[:,:,0]
    y=xyz[:,:,1]
    z=xyz[:,:,2]

    # Compute map position of hit
    latitude =np.where(hit,(0.5+np.arcsin(y)/np.pi)*src.shape[0],0.0)
    longitude=np.where(hit,(1.0+np.arctan2(z,x)/np.pi)*0.5*src.shape[1],0.0)
    latlong=np.array([latitude,longitude])

    # Resample, and zap non-hit pixels
    dst=np.zeros((size,size,3))
    for channel in [0,1,2]:
        dst[:,:,channel]=np.where(
            hit,
            scipy.ndimage.interpolation.map_coordinates(
                src[:,:,channel],
                latlong,
                order=1
                ),
            0.0
            )

    # Save to f0000.png, f0001.png, ...
    scipy.misc.imsave('f{:04}.png'.format(frame),dst)

# Use imagemagick to make an animated gif
subprocess.call('convert -delay 10 f????.png anim.gif',shell=True)

rawDescription: How to draw orthographic projection from equirectangular projection

description: Draw orthographic projection from equirectangular projection


code:
from pylab import *
import time

data = []   # make the data
for i in range(1000):
    a = .01*pi*i+.0007
    m = -1./tan(a)
    x = arange(-3, 3, .1)
    y = m*x
    data.append((clip(x+cos(a), -3, 3),clip(y+sin(a), -3, 3)))

for x, y in data:  # make a dynamic plot from the data
    try:
        plotdata.set_data(x, y)
    except NameError:
        ion()
        fig = figure()
        plot(cos(arange(0, 2.21*pi, .2)), sin(arange(0, 2.21*pi, .2)))
        plotdata = plot(x, y)[0]
        xlim(-2, 2)
        ylim(-2, 2)
    draw()
    time.sleep(.01)

rawDescription: Quitting matplotlib.pyplot animation gracefully


code:
db = Document._get_db()
client_count = db.command("serverStatus")["connections"]['current'] - 1

rawDescription: MongoEngine & serverStatus

description: MongoEngine & serverStatus


code:
s = "aaabbbb"
len(s) - len(s.rstrip(s[-1]))

rawDescription: Find the length of the longest trailing substring


code:
filenames = [
  'billing_report_2014-02-01.csv',
  'billing_report_2014-02-02.csv'
]

with open('out.csv', 'w') as fout:
    for filename in filenames:
        to_append = filename.rpartition('_')[2].partition('.')[0]
        with open(filename) as fin:
            fout.writelines('{},{}\n'.format(line.rstrip(),to_append) for line in fin)

rawDescription: adding date column to the appending output csv file in python

description: Adding date column to the appending output csv file in python


code:
from test import x
x[0] = 1001
x
import test
test.x
imp.reload(test)
test.x   # test is rebound to a new object
x        # the old local variable isn't affected, of course

rawDescription: Mutable objects in imported modules

description: Mutable objects in imported modules


code:
def name_of_function(img_x, img_y):  # for lack of a better name
    image_dimensions = (img_x, img_y)
    min_dimensions = (55.0, 168.0)
    scale = min(image_dimensions[i]/min_dimensions[i] for i in range(2))
    return max(i/scale for i in image_dimensions)

name_of_function(1000, 500)
# 336.0
name_of_function(200, 1000)
# 275.0

rawDescription: Scale an image by a single dimension (x OR y) given minimum dimensions


code:
None or False
True or False
0 or False
'Value' or False

rawDescription: In Python, what's the point of 'x or False' and 'False and x?


code:
from nltk.corpus import brown

out = open('corpus.vrt','w')
for sentence in nltk.brown.sents():
     print >>out,'<s>'
     for word in sentence:
          print >>out,word
     print >>out,'</s>'
out.close()

rawDescription: How to build a IMS open source corpus workbench and NLTK readable corpus?

description: Build a IMS open source corpus workbench and NLTK readable corpus


code:
with open('list.csv', 'rb') as csvfile:
    reader = csv.DictReader(csvfile)

rawDescription: Can certain values cause Python's csv.DictReader to terminate prematurely


code:
i = theano.shared(numpy.asarray(range(n)))
b = a[:,i,i,3:-3]

rawDescription: How to extract pairwise diagonal in tensor in theano without for loop?

description: Extract pairwise diagonal in tensor in theano without for loop


code:
import sfml as sf

win = sf.RenderWindow(sf.VideoMode(100,100),"hi")

while(1):
    for i in win.events :
        pass
    win.clear()
    win.display()

rawDescription: pysfml breaks on runtime while displaying a render window

description: Pysfml breaks on runtime while displaying a render window


code:
def get_user(self, user_id):
    try:
        return User.objects.get(pk=user_id)
    except User.DoesNotExist:
        return None

rawDescription: Custom django auth backend not logging the user with base login view


code:
class classproperty(object):
    def __init__(self, getter):
        self.getter= getter
    def __get__(self, instance, owner):
        return self.getter(owner)

class Foo(object):
    x= 4
    @classproperty
    def number(cls):
        return cls.x

Foo().number
Foo.number

rawDescription: How to create a read-only class property in Python?

description: Create a read-only class property in Python


code:
# This is used to ensure paths in generated ZIP files always use
# forward slashes as the directory separator, as required by the
# ZIP format specification.
if os.sep != "/" and os.sep in filename:
    filename = filename.replace(os.sep, "/")

rawDescription: does Python zipfile always use posixpath filenames regardless of operating system?

description: Does Python zipfile always use posixpath filenames regardless of operating system


code:
from itertools import tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)
for pair in pairwise({1, 2, 3, 4}):
    print(pair)

rawDescription: Generating a path from an iterable of points


code:
from openpyxl.cell import coordinate_from_string, column_index_from_string
xy = coordinate_from_string('A4') # returns ('A',4)
col = column_index_from_string(xy[0]) # returns 1
row = xy[1]

rawDescription: getting the row and column numbers from coordinate value in openpyxl

description: Getting the row and column numbers from coordinate value in openpyxl


rawDescription: Script to find all network adapters I'm connected to in Python


code:
#
# 1. CamelCasing for classes
#
class Account:
    def __init__(self):
        # 2. to refer to the inner class, you must use self.Bank
        # 3. no need to use an inner class here
        self.bank = self.Bank()

    class Bank:
        def __init__(self):
            self.balance = 100000

        # 4. in your original code, you had a method with the same name as
        #    the attribute you set in the constructor. That meant that the
        #    method was replaced with a value every time the constructor was
        #    called. No need for a method to do a simple attribute lookup. This
        #    is Python, not Java.

        def withdraw(self, amount):
            self.balance -= amount

        def deposit(self, amount):
            self.balance += amount

a = Account()
print(a.bank.balance)

rawDescription: python nested classes

description: Python nested classes


rawDescription: How do I show decimal calculations in python?

description: Show decimal calculations in python


rawDescription: Python: how can I get rid of the second element of each sublist?


code:
import Tkinter as tk

class App():
    def __init__(self, tick):
        self.tick = tick
        self.idle_time = 0

        self.root = tk.Tk()
        frame = tk.Frame(self.root, width=100, height=100)
        frame.bind_all("<Motion>", self.reset_idle)
        frame.bind_all("<Key>", self.reset_idle)
        frame.pack()

        self.root.after(self.tick, self.update_timer)
        self.root.mainloop()

    def update_timer(self):
        print('Idle for %sms' % self.idle_time)
        self.idle_time += self.tick
        self.root.after(self.tick, self.update_timer)

    def reset_idle(self, event):
        self.idle_time = 0

app = App(1000)

rawDescription: Load and modify a tkinter gui from a pickle file


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

random = np.random.normal(0,1,size=[100,100])
plt.imshow(random,aspect="auto")
plt.show()

rawDescription: how to convert ndarray to image and display it using python

description: Convert ndarray to image and display it using python


code:
chapter_key = ndb.Key('Book', long(bookId), 'Chapter', long(chapterId))
page = Page.query(Page.pageNumber==pageNumber, ancestor=chapter_key)

rawDescription: Using Key in NDB to retrieve an entity

description: Using Key in NDB to retrieve an entity


code:
my_list = [3, 5, 6, None, 6, None]
np.array(my_list, dtype=np.float)

rawDescription: Convert python list with None values to numpy array with nan values


code: import logging

rawDescription: Trying to provide a global logging function


code: sec_since_epoch = (date_obj.date() - date(1970, 1, 1)).total_seconds()

rawDescription: Round timestamp to nearest day in Python


code:
import numpy as np
from scipy.misc import lena
import OpenGL.GL as gl
import wx
from wx.glcanvas import GLCanvas

class Canvas(GLCanvas):
    def __init__(self,parent):
        """ create the canvas """
        super(Canvas,self).__init__(parent)
        self.done_init_texture = False

        # execute self.onPaint whenever the parent frame is repainted
        wx.EVT_PAINT(self,self.onPaint)

    def initTexture(self):
        """
        init the texture - this has to happen after an OpenGL context
        has been created
        """

        # make the OpenGL context associated with this canvas the current one
        self.SetCurrent()

        data = np.uint8(np.flipud(lena()))
        w,h = data.shape

        # generate a texture id, make it current
        self.texture = gl.glGenTextures(1)
        gl.glBindTexture(gl.GL_TEXTURE_2D,self.texture)

        # texture mode and parameters controlling wrapping and scaling
        gl.glTexEnvf( gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE )
        gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT )
        gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT )
        gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR )
        gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR )

        # map the image data to the texture. note that if the input
        # type is GL_FLOAT, the values must be in the range [0..1]
        gl.glTexImage2D(gl.GL_TEXTURE_2D,0,gl.GL_RGB,w,h,0,
            gl.GL_LUMINANCE,gl.GL_UNSIGNED_BYTE,data)

    def onPaint(self,event):
        """ called when window is repainted """
        # make sure we have a texture to draw
        if not self.done_init_texture:
            self.initTexture()
            self.done_init_texture = True
        self.onDraw()

    def onDraw(self):
        """ draw function """

        # make the OpenGL context associated with this canvas the current one
        self.SetCurrent()

        # set the viewport and projection
        w,h = self.GetSize()
        gl.glViewport(0,0,w,h)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0,1,0,1,0,1)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glClear( gl.GL_COLOR_BUFFER_BIT )

        # enable textures, bind to our texture
        gl.glEnable(gl.GL_TEXTURE_2D)
        gl.glBindTexture(gl.GL_TEXTURE_2D,self.texture)

        gl.glColor3f( 1, 1, 1 )

        # draw a quad
        gl.glBegin( gl.GL_QUADS )
        gl.glTexCoord2f( 0, 1 );    gl.glVertex2f( 0, 1 )
        gl.glTexCoord2f( 0, 0 );    gl.glVertex2f( 0, 0 )
        gl.glTexCoord2f( 1, 0 );    gl.glVertex2f( 1, 0 )
        gl.glTexCoord2f( 1, 1 );    gl.glVertex2f( 1, 1 )
        gl.glEnd(  )

        gl.glDisable(gl.GL_TEXTURE_2D)

        # swap the front and back buffers so that the texture is visible
        self.SwapBuffers()

def run():
    app = wx.App()
    fr = wx.Frame(None,size=(512,512),title='wxPython texture demo')
    canv = Canvas(fr)
    fr.Show()
    app.MainLoop()

if __name__ == "__main__":
    run()

rawDescription: Displaying a simple 2D textured rectangle inside a wxGLCanvas using PyOpenGL


code:
some_list = [-5, -1, -13, -11, 4, 8, 16, 32]
max([n for n in some_list if n<0])
min([n for n in some_list  if n>0])

rawDescription: Retrieve largest negative number and smallest positive number from list


rawDescription: How to get words's id in the vocabulary of bag-of-words given the word?

description: Get words's id in the vocabulary of bag-of-words given the word


code:
def addNewAttribute(entity, *args, **kwargs):
    try:
        if not entity.get("newattribute"):
            entity["newattribute"] = False
            yield op.db.Put(entity) # save the entity back to datastore
            yield op.counters.Increment("touched") # use mapreduce counter to track operations
    except:
        yield op.counters.Increment("touchFail")

rawDescription: Is there something like DatastoreOutputWriter?


code:
import itertools
a = [1,2]
b = [4,5]
list(itertools.product(a,b))

rawDescription: All possible variants of zip in Python

description: All possible variants of zip in Python


code:
data = [['AB', 'BS, BT'], ['AH', 'AH'], ['AS', 'AS, GS']]
[list(itertools.product([d[0]], d[1].split(','))) for d in data]
list(itertools.chain.from_iterable([list(itertools.product([d[0]], d[1].split(','))) for d in data]))

rawDescription: iterating through a list to append a value to variable lists

description: Iterating through a list to append a value to variable lists


code:
id_list = ['abc', 'def', 'ghi']
query_string = "delete from test where id in (%s)" % ','.join(['?'] * len(id_list))
cursor.execute(query_string, id_list)

rawDescription: Delete multiple rows in MYSQL with info from python list


code:
cherrypy.config.update(conffile)
cherrypy.config.update(confdict)

app = cherrypy.tree.mount(HelloWorld(), '/', conffile)
app.merge(confdict)

if hasattr(cherrypy.engine, "signal_handler"):
    cherrypy.engine.signal_handler.subscribe()
if hasattr(cherrypy.engine, "console_control_handler"):
    cherrypy.engine.console_control_handler.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()

rawDescription: CherryPy combine file and dictionary based configuration


rawDescription: Matching a group with OR condition in pattern


code:
class My3dNodeWrapper(object):
    def __init__(self):
        self.node = Some3dNodeThing()

    @property
    def translateX(self):
        return self.node.getXTranslation() # or whatever

    @translateX.setter
    def translateX(self, value):
        self.node.setXTranslation(value) # or whatever

rawDescription: How to run a method when changing a class variable?

description: Run a method when changing a class variable


code:
import sys, StringIO
buffer = StringIO.StringIO()
sys.stdout = buffer
main()
buffer.seek(0)
all_mods = buffer.read().splitlines()
sys.stdout = sys.__stdout__

rawDescription: Imported functioning is not iterating "TypeError: 'NoneType' object > is not iterable"... how do I make this work?


code:
import numpy as np
import matplotlib.pyplot as plt
from pylab import *

X = np.linspace(0,100,11)

plt.plot(X,-X, label='plot 1', color='red')
plt.plot(X,-2*X, label='plot 2', color='green')
plt.plot(X,-3*X, label='plot 3', color='blue')

line1 = Line2D(range(10), range(10), marker='', color="red")
line2 = Line2D(range(10), range(10), marker='',color="green")
line3 = Line2D(range(10), range(10), marker='', color="blue")
line4 = Line2D(range(10), range(10), marker='', color="white")
plt.legend((line1,line4, line3,line2),('plot1','','plot3','plot2'),numpoints=1, loc=4,ncol=2)

plt.show()

rawDescription: Fill the right column of a matplotlib legend first


code:
def run_game():
    my_settings = Settings() # create Settings instance
    pygame.init()
    screen = pygame.display.set_mode((my_settings.screen_width, # lookup attributes on it
                                      my_settings.screen_height),
                                     pygame.FULLSCREEN)
    # ...

rawDescription: python - Issue using classes imported from a module

description: Python - Issue using classes imported from a module


code:
#! /usr/bin/python3
import os

tobeprocessed = {}
for curdir, subdirs, files in os.walk ('/home/lorenzo/stackoverflow/images'):
    if not files: continue
    tobeprocessed [curdir] = files

print (tobeprocessed)

rawDescription: Passing values to a dict whilst in a for loop in Python


code:
estimator = GridSearchCV(pipe, dict(pca__n_components=n_components,
                                    logistic__C=Cs),
                         verbose=1)
estimator.fit(X_digits, y_digits)

rawDescription: Number of trainings done with Pipeline and GridSearchCV


code:
results = dict()

if xxx:
    results.update((func1(), func2(), func5()))
if yyy:
    results.update((func3(), func5()))
if zzz:
    results.update((func2(), func5()))

rawDescription: How do I insert a tuple into an existing dictionary in Python

description: Insert a tuple into an existing dictionary in Python


code: return m.sub(partial(process_pseudo_ternary, custom_1=True, custom_2=True), ts)

rawDescription: pass kwargs to re.sub()

description: Pass kwargs to re.sub()


code:
df.apply(pd.Series.nunique)
df.loc[:, ~(df.apply(pd.Series.nunique) == 1)]

rawDescription: Remove all variables that have only 1 value in Pandas


code:
lists = [mylist1, mylist2, mylist3]
selected_lists = (b for a, b in zip(selected, lists) if a)
result = zip(*selected_lists) # itertools if necessary

rawDescription: zip based on true/false tuple in python

description: Zip based on true/false tuple in python


code:
from pandas import merge, DataFrame
df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3,5], 'C': range(4)})
filter_list = [(6,2),(3,3)]
filter_df = DataFrame(filter_list, columns=['A','B'])
filtr = merge(df, filter_df, on=["A","B"], how="inner")

rawDescription: How to select a filter a list of columns within a selection list

description: Select a filter a list of columns within a selection list


code:
def reloader_loop(extra_files=None, interval=1):
    """When this function is run from the main thread, it will force other
    threads to exit when any modules currently loaded change.

    Copyright notice.  This function is based on the autoreload.py from
    the CherryPy trac which originated from WSGIKit which is now dead.

    :param extra_files: a list of additional files it should watch.
    """
    def iter_module_files():
        for module in sys.modules.values():
            filename = getattr(module, '__file__', None)
            if filename:
                old = None
                while not os.path.isfile(filename):
                    old = filename
                    filename = os.path.dirname(filename)
                    if filename == old:
                        break
                else:
                    if filename[-4:] in ('.pyc', '.pyo'):
                        filename = filename[:-1]
                    yield filename

    mtimes = {}
    while 1:
        for filename in chain(iter_module_files(), extra_files or ()):
            try:
                mtime = os.stat(filename).st_mtime
            except OSError:
                continue

            old_time = mtimes.get(filename)
            if old_time is None:
                mtimes[filename] = mtime
                continue
            elif mtime > old_time:
                _log('info', ' * Detected change in %r, reloading' % filename)
                sys.exit(3)
        time.sleep(interval)

def restart_with_reloader():
    """Spawn a new Python interpreter with the same arguments as this one,
    but running the reloader thread.
    """
    while 1:
        _log('info', ' * Restarting with reloader...')
        args = [sys.executable] + sys.argv
        new_environ = os.environ.copy()
        new_environ['WERKZEUG_RUN_MAIN'] = 'true'

        # a weird bug on windows. sometimes unicode strings end up in the
        # environment and subprocess.call does not like this, encode them
        # to latin1 and continue.
        if os.name == 'nt':
            for key, value in new_environ.iteritems():
                if isinstance(value, unicode):
                    new_environ[key] = value.encode('iso-8859-1')

        exit_code = subprocess.call(args, env=new_environ)
        if exit_code != 3:
            return exit_code

def run_with_reloader(main_func, extra_files=None, interval=1):
    """Run the given function in an independent python interpreter."""
    if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        thread.start_new_thread(main_func, ())
        try:
            reloader_loop(extra_files, interval)
        except KeyboardInterrupt:
            return
    try:
        sys.exit(restart_with_reloader())
    except KeyboardInterrupt:
        pass

rawDescription: Dynamically loading python source code

description: Dynamically loading python source code


code:
import sys, os

sys.path.append('/Path/To/Django/Projects/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

from django.core.serializers import serialize
from myproject.myapp import models

model_names = [] # a list of the names of the models you want to export

for model_name in model_names:
    cls = getattr(models, model_name)
    filename = model_name.lower() + ".json"
    file = open(filename, "w")
    file.write(serialize("json", cls.objects.all()))

rawDescription: saving data in Bulk using Django

description: Saving data in Bulk using Django


code: {k:list(v) for k,v in user_last3.iteritems()}

rawDescription: How to print items in deque (python)

description: Print items in deque (python)


code:
re.split('".*?"', 'print "HELLO"')
re.split('".*?"', '"Goodbye", "Farewell", and "Amen"')

rawDescription: Python split everything between ""s

description: Python split everything between ""s


rawDescription: Django Python noob - how do I get the NUMBER out of a Aggregate sum?


code:
def giveChange(amount, coins):
    if amount == 0:
        return [0, []]
    if coins == []:
        return [float("inf"), []]
    if coins[0] > amount:
        return giveChange(amount, coins[1:])
    [use_it_amt, use_it_list] = giveChange(amount-coins[0], coins)
    [lose_it_amt, lose_it_list] = giveChange(amount, coins[1:])
    if use_it_amt+1 < lose_it_amt:
        use_it_list.append(coins[0])
        return [use_it_amt+1, use_it_list]
    else:
        return [lose_it_amt, lose_it_list]

rawDescription: How do I recursively increment the first value in a list and append to a nested list in python?

description: Recursively increment the first value in a list and append to a nested list in python


code:
objects = {}
a = A(1234)
if a.hash in objects:
    a = objects[a.hash]
objects[a.hash] = a

rawDescription: Objects with user-defined hash

description: Objects with user-defined hash


code:
myString = "a:::b:::c:::d"
myList = [1,2,3,4]

s = iter(myString.split(":::"))

print(next(s) + "".join(str(y)+x for x,y in zip(s,myList)))

rawDescription: Python: How to replace substring occurrences with next values from list?


code:
class Bag(object):
  pass

spam = Bag()
spam.eggs = []

rawDescription: How to define an anonymous type in python

description: Define an anonymous type in python


code:
import m as m_

def f(m=None):
    if m is None:
        k = m_.M()

rawDescription: How to access module-level names in Python?

description: Access module-level names in Python


code:
if 'test' in sys.argv:
    DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
    SOUTH_TESTS_MIGRATE = False # if you're using south

rawDescription: Django variable that is true when testing


code:
if letter in 'aeiou':
    ...

rawDescription: detecting vowels in python

description: Detecting vowels in python


code:
# Please don't name a variable `list` -- it overshadows the built-in.
lst = ['hello there 123 456', 'hello there 234 567', 'hello there 345 678']
[x.split()[2] for x in lst]

rawDescription: Saving only a portion of each member of a Python list


code:
a.append(b) #  equivalent to pd.concat([a, b])
a.append(b).sort_index()

rawDescription: Pandas: How to merge Time Series with complementary Dates?


code:
import mock
from django.core.management import call_command
import django.core.management
from myapp.models import User

class TestCommands(TestCase):

    def test_mytest(self):

        users = User.objects.filter(can_user_service=True)

        with mock.patch.object(django.core.management, 'module'):
            call_command('djangocommand', my_option=True)
            django.core.management.module.assert_called_once_with(users)

rawDescription: Testing Django Commands with Mock

description: Testing Django Commands with Mock


code:
actor_sets = data['video'].video_actor_set.all()
data['actors'] = {}

for actor_set in actor_sets:
    if not data['actors'].has_key( actor_set.actor ):
        data['actors'][actor_set.actor] = []
        data['actors'][actor_set.actor].append( actor_set.time )

rawDescription: Reorganizing many to many relationships in Django


rawDescription: Merging custom objects with structure similar to lists, using Python


code:
language= environ['SCRIPT_NAME'][1:].split('/', 1)[0]
if language not in ('english', 'italiano'):
    language= 'english'

rawDescription: App Engine Python how to handle urls?

description: App Engine Python how to handle urls


code:
e = {}
setup_testing_defaults(e)
s = urlencode({'q': 'is there a way to set the value of wsgi input'})
e['wsgi.input'] = StringIO(s)

rawDescription: Is there a way to set the value of wsgi.input when testing?


code:
import ModelClass
ModelClass.associationProperty = association_proxy()
mapper() #etc..

rawDescription: SQLAlchemy AssociationProxy on a clean POPO?


code:
if request.method == "POST":
    try:
        # Remember, *never* trust user input
        # This is most likely a number but you are not guaranteed that
        data_id = int(request["id"])
    except ValueError:
        abort(400)
    # If we got here, we have a valid int
    # Insert data into MongoDB

rawDescription: Prevent Flask + jinja2 from converting a long integer into a decimal


code:
from django.db.backends.signals import connection_created

def set_role(**kwargs):
    connection = kwargs.get("connection", None)
    if connection:
        cursor = connection.cursor()
        cursor.execute("SET ROLE R_HRP IDENTIFIED BY %s", "myp4ssw0rd")

connection_created.connect(set_role)

rawDescription: Set role to oracle database user on django orm


code:
import sys
import os

def call_legacy_func(func, *args, **opts):
    prev = os.path.abspath(os.getcwd()) # Save the real cwd
    try:
        # Get the child's physical location.
        func_path = sys.modules[func.__module__].__file__
    except:
        # Die; we got passed a built-in function (no __file__)
        # Or you could just call it, I guess: return func(*args, **opts)
        return None

    # Change to the expected directory and run the function.
    os.chdir(func_path)
    result = func(*args, **opts)

    # Fix the cwd, and return.
    os.chdir(prev)
    return result

import ChildOneScript.ChildOne as ChildOne
call_legacy_func(ChildOne.myChildFunction, 0, 1, kwarg=False)

rawDescription: Python - Executing a function in another script in a child folder


code:
import plotly.plotly as py
from plotly.graph_objs import *

data = Data([
    Box(
        y=[0, 1, 1, 2, 3, 5, 8, 13, 21],
        boxpoints='all',
        jitter=0.3,
        pointpos=-1.8
    )
])

layout = Layout(
    boxgap=0.5
)

fig = Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='box-plot-with-gap')

rawDescription: How do you set the box width in a plotly box in python?

description: Set the box width in a plotly box in python


code:
import re, htmlentitydefs

##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)

rawDescription: Convert XML/HTML Entities into Unicode String in Python


code:
redirect(URL(f='first', args=['mydata', 'view', 'mydata', request.vars.id],
             user_signature=True))

rawDescription: How to redirect user to 'view' without going through smartgrid in web2py

description: Redirect user to 'view' without going through smartgrid in web2py