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
Maybe "kind-of" monad in python
8,507,200
18
2011-12-14T15:34:24Z
8,507,334
33
2011-12-14T15:44:48Z
[ "python", "haskell" ]
Trying to find a way to clean up some of my code. So I have something like this in my python code: ``` company = None country = None person = Person.find(id=12345) if person is not None: # found company = Company.find(person.companyId) if company is not None: country = Country.find(company....
``` company = country = None try: person = Person.find(id=12345) company = Company.find(person.companyId) country = Country.find(company.countryId) except AttributeError: pass # `person` or `company` might be None ``` [EAFP](http://docs.python.org/glossary.html#term-eafp)
Maybe "kind-of" monad in python
8,507,200
18
2011-12-14T15:34:24Z
8,507,440
12
2011-12-14T15:52:42Z
[ "python", "haskell" ]
Trying to find a way to clean up some of my code. So I have something like this in my python code: ``` company = None country = None person = Person.find(id=12345) if person is not None: # found company = Company.find(person.companyId) if company is not None: country = Country.find(company....
Python does not have a particularly nice syntax for monads. That being said, if you want to limit yourself to using something like the `Maybe` monad (Meaning that you'll only be able to use `Maybe`; you won't be able to make generic functions that deal with any monad), you can use the following approach: ``` class May...
Maybe "kind-of" monad in python
8,507,200
18
2011-12-14T15:34:24Z
8,507,638
15
2011-12-14T16:05:04Z
[ "python", "haskell" ]
Trying to find a way to clean up some of my code. So I have something like this in my python code: ``` company = None country = None person = Person.find(id=12345) if person is not None: # found company = Company.find(person.companyId) if company is not None: country = Country.find(company....
Exploit the short-circuit behavior and that a custom object is true by default and `None` is false: ``` person = Person.find(id=12345) company = person and person.company country = company and company.country ```
NumPy - Using isnan(x)
8,507,509
5
2011-12-14T15:57:43Z
8,507,755
11
2011-12-14T16:13:28Z
[ "python", "numpy", "notimplementedexception" ]
I'm trying to use numpy to check if a user input is numerical, I've tried using: ``` from numpy import * a = input("\n\nInsert A: ") if isnan(a) == True: print 'Not a number...' else: print "Yep,that's a number" ``` On it's own and it works fine, however when I embed it into a function such as in this case:...
"Not a Number" or "NaN" is a special kind of floating point value according to the IEEE-754 standard. The functions `numpy.isnan()` and `math.isnan()` test if a given floating point number has this special value (or one of several "NaN" values). Passing anything else than a floating point number to one of these functio...
pyparsing example
8,507,694
6
2011-12-14T16:09:11Z
8,507,950
14
2011-12-14T16:24:37Z
[ "python", "pyparsing" ]
It is my first attempt to use pyparsing and I'd like to ask how to filter this sample line: ``` survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812''' ``` to get output like: 1,52.125133215643,21.031048525561,116.898812 In general I have problem with understanding pyparsing logic so any help with th...
You could start with something like this: ``` from pyparsing import * survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812''' number = Word(nums+'.').setParseAction(lambda t: float(t[0])) separator = Suppress(',') latitude = Suppress('LA') + number longitude = Suppress('LN') + number elevation = Supp...
Check if request is AJAX in Python
8,508,602
12
2011-12-14T17:05:49Z
8,508,785
20
2011-12-14T17:17:33Z
[ "python", "ajax", "http-headers", "xmlhttprequest" ]
Is there a way to check if a request is AJAX in Python? The equivalent of PHP's `$_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest'`?
If the AJAX framework sets the X-Requested-With header in its requests, then you will be able to use that header to detect AJAX calls. It's up to the client-side framework to do this. Getting hold of the HTTP headers depends on your Python framework of choice. In Django, the `request` object has an [`is_ajax` method](...
Bit masking in Python
8,508,799
4
2011-12-14T17:18:28Z
8,508,963
7
2011-12-14T17:29:02Z
[ "python", "bit-manipulation" ]
I have a byte (from some other vendor) where the potential bit masks are as follows: value1 = 0x01 value2 = 0x02 value3 = 0x03 value4 = 0x04 value5 = 0x05 value6 = 0x06 value7 = 0x40 value8 = 0x80 I can count on ONE of value1 through value6 being present. And then value7 may or may not be set. value8 may or may not b...
Most of your `value*` constants aren't actually bit masks, only `value7` and `value8` are. I'd define another bit mask to extract the lower bits, so I would have three bit masks in total: ``` mask0 = 0x07 mask1 = 0x40 mask2 = 0x80 ``` Now your function becomes ``` def parse_byte(byte): return byte & mask2, byte ...
Constructing Django filter queries dynamically with args and kwargs
8,510,057
13
2011-12-14T18:51:39Z
8,510,228
9
2011-12-14T19:07:33Z
[ "python", "django" ]
I'm constructing some Django filter queries dynamically, [using this example](http://www.nomadjourney.com/2009/04/dynamic-django-queries-with-kwargs/): ``` kwargs = { 'deleted_datetime__isnull': True } args = ( Q( title__icontains = 'Foo' ) | Q( title__icontains = 'Bar' ) ) entries = Entry.objects.filter( *args, **kwa...
You can iterate it directly using a kwarg format (I don't know the proper term) ``` argument_list = [] #keep this blank, just decalring it for later fields = ('title') #any fields in your model you'd like to search against query_string = 'Foo Bar' #search terms, you'll probably populate this from some source for quer...
Constructing Django filter queries dynamically with args and kwargs
8,510,057
13
2011-12-14T18:51:39Z
15,859,684
10
2013-04-07T06:40:30Z
[ "python", "django" ]
I'm constructing some Django filter queries dynamically, [using this example](http://www.nomadjourney.com/2009/04/dynamic-django-queries-with-kwargs/): ``` kwargs = { 'deleted_datetime__isnull': True } args = ( Q( title__icontains = 'Foo' ) | Q( title__icontains = 'Bar' ) ) entries = Entry.objects.filter( *args, **kwa...
you have list of Q class objects, ``` args_list = [Q1,Q2,Q3] # Q1 = Q(title__icontains='Foo') or Q1 = Q(**{'title':'value'}) args = Q() #defining args as empty Q class object to handle empty args_list for each_args in args_list : args = args | each_args query_set= query_set.filter(*(args,) ) # will excute, q...
how can i use pip with pypy installed from launchpad?
8,510,615
18
2011-12-14T19:40:57Z
8,510,829
18
2011-12-14T19:57:18Z
[ "python", "ubuntu", "pip", "pypy" ]
I have ubuntu 11.10. I apt-get installed pypy from this launchpad repository: <https://launchpad.net/~pypy> the computer already has python on it, and python has its own pip. How can I install pip for pypy and how can I use it differently from that of python?
To keep a separate installation, you might want to create a [virtualenv](http://pypi.python.org/pypi/virtualenv) for PyPy. Within the virtualenv, you can then just run `pip install whatever` and it will install it for PyPy. When you create a virtualenv, it automatically installs pip for you. Otherwise, you will need t...
how can i use pip with pypy installed from launchpad?
8,510,615
18
2011-12-14T19:40:57Z
9,943,835
34
2012-03-30T13:21:47Z
[ "python", "ubuntu", "pip", "pypy" ]
I have ubuntu 11.10. I apt-get installed pypy from this launchpad repository: <https://launchpad.net/~pypy> the computer already has python on it, and python has its own pip. How can I install pip for pypy and how can I use it differently from that of python?
Quoting (with minor changes) from here the [pypy website](http://doc.pypy.org/en/latest/install.html): > If you want to install 3rd party libraries, the most convenient way is > to install pip: > > ``` > $ curl -O https://bootstrap.pypa.io/get-pip.py > $ ./pypy-2.1/bin/pypy get-pip.py > $ ./pypy-2.1/bin/pip install py...
Building OpenCV 2.3.1 with Python 2.7 support in Ubuntu 11.10 64bit
8,510,972
6
2011-12-14T20:09:53Z
8,511,132
15
2011-12-14T20:23:13Z
[ "python", "ubuntu", "opencv" ]
I have seen a lot of posts on this topic, however I have not found regarding this warning: ``` CMake Warning: Manually-specified variables were not used by the project: BUILD_PYTHON_SUPPORT ``` when I compile with cmake. When building OpenCV with this warning, it turns out that it doesn't include python suppor...
It looks like you're using an old install guide. Use `BUILD_NEW_PYTHON_SUPPORT` instead. So, execute CMake like this: ``` cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. ``` Also, if you use the CMake GUI, it is easier to see all of the opti...
Raise Http404 in url pattern
8,513,341
4
2011-12-14T23:45:00Z
8,513,384
9
2011-12-14T23:49:52Z
[ "python", "django", "django-urls" ]
I'm trying to override a url in django-profiles to raise a 404 instead of passing to the view. I'm looking for something along the lines of: ``` url(r'^profiles/$', lamdba x: raise Http404) ``` But the above doesn't work. Is this sort of thing possible? I know I can write a new view that raises a 404, but I'd rathe...
Just use the view [`django.views.defaults.page_not_found`](https://docs.djangoproject.com/en/dev/topics/http/views/#the-404-page-not-found-view).
How to decide the language from cookies/headers/session in webapp2?
8,514,017
6
2011-12-15T01:28:02Z
8,522,855
12
2011-12-15T15:55:03Z
[ "python", "django", "google-app-engine", "internationalization", "webapp2" ]
I'd like to take advantage of webapp2's new features for localization that also has locale-specific formatting for time and currency. Django has a good function called get\_language\_from\_request that I made use of before I completely migrated to webapp2 and I now use the i18n from webapp2 instead and I can switch be...
Here's what I do - I have a base request handler that all my request handlers inherit from, then in here I have a constant that contains the available languages, and I [override the init method](http://webapp-improved.appspot.com/guide/handlers.html#overriding-init) to set the language on each request: ``` import weba...
marshal dumps faster, cPickle loads faster
8,514,020
17
2011-12-15T01:28:39Z
8,552,147
18
2011-12-18T13:49:39Z
[ "python", "performance", "serialization" ]
I'm implementing a program that needs to serialize and deserialize large objects, so I was making some tests with `pickle`, `cPickle` and `marshal` modules to choose the best module. Along the way I found something very interesting: I'm using `dumps` and then `loads` (for each module) on a list of dicts, tuples, ints,...
[`cPickle`](http://docs.python.org/release/2.5/lib/module-cPickle.html) has a smarter algorithm than [`marshal`](http://docs.python.org/library/marshal.html) and is able to do tricks to reduce the space used by large objects. That means it'll be slower to decode but faster to encode as the resulting output is smaller. ...
marshal dumps faster, cPickle loads faster
8,514,020
17
2011-12-15T01:28:39Z
9,270,029
9
2012-02-14T00:16:38Z
[ "python", "performance", "serialization" ]
I'm implementing a program that needs to serialize and deserialize large objects, so I was making some tests with `pickle`, `cPickle` and `marshal` modules to choose the best module. Along the way I found something very interesting: I'm using `dumps` and then `loads` (for each module) on a list of dicts, tuples, ints,...
Some people might think this too much of a hack, but I've had great success by simply wrapping the pickle dump calls with gc.disable() and gc.enable(). For example, the the snips below writing a ~50MB list of dictionaries goes from 78 seconds to 4. ``` # not a complete example.... gc.disable() cPickle.dump(params,fou...
Proper installation script for a small Python program (Not module) under Linux
8,514,471
7
2011-12-15T02:42:49Z
8,514,530
11
2011-12-15T02:50:15Z
[ "python", "installation" ]
I have a small program in python that consists in one .py file plus a directory of data files used by the program. I would like to know the proper way to create an installation procedure for a user with admin rights on Linux so that he can install the program on his system and use it from the command line, with option...
> Am I wrong that the setup.py method (ie: python setup.py install), is only for installing modules, later to be used from within the interpreter or other scripts? Yes. You're wrong. You can install into Python's scripts directory. Keep reading up on all the things `setup.py` can do. <http://docs.python.org/distutils...
Numpy matrix power/exponent with modulo?
8,514,565
8
2011-12-15T02:54:18Z
8,518,147
8
2011-12-15T09:55:12Z
[ "python", "matrix", "modulo", "exponent" ]
Is it possible to use numpy's linalg.matrix\_power with a modulo so the elements don't grow larger than a certain value?
In order to prevent overflow, you can use the fact that you get the same result if you first take the modulo of each of your input numbers; in fact: ``` (M**k) mod p = ([M mod p]**k) mod p, ``` for a *matrix* `M`. This comes from the following two fundamental identities, which are valid for integers `x` and `y`: ```...
Regular expression for repeating sequence
8,516,625
3
2011-12-15T07:39:56Z
8,516,687
8
2011-12-15T07:45:25Z
[ "python", "regex" ]
I'd like to match three-character sequences of letters (only letters 'a', 'b', 'c' are allowed) separated by comma (last group is not ended with comma). Examples: ``` abc,bca,cbb ccc,abc,aab,baa bcb ``` I have written following regular expression: ``` re.match('([abc][abc][abc],)+', "abc,defx,df") ``` However it d...
Try following regex: ``` ^[abc]{3}(,[abc]{3})*$ ``` `^...$` from the start till the end of the string `[...]` one of the given character `...{3}` three time of the phrase before `(...)*` 0 till n times of the characters in the brackets
Turn some print off in python unittest
8,518,043
5
2011-12-15T09:46:26Z
8,518,241
7
2011-12-15T10:01:37Z
[ "python", "unit-testing", "runner" ]
Im using unittest and it prints ".", "E" or "F" for "ok", "error" and "fail" after each test it does. How do I switch it off ? Im using Python 2.7 and these print come from the runner class which is built in. It sounds very tough to override the classes because it's all nested. edit: I only want to take off the charac...
The output of `unittest` is written to the standard error stream, which you can pipe somewhere else. On a \*nix box this would be possible like this: ``` python -m unittest some_module 2> /dev/null ``` On windows, this should look like this (thanks Karl Knechtel): ``` python -m unittest some_module 2> NUL ``` --- ...
Converting grayscale png with transparency using PIL
8,518,949
3
2011-12-15T10:56:38Z
8,519,025
7
2011-12-15T11:03:11Z
[ "python", "png", "transparency", "python-imaging-library" ]
PIL corrupt png images with transparency if i make them grayscale. Why? Here's my code: ``` input = Image.open('input.png') output = ImageOps.grayscale(input) output.save('output.png', **input.info) ``` Input ![http://imgur.com/a/m50p6](http://i.stack.imgur.com/H6VjF.jpg) Output ![http://imgur.com/a/m50p6](http:/...
You can use `convert` method with luminance trick: ``` Image.open('input.png').convert('LA').save('output.png') ```
comparison of two strings and returning the one most similar
8,519,181
5
2011-12-15T11:14:37Z
8,519,258
10
2011-12-15T11:20:31Z
[ "python", "comparison" ]
I have to write a function that takes a string as argument and compair this string to two other strings and return the string most similar and the number of differences. ``` def func("LUMB"): lst=["JIBM", "NUNE", "NUMB"] should return: ("NUMB",1) ``` I have tried: ``` def f(word): lst=["JIBM", "NUNE", "NUMB"...
Looks like Shawn Chin has provided the best solution, but if you're prevented from using non-builtin modules, it seems like [`get_close_matches`](http://docs.python.org/library/difflib.html#difflib.get_close_matches) from `difflib` might help: ``` import difflib difflib.get_close_matches("LUMB", ["JIBM", "NUNE", "NUMB...
python: dictionary to string, custom format?
8,519,599
12
2011-12-15T11:46:32Z
8,519,646
37
2011-12-15T11:50:06Z
[ "python", "string", "dictionary" ]
currently I'm displaying keys only, each in new line: ``` '<br/>'.join(mydict) ``` how do I display them like *key*:: *value*, each in the new line?
Go through the `dict.items()` iterator that will yield a key, value tuple: ``` '<br/>'.join(['%s:: %s' % (key, value) for (key, value) in d.items()]) ```
None vs Empty String in Python
8,519,647
5
2011-12-15T11:50:09Z
8,519,683
9
2011-12-15T11:52:28Z
[ "python" ]
I have an existing application which connects to a database. It is running under Python 2.7. The application is inconsistent in the way it uses None and "" to populate variables which do not have a value. I want to make this consistent and try to update the code to one way or the other. Thinking as a database person ...
You could cut down on code slightly by just writing ``` if variable and variable.upper() == "X": #Do something ``` If the variable is none or empty, then it's equivalent to False.
Posting raw data with Python
8,519,922
6
2011-12-15T12:10:02Z
10,581,202
10
2012-05-14T10:05:01Z
[ "python", "post", "curl", "urllib2", "pycurl" ]
I'm playing around with the Google Checkout API and I want to pull it into a Django app. I need to post data to Google using basic http authentication. I've been testing this with `curl` like this: ``` curl -d "$(cat mytest.xml)" -u username:password https://url ``` And that posts the content of my test XML file to G...
I've been having similar turmoils with the stdlib packages, until somoneone pointed to the awesome [requests](http://docs.python-requests.org/en/latest/user/quickstart/#basic-authentication) that supports basic Http Authentication and other authentication means straight out-of-the-box! And it has a beautiful and simple...
How to find the names of classes inside a python module?
8,520,053
2
2011-12-15T12:21:14Z
8,520,189
8
2011-12-15T12:34:22Z
[ "python" ]
If I import a module: ``` import foo ``` How can I find the names of the classes it contains?
You can use the [inspect](http://docs.python.org/library/inspect.html) module to do this. For example: ``` import inspect import foo for name, obj in inspect.getmembers(foo): if inspect.isclass(obj): print name ```
argparse optional subparser (for --version)
8,521,612
16
2011-12-15T14:27:26Z
8,521,644
14
2011-12-15T14:29:42Z
[ "python", "command-line-interface", "argparse", "subcommand" ]
I have the following code (using Python 2.7): ``` # shared command line options, like --version or --verbose parser_shared = argparse.ArgumentParser(add_help=False) parser_shared.add_argument('--version', action='store_true') # the main parser, inherits from `parser_shared` parser = argparse.ArgumentParser(descriptio...
According to documentation, `--version` with `action='version'` (and not with `action='store_true'`) prints automatically the version number: ``` parser.add_argument('--version', action='version', version='%(prog)s 2.0') ```
Pythonic way to send contents of a file to a pipe and count # lines in a single step
8,521,858
4
2011-12-15T14:45:47Z
8,522,115
7
2011-12-15T15:04:24Z
[ "python", "bash", "shell", "awk", "bigdata" ]
given the > 4gb file myfile.gz, I need to zcat it into a pipe for consumption by Teradata's fastload. I also need to count the number of lines in the file. Ideally, I only want to make a single pass through the file. I use awk to output the entire line ($0) to stdout and through using awk's END clause, writes the numbe...
There's no need for either of `zcat` or Awk. Counting the lines in a gzipped file can be done with ``` import gzip nlines = sum(1 for ln in gzip.open("/path/to/file/myfile.gz")) ``` If you want to do something else with the lines, such as pass them to a different process, do ``` nlines = 0 for ln in gzip.open("/pat...
multiprocessing.pool.map and function with two arguments
8,521,883
7
2011-12-15T14:47:48Z
8,523,756
7
2011-12-15T16:57:21Z
[ "python", "multithreading", "concurrency", "multiprocessing" ]
I am using `multiprocessing.Pool()` here is what i want to Pool: ``` def insert_and_process(file_to_process,db): db = DAL("path_to_mysql" + db) #Table Definations db.table.insert(**parse_file(file_to_process)) return True if __name__=="__main__": file_list=os.listdir(".") P = Pool(processes=4...
Your pool will spawn four processes, each run by it's own instance of the Python interpreter. You can use a global variable to hold your database connection object, so that exactly one connection is created per process: ``` global_db = None def insert_and_process(file_to_process, db): global global_db if glob...
multiprocessing.pool.map and function with two arguments
8,521,883
7
2011-12-15T14:47:48Z
8,523,763
18
2011-12-15T16:57:53Z
[ "python", "multithreading", "concurrency", "multiprocessing" ]
I am using `multiprocessing.Pool()` here is what i want to Pool: ``` def insert_and_process(file_to_process,db): db = DAL("path_to_mysql" + db) #Table Definations db.table.insert(**parse_file(file_to_process)) return True if __name__=="__main__": file_list=os.listdir(".") P = Pool(processes=4...
The `Pool` documentation does not say of a way of passing more than one parameter to the target function - I've tried just passing a sequence, but does not get unfolded (one item of the sequence for each parameter). However, you can write your target function to expect the first (and only) parameter to be a tuple, in ...
How to temporary hide stdout or stderr while running a unittest in Python
8,522,689
9
2011-12-15T15:43:03Z
8,522,803
13
2011-12-15T15:51:23Z
[ "python" ]
I have a faulty third party python module that is outputing to stdout or stderr while it is imported and this is breaking the output of my unittests. How can I temporary redirect the `stdout` in order to hide its output. Limit to Python 2.5 syntax :) **Update**, I forgot to mention that `sys.stdout` and `sys.__stder...
You can do it something like this: ``` >>> import sys, os >>> _stderr = sys.stderr >>> _stdout = sys.stdout >>> null = open(os.devnull,'wb') >>> sys.stdout = sys.stderr = null >>> print "Bleh" >>> sys.stderr = _stderr >>> sys.stdout = _stdout >>> print "Bleh" Bleh ```
How to temporary hide stdout or stderr while running a unittest in Python
8,522,689
9
2011-12-15T15:43:03Z
8,523,408
15
2011-12-15T16:32:32Z
[ "python" ]
I have a faulty third party python module that is outputing to stdout or stderr while it is imported and this is breaking the output of my unittests. How can I temporary redirect the `stdout` in order to hide its output. Limit to Python 2.5 syntax :) **Update**, I forgot to mention that `sys.stdout` and `sys.__stder...
You can also use [`mock`](http://www.voidspace.org.uk/python/mock/) to let you patch `sys.stdout` and `sys.stderr` for you when the module is imported. An example of a testing module that using this strategy would be: ``` import os devnull = open(os.devnull, 'w') from mock import patch with patch('sys.stdout', devnul...
Sorting a Python list by third element, then by first element, etc?
8,522,800
3
2011-12-15T15:51:19Z
8,522,862
12
2011-12-15T15:55:33Z
[ "python", "list", "sorting" ]
Say I have a list in the form [[x,y,z], [x,y,z] etc...] etc where each grouping represents a random point. I want to order my points by the z coordinate, then within each grouping of z's, sort them by x coordinate. Is this possible?
Sure, look at [this page](http://wiki.python.org/moin/HowTo/Sorting) under the section called "Operator Module Functions." Basically you just need to use sort's key feature with the itemgetter operator... ``` from operator import itemgetter sorted(tuples, key=itemgetter(2,0)) ```
Catching exceptions in django templates
8,524,077
10
2011-12-15T17:20:03Z
8,524,143
9
2011-12-15T17:25:43Z
[ "python", "django", "exception", "django-templates" ]
I'm using a template tag in a Django template (the tag is `thumbnail`) and it's throwing an exception that makes the template fail with a 500 error. I would like to stop this from happening, as I don't have complete control over the source images that sporadically trigger this exception, and use a blank/placeholder ima...
The way I've always handled this is to push it up to the model layer. So in your model: ``` class MyImageModel(model.Model): # model fields go here.. def get_url(self): try: # or whatever causes the exception return self.url except IOError: ...
How can I place a table on a plot in Matplotlib?
8,524,401
15
2011-12-15T17:46:53Z
8,531,491
31
2011-12-16T08:19:55Z
[ "python", "table", "matplotlib" ]
I'm not having any success in getting the matplotlib table commands to work. Here's an example of what I'd like to do: Can anyone help with the table construction code? Thanks ``` import pylab as plt plt.figure() ax=plt.gca() y=[1,2,3,4,5,4,3,2,1,1,1,1,1,1,1,1] plt.plot([10,10,14,14,10],[2,4,4,2,2],'r') col_labels=[...
AFAIK, you can't *arbitrarily* place a table on the `matplotlib` plot using only native `matplotlib` features. What you can do is take advantage of the possibility of [`latex` text rendering](http://matplotlib.sourceforge.net/users/usetex.html). However, in order to do this you should have working `latex` environment i...
Google App Engine dev app server does not display detailed error message
8,524,957
9
2011-12-15T18:37:01Z
8,527,695
7
2011-12-15T22:45:11Z
[ "python", "google-app-engine" ]
When developing on Google App Engine dev app server locally (python) and encounter an error, the browser will just show something like the following: Server error The website encountered an error while retrieving <http://localhost:8080/>. It may be down for maintenance or configured incorrectly. Here are some suggesti...
You can use commandline and start dev server with --debug to get verbose debug messages. Here are the docs: <http://code.google.com/appengine/docs/python/tools/devserver.html#Command_Line_Arguments> You can also add logging to your app to capture the info: <http://code.google.com/appengine/docs/python/runtime.html#Log...
How to install JPype on OS X Lion to use with Neo4j?
8,525,193
7
2011-12-15T18:59:28Z
8,527,108
11
2011-12-15T21:50:09Z
[ "java", "python", "gcc", "osx-lion", "neo4j" ]
I am trying to use Neo4j for a project, and want to interface with it through Python since I'm a newbie to programming and don't know any Java. I'm following the [installation instructions](http://docs.neo4j.org/chunked/snapshot/python-embedded-installation.html), but I'm stuck on the first step, which is to install JP...
I'm not a Python guy, but tried installing JPype on my machine: ``` % uname -a Darwin fatty-i7.local.tld 11.2.0 Darwin Kernel Version 11.2.0: Tue Aug 9 20:54:00 PDT 2011; root:xnu-1699.24.8~1/RELEASE_X86_64 x86_64 % java -version java version "1.6.0_29" Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11M3527)...
How to install JPype on OS X Lion to use with Neo4j?
8,525,193
7
2011-12-15T18:59:28Z
12,531,856
10
2012-09-21T13:48:20Z
[ "java", "python", "gcc", "osx-lion", "neo4j" ]
I am trying to use Neo4j for a project, and want to interface with it through Python since I'm a newbie to programming and don't know any Java. I'm following the [installation instructions](http://docs.neo4j.org/chunked/snapshot/python-embedded-installation.html), but I'm stuck on the first step, which is to install JP...
On my Lion, the "include" directory in the JDK was gone, so JPype couldn't find jni.h. I updated setup.py in two places, one to set where to find jar libraries: ``` def setupMacOSX(self): self.javaHome = '/System/Library/Frameworks/JavaVM.framework' self.jdkInclude = "" self.libraries = ["dl"] self.li...
Comment conventions in python
8,525,386
3
2011-12-15T19:16:13Z
8,525,551
8
2011-12-15T19:30:16Z
[ "python", "comments" ]
It seems like you can use both `'''comments...'''` and `"""comments..."""` for multi-line comments. Is there any substantive difference between the two, or is it just a matter of preference?
These are not comments, they are [docstrings](http://www.python.org/dev/peps/pep-0257/). Python allows you to define multi-line strings using triplets of either apostrophes or quotation marks, but PEP 257 recommends using the quotation marks with docstrings for consistency. It has no effect on the contents of the strin...
Python max and min
8,525,447
2
2011-12-15T19:21:05Z
8,525,518
13
2011-12-15T19:26:19Z
[ "python", "max", "min" ]
I'm pretty new to Python, and what makes me mad about my problem is that I feel like it's really simple.I keep getting an error in line 8. I just want this program to take the numbers the user entered and print the largest and smallest, and I want it to cancel the loop if they enter negative 1. `'int' object is not it...
The problem is that `number` is an `int`. `max` and `min` both require lists (or other iterable things) - so instead, you have to add `number` to a list like so: ``` number = int(raw_input("Please enter a number: ")) num_list = [] while (number != int(-1)): num_list.append(number) number = int(raw_input("Plea...
load parameters from a file in Python
8,525,765
8
2011-12-15T19:51:25Z
8,526,061
8
2011-12-15T20:19:07Z
[ "python", "file", "serialization", "input" ]
I am writing a Python class to model a process and I want to initialized the parameters from a file, say `'input.dat'`. The format of the input file looks like this. `'input.dat'` file: ``` Z0: 0 0 k: 0.1 g: 1 Delta: 20 t_end: 300 ``` The code I wrote is the following. It works but appears redundant and inflexible. ...
* If you are open to some other kind of file where you can keep your parameters, I would suggest you to use [YAML](http://www.yaml.org/) file. * The python lib is [PyYAML](http://pyyaml.org/) [This](http://pyyaml.org/wiki/PyYAMLDocumentation) is how you can easily use it with Python * For better introduction, look at t...
load parameters from a file in Python
8,525,765
8
2011-12-15T19:51:25Z
8,527,168
7
2011-12-15T21:57:12Z
[ "python", "file", "serialization", "input" ]
I am writing a Python class to model a process and I want to initialized the parameters from a file, say `'input.dat'`. The format of the input file looks like this. `'input.dat'` file: ``` Z0: 0 0 k: 0.1 g: 1 Delta: 20 t_end: 300 ``` The code I wrote is the following. It works but appears redundant and inflexible. ...
Assuming the params are coming from a safe place (made by you or users, not the internet), just make the parameters file a Python file, `params.py`: ``` Z0 = (0, 0) k = 0.1 g = 1 Delta = 20 t_end = 300 ``` Then in your code all you need is: ``` import params fancy_calculation(10, k=params.k, delta=params.Delta) ``` ...
Python xlwt - making a column readonly (cell protect)
8,526,296
4
2011-12-15T20:39:59Z
13,319,286
8
2012-11-10T04:37:27Z
[ "python", "excel", "override", "protected", "xlwt" ]
Is there a way to make a particular cell read-only/write protected in python xlwt? I know there's is a cell\_overwrite\_ok flag which does not allow to overwrite contents of cells (all cells) but can this be done on cell by cell basis. Thanks, Sun
Excel cells have a **locked** attribute that is enabled by default. However, this attribute is only invoked when the worksheet's **protection** attribute is also set to `True`. If the worksheet is not protected, the **locked** attribute is ignored. Therefore, your question isn't best framed as *how to make cells read-...
python argparse - optional append argument with choices
8,526,675
11
2011-12-15T21:13:18Z
8,527,629
8
2011-12-15T22:38:06Z
[ "python", "argparse" ]
I have a script where I ask the user for a list of pre-defined actions to perform. I also want the ability to assume a particular list of actions when the user doesn't define anything. however, it seems like trying to do both of these together is impossible. when the user gives no arguments, they receive an error that...
What you need can be done using a customized `argparse.Action` as in the following example: ``` import argparse parser = argparse.ArgumentParser() class DefaultListAction(argparse.Action): CHOICES = ['clear','copy','dump','lock'] def __call__(self, parser, namespace, values, option_string=None): if v...
Python pickle: fix \r characters before loading
8,527,241
5
2011-12-15T22:03:34Z
8,529,113
8
2011-12-16T02:23:53Z
[ "python", "carriage-return", "pickle" ]
I got a pickled object (a list with a few numpy arrays in it) that was created on Windows and apparently saved to a file loaded as text, not in binary mode (ie. with `open(filename, 'w')` instead of `open(filename, 'wb')`). Result is that now I can't unpickle it (not even on Windows) because it's infected with `\r` cha...
Presuming that the file was created with the default protocol=0 ASCII-compatible method, you should be able to load it anywhere by using `open('pickled_file', 'rU')` i.e. universal newlines. If this doesn't work, show us the first few hundred bytes: `print repr(open('pickled_file', 'rb').read(200))` and paste the resu...
Python Mechanize won't open these sites
8,527,862
6
2011-12-15T23:05:21Z
8,528,248
14
2011-12-15T23:57:07Z
[ "python", "mechanize" ]
I'm working with Python's Mechanize module. I've come across 3 different sites that cannot be opened by mechanize directly: 1. en.wikipedia.org/wiki/Dog (new user, can't post more than 2 links T-T ) 2. <https://www.google.com/search?num=100&hl=en&site=&q=dog&oq=dog&aq=f&aqi=g10&aql=1&gs_sm=e&gs_upl=618l914l0l1027l3l2l...
In the case of the cpsc.gov site, it looks like there's a [refresh](http://en.wikipedia.org/wiki/HTTP_refresh) header that isn't being correctly processed by mechanize HTTPRefreshProcessor. However, you can workaround the problem as follows: ``` import mechanize url = 'http://www.cpsc.gov/cpscpub/prerel/prhtml03/0305...
Why can I access an object during it's post_save Signal, but not when I trigger code within that signal that calls it on another process
8,528,264
8
2011-12-15T23:59:41Z
8,529,935
9
2011-12-16T04:53:50Z
[ "python", "django", "django-signals" ]
All, I've got a issue with django signals. I have a model In an effort to speed up responsiveness of page loads, I'm offloading some intensive processing that must be done, via a call to a second localhost webserver we're running, both using the same database. I'm seeing behavior where the calling process can retrieve...
I believe post\_save fires after the save occurs, but before the transaction is commited to the database. By default, Django only commits changes to the database after the request has been completed. Two possible solutions to your problem: 1. [Manage your transactions manually](https://docs.djangoproject.com/en/dev/t...
Is there a way to access __dict__ (or something like it) that includes base classes?
8,529,192
11
2011-12-16T02:39:56Z
8,529,470
9
2011-12-16T03:36:24Z
[ "python", "attributes" ]
Suppose we have the following class hierarchy: ``` class ClassA: @property def foo(self): return "hello" class ClassB(ClassA): @property def bar(self): return "world" ``` If I explore **\_\_*dict*\_\_** on ClassB like so, I only see the bar attribute: ``` for name,_ in ClassB.__dict__.items(): ...
You should use python's `inspect` module for any such introspective capabilities. ``` . . >>> class ClassC(ClassB): ... def baz(self): ... return "hiya" ... >>> import inspect >>> for attr in inspect.getmembers(ClassC): ... print attr ... ('__doc__', None) ('__module__', '__main__') ('bar', <property ob...
Google Authenticator implementation in Python
8,529,265
78
2011-12-16T02:57:13Z
8,549,884
110
2011-12-18T04:47:18Z
[ "python", "security", "authentication", "one-time-password", "google-authenticator" ]
I am trying to use one-time passwords that can be generated using [Google Authenticator application](https://market.android.com/details?id=com.google.android.apps.authenticator). ## What Google Authenticator does Basically, Google Authenticator implements two types of passwords: * **HOTP** - HMAC-based One-Time Pass...
I wanted to set a bounty on my question, but I have succeeded in creating solution. My problem seemed to be connected with incorrect value of `secret` key (it must be correct parameter for `base64.b32decode()` function). Below I post full working solution with explanation on how to use it. ## Code The following code...
is there a quiet version of subprocess.call?
8,529,390
26
2011-12-16T03:23:23Z
8,529,412
28
2011-12-16T03:27:11Z
[ "python", "subprocess" ]
Is there a variant of `subprocess.call` that can run the command without printing to standard out, or a way to block out it's standard out messages?
Yes. Redirect its `stdout` to `/dev/null`. ``` process = subprocess.call(["my", "command"], stdout=open(os.devnull, 'wb')) ```
is there a quiet version of subprocess.call?
8,529,390
26
2011-12-16T03:23:23Z
8,529,600
8
2011-12-16T03:57:26Z
[ "python", "subprocess" ]
Is there a variant of `subprocess.call` that can run the command without printing to standard out, or a way to block out it's standard out messages?
Note, often that kind of chatter is on stderr, so you might want to silence that too. Here's my example: ``` import os from subprocess import check_call with open(os.devnull, 'w') as shutup: return_code = check_call(args, stdout=shutup, stderr=shutup) ```
is there a quiet version of subprocess.call?
8,529,390
26
2011-12-16T03:23:23Z
8,529,636
9
2011-12-16T04:04:15Z
[ "python", "subprocess" ]
Is there a variant of `subprocess.call` that can run the command without printing to standard out, or a way to block out it's standard out messages?
`subprocess.call` also accept stdin/stdout/stderr redirections: ``` process = subprocess.call(["my", "command"], stdout=open(os.devnull, 'wb')) ```
Most Pythonic Way to Split an Array by Repeating Elements
8,530,210
13
2011-12-16T05:33:46Z
8,530,296
13
2011-12-16T05:46:13Z
[ "python" ]
I have a list of items that I want to split based on a delimiter. I want all delimiters to be removed and the list to be split when a **delimiter occurs twice**. For example, if the delimiter is `'X'`, then the following list: ``` ['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g'] ``` Would turn into: ``` [['a'...
I don't think there's going to be a nice, elegant solution to this (I'd love to be proven wrong of course) so I would suggest something straightforward: ``` def nSplit(lst, delim, count=2): output = [[]] delimCount = 0 for item in lst: if item == delim: delimCount += 1 elif deli...
Remove ' from python list
8,530,925
2
2011-12-16T07:10:38Z
8,531,073
8
2011-12-16T07:25:05Z
[ "python", "list" ]
I have a list, that looks like this in python: ``` ex = ['(1..3),(5..8)'] ``` I need to get out the list like this: ``` [(1, 3), (5, 8)] ``` I tried using the replace function, but could only get like `['(1, 3), (5,8)']` and could not lose the `'` marks. Hope someone can help me. Thanks
``` import ast ex = ['(1..3),(5..8)'] list(ast.literal_eval(ex[0].replace('..', ','))) # returns [(1, 3), (5, 8)] ``` `ast.literal_eval` is safe. `eval` is not. For your updated question: ``` ex2 = ['(2..5)', '(7..10)'] [ast.literal_eval(a.replace('..', ',')) for a in ex2] # returns [(2, 5), (7, 10)] ```
Opposite of os.path.commonprefix
8,531,275
9
2011-12-16T07:49:48Z
8,531,308
12
2011-12-16T07:54:09Z
[ "python", "path" ]
What's the opposite of os.path.commonprefix? I have two paths and I want the non-overlapping path, e.g.: ``` >>> p1 = '/Users/foo/something' >>> p2 = '/Users/foo/something/else/etc' >>> print somefunction([p1, p2]) '/else/etc' ```
``` >>> p1 = '/Users/foo/something' >>> p2 = '/Users/foo/something/else/etc' >>> os.path.relpath(p2, start=p1) 'else/etc' ``` The correct answer is `'else/etc'` and not `'/else/etc'`. If you are in p1 and type `cd /else/etc` you wouldn't land in p2, but somewhere else. `os.path.join(p1, 'else/etc')` gives you p2 aga...
'easy_install -U cython' fails complaining about vcvarsall.bat and -mno-cygwin
8,531,983
11
2011-12-16T09:12:28Z
8,532,579
15
2011-12-16T10:05:14Z
[ "python", "windows", "mingw", "cython", "easy-install" ]
Under Windows, it seems that `easy_install` with a C dependency isn't very easy. ## Attempt 1 - `vcvarsall.bat` errors I am installing `cython` under Windows7, with `MinGw`; I modified Windows7's `PATH` to include `C:\MinGw\bin`. At this point, I tried to `easy_install -U cython`, and got... ``` C:\Users\mike_pennin...
After more some googling, I found guidance that recommended removing `-mno-cygwin` from `C:\Python27\Lib\distutils\cygwinccompiler.py` because of a [distutils bug](http://bugs.python.org/issue12641). Removing `-mno-cygwin` from `C:\Python27\Lib\distutils\cygwinccompiler.py` got `cython` to compile.
Python dictionary : TypeError: unhashable type: 'list'
8,532,146
14
2011-12-16T09:28:16Z
8,532,168
16
2011-12-16T09:30:40Z
[ "python", "hash", "dictionary" ]
I'm having troubles in populating a python dictionary starting from another dictionary. Let's assume that the "source" dictionary has string as keys and has a list of custom objects per value. I'm creating my target dictionary exactly as I have been creating my "source" dictionary how is it possible this is not worki...
The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type. Your error says that you try to use a list as dictionary key, **you'll have to change your list into tuples** if you want to put them as keys in your di...
Scrapy - logging to file and stdout simultaneously, with spider names
8,532,252
10
2011-12-16T09:37:41Z
8,532,689
17
2011-12-16T10:13:02Z
[ "python", "web-crawler", "scrapy" ]
I've decided to use the Python logging module because the messages generated by Twisted on std error is too long, and I want to `INFO` level meaningful messages such as those generated by the `StatsCollector` to be written on a separate log file while maintaining the on screen messages. ``` from twisted.python import...
You want to use the [`ScrapyFileLogObserver`](https://github.com/scrapy/scrapy/blob/master/scrapy/log.py#L37). ``` import logging from scrapy.log import ScrapyFileLogObserver logfile = open('testlog.log', 'w') log_observer = ScrapyFileLogObserver(logfile, level=logging.DEBUG) log_observer.start() ``` I'm glad you as...
Scrapy - logging to file and stdout simultaneously, with spider names
8,532,252
10
2011-12-16T09:37:41Z
9,446,470
8
2012-02-25T17:55:42Z
[ "python", "web-crawler", "scrapy" ]
I've decided to use the Python logging module because the messages generated by Twisted on std error is too long, and I want to `INFO` level meaningful messages such as those generated by the `StatsCollector` to be written on a separate log file while maintaining the on screen messages. ``` from twisted.python import...
It is very easy to redirect output using: `scrapy some-scrapy's-args 2>&1 | tee -a logname` This way, all what scrapy ouputs into stdout and stderr, will be redirected to a logname file and also, prited to the screen.
Python multiprocessing.Pool: when to use apply, apply_async or map?
8,533,318
121
2011-12-16T11:08:12Z
8,533,626
192
2011-12-16T11:36:50Z
[ "python", "multithreading", "concurrency", "multiprocessing" ]
I have not seen clear examples with use-cases for [Pool.apply](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply), [Pool.apply\_async](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply_async) and [Pool.map](https:/...
Back in the old days of Python, to call a function with arbitrary arguments, you would use `apply`: ``` apply(f,args,kwargs) ``` `apply` still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays, ``` f(*args,**kwargs) ``` is preferred. The `multiprocessing.Pool` modules tries to p...
Python multiprocessing.Pool: when to use apply, apply_async or map?
8,533,318
121
2011-12-16T11:08:12Z
22,485,521
34
2014-03-18T16:35:18Z
[ "python", "multithreading", "concurrency", "multiprocessing" ]
I have not seen clear examples with use-cases for [Pool.apply](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply), [Pool.apply\_async](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply_async) and [Pool.map](https:/...
Regarding `apply` vs `map`: `pool.apply(f, args)`: `f` is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run `f(args)`. `pool.map(f, iterable)`: This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advanta...
Pypy JIT gives a speed boost even if a script is run only once?
8,535,310
2
2011-12-16T14:05:59Z
8,535,357
10
2011-12-16T14:09:44Z
[ "python", "pypy" ]
I have a script that loads several hundred images, resize them and then composes a bigger image Every time is started with a different set of images: ``` python myscript.py imageFolder/ ``` Running it in a virtualenv with Pypy doesn't show a noticeable speed gain (all run in ~8 seconds with mprofile, with the pypy v...
From your description it appears that `PIL.resize()` is the dominant operation. That function is written in C and not in Python. Therefore, I doubt you can expect PyPy to make much of a difference to your script. If you're looking to speed things up, you could consider parallelizing the loading and resizing of the ima...
Iterate through tuple values python
8,535,662
2
2011-12-16T14:36:33Z
8,535,690
10
2011-12-16T14:38:36Z
[ "python", "tuples", "loops" ]
I have a list like `[(1, 3), (6, 7)]` and a string `'AABBCCDD'` I need to get the result `AABCD`. I know I can get the integers form the tuple with `nameOfTuple[0][0]` yielding 1. I also know that I can get the chars form the string with `nameOfString[0]` yielding A. My question is, how do I iterate throu...
``` In [1]: l = [(1, 3), (6, 7)] In [2]: s = 'AABBCCDD' In [3]: ''.join(s[start-1:end] for (start,end) in l) Out[3]: 'AABCD' ``` Here, pairs of indices from `l` are assigned to `start` and `end`, one pair at a time. The relevant portion of the string is then extracted using `s[start-1:end]`, yielding a sequence of s...
Array initialization in Python
8,535,672
6
2011-12-16T14:37:43Z
8,535,714
13
2011-12-16T14:40:20Z
[ "python", "arrays", "algorithm", "initialization" ]
I want to initialize an array with 10 values starting at X and incrementing by Y. I cannot directly use `range()` as it requires to give the maximum value, not the number of values. I can do this in a loop, as follows: ``` a = [] v = X for i in range(10): a.append(v) v = v + Y ``` But I'm certain there's a c...
``` >>> x = 2 >>> y = 3 >>> [i*y + x for i in range(10)] [2, 5, 8, 11, 14, 17, 20, 23, 26, 29] ```
Array initialization in Python
8,535,672
6
2011-12-16T14:37:43Z
8,535,715
8
2011-12-16T14:40:22Z
[ "python", "arrays", "algorithm", "initialization" ]
I want to initialize an array with 10 values starting at X and incrementing by Y. I cannot directly use `range()` as it requires to give the maximum value, not the number of values. I can do this in a loop, as follows: ``` a = [] v = X for i in range(10): a.append(v) v = v + Y ``` But I'm certain there's a c...
You can use this: ``` >>> x = 3 >>> y = 4 >>> range(x, x+10*y, y) [3, 7, 11, 15, 19, 23, 27, 31, 35, 39] ```
How do I create multiple checkboxes from a list in a for loop in python tkinter
8,536,518
3
2011-12-16T15:42:55Z
8,537,280
7
2011-12-16T16:41:49Z
[ "python", "checkbox", "for-loop", "tkinter" ]
I have a list of variable length and want to create a checkbox (with python TKinter) for each entry in the list (each entry corresponds to a machine which should be turned on or off with the checkbox -> change the value in the dictionary). ``` print enable {'ID1050': 0, 'ID1106': 0, 'ID1104': 0, 'ID1102': 0} ``` (exa...
The "variable" passed to each checkbutton must be an instance of Tkinter Variable - as it is, it is just the value "0" that is passed, and this causes the missbehavior. You can create the Tkinter.Variable instances on he same for loop you create the checkbuttons - just change your code to: ``` for machine in enable: ...
Is there a django template equivalent of the python string multiplication function?
8,536,757
3
2011-12-16T16:01:12Z
8,538,890
12
2011-12-16T19:01:20Z
[ "python", "django", "django-templates", "django-template-filters" ]
In python I can write `"Hello" * 5` and get ``` HelloHelloHelloHelloHello ``` Is there a way to do this in a django template? Something like `{% multiply "Hello" 5 %}` or as a filter `{% "Hello"|multiply:"5" %}` Or maybe a "repeat" loop control? Something like: ``` {% repeat 5 %} Hello {% endrepeat %} ``` I can wr...
Here's another hack: ``` {% for x in ""|ljust:"100" %} Hello World! {% endfor %} ``` I'm using an empty string as the value here, and I repeat the thing 100x. You can also use a variable to determine the number of repeats with this hack :) just replace "100" with the variable. ``` {% for x in ""|ljust:repeat_cou...
Scrapy is following and scraping non-allowed links
8,537,687
5
2011-12-16T17:10:47Z
8,542,978
7
2011-12-17T06:09:42Z
[ "python", "screen-scraping", "scrapy", "web-crawler" ]
I have a CrawlSpider set up to following certain links and scrape a news magazine where the links to each issue follow the following URL scheme: <http://example.com/YYYY/DDDD/index.htm> where YYYY is the year and DDDD is the three or four digit issue number. I only want issues 928 onwards, and have my rules below. I ...
You need to pass `deny` arguments to `SgmlLinkExtractor` which collects links to `follow`. And you don't need to create so many `Rule`'s if they call one function `parse_item`. I would write your code as: ``` rules = ( Rule(SgmlLinkExtractor( allow = ('\d\d\d\d/(92[8-9]|9[3-9][0-9]|\d\d\d\d...
modify list element with list comprehension in python
8,537,824
6
2011-12-16T17:21:26Z
8,537,850
9
2011-12-16T17:24:21Z
[ "python", "list-comprehension" ]
folks, I want to modify list element with list comprehension. For example, if the element is negative, add 4 to it. Thus the list ``` a = [1, -2 , 2] ``` will be converted to ``` a = [1, 2, 2] ``` The following code works, but i am wondering if there is a better way to do it? Thanks. ``` for i in range(len(a)):...
``` a = [b + 4 if b < 0 else b for b in a] ```
What's the idiomatic syntax for prepending to a short python list?
8,537,916
235
2011-12-16T17:30:01Z
8,537,946
8
2011-12-16T17:32:48Z
[ "python", "list", "prepend" ]
`list.append()` is the obvious choice for adding to the end of a list. Here's a [reasonable explanation](http://mail.python.org/pipermail/tutor/2005-March/036803.html) for the missing `list.prepend()`. Assuming my list is short and performance concerns are negligible, is ``` list.insert(0, x) ``` or ``` list[0:0] = ...
The first one is certainly a lot clearer and expresses the intent much better: you only want to insert a single element, not a whole list.
What's the idiomatic syntax for prepending to a short python list?
8,537,916
235
2011-12-16T17:30:01Z
8,538,295
321
2011-12-16T18:08:26Z
[ "python", "list", "prepend" ]
`list.append()` is the obvious choice for adding to the end of a list. Here's a [reasonable explanation](http://mail.python.org/pipermail/tutor/2005-March/036803.html) for the missing `list.prepend()`. Assuming my list is short and performance concerns are negligible, is ``` list.insert(0, x) ``` or ``` list[0:0] = ...
The `s.insert(0, x)` form is the most common. Whenever you see it though, it may be time to consider using a [collections.deque](http://docs.python.org/library/collections.html#collections.deque) instead of a list.
What's the idiomatic syntax for prepending to a short python list?
8,537,916
235
2011-12-16T17:30:01Z
10,892,614
91
2012-06-05T06:25:16Z
[ "python", "list", "prepend" ]
`list.append()` is the obvious choice for adding to the end of a list. Here's a [reasonable explanation](http://mail.python.org/pipermail/tutor/2005-March/036803.html) for the missing `list.prepend()`. Assuming my list is short and performance concerns are negligible, is ``` list.insert(0, x) ``` or ``` list[0:0] = ...
If you can go the functional way, the following is pretty clear ``` new_list = [x] + your_list ``` Of course you haven't inserted `x` into `your_list`, rather you have created a new list with `x` preprended to it.
What's the idiomatic syntax for prepending to a short python list?
8,537,916
235
2011-12-16T17:30:01Z
28,828,172
23
2015-03-03T09:25:56Z
[ "python", "list", "prepend" ]
`list.append()` is the obvious choice for adding to the end of a list. Here's a [reasonable explanation](http://mail.python.org/pipermail/tutor/2005-March/036803.html) for the missing `list.prepend()`. Assuming my list is short and performance concerns are negligible, is ``` list.insert(0, x) ``` or ``` list[0:0] = ...
If someone finds this question like me, here are my performance tests of proposed methods: ``` Python 2.7.8 In [1]: %timeit ([1]*1000000).insert(0, 0) 100 loops, best of 3: 4.62 ms per loop In [2]: %timeit ([1]*1000000)[0:0] = [0] 100 loops, best of 3: 4.55 ms per loop In [3]: %timeit [0] + [1]*1000000 100 loops, b...
What's the idiomatic syntax for prepending to a short python list?
8,537,916
235
2011-12-16T17:30:01Z
30,673,383
15
2015-06-05T18:26:21Z
[ "python", "list", "prepend" ]
`list.append()` is the obvious choice for adding to the end of a list. Here's a [reasonable explanation](http://mail.python.org/pipermail/tutor/2005-March/036803.html) for the missing `list.prepend()`. Assuming my list is short and performance concerns are negligible, is ``` list.insert(0, x) ``` or ``` list[0:0] = ...
> **What's the idiomatic syntax for prepending to a short python list?** # `list.insert` The `list.insert` can be used this way. ``` list.insert(0, x) ``` But this is inefficient, because in Python, a `list` is an array of pointers, and Python must now take every pointer in the list and move it down one to insert t...
python's glob only returning the first result
8,538,564
9
2011-12-16T18:32:44Z
8,538,672
12
2011-12-16T18:43:07Z
[ "python" ]
I am really stumped on this one. I have a simple python wrapper which looks something like this: ``` import glob for found in glob.glob(filename): if not os.path.isdir(found): my_module.do_stuff(found) ``` where `filename` has been read in from `sys.argv`. When I try `glob` in an interactive shell, or a hell...
The shell is expanding the glob before your Python script sees it. Therefore your Python script sees the first full filename that matches the glob in `sys.argv[1]`, passes that to `glob()`, and of course it only matches one file. Either quote the argument in the shell with single quotes so that the shell does not expa...
Return min/max of multidimensional in Python?
8,538,714
5
2011-12-16T18:46:12Z
8,538,797
13
2011-12-16T18:53:37Z
[ "python", "list", "sorting", "max", "min" ]
I have a list in the form of ``` [ [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] ... ] etc. ``` I want to return the minimal c value and the maximal c+f value. Is this possible?
For the minimum `c`: ``` min(c for (a,b,c),(d,e,f) in your_list) ``` For the maximum `c+f` ``` max(c+f for (a,b,c),(d,e,f) in your_list) ``` Example: ``` >>> your_list = [[[1,2,3],[4,5,6]], [[0,1,2],[3,4,5]], [[2,3,4],[5,6,7]]] >>> min(c for (a,b,c),(d,e,f) in lst) 2 >>> max(c+f for (a,b,c),(d,e,f) in lst) 11 ```
sklearn (scikit-learn) logistic regression package -- set trained coefficients for classification.
8,539,141
3
2011-12-16T19:23:58Z
8,539,745
7
2011-12-16T20:29:37Z
[ "python", "machine-learning", "scikits", "scikit-learn" ]
So I read the scikit-learn package webpate: <http://scikit-learn.sourceforge.net/dev/modules/generated/sklearn.linear_model.LogisticRegression.html> I can use logistic regression to fit the data, and after I obtain an instance of LogisticRegression, I can use it to classify new data points. So far so good. Is there ...
The coefficients are attributes of the estimator object--that you created when you instantiated the Logistic Regression class--so you can access them in the normal python way: ``` >>> import numpy as NP >>> from sklearn import datasets >>> from sklearn import datasets as DS >>> digits = DS.load_digits() >>> D = digits...
Private/Public Encryption in Python with Standard Library
8,539,441
15
2011-12-16T19:56:40Z
8,539,470
23
2011-12-16T19:59:53Z
[ "python", "python-3.x", "encryption-asymmetric" ]
Is there a module that has my searching has been unable to discover that would allow writing code like the following? The reason for wanting to write code like this is unimportant. All I am after is some code that has a simple API to generate public and private byte keys and to easily encode and decode data with those ...
Public key encryption is not in the standard library. There are some third party libraries on [PyPi](http://pypi.python.org/) for it though: * [PyCrypto](http://packages.python.org/pycrypto/) * [RSA Python](http://stuvel.eu/rsa) If you're interested in the math behind it, Python makes it easy to experiment: ``` code...
How to easily extract ID from iTunes URL using Python
8,541,783
4
2011-12-17T00:43:18Z
8,541,824
7
2011-12-17T00:54:10Z
[ "python", "regex" ]
iTunes URLs look like the following: ``` http://itunes.apple.com/us/album/break-of-dawn/id472335316?ign-mpt=uo%3D http://itunes.apple.com/us/app/monopoly-here-now-the-world/id299110947?mt=8 http://itunes.apple.com/es/app/revista-/id397781759?mt=8%3Futm_so%3Dtwitter http://itunes.apple.com/app/id426698291&mt=8" http://...
``` import re def get_id(toParse): return re.search('id(\d+)', toParse).groups()[0] ``` I'll let you figure out error handling...
django-admin: Add extra row with totals
8,541,956
26
2011-12-17T01:34:11Z
8,745,026
18
2012-01-05T15:27:25Z
[ "python", "django", "django-admin", "django-views", "django-1.2" ]
I'm using the standard django admin module to display a list of rows. One of the columns is a numerical field. I'd like to display an extra 'totals' row that has most of the columns as blank, except for the numerical column, which should be the total for all of the objects. Is there a simple way to do this within the ...
I think the Django way to do this is to override the ChangeList class which django's admin app uses. You do this in django 1.2 by calling the `get_changelist` method in your admin class. In my example: `TomatoAdmin` calls this method returning a custom ChangeList calss. This ChangeList class: `MyChangeList` simply adds...
django-admin: Add extra row with totals
8,541,956
26
2011-12-17T01:34:11Z
8,758,854
27
2012-01-06T13:53:09Z
[ "python", "django", "django-admin", "django-views", "django-1.2" ]
I'm using the standard django admin module to display a list of rows. One of the columns is a numerical field. I'd like to display an extra 'totals' row that has most of the columns as blank, except for the numerical column, which should be the total for all of the objects. Is there a simple way to do this within the ...
Yes, you can do it in many ways, but most django-ist way to do is: First override the default django listing view... And give a new template file directory ``` ModelAdmin.changelist_view(self, request, extra_context=None) ``` Like: ``` class MyModelAdmin(admin.ModelAdmin): # A template for a very customized ch...
Why is a line in this python function necessary? (memoized recursion)
8,542,087
12
2011-12-17T02:13:20Z
8,542,106
12
2011-12-17T02:17:07Z
[ "python", "recursion", "decorator" ]
I got the following code snippet from Peter Norvig's website; it's a decorator to enable memoization on function calls (caching prior calls to the function to change an exponential recursion into a simple dynamic program). ``` def memo(f): table = {} def fmemo(*args): if args not in table: ...
Since functions are objects just like anything else, you can set attributes on them. See: ``` >>> def foo(): pass >>> foo.x = 1 >>> foo.x 1 ``` The second-to-line sets the internal cache of values as an attribute on the function object, thus exposing it. This means that you can take a memoised function and fiddle wit...
Object does not support item assignment error
8,542,343
24
2011-12-17T03:27:26Z
8,542,369
34
2011-12-17T03:34:16Z
[ "python", "django", "loops", "dictionary" ]
In my `views.py` I assign values before saving the form. I used to do it the following way: ``` projectForm.lat = session_results['lat'] projectForm.lng = session_results['lng'] ``` Now, since the list of variables got a bit long, I wanted to loop over `session_results` with the following loop (as described by Adam [...
The error seems clear: model objects do not support item assignment. `MyModel.objects.latest('id')['foo'] = 'bar'` will throw this same error. It's a little confusing that your model instance is called `projectForm`... To reproduce your first block of code in a loop, you need to use `setattr` ``` for k,v in session_...
passing strings to ctypes functions under Python 3.x
8,542,679
10
2011-12-17T04:54:31Z
8,544,421
14
2011-12-17T11:31:27Z
[ "python", "python-3.x", "ctypes" ]
``` from ctypes import * msvcrt = cdll.msvcrt message_string = "Hello world!\n" msvcrt.printf("Testing: %s", message_string) ``` I'm going through a book about Ctypes and Python but the example code just doesn't work. Could it be because the book was written for python 2 whereas I am on Python 3? printf is only prin...
The C `printf` function is expecting byte strings. In Python 3 all strings are unicode so you'll have to encode to bytes: ``` >>> msvcrt.printf("Testing: %s".encode('ascii'), message_string.encode('ascii')) Testing: Hello world! 22 ``` If you have any non-ascii characters then encode to the relevant windows codepage ...
Change datetime to Unix time stamp in Python
8,542,723
14
2011-12-17T05:04:29Z
8,542,762
13
2011-12-17T05:15:22Z
[ "python", "unix", "datetime", "time", "timestamp" ]
Please help me to change datetime object (for example: `2011-12-17 11:31:00-05:00`) (including timezone) to Unix timestamp (like function time.time() in Python).
This will work with Linux (glibc) at least (and isn't mentioned in the Python documentation, though it is in the Linux strftime man page): ``` #!/usr/bin/env python import datetime now = datetime.datetime.now() utc_now = datetime.datetime.utcnow() ts = now.strftime("%s") utc_ts = utc_now.strftime("%s") p...
Change datetime to Unix time stamp in Python
8,542,723
14
2011-12-17T05:04:29Z
12,011,693
11
2012-08-17T19:01:42Z
[ "python", "unix", "datetime", "time", "timestamp" ]
Please help me to change datetime object (for example: `2011-12-17 11:31:00-05:00`) (including timezone) to Unix timestamp (like function time.time() in Python).
Another way is: ``` import calendar from datetime import datetime d = datetime.utcnow() timestamp=calendar.timegm(d.utctimetuple()) ``` Timestamp is the unix timestamp which shows the same date with datetime object d.
Change datetime to Unix time stamp in Python
8,542,723
14
2011-12-17T05:04:29Z
18,180,207
7
2013-08-12T05:39:15Z
[ "python", "unix", "datetime", "time", "timestamp" ]
Please help me to change datetime object (for example: `2011-12-17 11:31:00-05:00`) (including timezone) to Unix timestamp (like function time.time() in Python).
``` import time import datetime dtime = datetime.datetime.now() ans_time = time.mktime(dtime.timetuple()) ```
How can I print all arguments passed to a python script?
8,542,725
3
2011-12-17T05:05:38Z
8,542,731
14
2011-12-17T05:08:22Z
[ "python" ]
How can I print all arguments passed to a python script? This is what I was trying: ``` #!/usr/bin/python print(sys.argv[1:]); ``` **update** How can I save them to a file? ``` #!/usr/bin/python import sys print sys.argv[1:] file = open("/tmp/test.txt", "w") file.write(sys.argv[1:]) ``` I get ``` TypeError: expe...
You'll need to `import sys` for that to work. ``` #!/usr/bin/python import sys print sys.argv[1:] ``` --- **Example** ``` :/tmp% cat foo.py #!/usr/bin/python import sys print (sys.argv[1:]); :/tmp% python foo.py 'hello world' arg3 arg4 arg5 ['hello world', 'arg3', 'arg4', 'arg5'] ```
Counting passed seconds
8,543,725
2
2011-12-17T09:08:01Z
8,543,754
9
2011-12-17T09:14:37Z
[ "python", "pys60" ]
How can we count the number of seconds passed since the start of the day 0.00 ? Is there a module function or do we have to do it ourselves?
``` from datetime import datetime, time now = datetime.now() beginning_of_day = datetime.combine(now.date(), time(0)) print (now - beginning_of_day).seconds ``` See docs for `datetime` module [here](http://docs.python.org/library/datetime.html).
how to correctly modify the iterator of a loop in python from within the loop
8,544,559
6
2011-12-17T11:58:20Z
8,544,571
7
2011-12-17T12:00:01Z
[ "python", "loops", "iterator" ]
what I basically need is to check every element of a list and if some criteria fit I want to remove it from the list. So for example let's say that list=['a','b','c','d','e'] I basically want to write (in principle and not the actual code I try to implement) If an element of the list is 'b' or 'c' remove it from th...
The easier way is to use a copy of the list - it can be done with a slice that extends "from the beginning" to the "end" of the list, like this: ``` for s in list[:]: if s=='b' or s=='c': list.remove(s) ``` You have consiered this, and this is simple enough to be in yoir code, unless this list is really b...
How to make an menu bar (system tray) app for OSX in Python?
8,544,853
17
2011-12-17T12:50:02Z
8,546,218
11
2011-12-17T16:39:29Z
[ "python", "osx", "menubar" ]
After having spent quite some time looking at ways to an app for the menu bar we're close to admit defeat. We are basically just looking for an example/pointer on how to create an app that will put itself in the menu bar (the small icons next to the clock), and have a menu. Nothing fancy at all. It feels like somethi...
wxPython won't be able to add a taskbar item. You can do this by instead using PyObjC like so: ``` from AppKit import NSStatusBar status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(-1) #NSVariableStatusItemLength status_item.setImage_(<NSImage instance to status icon>) ``` Just refer to the NSStatusIte...
How to make an menu bar (system tray) app for OSX in Python?
8,544,853
17
2011-12-17T12:50:02Z
17,984,647
17
2013-08-01T03:11:20Z
[ "python", "osx", "menubar" ]
After having spent quite some time looking at ways to an app for the menu bar we're close to admit defeat. We are basically just looking for an example/pointer on how to create an app that will put itself in the menu bar (the small icons next to the clock), and have a menu. Nothing fancy at all. It feels like somethi...
An option would be to use [`rumps`](https://github.com/jaredks/rumps) which provides a level of abstraction on top of PyObjC. I wrote it specifically for quickly generating these types of simple status bar apps. I hope that this could help a few people out there looking for a simple, semantic solution! A short exampl...
Dynamically mixin a base class to an instance in Python
8,544,983
17
2011-12-17T13:11:01Z
8,545,134
22
2011-12-17T13:39:50Z
[ "python", "oop", "mixins" ]
Is it possible to add a base class to an object instance (not a class!) at runtime? Something along the lines of how `Object#extend` works in Ruby: ``` class Gentleman(object): def introduce_self(self): return "Hello, my name is %s" % self.name class Person(object): def __init__(self, name): self.name = n...
This dynamically defines a new class `GentlePerson`, and reassigns `p`'s class to it: ``` class Gentleman(object): def introduce_self(self): return "Hello, my name is %s" % self.name class Person(object): def __init__(self, name): self.name = name p = Person("John") p.__class__ = type('GentlePerson',(Per...
Python concat string with list
8,546,245
20
2011-12-17T16:42:42Z
8,546,259
11
2011-12-17T16:44:58Z
[ "python", "list" ]
I wanted to build a string from a list. I used the string.join() command, but if I have : ``` ['hello', 'good', 'morning'] ``` I get : `hellogoodmorning` Is there a method that allows me to put a space between every word ? (without the need to write a for loop) kind regards.
``` >>> ' '.join(['hello', 'good', 'morning']) 'hello good morning' ``` The standard and best way to join a list of strings. I can think of nothing better than this.
Python concat string with list
8,546,245
20
2011-12-17T16:42:42Z
8,546,271
34
2011-12-17T16:45:46Z
[ "python", "list" ]
I wanted to build a string from a list. I used the string.join() command, but if I have : ``` ['hello', 'good', 'morning'] ``` I get : `hellogoodmorning` Is there a method that allows me to put a space between every word ? (without the need to write a for loop) kind regards.
All you need to do is add the space in front of join. ``` ' '.join(list) ```
Why does this socket connection only allow 1 send and receive?
8,546,870
4
2011-12-17T18:16:16Z
8,546,895
8
2011-12-17T18:19:46Z
[ "python", "sockets", "tcp", "socketserver", "broken-pipe" ]
**Background** I have a simple socket server setup that I am trying to allow simultaneous connections to and echo back the data. The client side launches several threads each making its own connection to the server. This works fine for the socket.send() call, but all subsequent calls cause either a "Connection reset ...
When you return from `handle` the socket is closed. Use a while loop and return from `handle` only when `self.data == ''`. `recv` returns zero bytes when the client closes the connection. Also don't `strip()` the result until after testing the return value or you could get a false close. Finally, use `ThreadingTCPServe...
Google Calendar API v3 - How to obtain a refresh token (Python)
8,546,907
14
2011-12-17T18:21:20Z
8,548,319
17
2011-12-17T22:19:58Z
[ "python", "google-calendar", "google-api-python-client" ]
I am trying to write a Django app which creates events in a specific Google calendar. So far I have been successful. There is only a little problem: **I don't know how to obtain a refresh token with the google python client.** The result is that after my token expires the app does not work and I have to create a new ...
I don't know how to do this with the Python Client or the Calendar API (I'm just using a ruby OAuth2 library for access to the Contacts API), but I found I needed to request "offline" access from the user. This is done by adding the an "access\_type" parameter with the value "offline" to the authorization url (the one...
Google Calendar API v3 - How to obtain a refresh token (Python)
8,546,907
14
2011-12-17T18:21:20Z
14,288,818
11
2013-01-12T00:24:18Z
[ "python", "google-calendar", "google-api-python-client" ]
I am trying to write a Django app which creates events in a specific Google calendar. So far I have been successful. There is only a little problem: **I don't know how to obtain a refresh token with the google python client.** The result is that after my token expires the app does not work and I have to create a new ...
So if you've already accepted consent without setting `access_type='offline'`, you need to force the user to consent to your app with offline access by also passing `approval_prompt='force'`. ``` self.flow = OAuth2WebServerFlow( client_id=self.client_id, client_secret=self.client_secret, scope=self.SCOPE, ...
Converting PIL image to MIMEImage
8,547,625
4
2011-12-17T20:11:36Z
8,547,691
7
2011-12-17T20:24:04Z
[ "python", "email", "python-imaging-library" ]
I'd like to create an image using PIL and be able to email it without having to save it to disk. This is what works, but involves saving to disk: ``` from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() im = Image.new("RGB", (200, 200)) with open("tempimg.jpg"...
`im.tostring` returns raw image data but you need to pass whole image file data to `MIMEImage`, so use [StringIO](http://docs.python.org/library/stringio.html) module to save the image to memory and use that data: ``` from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from PIL import...
Why does "pip install" raise a SyntaxError?
8,548,030
67
2011-12-17T21:23:32Z
8,548,165
88
2011-12-17T21:51:27Z
[ "python", "pip" ]
I'm trying to use pip to install a package. I try to run `pip install` from the Python shell, but I get a `SyntaxError`. Why do I get this error? How do I use pip to install the package? ``` >>> pip install selenium ^ SyntaxError: invalid syntax ```
pip is run from the command line, not the Python interpreter. It is a program that **installs** modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do `import selenium`. The Python shell is not a command line, it is an interactive interpreter. You type P...