title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
3,661,417
38
2010-09-07T18:16:21Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
I always assumed it had to do with this line of the zen of python: > There should be one — and preferably only one — obvious way to do it. x++ and x+=1 do the exact same thing, so there is no reason to have both.
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
27,989,469
7
2015-01-16T17:27:54Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
## Clarity! Python is a lot about **clarity** and no programmer is likely to correctly guess the meaning of `--a` unless s/he's learned a language having that construct. Python is also a lot about **avoiding constructs that invite mistakes** and the `++` operators are known to be rich sources of defects. These two re...
Python: Listen on two ports
3,655,053
5
2010-09-07T00:36:15Z
3,655,592
7
2010-09-07T03:37:26Z
[ "python", "sockets", "listen" ]
``` import socket backlog = 1 #Number of queues sk_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local = {"port":1433} internet = {"port":9999} sk_1.bind (('', internet["port"])) sk_1.listen(backlog) sk_2.bind (('', local["port"])) sk_2.listen(backlog...
The fancy-pants way to do this if you want to use Python std-lib would be to use SocketServer with the ThreadingMixin -- although the 'select' suggestion is probably the more efficient. Even though we only define one ThreadedTCPRequestHandler you can easily repurpose it such that each listener has it's own unique hand...
ubuntu /usr/bin/env: python: No such file or directory
3,655,306
12
2010-09-07T02:06:34Z
8,735,625
58
2012-01-04T23:32:38Z
[ "python", "ubuntu-9.04" ]
I update the kernel, after that the Ubuntu doesn't work well, PS: I try to exec "meld" command, it will report that "/usr/bin/env: python: No such file or directory", then I exec "sudo apt-get install python" and get the result "python is already the newest version.", what should I do for it. --- I'm not good at linu...
Having been momentarily stumped by this error myself, I thought I'd post how I fixed my problem. My problem was an error: ``` : No such file or directory ``` Which made little sense to me. My problem is that my editor had silently converted the script from Unix LF to Windows CR/LF line-termination. A rather unfortun...
How to access files inside a python egg file?
3,655,352
9
2010-09-07T02:19:58Z
3,655,363
8
2010-09-07T02:23:33Z
[ "python", "egg" ]
Folks This might be a weird requirement but it's what I've run into. I googled but yield nothing. I'm coding an application who's using a lot of constant attributes / values recorded in a XML file (they'll not change so a static file), things work fine until I generated an egg file for it. When the logic reaches the...
`egg` files are zipfiles, so you must access "stuff" inside them with the [zipfile](http://docs.python.org/library/zipfile.html) module of the Python standard libraries, *not* with the built-in `open` function!
selection based on percentage weighting
3,655,430
22
2010-09-07T02:52:10Z
3,655,494
8
2010-09-07T03:10:21Z
[ "c#", "python", "algorithm", "random" ]
I have a set of values, and an associated percentage for each: a: 70% chance b: 20% chance c: 10% chance I want to select a value (a, b, c) based on the percentage chance given. how do I approach this? my attempt so far looks like this: ``` r = random.random() if r <= .7: return a elif r <= .9: return ...
For Python: ``` >>> import random >>> dst = 70, 20, 10 >>> vls = 'a', 'b', 'c' >>> picks = [v for v, d in zip(vls, dst) for _ in range(d)] >>> for _ in range(12): print random.choice(picks), ... a c c b a a a a a a a a >>> for _ in range(12): print random.choice(picks), ... a c a c a b b b a a a a >>> for _ in range...
selection based on percentage weighting
3,655,430
22
2010-09-07T02:52:10Z
3,655,534
27
2010-09-07T03:22:32Z
[ "c#", "python", "algorithm", "random" ]
I have a set of values, and an associated percentage for each: a: 70% chance b: 20% chance c: 10% chance I want to select a value (a, b, c) based on the percentage chance given. how do I approach this? my attempt so far looks like this: ``` r = random.random() if r <= .7: return a elif r <= .9: return ...
**Here is a complete solution in C#:** ``` public class ProportionValue<T> { public double Proportion { get; set; } public T Value { get; set; } } public static class ProportionValue { public static ProportionValue<T> Create<T>(double proportion, T value) { return new ProportionValue<T> { Prop...
selection based on percentage weighting
3,655,430
22
2010-09-07T02:52:10Z
3,655,773
8
2010-09-07T04:26:52Z
[ "c#", "python", "algorithm", "random" ]
I have a set of values, and an associated percentage for each: a: 70% chance b: 20% chance c: 10% chance I want to select a value (a, b, c) based on the percentage chance given. how do I approach this? my attempt so far looks like this: ``` r = random.random() if r <= .7: return a elif r <= .9: return ...
Knuth references Walker's method of aliases. Searching on this, I find <http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/> and <http://prxq.wordpress.com/2006/04/17/the-alias-method/>. This gives the exact probabilities required in constant time per number generated with lin...
Underline Text in Tkinter Label widget?
3,655,449
3
2010-09-07T02:57:40Z
3,658,463
8
2010-09-07T12:01:51Z
[ "python", "windows", "label", "tkinter", "underline" ]
I am working on a project that requires me to underline some text in a Tkinter Label widget. I know that the underline method can be used, but I can only seem to get it to underline 1 character of the widget, based on the argument. i.e. ``` p = Label(root, text=" Test Label", bg='blue', fg='white', underline=0) chang...
To underline all the text in a label widget you'll need to create a new font that has the underline attribute set to True. Here's an example: ``` import Tkinter as tk import tkFont class App: def __init__(self): self.root = tk.Tk() self.count = 0 l = tk.Label(text="Hello, world") l...
How can I test whether a variable holds a lambda?
3,655,842
15
2010-09-07T04:46:40Z
3,655,857
9
2010-09-07T04:49:54Z
[ "python", "class", "types", "lambda" ]
Is there a way to test whether a variable holds a `lambda`? The context is I'd like to check a type in a unit test: ``` self.assertEquals(lambda, type(myVar)) ``` The `type` seems to be "function" but I didn't see any obvious builtin type to match it. Obviously, I could write this, but it feels clumsy: ``` self.asse...
``` def isalambda(v): LAMBDA = lambda:0 return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__ ```
How can I test whether a variable holds a lambda?
3,655,842
15
2010-09-07T04:46:40Z
24,578,359
8
2014-07-04T16:45:17Z
[ "python", "class", "types", "lambda" ]
Is there a way to test whether a variable holds a `lambda`? The context is I'd like to check a type in a unit test: ``` self.assertEquals(lambda, type(myVar)) ``` The `type` seems to be "function" but I didn't see any obvious builtin type to match it. Obviously, I could write this, but it feels clumsy: ``` self.asse...
This is years past-due, but `callable(mylambda)` will return `True` for any callable function or method, lambdas included. `hasattr(mylambda, '__call__')` does the same thing but is much less elegant. If you need to know if something is *absolutely exclusively* a lambda, then `mylambda.__name__ == "<lambda>"` is what ...
Binary Search Trees
3,656,008
5
2010-09-07T05:31:35Z
3,656,039
10
2010-09-07T05:37:39Z
[ "python", "algorithm", "binary-tree", "binary-search-tree" ]
This is some code found on wikipedia regarding BST : ``` # 'node' refers to the parent-node in this case def search_binary_tree(node, key): if node is None: return None # key not found if key < node.key: return search_binary_tree(node.leftChild, key) elif key > node.key: ret...
It's just because your tree is not a binary search tree: it is not ordered correctly. The BST is build as described in the algorithm actually. For instance in your tree: the node '9' is not at the right position because as 9 < 10 it should be under the left branch of your root node '10'. Same for '14' and '11' which sh...
Numpy matrix operations
3,657,884
2
2010-09-07T10:42:51Z
3,659,619
13
2010-09-07T14:33:48Z
[ "python", "matrix", "numpy" ]
I want to compute the following values for all `i` and `j`: ``` M_ki = Sum[A_ij - A_ik - A_kj + A_kk, 1 <= j <= n] ``` How can I do it using Numpy (Python) without an explicit loop? Thanks!
Here is a general strategy for solving this kind of problem. First, write a small script, with the loop written explicitly in two different functions, and a test at the end making sure that the two functions are exactly the same: ``` import numpy as np from numpy import newaxis def explicit(a): n = a.shape[0] ...
How to send a package to PyPi?
3,658,084
14
2010-09-07T11:08:11Z
3,660,694
11
2010-09-07T16:40:11Z
[ "python", "packaging", "distutils", "python-sphinx", "pypi" ]
i wrote a little module and i would like to know what are the basic steps to package it in order to send it to [pypi](http://pypi.python.org/pypi): * what is the file hierarchy? * how should i name files? * should i use distutils to create PKG-INFO? * where should i include my documentation (made with sphinx)?
I recommend reading [*The Hitchhiker's Guide to Packaging*](https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/). Specifically, you should look at the [*Quick Start* section](http://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/quickstart.html), which describes how to: > 1. Lay out you...
Does "Find-Replace whole word only" exist in python?
3,658,215
14
2010-09-07T11:27:08Z
3,658,270
28
2010-09-07T11:33:41Z
[ "python", "regex" ]
Does "Find-Replace whole word only" exist in python? e.g. "old string oldstring boldstring bold" if i want to replace 'old' with 'new', new string should look like, "new string oldstring boldstring bold" can somebody help me?
``` >>> import re >>> s = "old string oldstring boldstring bold" >>> re.sub(r'\bold\b', 'new', s) 'new string oldstring boldstring bold' ``` This is done by using [**word boundaries**](http://www.regular-expressions.info/wordboundaries.html). Needless to say, this regex is not Python-specific and is implemented in mos...
Bulk insert with SQLAlchemy ORM
3,659,142
48
2010-09-07T13:42:43Z
3,663,101
22
2010-09-07T22:03:39Z
[ "python", "mysql", "database", "orm", "sqlalchemy" ]
Is there any way to get SQLAlchemy to do a bulk insert rather than inserting each individual object. i.e., doing: ``` INSERT INTO `foo` (`bar`) VALUES (1), (2), (3) ``` rather than: ``` INSERT INTO `foo` (`bar`) VALUES (1) INSERT INTO `foo` (`bar`) VALUES (2) INSERT INTO `foo` (`bar`) VALUES (3) ``` I've just conv...
As far as I know, there is no way to get the ORM to issue bulk inserts. I believe the underlying reason is that SQLAlchemy needs to keep track of each object's identity (i.e., new primary keys), and bulk inserts interfere with that. For example, assuming your `foo` table contains an `id` column and is mapped to a `Foo`...
Bulk insert with SQLAlchemy ORM
3,659,142
48
2010-09-07T13:42:43Z
31,205,155
37
2015-07-03T10:57:53Z
[ "python", "mysql", "database", "orm", "sqlalchemy" ]
Is there any way to get SQLAlchemy to do a bulk insert rather than inserting each individual object. i.e., doing: ``` INSERT INTO `foo` (`bar`) VALUES (1), (2), (3) ``` rather than: ``` INSERT INTO `foo` (`bar`) VALUES (1) INSERT INTO `foo` (`bar`) VALUES (2) INSERT INTO `foo` (`bar`) VALUES (3) ``` I've just conv...
SQLAlchemy introduced that in version `1.0.0`: [Bulk operations - SQLAlchemy docs](http://docs.sqlalchemy.org/en/rel_1_0/orm/persistence_techniques.html#bulk-operations) With these operations, you can now do bulk inserts or updates! For instance, you can do: ``` s = Session() objects = [ User(name="u1"), Us...
Why does django not see my tests?
3,659,405
7
2010-09-07T14:10:19Z
7,691,385
18
2011-10-07T18:29:04Z
[ "python", "django", "testing", "client" ]
I've created test.py module, filled with ``` from django.test import TestCase from django.test.client import Client from django.contrib.auth.models import User from django.contrib.sites.models import Site from forum.models import * class SimpleTest(TestCase): def setUp(self): u = User.objects.create_us...
You´ll need to use the prefix `test_` for each test method.
Making HTTP POST request
3,659,595
21
2010-09-07T14:30:21Z
3,662,621
24
2010-09-07T20:49:12Z
[ "python", "http", "post", "urllib" ]
I'm trying to make a POST request to retrieve information about a book. Here is the code that returns HTTP code: 302, Moved ``` import httplib, urllib params = urllib.urlencode({ 'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' }) headers = {"Content-t...
Their server seems to want you to acquire the proper cookie. This works: ``` import urllib, urllib2, cookielib cookie_jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar)) urllib2.install_opener(opener) # acquire cookie url_1 = 'http://www.bkstr.com/webapp/wcs/stores/serv...
how to shift a datetime object by 12 hours in python
3,660,210
2
2010-09-07T15:42:37Z
3,660,235
9
2010-09-07T15:46:03Z
[ "python", "datetime" ]
Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more.
The [`datetime`](http://docs.python.org/library/datetime.html) library has a `timedelta` object specifically for this kind of thing: ``` import datetime mydatetime = datetime.now() # or whatever value you want twelvelater = mydatetime + datetime.timedelta(hours=12) twelveearlier = mydatetime - datetime.timedelta(hour...
How to remove tags from a string in python using regular expressions? (NOT in HTML)
3,662,142
8
2010-09-07T19:48:51Z
3,662,277
37
2010-09-07T20:07:57Z
[ "python", "strip", "arcmap" ]
I need to remove tags from a string in python. ``` <FNT name="Century Schoolbook" size="22">Title</FNT> ``` What is the most efficient way to remove the entire tag on both ends, leaving only "Title"? I've only seen ways to do this with HTML tags, and that hasn't worked for me in python. I'm using this particularly fo...
This should work: ``` import re re.sub('<[^>]*>', '', mystring) ``` **To everyone saying that regexes are not the correct tool for the job:** The context of the problem is such that all the objections regarding regular/context-free languages are invalid. His language essentially consists of three entities: `a = <`, ...
Fill in missing values with nearest neighbour in Python numpy masked arrays?
3,662,361
8
2010-09-07T20:17:55Z
3,662,537
8
2010-09-07T20:39:28Z
[ "python", "numpy", "scipy" ]
I am working with a 2D Numpy masked\_array in Python. I need to change the data values in the masked area such that they equal the nearest unmasked value. NB. If there are more than one nearest unmasked values then it can take any of those nearest values (which ever one turns out to be easiest to code…) e.g. ``` i...
You could use `np.roll` to make shifted copies of `a`, then use boolean logic on the masks to identify the spots to be filled in: ``` import numpy as np import numpy.ma as ma a = np.arange(100).reshape(10,10) fill_value=-99 a[2:4,3:8] = fill_value a[8,8] = fill_value a = ma.masked_array(a,a==fill_value) print(a) # [...
Python multi-dimensional array initialization without a loop
3,662,475
10
2010-09-07T20:30:40Z
3,662,541
9
2010-09-07T20:39:39Z
[ "python" ]
Is there a way in Python to initialize a multi-dimensional array / list without using a loop?
Depending on your real needs, the de facto "standard" package [Numpy](http://www.scipy.org/Tentative_NumPy_Tutorial) might provide you with exactly what you need. You can for instance create a multi-dimensional array with ``` numpy.empty((10, 4, 100)) # 3D array ``` (initialized with *arbitrary values*) or create t...
Python multi-dimensional array initialization without a loop
3,662,475
10
2010-09-07T20:30:40Z
3,663,300
12
2010-09-07T22:43:52Z
[ "python" ]
Is there a way in Python to initialize a multi-dimensional array / list without using a loop?
Sure there *is* a way ``` arr = eval(`[[0]*5]*10`) ``` or ``` arr = eval(("[[0]*5]+"*10)[:-1]) ``` but it's horrible and wasteful, so everyone uses loops (usually list comprehensions) or numpy
Why does my PyQt application open in the background on Mac OS X?
3,662,559
8
2010-09-07T20:42:25Z
3,663,354
12
2010-09-07T22:58:32Z
[ "python", "pyqt" ]
I've got a PyQt app which I'm developing in Mac OS X, and whenever I try launching the app, it always is the very bottom application on the stack. So after launching, I always need to command+tab all the way to the end of the application list to switch focus to it. I read that this behavior can be fixed by launching t...
Based on this article <http://diotavelli.net/PyQtWiki/PyInstallerOnMacOSX>, you need to call app.raise\_() after app.show() ``` ui = MainWindow() ui.show() ui.raise_() ``` ref: <http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg18945.html>
python: remove substring only at the end of string
3,663,450
24
2010-09-07T23:25:17Z
3,663,505
32
2010-09-07T23:34:32Z
[ "python", "string" ]
i have a bunch of strings some of them have `' rec'` i want to remove that only if those are the last 4 characters so another words ``` somestring='this is some string rec' ``` i want it to be: ``` somestring='this is some string' ``` what is the python way to approach this?
``` def rchop(thestring, ending): if thestring.endswith(ending): return thestring[:-len(ending)] return thestring somestring = rchop(somestring, ' rec') ```
python: remove substring only at the end of string
3,663,450
24
2010-09-07T23:25:17Z
3,663,767
18
2010-09-08T00:36:21Z
[ "python", "string" ]
i have a bunch of strings some of them have `' rec'` i want to remove that only if those are the last 4 characters so another words ``` somestring='this is some string rec' ``` i want it to be: ``` somestring='this is some string' ``` what is the python way to approach this?
Since you have to get `len(trailing)` anyway (where `trailing` is the string you want to remove IF it's trailing), I'd recommend avoiding the slight duplication of work that `.endswith` would cause in this case. Of course, the proof of the code is in the timing, so, let's do some measurement (naming the functions after...
python: remove substring only at the end of string
3,663,450
24
2010-09-07T23:25:17Z
13,688,054
8
2012-12-03T16:58:03Z
[ "python", "string" ]
i have a bunch of strings some of them have `' rec'` i want to remove that only if those are the last 4 characters so another words ``` somestring='this is some string rec' ``` i want it to be: ``` somestring='this is some string' ``` what is the python way to approach this?
If speed is not important, use regex: ``` import re somestring='this is some string rec' somestring = re.sub(' rec$', '', somestring) ```
Representing a multi-select field for weekdays in a Django model
3,663,898
6
2010-09-08T01:05:11Z
8,152,717
12
2011-11-16T13:51:04Z
[ "python", "django", "django-models" ]
I've been searching for an elegant way to represent a multi-select weekday field (Mon, Tues, Wed...) in a Django model. I was initially thinking of going integer field using bitwise math but I am not sure if this would be the way to go. This would be a mostly-read field. I would want the Queryset method to be somethin...
This is an old question, but I thought I would show how it could be done reasonably simply in Django. Here is a helper class for preparing your choices: ``` class BitChoices(object): def __init__(self, choices): self._choices = [] self._lookup = {} for index, (key, val) in enumerate(choices): inde...
How to dynamically create module level functions from methods in a class
3,664,302
8
2010-09-08T02:45:40Z
3,664,396
9
2010-09-08T03:12:22Z
[ "python", "metaprogramming", "fabric" ]
I am trying to dynamically create module level functions from the methods in a class. So for every method in a class, I want to create a function with the same name which creates an instance of the class and then calls the method. The reason I want to do this is so I can take an object-oriented approach to creating Fa...
You're over-thinking your solution. Change the end of `fabric_class_to_function_magic` to be this: ``` tc = TestClass() func = getattr(tc, method_name) # add the new function to the current module setattr(module_obj, method_name, func) ``` and it works fine. No need to make a new function object, you...
Optional dependencies in a pip requirements file
3,664,478
23
2010-09-08T03:37:54Z
3,664,685
26
2010-09-08T04:43:18Z
[ "python", "dependencies", "pip", "pypi" ]
How can I specify optional dependencies in a pip requirements file? According to the [pip documentation](http://pip.openplans.org/#requirements-files) this is possible, but the documentation doesn't explain how to do it and I can't find any examples on the web.
Instead of specifying optional dependencies in the same file as the hard requirements, you can create a `optional-requirements.txt` and a `requirements.txt`. To export your current environment's packages into a text file, you can do this: ``` pip freeze > requirements.txt ``` If necessary, modify the contents of the...
Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx
3,664,708
5
2010-09-08T04:49:49Z
3,665,825
9
2010-09-08T08:24:29Z
[ "python", "django", "django-models" ]
Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx such filter, value\_list or ...
Probably most pythonic way: ``` myset = Customer.objects.filter(<something>).order_by(<something>) first, last = myset[0], myset.reverse()[0] ```
web.py on Google App Engine
3,665,292
9
2010-09-08T06:54:37Z
3,665,324
11
2010-09-08T07:00:00Z
[ "python", "google-app-engine", "web.py" ]
I'm trying to get a `web.py` application running on GAE. I hoped that sth like the following might work ``` import web from google.appengine.ext.webapp.util import run_wsgi_app [...] def main(): app = web.application(urls, globals()) run_wsgi_app(app) ``` But obviously the `app` object doesn't conform with ...
Here is a snippet of [StackPrinter](http://stackprinter.appspot.com/), a [webpy](http://webpy.org/) application that runs on top of Google App Engine. ``` from google.appengine.ext.webapp.util import run_wsgi_app import web ... app = web.application(urls, globals()) def main(): application = app.wsgifunc() r...
How is Ruby more object-oriented than Python?
3,665,656
21
2010-09-08T07:55:27Z
3,665,746
8
2010-09-08T08:11:46Z
[ "python", "ruby", "oop" ]
Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python?
From [WikiVS](http://www.wikivs.com/wiki/Python_vs_Ruby), > … where in Ruby all functions and most operators are in fact methods of an object, a number of Python functions are procedural functions rather than methods. The following [interview](http://linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html) with Matz, the...
How is Ruby more object-oriented than Python?
3,665,656
21
2010-09-08T07:55:27Z
3,665,937
14
2010-09-08T08:39:31Z
[ "python", "ruby", "oop" ]
Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python?
One example that's commonly given is `len`, which in Python is a built-in function. You may implement a special `__len__` method in your objects which will be called by `len`, but `len` is still a function. In Ruby, objects just have the `.length` property/method so it appears more object oriented when you say `obj.len...
How is Ruby more object-oriented than Python?
3,665,656
21
2010-09-08T07:55:27Z
3,666,579
20
2010-09-08T10:02:27Z
[ "python", "ruby", "oop" ]
Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python?
If you take the Python from 1993 and compare it with Ruby then the latter is more object oriented. However, after the [overhaul in Python 2.2](http://python-history.blogspot.com/2010/06/new-style-classes.html) this is no longer true. I'd say that modern Python is as object oriented as it gets.
Can I get SQLite to string instead of unicode for TEXT in Python?
3,666,328
3
2010-09-08T09:31:16Z
3,666,770
8
2010-09-08T10:29:44Z
[ "python", "string", "sqlite", "unicode" ]
AFAIK SQLite returns unicode objects for `TEXT` in Python. Is it possible to get SQLite to return string objects instead?
On further inspection of the Python SQLite API, I found this little bit: <http://docs.python.org/library/sqlite3.html#sqlite3.Connection.text_factory> Case closed.
Python: Testing if a value is present in a defaultdict list
3,667,411
2
2010-09-08T11:52:53Z
3,667,443
12
2010-09-08T11:56:40Z
[ "python", "list", "collections", "dictionary" ]
I want test whether a string is present within any of the list values in a defaultdict. For instance: ``` from collections import defaultdict animals = defaultdict(list) animals['farm']=['cow', 'pig', 'chicken'] animals['house']=['cat', 'rat'] ``` I want to know if 'cow' occurs in any of the lists within anima...
defaultdict is no different from a regular dict in this case. You need to iterate over the values in the dictionary: ``` any('cow' in v for v in animals.values()) ``` or more procedurally: ``` def in_values(s, d): """Does `s` appear in any of the values in `d`?""" for v in d.values(): if s in v: ...
Sorting a sublist within a Python list of integers
3,668,930
5
2010-09-08T14:45:55Z
3,668,946
12
2010-09-08T14:48:27Z
[ "python" ]
I have an unsorted list of integers in a Python list. I want to sort the elements in a subset of the full list, not the full list itself. I also want to sort the list in-place so as to not create new lists (I'm doing this very frequently). I initially tried ``` p[i:j].sort() ``` but this didn't change the contents of...
You can write `p[i:j] = sorted(p[i:j])`
How to check if a character is upper-case in Python?
3,668,964
36
2010-09-08T14:50:13Z
3,669,033
44
2010-09-08T14:55:48Z
[ "python", "string" ]
I have a string like this ``` >>> x="Alpha_beta_Gamma" >>> words = [y for y in x.split('_')] >>> words ['Alpha', 'beta', 'Gamma'] ``` I want output saying X is non conformant as the the second element of the list words starts with a lower case and if the string `x = "Alpha_Beta_Gamma"` then it should print string is ...
To test that all words start with an upper case use this: ``` print all(word[0].isupper() for word in words) ```
How to check if a character is upper-case in Python?
3,668,964
36
2010-09-08T14:50:13Z
3,669,077
37
2010-09-08T15:00:42Z
[ "python", "string" ]
I have a string like this ``` >>> x="Alpha_beta_Gamma" >>> words = [y for y in x.split('_')] >>> words ['Alpha', 'beta', 'Gamma'] ``` I want output saying X is non conformant as the the second element of the list words starts with a lower case and if the string `x = "Alpha_Beta_Gamma"` then it should print string is ...
Maybe you want [`str.istitle`](https://docs.python.org/library/stdtypes.html#str.istitle) ``` >>> help(str.istitle) Help on method_descriptor: istitle(...) S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. uppercase characters may only follow uncas...
Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python)
3,669,436
4
2010-09-08T15:40:57Z
3,669,555
8
2010-09-08T15:52:45Z
[ "python", "string", "unicode", "urllib", "unicode-string" ]
I want to send Chinese characters to be translated by an online service, and have the resulting English string returned. I'm using simple [JSON](http://en.wikipedia.org/wiki/JSON) and urllib for this. And yes, I am declaring. ``` # -*- coding: utf-8 -*- ``` on top of my code. Now everything works fine if I feed url...
When you get a `unicode` object and want to return a UTF-8 encoded byte string from it, use `theobject.encode('utf8')`. It seems strange that you don't know whether the incoming object is a `str` or `unicode` -- surely you do control the *call sites* to that function, too?! But if that is indeed the case, for whatever...
Python SocketServer: sending to multiple clients?
3,670,127
8
2010-09-08T17:01:40Z
3,672,635
14
2010-09-08T23:18:06Z
[ "python", "python-2.7", "sockets", "networking", "socketserver" ]
Well, I'm trying to build a small python prgram with a SocketServer that is supposed to send messages it receives to all connected clients. I'm stuck, I don't know how to store clients on the serverside, and I don't know how to send to multiple clients. Oh and, my program fails everytime more then 1 client connects, an...
You want to look at [asyncore](http://docs.python.org/library/asyncore.html) here. The socket operations you're calling on the client side are blocking (don't return until some data is received or a timeout occurs) which makes it hard to listen for messages sent from the host and let the client instances enqueue data t...
Setting smaller buffer size for sys.stdin?
3,670,323
18
2010-09-08T17:25:14Z
3,670,470
24
2010-09-08T17:40:36Z
[ "python", "stdin", "buffering" ]
I'm running memcached with the following bash command pattern: ``` memcached -vv 2>&1 | tee memkeywatch2010098.log 2>&1 | ~/bin/memtracer.py | tee memkeywatchCounts20100908.log ``` to try and track down unmatched gets to sets for keys platform wide. The memtracer script is below and works as desired, with one minor ...
You can completely remove buffering from stdin/stdout by using python's `-u` flag: ``` -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) see man page for details on internal buffering relating to '-u' ``` and the man page clarifies: ``` -u Force stdin, stdout and stderr to be t...
Setting smaller buffer size for sys.stdin?
3,670,323
18
2010-09-08T17:25:14Z
18,235,323
14
2013-08-14T15:03:34Z
[ "python", "stdin", "buffering" ]
I'm running memcached with the following bash command pattern: ``` memcached -vv 2>&1 | tee memkeywatch2010098.log 2>&1 | ~/bin/memtracer.py | tee memkeywatchCounts20100908.log ``` to try and track down unmatched gets to sets for keys platform wide. The memtracer script is below and works as desired, with one minor ...
You can simply use `sys.stdin.readline()` instead of `sys.stdin.__iter__()`: ``` import sys while True: line = sys.stdin.readline() if not line: break # EOF sys.stdout.write('> ' + line.upper()) ``` This gives me line-buffered reads using Python 2.7.4 and Python 3.3.1 on Ubuntu 13.04.
Python - Make Script to Manipulate Windows File Paths but running on Linux
3,670,673
5
2010-09-08T18:11:00Z
3,670,715
7
2010-09-08T18:17:17Z
[ "python", "windows", "linux", "filesystems" ]
I have this script which processes lines containing windows file paths. However the script is running on Linux. Is there a way to change the os library to do Windows file path handling while running on linux? I was thinking something like: ``` import os os.pathsep = '\\' ``` (which doesn't work since os.pathsep is ;...
Look at the [ntpath](http://docs.python.org/library/os.path.html) module On Linux, I did: ``` >> import ntpath >> ntpath.split("c:\windows\i\love\you.txt") ('c:\\windows\\i\\love', 'you.txt') >> ntpath.splitext("c:\windows\i\love\you.txt") ('c:\\windows\\i\\love\\you', '.txt') >> ntpath.basename("c:\windows\i\l...
Working around Python bug in different versions
3,670,816
5
2010-09-08T18:30:26Z
3,670,824
8
2010-09-08T18:31:54Z
[ "python", "python-2.7", "python-2.6" ]
I've come across a bug in Python (at least in 2.6.1) for the `bytearray.fromhex` function. This is what happens if you try the example from the docstring: ``` >>> bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: fromhex() argument 1 must be unicode, not s...
For cases like this it's good to remember that a `try` block is very cheap if no exception is thrown. So I'd use: ``` try: x = bytearray.fromhex(some_str) except TypeError: # Work-around for Python 2.6 bug x = bytearray.fromhex(unicode(some_str)) ``` This lets Python 2.6 work with a small performance hit...
Sharing a complex object between Python processes?
3,671,666
13
2010-09-08T20:36:37Z
3,697,322
18
2010-09-13T00:52:11Z
[ "python", "process", "multiprocessing", "sharing" ]
I have a fairly complex Python object that I need to share between multiple processes. I launch these processes using `multiprocessing.Process`. When I share an object with `multiprocessing.Queue` and `multiprocessing.Pipe` in it, they are shared just fine. But when I try to share an object with other non-multiprocessi...
You can do this using Python's Multiprocessing "Manager" classes and a proxy class that you define. From the Python docs: <http://docs.python.org/library/multiprocessing.html#proxy-objects> What you want to do is define a proxy class for your custom object, and then share the object using a "Remote Manager" -- look at...
How does Python's lack of static typing affect maintainability and extensibility in larger projects?
3,671,827
16
2010-09-08T20:54:58Z
3,672,201
13
2010-09-08T21:55:33Z
[ "java", "python", "project-management", "static-typing" ]
After reading [this very informative (albeit somewhat argumentative) question](http://stackoverflow.com/questions/3621297/how-to-deal-with-python-static-typing-closed) I would like to know your experience with programming large projects with Python. Do things become un manageable as the project becomes larger? This con...
I work on a large scale commercial product done in Python. I give a very rough estimate of 5000 files x 500 lines each. That's about 2.5 millions lines of Python. Mind you the complexity of this project is probably equivalent to 10 mil+ lines of code in other languages. I've not heard from a single engineer/architectur...
python problems with integer comparision
3,671,936
5
2010-09-08T21:10:40Z
3,671,954
12
2010-09-08T21:13:43Z
[ "python" ]
I'm using a function in a card game, to check the value of each card, and see if it is higher than the last card played. ``` def Valid(card): prev=pile[len(pile)-1] cardValue=0 prevValue=0 if card[0]=="J": cardValue=11 elif card[0]=="Q": cardValue=12 elif card[0]=="K": cardValue=13 elif card[0]=="A": c...
I think what you meant is that it is saying that "2" > 13 which is true. You need to change ``` cardValue=card[0] ``` to ``` cardValue=int(card[0]) ```
Best way to find max and min of two values
3,672,599
10
2010-09-08T23:09:08Z
3,672,613
15
2010-09-08T23:12:33Z
[ "python" ]
I have a function that is passed two values and then iterates over the range of those values. The values can be passed in any order, so I need to find which one is the lowest first. I had the function written like this: ``` def myFunc(x, y): if x > y: min_val, max_val = y, x else: min_val, max_...
[min](http://docs.python.org/library/functions.html#min) and [max](http://docs.python.org/library/functions.html#max) are your friends. ``` def myFunc(x, y): min_val, max_val = min(x, y), max(x, y) ``` --- Edit. Benchmarked `min-max` version againt a simple `if`. Due to the function call overhead, `min-max` take...
What is the most 'pythonic' way to logically combine a list of booleans?
3,673,337
17
2010-09-09T02:16:34Z
3,673,345
49
2010-09-09T02:19:31Z
[ "python", "list", "boolean" ]
I have a list of booleans I'd like to logically combine using and/or. The expanded operations would be: ``` vals = [True, False, True, True, True, False] # And-ing them together result = True for item in vals: result = result and item # Or-ing them together result = False for item in vals: result = result or...
See [`all(iterable)`](http://docs.python.org/library/functions.html#all) : > Return `True` if all elements of the > *iterable* are true (or if the *iterable* > is empty). And [`any(iterable)`](http://docs.python.org/library/functions.html#any) : > Return `True` if any element of the > *iterable* is true. If the *ite...
Convert int to ASCII and back in Python
3,673,428
54
2010-09-09T02:47:08Z
3,673,447
98
2010-09-09T02:51:10Z
[ "python", "integer", "ascii", "encode" ]
I'm working on making a URL shortener for my site, and my current plan (I'm open to suggestions) is to use a node ID to generate the shortened URL. So, in theory, node 26 might be `short.com/z`, node 1 might be `short.com/a`, node 52 might be `short.com/Z`, and node 104 might be `short.com/ZZ`. When a user goes to that...
ASCII to int: ``` ord('a') ``` gives `97` And back to a string: ``` str(unichr(97)) ``` gives `'a'`
Convert int to ASCII and back in Python
3,673,428
54
2010-09-09T02:47:08Z
31,096,318
26
2015-06-28T05:03:13Z
[ "python", "integer", "ascii", "encode" ]
I'm working on making a URL shortener for my site, and my current plan (I'm open to suggestions) is to use a node ID to generate the shortened URL. So, in theory, node 26 might be `short.com/z`, node 1 might be `short.com/a`, node 52 might be `short.com/Z`, and node 104 might be `short.com/ZZ`. When a user goes to that...
``` >>> ord("a") 97 >>> chr(97) 'a' ```
Find subsequences of strings within strings
3,673,434
5
2010-09-09T02:48:44Z
3,673,467
10
2010-09-09T02:56:03Z
[ "python" ]
I want to make a function which checks a string for occurrences of other strings within them. However, the sub-strings which are being checked may be interrupted within the main string by other letters. For instance: ``` a = 'abcde' b = 'ace' c = 'acb' ``` The function in question should return as `b` being in `a`...
You can turn your expected sequence into a regex: ``` import re def sequence_in(s1, s2): """Does `s1` appear in sequence in `s2`?""" pat = ".*".join(s1) if re.search(pat, s2): return True return False # or, more compactly: def sequence_in(s1, s2): """Does `s1` appear in sequence in `s2`?"...
What is a best practice method to log visits per page / object
3,673,556
7
2010-09-09T03:25:59Z
3,995,175
16
2010-10-22T08:41:14Z
[ "php", "asp.net", "python", "design" ]
Take [my profile](http://stackoverflow.com/users/104071/dassouki) for example, or any question number of views on this site, what is the process of logging the number of visits per page or object on a website, which I presumably think includes: * Counting registered users once (this must be reflected in the db, which ...
The "correct" answer varies according to the situation; primarily the most desired statistic and the availability of resources to gather and process them: eg: # Server Side ## Raw web server logs All webservers have some facility to log requests. The trouble with them is that it requires a lot of processing to get m...
TypedChoiceField or ChoiceField in Django
3,673,833
10
2010-09-09T04:45:50Z
3,673,875
10
2010-09-09T04:55:28Z
[ "python", "django", "django-forms" ]
When should you use TypedChoiceField with a coerce function over a ChoiceField with a clean method on the form for the field? In other words why would you use MyForm over MyForm2 or vice versa. Is this simply a matter of preference? ``` from django import forms CHOICES = (('1', 'A'), ('2', 'B'), ('3', 'C')) class M...
I would use a `clean_field` method for doing "heavy lifting". For instance if your field requires non-trivial, custom cleaning and/or type conversion etc. If on the other hand the requirement is straightforward such as coercing to `int` then the `clean_field` is *probably* an overkill. `TypedChoiceField` would be the w...
Numpy: How to split/partition a dataset (array) into training and test datasets for, e.g., cross validation?
3,674,409
23
2010-09-09T06:57:34Z
3,677,283
35
2010-09-09T14:00:59Z
[ "python", "arrays", "optimization", "numpy" ]
What is a good way to split a numpy array randomly into training and testing / validation dataset? Something similar to the cvpartition or crossvalind functions in Matlab.
If you want to divide the data set once in two halves, you can use `numpy.random.shuffle`, or `numpy.random.permutation` if you need to keep track of the indices: ``` import numpy # x is your dataset x = numpy.random.rand(100, 5) numpy.random.shuffle(x) training, test = x[:80,:], x[80:,:] ``` or ``` import numpy # x...
Numpy: How to split/partition a dataset (array) into training and test datasets for, e.g., cross validation?
3,674,409
23
2010-09-09T06:57:34Z
18,544,946
8
2013-08-31T05:45:30Z
[ "python", "arrays", "optimization", "numpy" ]
What is a good way to split a numpy array randomly into training and testing / validation dataset? Something similar to the cvpartition or crossvalind functions in Matlab.
There is another option that just entails using scikit-learn. As [scikit's wiki describes](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html), you can just use the following instructions: ``` from sklearn.cross_validation import train_test_split data, labels = np.arange(1...
Adding per-object permissions to django admin
3,674,463
11
2010-09-09T07:07:19Z
3,691,005
18
2010-09-11T12:36:10Z
[ "python", "django", "django-admin" ]
**Background** I'm developing a django app for a vacation rental site. It will have two types of users, renters and property managers. I'd like the property managers to be able to manage their rental properties in the django admin. However, they should only be able to manage their own properties. I realize the defau...
I would simply add a method to each model `is_owned_by(user)`, and it is upto the model to decide if it is owned by that user or not. In most case `is_owned_by` can be a generic function in a base model class and you can tweak it in special cases. e.g. ``` class RentalPhoto(BaseModel): def is_owned_by(self, user):...
Remove class attribute in inherited class Python
3,674,597
5
2010-09-09T07:32:29Z
3,674,714
7
2010-09-09T07:55:01Z
[ "python", "inheritance", "class-attributes" ]
Consider such code: ``` class A (): name = 7 description = 8 color = 9 class B(A): pass ``` Class B now has (inherits) all attributes of class A. For some reason I want B not to inherit attribute 'color'. Is there a possibility to do this? Yes, I know, that I can first create class B with attributes 'n...
You can supply a different value for `color` in B, but if you want B not to have some property of A then there's only one clean way to do it: create a new base class. ``` class Base(): name = 7 description = 8 class A(Base): color = 9 class B(Base): pass ```
Remove class attribute in inherited class Python
3,674,597
5
2010-09-09T07:32:29Z
3,675,153
7
2010-09-09T09:01:36Z
[ "python", "inheritance", "class-attributes" ]
Consider such code: ``` class A (): name = 7 description = 8 color = 9 class B(A): pass ``` Class B now has (inherits) all attributes of class A. For some reason I want B not to inherit attribute 'color'. Is there a possibility to do this? Yes, I know, that I can first create class B with attributes 'n...
I think the best solution would be to [change your class hierarchy](http://stackoverflow.com/questions/3674597/remove-class-attribute-in-inherited-class-python/3674714#3674714) so you can get the classes you want without any fancy tricks. However, if you have a really good reason not to do this you could hide the `col...
regex error - nothing to repeat
3,675,144
33
2010-09-09T09:00:29Z
3,675,427
24
2010-09-09T09:42:23Z
[ "python", "regex" ]
I get an error message when I use this expression: ``` re.sub(r"([^\s\w])(\s*\1)+","\\1","...") ``` I checked the regex at [RegExr](http://regexr.com/3ctdn) and it returns `.` as expected. But when I try it in Python I get this error message: ``` raise error, v # invalid expression sre_constants.error: nothing to re...
It seems to be a python bug (that works perfectly in vim). The source of the problem is the (\s\*...)+ bit. Basically , you can't do `(\s*)+` which make sense , because you are trying to repeat something which can be null. ``` >>> re.compile(r"(\s*)+") Traceback (most recent call last): File "<stdin>", line 1, in <m...
How to replace the some characters from the end of a string?
3,675,318
9
2010-09-09T09:24:27Z
3,675,423
21
2010-09-09T09:41:13Z
[ "python", "string", "replace" ]
I want to replace characters at the end of a python string. I have this string: ``` s = "123123" ``` I want to replace the last `2` with `x`. Suppose there is a method called `replace_last`: ``` r = replace_last(s, '2', 'x') print r 1231x3 ``` Is there any built-in or easy method to do this?
This is exactly what the `rpartition` function is used for: > rpartition(...) > S.rpartition(sep) -> (head, sep, tail) > > ``` > Search for the separator sep in S, starting at the end of S, and return > the part before it, the separator itself, and the part after it. If the > separator is not found, return two empty ...
best way to compare sequence of letters inside file?
3,675,895
2
2010-09-09T11:00:31Z
3,676,544
8
2010-09-09T12:34:40Z
[ "python" ]
I have a file, that have lots of sequences of letters. Some of these sequences might be equal, so I would like to compare them, all to all. I'm doing something like this but this isn't exactly want I wanted: ``` for line in fl: line = line.split() for elem in line: if '>' in elem: pass else: ...
If the goal is to simply group like sequences together, then simply sorting the data will do the trick. Here is a solution that uses [BioPython](http://biopython.org/wiki/Biopython) to parse the input FASTA file, sorts the collection of sequences, uses the standard Python [itertools.groupby](http://docs.python.org/libr...
Is it possible to check if an email contains an attachement just from the e-mail header?
3,676,344
4
2010-09-09T12:05:20Z
3,676,417
7
2010-09-09T12:17:39Z
[ "python", "email", "imap", "imaplib" ]
I am developing an email client in Python. Is it possible to check if an email contains an attachement just from the e-mail header without downloading the whole E-Mail?
Try `IMAP4.fetch(message_set, "BODYSTRUCTURE")` Read the [RFC3501](http://www.faqs.org/rfcs/rfc3501.html) for details about the FETCH BODYSTRUCTURE response.
problems using observer pattern in django
3,676,517
2
2010-09-09T12:30:05Z
3,676,583
9
2010-09-09T12:40:06Z
[ "python", "django", "design-patterns", "observer-pattern" ]
I'm working on a website where I sell products (one class Sale, one class Product). Whenever I sell a product, I want to save that action in a History table and I have decided to use the observer pattern to do this. That is: my class Sales is the subject and the History class is the observer, whenever I call the save\...
This may not be an acceptable answer since it's more architecture related, but have you considered using signals to notify the system of the change? It seems that you are trying to do exactly what signals were designed to do. Django signals have the same end-result functionality as Observer patterns. <http://docs.djan...
python multidimensional list.. how to grab one dimension?
3,676,805
14
2010-09-09T13:10:13Z
3,676,847
8
2010-09-09T13:14:46Z
[ "python", "list" ]
my question is, is I have a list like the following: ``` someList = [[0,1,2],[3,4,5],[6,7,8]] ``` how would I get the first entry of each sublist? I know I could do this: ``` newList = [] for entry in someList: newList.append(entry[0]) ``` where newList would be: ``` [0, 3, 6] ``` But is there a way to do so...
``` zip(*someList)[0] ``` EDIT: In response to recursive's comment: One might also use ``` from itertools import izip izip(*someList).next() ``` for better performance. Some timing analysis: ``` python -m timeit "someList = [range(1000000), range(1000000), range(1000000)]; newlist = zip(*someList)[0]" 10 loops, b...
python multidimensional list.. how to grab one dimension?
3,676,805
14
2010-09-09T13:10:13Z
3,676,864
10
2010-09-09T13:17:03Z
[ "python", "list" ]
my question is, is I have a list like the following: ``` someList = [[0,1,2],[3,4,5],[6,7,8]] ``` how would I get the first entry of each sublist? I know I could do this: ``` newList = [] for entry in someList: newList.append(entry[0]) ``` where newList would be: ``` [0, 3, 6] ``` But is there a way to do so...
Perfect case for a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` [sublist[0] for sublist in someList] ``` Since efficiency is a major concern, this will be much faster than the `zip` approach. Depending what you're doing with the result, you may be able to get even...
python multidimensional list.. how to grab one dimension?
3,676,805
14
2010-09-09T13:10:13Z
3,676,991
17
2010-09-09T13:29:38Z
[ "python", "list" ]
my question is, is I have a list like the following: ``` someList = [[0,1,2],[3,4,5],[6,7,8]] ``` how would I get the first entry of each sublist? I know I could do this: ``` newList = [] for entry in someList: newList.append(entry[0]) ``` where newList would be: ``` [0, 3, 6] ``` But is there a way to do so...
EDIT: Here's some actual numbers! The `izip`, list comprehension, and `numpy` ways of doing this are all about the same speed. ``` # zip >>> timeit.timeit( "newlist = zip(*someList)[0]", setup = "someList = [range(1000000), range(1000000), range(1000000)]", number = 10 ) 1.4984046398561759 # izip >>> timeit.timeit( "...
matplotlib: format axis offset-values to whole numbers or specific number
3,677,368
71
2010-09-09T14:09:11Z
3,679,918
22
2010-09-09T19:31:15Z
[ "python", "matplotlib" ]
I have a matplotlib figure which I am plotting data that is always referred to as nanoseconds(1e-9). On the y-axis, if I have data that is tens of nanoseconds, ie. 44e-9, the value on the axis shows as 4.4 with a +1e-8 as an offset. Is there anyway to force the axis to show 44 with a +1e-9 offset? The same goes for my...
You have to subclass `ScalarFormatter` to do what you need... `_set_offset` just adds a constant, you want to set `ScalarFormatter.orderOfMagnitude`. Unfortunately, manually setting `orderOfMagnitude` won't do anything, as it's reset when the `ScalarFormatter` instance is called to format the axis tick labels. It shoul...
matplotlib: format axis offset-values to whole numbers or specific number
3,677,368
71
2010-09-09T14:09:11Z
3,680,707
31
2010-09-09T21:27:35Z
[ "python", "matplotlib" ]
I have a matplotlib figure which I am plotting data that is always referred to as nanoseconds(1e-9). On the y-axis, if I have data that is tens of nanoseconds, ie. 44e-9, the value on the axis shows as 4.4 with a +1e-8 as an offset. Is there anyway to force the axis to show 44 with a +1e-9 offset? The same goes for my...
A much easier solution is to simply customize the tick labels. Take this example: ``` from pylab import * # Generate some random data... x = linspace(55478, 55486, 100) y = random(100) - 0.5 y = cumsum(y) y -= y.min() y *= 1e-8 # plot plot(x,y) # xticks locs,labels = xticks() xticks(locs, map(lambda x: "%g" % x, lo...
matplotlib: format axis offset-values to whole numbers or specific number
3,677,368
71
2010-09-09T14:09:11Z
4,868,642
10
2011-02-01T22:21:26Z
[ "python", "matplotlib" ]
I have a matplotlib figure which I am plotting data that is always referred to as nanoseconds(1e-9). On the y-axis, if I have data that is tens of nanoseconds, ie. 44e-9, the value on the axis shows as 4.4 with a +1e-8 as an offset. Is there anyway to force the axis to show 44 with a +1e-9 offset? The same goes for my...
Similar to Amro's answer, you can use FuncFormatter ``` import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter # Generate some random data... x = np.linspace(55478, 55486, 100) y = np.random.random(100) - 0.5 y = np.cumsum(y) y -= y.min() y *= 1e-8 # Plot the data... fig = pl...
matplotlib: format axis offset-values to whole numbers or specific number
3,677,368
71
2010-09-09T14:09:11Z
6,654,046
85
2011-07-11T17:34:31Z
[ "python", "matplotlib" ]
I have a matplotlib figure which I am plotting data that is always referred to as nanoseconds(1e-9). On the y-axis, if I have data that is tens of nanoseconds, ie. 44e-9, the value on the axis shows as 4.4 with a +1e-8 as an offset. Is there anyway to force the axis to show 44 with a +1e-9 offset? The same goes for my...
I had exactly the same problem, and these two lines fixed the problem: ``` y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) ax.yaxis.set_major_formatter(y_formatter) ```
Python: gettext doesn't load translations on Windows
3,678,174
7
2010-09-09T15:44:21Z
3,683,912
8
2010-09-10T10:36:38Z
[ "python", "windows", "translation", "gettext" ]
This particular piece of code works very well on Linux, but not on Windows: ``` locale.setlocale(locale.LC_ALL, '') gettext.bindtextdomain('exposong', LOCALE_PATH) gettext.textdomain('exposong') ``` Code from [here](http://code.google.com/p/exposong/source/browse/trunk/lib/exposong/__init__.py) Even if i specify the...
Standard gettext module in Python **does not use** startdard language settings from Windows settings, but instead relies on presence one of the environment variables: `LANGUAGE`, `LC_MESSAGES`, `LC_ALL` or `LANG`. (I'd say this is example of *slack* porting of Unix/Linux library to Windows.) The environment variables ...
Pythonic way to combine two lists in an alternating fashion?
3,678,869
36
2010-09-09T17:11:35Z
3,678,925
38
2010-09-09T17:18:57Z
[ "python" ]
I have two lists, **the first of which is guaranteed to contain exactly one more item than the second**. I would like to know the most Pythonic way to create a new list whose even-index values come from the first list and whose odd-index values come from the second list. ``` # example inputs list1 = ['f', 'o', 'o'] li...
There's a recipe for this in the [`itertools` documentation](http://docs.python.org/library/itertools.html): ``` def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) wh...
Pythonic way to combine two lists in an alternating fashion?
3,678,869
36
2010-09-09T17:11:35Z
3,678,930
22
2010-09-09T17:19:51Z
[ "python" ]
I have two lists, **the first of which is guaranteed to contain exactly one more item than the second**. I would like to know the most Pythonic way to create a new list whose even-index values come from the first list and whose odd-index values come from the second list. ``` # example inputs list1 = ['f', 'o', 'o'] li...
This should do what you want: ``` >>> iters = [iter(list1), iter(list2)] >>> print list(it.next() for it in itertools.cycle(iters)) ['f', 'hello', 'o', 'world', 'o'] ```
Pythonic way to combine two lists in an alternating fashion?
3,678,869
36
2010-09-09T17:11:35Z
3,678,938
40
2010-09-09T17:20:53Z
[ "python" ]
I have two lists, **the first of which is guaranteed to contain exactly one more item than the second**. I would like to know the most Pythonic way to create a new list whose even-index values come from the first list and whose odd-index values come from the second list. ``` # example inputs list1 = ['f', 'o', 'o'] li...
Here's one way to do it by slicing: ``` >>> list1 = ['f', 'o', 'o'] >>> list2 = ['hello', 'world'] >>> result = [None]*(len(list1)+len(list2)) >>> result[::2] = list1 >>> result[1::2] = list2 >>> result ['f', 'hello', 'o', 'world', 'o'] ```
Pythonic way to combine two lists in an alternating fashion?
3,678,869
36
2010-09-09T17:11:35Z
21,482,016
8
2014-01-31T14:06:23Z
[ "python" ]
I have two lists, **the first of which is guaranteed to contain exactly one more item than the second**. I would like to know the most Pythonic way to create a new list whose even-index values come from the first list and whose odd-index values come from the second list. ``` # example inputs list1 = ['f', 'o', 'o'] li...
``` import itertools print [x for x in itertools.chain.from_iterable(itertools.izip_longest(list1,list2)) if x] ``` I think this is the most pythonic way of doing it.
Calling Python from Ruby
3,679,501
17
2010-09-09T18:33:49Z
3,679,574
8
2010-09-09T18:42:42Z
[ "python", "ruby" ]
I have a compiled Python library and API docs that I would like to use from Ruby. Is it possible to load a Python library, instantiate a class defined in it and call methods on that object from Ruby?
[This article](http://www.decalage.info/python/ruby_bridge) gives some techniques for running Ruby code from Python which should also be applicable in the reverse direction (such as XML-RPC or pipes) as well as specific techniques for running Python code from Ruby. In particular [rubypython](http://rubypython.rubyforge...
Downtime when reloading mod_wsgi daemon?
3,679,537
4
2010-09-09T18:37:53Z
3,682,085
17
2010-09-10T03:27:55Z
[ "python", "django", "apache", "mod-wsgi" ]
I'm running a Django application on Apache with mod\_wsgi. Will there be any downtime during an upgrade? Mod\_wsgi is running in daemon mode, so I can reload my code by touching the .wsgi script file, as described in the "ReloadingSourceCode" document: <http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode>. Presu...
In daemon mode there is no concept of a graceful restart when WSGI script file is touched to force a download. That is, unlike Apache itself, which will start new Apache server child processes while waiting for old processes to finish up with current requests, for mod\_wsgi daemon processes, the existing process must e...
A weighted version of random.choice
3,679,694
75
2010-09-09T18:59:23Z
3,679,747
84
2010-09-09T19:08:40Z
[ "python", "optimization" ]
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: ``` def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being selected. choices can be any iterable ...
``` def weighted_choice(choices): total = sum(w for c, w in choices) r = random.uniform(0, total) upto = 0 for c, w in choices: if upto + w >= r: return c upto += w assert False, "Shouldn't get here" ```
A weighted version of random.choice
3,679,694
75
2010-09-09T18:59:23Z
3,679,780
12
2010-09-09T19:13:04Z
[ "python", "optimization" ]
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: ``` def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being selected. choices can be any iterable ...
Crude, but may be sufficient: ``` import random weighted_choice = lambda s : random.choice(sum(([v]*wt for v,wt in s),[])) ``` Does it work? ``` # define choices and relative weights choices = [("WHITE",90), ("RED",8), ("GREEN",2)] # initialize tally dict tally = dict.fromkeys(choices, 0) # tally up 1000 weighted ...
A weighted version of random.choice
3,679,694
75
2010-09-09T18:59:23Z
4,322,940
54
2010-12-01T09:37:07Z
[ "python", "optimization" ]
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: ``` def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being selected. choices can be any iterable ...
1. Arrange the weights into a cumulative distribution. 2. Use **random.random()** to pick a random float `0.0 <= x < total`. 3. Search the distribution using **bisect.bisect** as shown in the example at <http://docs.python.org/dev/library/bisect.html#other-examples>. ``` from random import random from bise...
A weighted version of random.choice
3,679,694
75
2010-09-09T18:59:23Z
10,655,801
8
2012-05-18T15:49:08Z
[ "python", "optimization" ]
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: ``` def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being selected. choices can be any iterable ...
If you have a weighted dictionary instead of a list you can write this ``` items = { "a": 10, "b": 5, "c": 1 } random.choice([k for k in items for dummy in range(items[k])]) ``` Note that `[k for k in items for dummy in range(items[k])]` produces this list `['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'b'...
A weighted version of random.choice
3,679,694
75
2010-09-09T18:59:23Z
15,551,339
13
2013-03-21T15:14:38Z
[ "python", "optimization" ]
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: ``` def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being selected. choices can be any iterable ...
If you don't mind using numpy, you can use [numpy.random.choice](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html#numpy.random.choice). For example: ``` import numpy items = [["item1", 0.2], ["item2", 0.3], ["item3", 0.45], ["item4", 0.05] elems = [i[0] for i in items] probs = [i[1] for ...
A weighted version of random.choice
3,679,694
75
2010-09-09T18:59:23Z
26,196,078
45
2014-10-04T18:56:28Z
[ "python", "optimization" ]
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: ``` def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being selected. choices can be any iterable ...
Since version 1.7.0, NumPy has a `choice` function that supports probability distributions. ``` from numpy.random import choice draw = choice(list_of_candidates, number_of_items_to_pick, p=probability_distribution) ``` Note that `probability_distribution` is a sequence in the same order of `list_of_candidates`. You c...
Run shell command with input redirections from python 2.4?
3,679,974
8
2010-09-09T19:38:56Z
3,680,037
11
2010-09-09T19:47:27Z
[ "python", "shell", "io-redirection" ]
What I'd like to achieve is the launch of the following shell command: ``` mysql -h hostAddress -u userName -p userPassword databaseName < fileName ``` From within a python 2.4 script with something not unlike: ``` cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName, "<", file] subprocess.call(cmd) ``` This pukes du...
You have to feed the file into mysql stdin by yourself. This should do it. ``` import subprocess ... filename = ... cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName] f = open(filename) subprocess.call(cmd, stdin=f) ```
How to slice a 2D Python Array? Fails with: "TypeError: list indices must be integers, not tuple"
3,680,262
11
2010-09-09T20:20:26Z
3,680,325
14
2010-09-09T20:30:18Z
[ "python", "multidimensional-array", "numpy" ]
I have a 2d array in the numpy module that looks like: ``` data = array([[1,2,3], [4,5,6], [7,8,9]]) ``` I want to get a slice of this array that only includes certain columns of element. For example I may want columns 0 and 2: ``` data = [[1,3], [4,6], [7,9]] ``` What is...
The error say it explicitely : data is not a numpy array but a list of lists. try to convert it to an numpy array first : ``` numpy.array(data)[:,[0,2]] ```
Parsing 'time string' with Python?
3,680,299
5
2010-09-09T20:26:27Z
3,680,386
7
2010-09-09T20:37:44Z
[ "python", "string" ]
I'm writing an application that involves having users enter time's in the following format: ``` 1m30s # 1 Minute, 30 Seconds 3m15s # 3 Minutes, 15 Seconds 2m25s # 2 Minutes, 25 Seconds 2m # 2 Minutes 55s # 55 Seconds ``` The data can have a single "minute designation", a single "second designation", or both...
``` import re tests=['1m30s','3m15s','2m25s','2m','55s'] for time_str in tests: match=re.match('(?:(\d*)m)?(?:(\d*)s)?',time_str) if match: minutes = int(match.group(1) or 0) seconds = int(match.group(2) or 0) print({'minutes':minutes, 'seconds':seconds}) # {'seconds': 3...
Python - How to recursively add a folder's content in a dict
3,680,464
2
2010-09-09T20:48:16Z
3,680,495
13
2010-09-09T20:51:55Z
[ "python" ]
I am building a python script which will be removing duplicates from my library as an exercise in python. The idea is to build a dict containing a dict ( with the data and statistic on the file / folder ) for every file in folder in the library. It currently works with a set number of subfolder. This is an example of w...
Use [`os.walk`](http://docs.python.org/library/os.html#os.walk). ``` import os for dirpath,dirs,files in os.walk(ROOT): for f in dirs + files: fn = os.path.join(dirpath, f) FILES[fn] = Analyse(fn) ```
python class [] function
3,680,981
3
2010-09-09T22:22:00Z
3,681,006
7
2010-09-09T22:26:22Z
[ "python" ]
I recently moved from ruby to python and in ruby you could create self[nth] methods how would i do this in python? in other words you could do this ``` a = myclass.new n = 0 a[n] = 'foo' p a[n] >> 'foo' ```
Welcome to the light side ;-) It looks like you mean [`__getitem__(self, key)`](http://docs.python.org/reference/datamodel.html#object.__getitem__). and [`__setitem__(self, key, value)`](http://docs.python.org/reference/datamodel.html#object.__setitem__). Try: ``` class my_class(object): def __getitem__(self, k...
django-admin.py startproject is not working
3,681,216
10
2010-09-09T23:07:15Z
5,601,612
38
2011-04-08T23:02:01Z
[ "python", "django", "windows-xp" ]
after installing django I tried `django-admin.py startproject mysite` and that worked, then I got a simple site working and I wanted to start on something real, so I tried `django-admin.py startproject newsite` and nothing happened. Whenever I try the command nothing happens now.. any idea what is wrong?
For anyone stumbling across this now, this problem is a result of Windows not obeying the #!C:\Path\To\Virtualenv\Scripts\Python.exe hashbang at the top of django-admin.py, and therefore running it with the wrong python.exe (evidently a virtualenv bug). However, with virtualenv active, you can use the following comman...
django-admin.py startproject is not working
3,681,216
10
2010-09-09T23:07:15Z
12,665,135
8
2012-09-30T21:07:20Z
[ "python", "django", "windows-xp" ]
after installing django I tried `django-admin.py startproject mysite` and that worked, then I got a simple site working and I wanted to start on something real, so I tried `django-admin.py startproject newsite` and nothing happened. Whenever I try the command nothing happens now.. any idea what is wrong?
**If you are running Windows for a quick fix you can create a batch file with the following values:** ``` @echo off @echo "Enter Proyect name" set /p proj_name= set building="Building django project %proj_name%" @echo %building% python c:/Python27/Scripts/django-admin.py startproject %proj_name% pause ``` **I named t...
Nested inlines in the Django admin?
3,681,258
29
2010-09-09T23:17:47Z
3,745,351
14
2010-09-19T10:37:38Z
[ "python", "django", "django-models", "django-admin" ]
Alright, I have a fairly simple design. ``` class Update(models.Model): pub_date = models.DateField() title = models.CharField(max_length=512) class Post(models.Model): update = models.ForeignKey(Update) body = models.TextField() order = models.PositiveIntegerField(blank=True) class Media(models....
As of now there is no "built-in" way to have nested inlines (inline inside inline) in django.contrib.admin. Pulling something like this off is possible by having your own ModelAdmin and InlineModelAdmin subclasses that would enable this kind of functionality. See the patches on this ticket <http://code.djangoproject.co...
Can I get a reference to a Python property?
3,681,272
29
2010-09-09T23:20:16Z
3,681,323
23
2010-09-09T23:32:25Z
[ "python", "properties" ]
If I have this: ``` class foo(object): @property def bar(self): return 0 f = foo() ``` How do I get a reference to f.bar without actually invoking the method, if this is even possible? Edited to add: What I want to do is write a function that iterates over the members of f and does something with th...
`get_dict_attr` (below) looks up `attr` in a given object's `__dict__`, and returns the associated value if its there. If `attr` is not a key in that `__dict__`, the object's MRO's `__dict__`s are searched. If the key is not found, an `AttributeError` is raised. ``` def get_dict_attr(obj,attr): for obj in [obj]+ob...
opencv macport python bindings
3,681,496
7
2010-09-10T00:22:23Z
3,682,214
10
2010-09-10T04:13:17Z
[ "python", "opencv", "macports" ]
using the MacPorts install of OpenCV does not seem to install the python bindings anywhere. Are they included, where do they go?
Have you selected the +python26 variant for the [MacPorts port](http://www.macports.org/ports.php?by=name&substr=opencv)? ``` $ sudo port install opencv +python26 ```
opencv macport python bindings
3,681,496
7
2010-09-10T00:22:23Z
5,209,157
7
2011-03-06T06:50:00Z
[ "python", "opencv", "macports" ]
using the MacPorts install of OpenCV does not seem to install the python bindings anywhere. Are they included, where do they go?
I experienced this same issue. It seems the OpenCV Python bindings are built and installed, but they are not referenced in the "site-packages" directory. I have found a solution by adding a symbolic link to the built "cv.so" file in the "site-packages" directory of the Python package installed by MacPorts. These instru...
Shading an area between two points in a matplotlib plot
3,681,872
19
2010-09-10T02:08:20Z
31,572,599
16
2015-07-22T19:44:58Z
[ "python", "matplotlib" ]
How do you add a shaded area between two points in a [matplotlib](http://matplotlib.org/index.html) plot? In the example [matplotlib](http://matplotlib.org/index.html) plot below, I manually added the shaded, yellow area using [Skitch](http://www.skitch.com/). I'd like to know how to do this sans-Skitch. ![alt text](...
You can just use the function `axvspan`. The advantage to this is that the vertical region (or horizontal, in the case of `axhspan`) will remain shaded regardless of how you pan/zoom the plot. There's a complete example [here](http://matplotlib.org/examples/pylab_examples/axhspan_demo.html). See a simple example below...
Improving __init__ where args are assigned directly to members
3,682,137
4
2010-09-10T03:46:38Z
3,682,153
7
2010-09-10T03:52:49Z
[ "python" ]
I'm finding myself writing a lot of classes with constructors like this: ``` class MyClass(object): def __init__(self, foo, bar, foobar=1, anotherfoo=None): self.foo = foo self.bar = bar self.foobar = foobar self.anotherfoo = anotherfoo ``` Is this a bad code smell? Does Python off...
If they're kwargs, you could do something like this: ``` def __init__(self, **kwargs): for kw,arg in kwargs.iteritems(): setattr(self, kw, arg) ``` posargs are a bit trickier since you don't get naming information in a nice way. If you want to provide default values, you can do it like this: ``` def __i...