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
Uploading multiple files with Flask
11,817,182
15
2012-08-05T14:23:46Z
11,817,318
29
2012-08-05T14:41:55Z
[ "python", "file-upload", "flask" ]
Is there a way to receive multiple uploaded files with Flask? I've tried the following: ``` <form method="POST" enctype="multipart/form-data" action="/upload"> <input type="file" name="file[]" multiple=""> <input type="submit" value="add"> </form> ``` And then printed the contents of `request.files['file']`: ```...
You can use method [getlist](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict.getlist) of [flask.request.files](http://flask.pocoo.org/docs/api/#flask.Request.files), for example: ``` @app.route("/upload", methods=["POST"]) def upload(): uploaded_files = flask.request.files.getlist(...
How to deal with unicode string in URL in python3?
11,818,362
12
2012-08-05T17:05:31Z
11,818,476
10
2012-08-05T17:21:00Z
[ "python", "unicode", "python-3.x" ]
``` # -*- coding: utf-8 -*- # Python3 import urllib import urllib.request as url_req opener = url_req.build_opener() url='http://zh.wikipedia.org/wiki/'+"毛泽东" opener.open(url).read() # opener.open(url.encode("utf-8")).read() # # doesn't work either ``` When I run it, it complains that: `UnicodeEncodeError: 'as...
The fantastic [requests](http://docs.python-requests.org/en/latest/index.html) library does this for you out of the box: ``` >>> url='http://zh.wikipedia.org/wiki/'+"毛泽东" >>> import requests >>> r = requests.get(url) >>> len(r.content) 818747 ```
How to deal with unicode string in URL in python3?
11,818,362
12
2012-08-05T17:05:31Z
11,818,515
16
2012-08-05T17:26:50Z
[ "python", "unicode", "python-3.x" ]
``` # -*- coding: utf-8 -*- # Python3 import urllib import urllib.request as url_req opener = url_req.build_opener() url='http://zh.wikipedia.org/wiki/'+"毛泽东" opener.open(url).read() # opener.open(url.encode("utf-8")).read() # # doesn't work either ``` When I run it, it complains that: `UnicodeEncodeError: 'as...
You could use [urllib.parse.quote()](http://docs.python.org/dev/library/urllib.parse.html#urllib.parse.quote) to encode the path section of URL. ``` #!/usr/bin/env python3 from urllib.parse import quote from urllib.request import urlopen url = 'http://zh.wikipedia.org/wiki/' + quote("毛泽东") content = urlopen(u...
regex - match character which is not escaped
11,819,059
2
2012-08-05T18:41:46Z
11,819,111
10
2012-08-05T18:49:10Z
[ "python", "regex" ]
I'm trying to make a regex to match unescaped comma characters in a string. The rule I'm looking for is "A comma not preceded by an even number of backslashes". Test cases: ``` True abc,abc False abc\,abc True abc\\,abc False abc\\\,abc True abc\\\\,abc False abc\\\\\,abc ``` I tried to use a negativ...
Try this regex: `(?<!\\)(?:\\\\)*,` Explanation: ``` (?<!\\) Matches if the preceding character is not a backslash (?:\\\\)* Matches any number of occurrences of two backslashes , Matches a comma ```
Generate a random number in that falls into a multiple range
11,819,265
2
2012-08-05T19:10:21Z
11,819,281
9
2012-08-05T19:12:24Z
[ "python", "random" ]
How would I go about generating a random integer in python that ***is*** random but falls into a multiplication table *(times table)* range per se and is determined by a value I specify? **Example.** Say i want to generate a random number between 10 and 100 but it should be a multiple of 7. Possible return values coul...
Why not just generate a multiplier of `fac` that gives you a number between your bounds? ``` import math import random def rand_multiple(fac, a, b): """Returns a random multiple of fac between a and b.""" min_multi = math.ceil(float(a) / fac) max_multi = math.floor(float(b) / fac) return fac * random....
Replace default handler of Python logger
11,820,338
16
2012-08-05T21:48:14Z
11,821,510
28
2012-08-06T01:12:25Z
[ "python", "logging" ]
I've got the following code running on each request of a wsgi (web2py) application: ``` import logging, logging.handlers from logging import StreamHandler, Formatter def get_configured_logger(name): logger = logging.getLogger(name) if (len(logger.handlers) == 0): # This logger has no handlers, so we...
Perhaps the following example will help. Basically you can either remove the handlers of the logger you'd like to disable, or don't propagate with the logger you are logging from. ``` $ cat testlog.py import logging logging.basicConfig(filename='foo', level=logging.DEBUG) root_logger = logging.getLogger() root_logger....
Inconsistent SignatureDoesNotMatch Amazon S3 with django-pipeline, s3boto and storages
11,820,566
2
2012-08-05T22:23:48Z
12,262,106
11
2012-09-04T10:59:38Z
[ "python", "django", "amazon-s3", "boto", "django-storage" ]
I have 2 files compiled by django-pipeline along with s3boto: master.css and master.js. They are set to "Public" in my buckets. However, when I access them, sometimes master.css is served, sometimes it errs with SignatureDoesNotMatch. The same with master.js. This doesn't happen on Chrome. What could I be missing? **E...
Happened to me too... Took a few hours to find, but I figured it out eventually. Turns out that if the right signature is : ssCNsAOxLf5vA80ldAI3M0CU2%2Bw= Then AWS will NOT accept: ssCNsAOxLf5vA80ldAI3M0CU2+w= Where the only difference is the translation of %2B to '+'. S3BotoStorage actually yields it correctly bu...
PIL doesn't recognize jpeg library under Mac OS
11,820,649
5
2012-08-05T22:37:48Z
11,820,698
8
2012-08-05T22:44:21Z
[ "python", "osx", "python-imaging-library" ]
Scripts like that: ``` from PIL import Image, ImageOps img = Image.open('1.JPG') thumb = ImageOps.fit(img, (200,200) , Image.ANTIALIAS, (0.5, 0.5)) ``` cause this IOError: ``` Traceback (most recent call last): (...) File "/Library/Python/2.7/site-packages/PIL/Image.py", line 385, in _getdecoder raise IOErro...
I don't understand why, but reinstalling PIL fixed the issue: ``` sudo pip uninstall pil sudo pip install pil ```
Failing to understand recursion
11,820,789
3
2012-08-05T22:57:07Z
11,820,826
8
2012-08-05T23:03:42Z
[ "python" ]
New to Python and trying to understand recursion. I'm trying to make a program that prints out the number of times string 'key' is found in string 'target' using a recursive function, as in Problem 1 of the MIT intro course [problem set](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introd...
By recursion you want to split the problem into smaller sub-problems that you can solve independently and then combine their solution together to get the final solution. In your case you can split the task in two parts: Checking where (if) first occurence of `key` exists and then counting recursively for the rest. Is...
Elegant way to store dictionary permanently with Python?
11,821,322
11
2012-08-06T00:28:21Z
11,821,343
29
2012-08-06T00:32:13Z
[ "python", "database", "json", "dictionary" ]
Currently expensively parsing a file, which generates a dictionary of ~400 key, value pairs, which is seldomly updated. Previously had a function which parsed the file, wrote it to a text file in dictionary syntax (ie. `dict = {'Adam': 'Room 430', 'Bob': 'Room 404'}`) etc, and copied and pasted it into another function...
Why not dump it to a JSON file, and then load it from there where you need it? ``` import json with open('my_dict.json', 'w') as f: json.dump(my_dict, f) # elsewhere... with open('my_dict.json') as f: my_dict = json.load(f) ``` Loading from JSON is fairly efficient. Another option would be to use [`pickle...
Elegant way to store dictionary permanently with Python?
11,821,322
11
2012-08-06T00:28:21Z
11,823,256
10
2012-08-06T06:11:05Z
[ "python", "database", "json", "dictionary" ]
Currently expensively parsing a file, which generates a dictionary of ~400 key, value pairs, which is seldomly updated. Previously had a function which parsed the file, wrote it to a text file in dictionary syntax (ie. `dict = {'Adam': 'Room 430', 'Bob': 'Room 404'}`) etc, and copied and pasted it into another function...
Why mess with all these serialization methods? It's already written to a file as a Python dict (although with the unfortunate name 'dict'). Change your program to write out the data with a better variable name - maybe 'data', or 'catalog', and save the file as a Python file, say data.py. Then you can just import the da...
Syntax error while trying to install Django
11,822,417
2
2012-08-06T03:58:14Z
11,822,443
8
2012-08-06T04:03:30Z
[ "python", "django", "installation" ]
I am brand new to Python, and have been trying to get the Django framework installed on my server. I can't seem to find an answer or even a hint in the right direction anywhere online for this issue. I have a VPS over at LiquidWeb and I am trying to install on that server. I've been following the Django installation g...
Wait, you're using Python 2.4?! [Django 1.4 dropped support for 2.4](https://docs.djangoproject.com/en/1.4/releases/1.4/). You'll have to upgrade Python to get it to work. If you're upgrading, you may as well use latest Python 2 version (2.7). The exact cause of the error is that the setup script uses the ternary cond...
Systrace | Android | No such file or directory
11,823,007
7
2012-08-06T05:38:55Z
11,851,028
12
2012-08-07T17:24:42Z
[ "android", "python", "android-sdk-tools" ]
I am unable to get systrace to work on my Mac. I am using a Galaxy Nexus running Jelly Beans. I have show traces enabled from the developer options. And in the terminal when I try to execute: ./systrace.py I get the following error message: ``` Traceback (most recent call last): File "./systrace.py", line 212, in <mod...
it looks like the script assumes adb is in your path. add the platform-tools sdk dir to your path and it should work.
Python code to automate desktop activities in windows
11,825,322
12
2012-08-06T09:06:53Z
11,827,165
12
2012-08-06T11:13:02Z
[ "python", "user-interface", "ui-automation" ]
I want to automate desktop activities in windows environment using python..can it be done?? If so please provide me the link(material).. examples will also be helpful..thanks in advance. update: desktop activities like taking control over mouse and keyboard tasks and if possible to access active windows properties.....
Have a look at [SIKULI](http://sikuli.org/). > Sikuli is a visual technology to automate and test graphical user > interfaces (GUI) using images (screenshots). SIKULI uses a very clever combination of taking screenshots, and embedding them into your python (it's [jython](http://www.jython.org/), actually) script. --...
PyCharm autocomplete, list of types
11,825,631
10
2012-08-06T09:29:47Z
11,825,632
11
2012-08-06T09:29:47Z
[ "python", "autocomplete", "casting", "pycharm", "heredoc" ]
How I can tell with `Docstring` to **PyCharm** that return type is the list of `SomeClass` instances? Tried out: `@rtype [SomeClass]`, but it acts only as `list`.
``` def do_something(): """ @rtype: list of SomeClass """ pass ``` Works well, interprets return value as list and autocompletes `SomeClass` methods when accessing `list` element.
pyside show / hide layouts
11,826,036
8
2012-08-06T09:56:14Z
11,826,600
9
2012-08-06T10:34:45Z
[ "python", "layout", "hide", "show", "pyside" ]
I'm trying to display one of two layouts depending on whether a checkbox is checked or not. Only using widgets I can do the following which works fine: (each widget in this example is a QLineEdit) ``` myCheckbox.stateChanged.connect(switchControls) def switchControls (self, state): if state == 2: self.wi...
Put the layouts into separate widgets. Now you're "only using widgets". Here's an example: ``` from PySide.QtCore import * from PySide.QtGui import * class MainWindow(QWidget): def __init__(self): QWidget.__init__(self) self.layout=QVBoxLayout() self.setLayout(self.layout) self...
ValueError: invalid literal for int() with base 16: '\x0e\xa3' Python
11,826,054
3
2012-08-06T09:57:04Z
11,826,089
9
2012-08-06T09:59:03Z
[ "python", "string", "tkinter", "decimal", "pyserial" ]
I get bytes from the serial port which represents the voltage on my PIC board. But I can't convert these bytes(strings) to decimal because I get the error message above. Here is the function(in fact, it's associated with tkinter button) ``` def channel8(): ser.write(chr(0xFF)) print "you have select channel8" ...
I think you should use [struct](http://docs.python.org/library/struct) module and unpack your binary data like this: ``` struct.unpack("h", x) ``` Because `int` is not really working with binary data, but with hexadecimal string like: `EF1D`. When your did `x=ser.read(2)` you received two bytes of binary data, there...
Django error in Heroku: "Please supply the ENGINE value"
11,826,326
7
2012-08-06T10:15:46Z
15,938,562
9
2013-04-10T23:55:36Z
[ "python", "django", "heroku" ]
I read and apply "Getting started with Django on Heroku" tutorial but ran into problem while syncing db: ``` raise ImproperlyConfigured("settings.DATABASES is improperly configured." django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. ``` I read ...
I ran into the same issue, but apparently for different reasons. In the Heroku docs at <https://devcenter.heroku.com/articles/django#prerequisites>, it says to add the following to `settings.py`: ``` DATABASES['default'] = dj_database_url.config() ``` You can pass in a parameter of: ``` DATABASES['default'] = dj_d...
Interleaving two numpy index arrays, one item from each array
11,827,100
12
2012-08-06T11:08:11Z
11,828,266
13
2012-08-06T12:25:41Z
[ "python", "arrays", "numpy", "vectorization" ]
I have two ordered numpy arrays and I want to interleave them so that I take one item from the first array, then another from the second, then back to the first - taking the next item that is larger than the one I just took from the second and so on. Those are actually arrays of indices to other arrays, and I'll be ok ...
### Vectorised solution (pedagogical style, easily understandable) We can vectorise this by augmenting the arrays with a discriminator index, such that `a` is tagged `0` and `b` is tagged `1`: ``` a_t = np.vstack((a, np.zeros_like(a))) b_t = np.vstack((b, np.ones_like(b))) ``` Now, let's combine and sort: ``` c = n...
Can we increase a lowercase character by one
11,827,226
5
2012-08-06T11:17:28Z
11,827,251
10
2012-08-06T11:19:10Z
[ "python" ]
If I am having ``` char = 'a' ``` how can I increase the value into 'b' and then into 'c' and so on.. I don't want to replace it or change it. Its much like ``` char = char + 1 ```
``` >>> chr(ord('a') + 1) 'b' ```
Can we increase a lowercase character by one
11,827,226
5
2012-08-06T11:17:28Z
11,827,332
8
2012-08-06T11:24:32Z
[ "python" ]
If I am having ``` char = 'a' ``` how can I increase the value into 'b' and then into 'c' and so on.. I don't want to replace it or change it. Its much like ``` char = char + 1 ```
You can make an incrementer translation like this. I've mapped 'z' back onto 'a' in this case ``` >>> from string import maketrans, ascii_lowercase >>> char_incrementer = maketrans(ascii_lowercase, ascii_lowercase[1:]+ascii_lowercase[0]) >>> 'a'.translate(char_incrementer) 'b' ``` you can just as easily apply it to a...
Checking for IP addresses
11,827,961
7
2012-08-06T12:07:05Z
11,828,000
11
2012-08-06T12:09:46Z
[ "python", "ip", "ipv6" ]
Are there any existing libraries to parse a string as an ipv4 or ipv6 address, or at least identify whether a string is an IP address (of either sort)?
Yes, there is `ipaddr` module, that can you help to check if a string is a IPv4/IPv6 address, and to detect its version. ``` import ipaddr import sys try: ip = ipaddr.IPAddress(sys.argv[1]) print '%s is a correct IP%s address.' % (ip, ip.version) except ValueError: print 'address/netmask is invalid: %s' % sy...
Checking for IP addresses
11,827,961
7
2012-08-06T12:07:05Z
11,828,014
7
2012-08-06T12:10:45Z
[ "python", "ip", "ipv6" ]
Are there any existing libraries to parse a string as an ipv4 or ipv6 address, or at least identify whether a string is an IP address (of either sort)?
for IPv4 You can use ``` socket.inet_aton(some_string) ``` if it throws an exception, `some_string` is not a valid ip address For IPv6, you can use: ``` socket.inet_pton(socket.AF_INET6, some_string) ``` again, it throws an exception if `some_string` is not a valid address
Differences between functools.partial and a similar lambda?
11,828,410
9
2012-08-06T12:36:08Z
11,828,489
7
2012-08-06T12:41:06Z
[ "python", "lambda", "partial", "functools" ]
In Python, suppose I have a function `f` that I want to pass around with some secondary arguments (assume for simplicity that it's just the first argument that remains variable). What are the differences between doing it these two ways (if any)? ``` # Assume secondary_args and secondary_kwargs have been defined impo...
1. A lambda function has the same type as a standard function, so it will behave like an instance method. 2. The `partial` object in your example can be called like this: ``` g1(x, y, z) ``` leading to this call (not valid Python syntax, but you get the idea): ``` f(*secondary_args, x, y, z, **seco...
pbkdf2 and hash comparison
11,829,602
3
2012-08-06T13:48:49Z
11,832,689
11
2012-08-06T17:01:08Z
[ "python", "hash", "comparison", "pbkdf2" ]
I use mitsuhiko's implementation of pbkdf2 for password hashing: ``` def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None): """Returns a binary digest for the PBKDF2 hash algorithm of `data` with the given `salt`. It iterates `iterations` time and produces a key of `keylen` bytes. By defa...
**To answer question 1**: There's no major security difference when comparing bytes vs comparing a base64 encoded string... you're just comparing `n` or `n*4/3` elements. The runtime will be `4/3` longer using base64, but the amount of time is still trivial :) That said, there was a python developer [discussion](http:...
How to check dict.has_key(k,x) with 2 variables
11,830,007
4
2012-08-06T14:12:14Z
11,830,085
9
2012-08-06T14:16:24Z
[ "python", "variables", "dictionary", "key" ]
I have formed a dictionary with 2 keys assigning to a single dictionary value, for example: ``` my_dict[x, y] = ... my_dict[a, u] = ... ``` Now how would i be able to use the `has_key()` method for 2 key variables, x and y like such: ``` if my_dict.has_key(x,y) == True: Do Something else: Do something else `...
Since `dict.has_key()` has been deprecated for a long time now, you should use the `in` operator instead: ``` if (x, y) in my_dict: # whatever ``` Note that your dictionary does not have "two keys". It probably uses a `tuple` of two elements as a key, but that tuple is a single object.
How can data remain persistent across multiple calls of decorated function?
11,830,656
6
2012-08-06T14:49:13Z
11,830,699
11
2012-08-06T14:52:02Z
[ "python", "decorator", "internals" ]
The following function is meant to be used as a decorator that stores the results of already computed values. If the argument has already been calculated before, the function will return the value stored in the `cache` dictionary: ``` def cached(f): f.cache = {} def _cachedf(*args): if args not in f.ca...
You are creating a [*closure*](http://en.wikipedia.org/wiki/Closure_%28computer_science%29) here: The function `_cachedf()` closes over the variable `cache` from the enclosing scope. This keeps `cache` alive as long as the function object lives. **Edit**: Maybe I should add a few more details on how this works in Pyth...
sqlalchemy simple example of `sum`, `average`, `min`, `max`
11,830,980
13
2012-08-06T15:10:41Z
11,832,380
23
2012-08-06T16:37:30Z
[ "python", "sql", "sqlalchemy" ]
For *sqlalchemy*, Who can gently give simple examples of `SQL` functions like `sum`, `average`, `min`, `max`, for a column (`score` in the following as an example). As for this mapper: ``` class Score(Base): #... name = Column(String) score= Column(Integer) #... ```
See [SQL Expression Language Tutorial](http://docs.sqlalchemy.org/en/rel_0_7/core/tutorial.html) for the usage. The code below shows the usage: ``` from sqlalchemy.sql import func qry = session.query(func.max(Score.score).label("max_score"), func.sum(Score.score).label("total_score"), ...
How to specify python requests http put body?
11,832,639
8
2012-08-06T16:57:32Z
11,833,013
27
2012-08-06T17:25:54Z
[ "python", "http", "put", "httplib2", "python-requests" ]
I'm trying to rewrite some old python code with requests module. The purpose is to upload an attachment. The mail server requires the following specification : ``` https://api.elasticemail.com/attachments/upload?username=yourusername&api_key=yourapikey&file=yourfilename ``` Old code which works: ``` h = httplib2.Htt...
Quoting from the [docs](http://docs.python-requests.org/en/latest/api/#main-interface) > **data** – (optional) Dictionary or bytes to send in the body of the **Request**. So this *should* work (not tested): ``` filepath = 'yourfilename.txt' with open(filepath) as fh: mydata = fh.read() response = reque...
Get the number of bytes needed for a Unicode string
11,832,824
5
2012-08-06T17:11:31Z
11,832,911
12
2012-08-06T17:17:43Z
[ "python", "string", "unicode", "cjk" ]
I have a Korean string encoded as Unicode like `u'정정'`. How do I know how many bytes are needed to represent this string? I need to know the exact byte count since I'm using the string for iOS push notification and it has a limit on the size of the payload. `len('정정')` doesn't work because that returns the nu...
You need to know what *encoding* you want to measure your byte size in: ``` >>> print u'\uC815\uC815' 정정 >>> print len(u'\uC815\uC815') 2 >>> print len(u'\uC815\uC815'.encode('UTF-8')) 6 >>> print len(u'\uC815\uC815'.encode('UTF-16-LE')) 4 >>> print len(u'\uC815\uC815'.encode('UTF-16')) 6 >>> print len(u'\uC815\uC...
removing first four and last four characters of strings in list, OR removing specific character patterns
11,832,984
6
2012-08-06T17:22:56Z
11,833,030
8
2012-08-06T17:27:10Z
[ "python", "list" ]
I am brand new to Python and have been working with it for a few weeks. I have a list of strings and want to remove the first four and last four characters of each string. OR, alternatively, removing specific character **patterns** (not just specific characters). I have been looking through the archives here but don't...
``` def remove_cruft(s): return s[4:-4] sites=['www.hattrick.com', 'www.google.com', 'www.wampum.net', 'www.newcom.com'] [remove_cruft(s) for s in sites] ``` result: ``` ['hattrick', 'google', 'wampum', 'newcom'] ``` If you know all of the strings you want to strip out, you can use `replace` to get rid of them....
How to create fake text file in python
11,833,428
5
2012-08-06T17:57:50Z
11,833,443
24
2012-08-06T17:59:09Z
[ "python", "python-2.7", "readlines" ]
How can I create a fake file object in python that contains text. Basically im trying to write some unite tests for a method that takes in a file object and retrieves the text via "readlines()" then do some text manipulation. Please note I can’t create an actual file on the file system and then pass it. The solution ...
This is exactly what [`StringIO`/`cStringIO`](http://docs.python.org/library/stringio) (renamed to [`io.StringIO`](http://docs.python.org/py3k/library/io.html#io.StringIO) in python 3) is for.
In Python, do I need to use close() after I use read() on a file?
11,833,585
4
2012-08-06T18:09:13Z
11,833,638
15
2012-08-06T18:13:04Z
[ "python", "django", "memory", "file-upload", "file-io" ]
I am using Django to read an ajax uploaded file to store it in a model. The upload request contains the raw uploaded image data. ``` def my_view(request): upload = request model_instance.image_field.save(uniquename, ContentFile(upload.read())) ``` If it matters, I am using AmazonS3 as my storage backend for u...
The python garbage collector will close files when they are no longer referenced. If your `upload` variable is a local variable in a function, it'll be cleared when the function returns. Thus, the file `upload` referred to will be automatically closed during the normal garbage collection cycle. That said, it's probab...
django messages not showing
11,834,174
4
2012-08-06T18:56:22Z
11,834,366
8
2012-08-06T19:10:32Z
[ "python", "django", "templates", "view", "messages" ]
I'm trying to use django messages framework to display a message when a user signs out of my application. I'm new to django and the documentation isn't very clear to me. Why is my message not showing up? <https://docs.djangoproject.com/en/dev/ref/contrib/messages/#adding-a-message> VIEW.PY ``` from django.contrib im...
Did you add the [context processor and the middleware](https://docs.djangoproject.com/en/dev/ref/contrib/messages/#enabling-messages)?
Python regex for matching two or three white spaces
11,834,344
3
2012-08-06T19:08:56Z
11,834,365
10
2012-08-06T19:10:31Z
[ "python", "regex", "string" ]
I'm trying to match the following text with a regex in Python 2.7 ``` SUBCASE 8 SUBCASE 9 SUBCASE 10 SUBCASE 11 ``` The number of spaces between "subcase" and the number drops from 3 to 2. I'm trying to use this regex in Python: `(SUBCASE)[\s+]([0-9]+)` Where am I going wrong? Shouldn't the `\s+` mean "catch ...
You'll want: ``` SUBCASE\s+([0-9]+) ``` or ``` SUBCASE\s+(\d+) ``` Putting `\s+` inside of `[...]` means, that you want precisely one symbol that either is a whitespace character, or a plus.
python subprocess set shell var. and then run command - how?
11,834,670
7
2012-08-06T19:30:30Z
11,834,697
8
2012-08-06T19:32:57Z
[ "python", "subprocess" ]
I need to do this: ``` $ export PYRO_HMAC_KEY=123 $ python -m Pyro4.naming ``` So, i found that the second one is possible to do with ``` subprocess.Popen(['python','-m','Pyro4.naming']) ``` but how export shell variable before that?
The subprocess functions accept an `env` argument that can be given a mapping of environment variables to use in the process: ``` subprocess.Popen(['python','-m','Pyro4.naming'], env={'PYRO_HMAC_KEY': '123'}) ```
python subprocess set shell var. and then run command - how?
11,834,670
7
2012-08-06T19:30:30Z
11,834,868
14
2012-08-06T19:45:40Z
[ "python", "subprocess" ]
I need to do this: ``` $ export PYRO_HMAC_KEY=123 $ python -m Pyro4.naming ``` So, i found that the second one is possible to do with ``` subprocess.Popen(['python','-m','Pyro4.naming']) ``` but how export shell variable before that?
To update the existing environment... ``` import os, subprocess d = dict(os.environ) # Make a copy of the current environment d['PYRO_HMAC_KEY'] = '123' subprocess.Popen(['python', '-m', 'Pyro4.naming'], env=d) ```
Boolean not changing value
11,834,833
4
2012-08-06T19:42:49Z
11,834,882
7
2012-08-06T19:46:32Z
[ "python", "python-2.7" ]
``` def shoot(self, limb): if not limb: pass else: limb = False print Joe.body.head #prints out true Bob.gun.shoot(Joe.body.head) # should print out false print Joe.body.head #prints out true (???) ``` I'm new to Python and am making a game as part of the LPTHW. My shoot function is suppo...
Python passes its object references by value, so by doing `limb = False` you're assigning a new object reference with the value `False` to the parameter `limb`, not modifying the object originally held by the parameter. (Well, technically it's not a "new" reference, as I believe `True`, `False`, and `None` are all sing...
Why #egg=foo when pip-installing from git repo
11,835,396
39
2012-08-06T20:24:15Z
11,835,524
15
2012-08-06T20:33:33Z
[ "python", "package", "pip" ]
When I do a "pip install -e ..." to install from a git repo, I have to specify #egg=somename or pip complains. For example: ``` pip install -e git://github.com/hiidef/oauth2app.git#egg=oauth2app ``` What's the significance of this "egg" string?
per pip install -h the "egg" string is the directory that gets checked out as part of the install
Why would shutil.copy() raise a permission exception when cp doesn't?
11,835,833
10
2012-08-06T20:58:53Z
11,835,950
20
2012-08-06T21:08:01Z
[ "python", "permissions", "copy" ]
shutil.copy() is raising a permissions error: ``` Traceback (most recent call last): File "copy-test.py", line 3, in <module> shutil.copy('src/images/ajax-loader-000000-e3e3e3.gif', 'bin/styles/blacktie/images') File "/usr/lib/python2.7/shutil.py", line 118, in copy copymode(src, dst) File "/usr/lib/pyth...
The operation that is failing is `chmod`, not the copy itself: ``` File "/usr/lib/python2.7/shutil.py", line 91, in copymode os.chmod(dst, mode) OSError: [Errno 1] Operation not permitted: 'bin/styles/blacktie/images/ajax-loader-000000-e3e3e3.gif' ``` This indicates that the file already exists and is owned by ...
How to mock a readonly property with mock?
11,836,436
22
2012-08-06T21:45:09Z
11,843,806
35
2012-08-07T10:17:53Z
[ "python", "unit-testing", "mocking" ]
How do you mock a readonly property with [mock](http://www.voidspace.org.uk/python/mock/index.html)? I tried: ``` setattr(obj.__class__, 'property_to_be_mocked', mock.Mock()) ``` but the issue is that it then applies to all instances of the class... which breaks my tests. Do you have any other idea? I don't want to...
Actually, the answer was (as usual) in the [documentation](http://www.voidspace.org.uk/python/mock/examples.html#mocking-properties), it's just that I was applying the patch to the instance instead of the class when I followed their example. Here is how to do it: ``` class MyClass: @property def last_transact...
How to mock a readonly property with mock?
11,836,436
22
2012-08-06T21:45:09Z
25,424,012
29
2014-08-21T10:28:54Z
[ "python", "unit-testing", "mocking" ]
How do you mock a readonly property with [mock](http://www.voidspace.org.uk/python/mock/index.html)? I tried: ``` setattr(obj.__class__, 'property_to_be_mocked', mock.Mock()) ``` but the issue is that it then applies to all instances of the class... which breaks my tests. Do you have any other idea? I don't want to...
I think the better way is to mock the property as `PropertyMock`, rather than to mock the `__get__` method directly. It is stated in the [documentation](https://docs.python.org/3/library/unittest.mock.html), search for `unittest.mock.PropertyMock`: A mock intended to be used as a property, or other descriptor, on a cl...
how to Implement __iadd__() for immutable type?
11,836,570
2
2012-08-06T21:58:08Z
11,836,636
13
2012-08-06T22:03:32Z
[ "python", "immutability", "augmented-assignment" ]
I would like to subclass an immutable type or implement one of my own which behaves like an `int` does as shown in the following console session: ``` >>> i=42 >>> id(i) 10021708 >>> i.__iadd__(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'int' object has no attribute '__i...
Simply don't implement `__iadd__`, but only `__add__`: ``` >>> class X(object): ... def __add__(self, o): ... return "added" >>> x = X() >>> x += 2 >>> x 'added' ``` If there's no `x.__iadd__`, Python simply calculates `x += y` as `x = x + y` [doc](http://docs.python.org/reference/datamodel.html#objec...
*large* python dictionary with persistence storage for quick look-ups
11,837,229
14
2012-08-06T23:11:38Z
11,837,260
13
2012-08-06T23:15:43Z
[ "python", "persistence", "object-persistence" ]
I have a 400 million lines of unique key-value info that I would like to be available for quick look ups in a script. I am wondering what would be a slick way of doing this. I did consider the following but not sure if there is a way to disk map the dictionary and without using a lot of memory except during dictionary ...
If you want to persist a large dictionary, you are basically looking at a database. Python comes with built in support for [sqlite3](http://docs.python.org/library/sqlite3), which gives you an easy database solution backed by a file on disk.
*large* python dictionary with persistence storage for quick look-ups
11,837,229
14
2012-08-06T23:11:38Z
11,837,582
10
2012-08-07T00:01:41Z
[ "python", "persistence", "object-persistence" ]
I have a 400 million lines of unique key-value info that I would like to be available for quick look ups in a script. I am wondering what would be a slick way of doing this. I did consider the following but not sure if there is a way to disk map the dictionary and without using a lot of memory except during dictionary ...
In principle the [shelve](http://docs.python.org/library/shelve#module-shelve) module does exactly what you want. It provides a persistent dictionary backed by a database file. Keys must be strings, but shelve will take care of pickling/unpickling values. The type of db file can vary, but it can be a [Berkeley DB](http...
*large* python dictionary with persistence storage for quick look-ups
11,837,229
14
2012-08-06T23:11:38Z
11,837,998
7
2012-08-07T01:05:41Z
[ "python", "persistence", "object-persistence" ]
I have a 400 million lines of unique key-value info that I would like to be available for quick look ups in a script. I am wondering what would be a slick way of doing this. I did consider the following but not sure if there is a way to disk map the dictionary and without using a lot of memory except during dictionary ...
No one has mentioned dbm. It is opened like a file, behaves like a dictionary and is in the standard distribution. From the docs <http://docs.python.org/release/3.0.1/library/dbm.html> ``` import dbm # Open database, creating it if necessary. db = dbm.open('cache', 'c') # Record some values db[b'hello'] = b'there' ...
What is producing this python AttributeError when using get_current_user() method?
11,837,693
3
2012-08-07T00:15:42Z
11,837,826
8
2012-08-07T00:37:02Z
[ "python", "google-app-engine", "syntax-error", "jinja2" ]
This line of code: ``` geted_nickname = user.nickname() ``` Of this Handler: ``` class MainHandler(webapp2.RequestHandler): def get(self): user = users.get_current_user() if user == None: self.redirect(users.create_login_url(self.request.uri)) geted_nickname = user.nic...
According to the [docs](http://webapp-improved.appspot.com/api/webapp2.html#webapp2.redirect) calling `redirect` does not stop code execution unless `abort` is set to `True`. It suggests returning the result of the redirect, e.g.: ``` return redirect('/some-path') ``` In your case, your method keeps executing, and `u...
Removing white space around a saved image in matplotlib
11,837,979
27
2012-08-07T01:02:57Z
11,847,260
41
2012-08-07T13:39:05Z
[ "python", "matplotlib" ]
I need to take an image and save it after some process. The figure looks fine when I display it, but when I save the figure I got some white space around the saved image. I have tried the `'tight'` option for `savefig` method, did not work either. The code: ``` import matplotlib.image as mpimg import matplotlib.py...
You can remove the white space padding by setting `bbox_inches="tight"` in `savefig`: ``` plt.savefig("test.png",bbox_inches='tight') ``` You'll have to put the argument to `bbox_inches` as a string, perhaps this is why it didn't work earlier for you. --- **Possible duplicates:** [Matplotlib plots: removing axis, ...
Removing white space around a saved image in matplotlib
11,837,979
27
2012-08-07T01:02:57Z
27,227,718
18
2014-12-01T11:45:51Z
[ "python", "matplotlib" ]
I need to take an image and save it after some process. The figure looks fine when I display it, but when I save the figure I got some white space around the saved image. I have tried the `'tight'` option for `savefig` method, did not work either. The code: ``` import matplotlib.image as mpimg import matplotlib.py...
I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file. (Note that I used matplotlib inside an IPython notebook, with the -pylab flag.) ``` gca().set_axis_off() subplots_adjust...
Multiply several matrices in numpy
11,838,352
14
2012-08-07T02:02:55Z
11,839,620
21
2012-08-07T05:12:31Z
[ "python", "numpy" ]
Suppose you have n square matrices A1,...,An. Is there anyway to multiply these matrices in a neat way? As far as I know dot in numpy accepts only two arguments. One obvious way is to define a function to call itself and get the result. Is there any better way to get it done?
This might be a relatively recent feature, but I like: ``` A.dot(B).dot(C) ``` or if you had a long chain you could do: ``` reduce(numpy.dot, [A1, A2, ..., An]) ``` Update: There is more info about reduce [here.](http://docs.python.org/library/functions.html#reduce) Here is an example that might help. ``` >>> A =...
Multiply several matrices in numpy
11,838,352
14
2012-08-07T02:02:55Z
26,999,758
9
2014-11-18T16:58:32Z
[ "python", "numpy" ]
Suppose you have n square matrices A1,...,An. Is there anyway to multiply these matrices in a neat way? As far as I know dot in numpy accepts only two arguments. One obvious way is to define a function to call itself and get the result. Is there any better way to get it done?
Resurrecting an old question with an update: As of [November 13, 2014](https://github.com/numpy/numpy/pull/4977) there is now a `np.linalg.multi_dot` function which does exactly what you want. It also has the benefit of optimizing call order, though that isn't necessary in your case. Note that this hasn't made it to ...
Python object references
11,838,560
2
2012-08-07T02:44:14Z
11,838,582
13
2012-08-07T02:48:07Z
[ "python", "python-3.x", "python-2.7" ]
I'm aware that in python every identifier or variable name is a reference to the actual object. ``` a = "hello" b = "hello" ``` When I compare the two strings ``` a == b ``` the output is ``` True ``` If I write an equivalent code in Java,the output would be `false` because the comparison is between references(wh...
If you actually ran that in Java, I think you'd find it probably prints out true because of string interning, but that's somewhat irrelevant. I'm not sure what you mean by "replaces it with the object it is referring to". What actually happens is that when you write `a == b`, Python [calls `a.__eq__(b)`](http://docs.p...
How to make QTableWidget's columns assume the maximum space?
11,839,813
10
2012-08-07T05:33:58Z
11,851,640
17
2012-08-07T18:08:17Z
[ "python", "resize", "pyqt", "pyqt4", "qtablewidget" ]
The columns of my QTableWidget do not fill in the space of the table, so that an empty space is left on the right hand-side. How to make the columns of my QTableWidget assume the maximum space so as to fill in this space?
The [headers](http://doc-snapshot.qt-project.org/4.8/qheaderview.html) of the table have methods for controlling this: ``` header = table.horizontalHeader() header.setStretchLastSection(True) ``` or: ``` header.setResizeMode(QHeaderView.Stretch) ```
Flask not getting any data from jQuery request data
11,839,855
10
2012-08-07T05:37:38Z
11,840,488
17
2012-08-07T06:34:23Z
[ "jquery", "python", "flask" ]
I've a handler for a URL, ``` @app.route("/", methods=['POST']) @crossdomain(origin='*') def hello(): ss=str(request.data) print ss return ss ``` The handler cannot retrive the data part of the request. When using jQuery: ``` jQuery.ajax( { type: "POST", dataType: "json", data:"adasd...
interesting, as it turns out you can only use `request.data` if the data was posted with a mimetype that flask can't handle, otherwise its an empty string `""` I think, the docs weren't very clear, I did some tests and that seems to be the case, you can take a look at the console output the flask generates when you run...
Can I add an operation to a list in Python?
11,841,118
5
2012-08-07T07:22:41Z
11,841,189
11
2012-08-07T07:29:05Z
[ "python" ]
I am quite often using Python instead of pseudocode. For that, I would like to have a stack. I know that using lists is the way to go ([source](http://docs.python.org/tutorial/datastructures.html#using-lists-as-stacks)), but I would like to use `myList.push` rather than `myList.append` to make clear that I use a stack....
You can make a subclass of *list* like this: ``` class List(list): def push(self, x): self.append(x) ``` Use your custom class the same way you would use a regular list: ``` >>> s = List() >>> s.push(10) >>> s.push(20) >>> s [10, 20] ```
Deletion behavior with relationship
11,841,586
6
2012-08-07T07:59:18Z
11,841,913
10
2012-08-07T08:23:45Z
[ "python", "sqlalchemy" ]
This isn’t trully a problem, I just want to understand. Considering the following code: ``` from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import * from sqlalchemy.orm import sessionmaker, relationship Base = declarative_base() class AB(Base): __tablename__= 'ab' id_a = Column(Integ...
`cascade` on `relationship` configures the cascades of `Session` operations, such as `Session.delete`. It's independent from any `ON X CASCADE` directives you may have on your foreign keys constraints in the database itself. In your case, having `cascade='all'` tells SQLAlchemy to cascade the `Session.delete` (among o...
SMTP sending an priority email
11,843,148
3
2012-08-07T09:38:44Z
11,844,141
12
2012-08-07T10:38:53Z
[ "python", "smtplib" ]
I am trying to use Python's `smtplib` to set the priority of an email to high. I have successfully used this library to send email, but am unsure how to get the priority working. ``` import smtplib from smtplib import SMTP ``` My first attempt was to use this from researching how to set the priority: ``` smtp.send...
Priority is just a matter of email content (to be exact, header content). See [here](http://www.chilkatsoft.com/p/p_471.asp). The next question would be how to put that into an email. That completely depends how you build that email. If you use the `email` module, you would do it this way: ``` from email.Message imp...
Python: TypeError: cannot concatenate 'str' and 'int' objects
11,844,072
69
2012-08-07T10:35:24Z
11,844,109
40
2012-08-07T10:37:09Z
[ "python", "string", "printing", "integer" ]
I have this python program that adds strings to integers: ``` a = raw_input("Enter a: ") b = raw_input("Enter b: ") print "a + b as strings: " + a + b a = int(a) b = int(b) c = a + b str(c) print "a + b as integers: " + c ``` I get this error: ``` Python: TypeError: cannot concatenate 'str' and 'int' objects ``` Ho...
`str(c)` returns a **new** string representation of `c`, and does not mutate `c` itself. ``` c = str(c) ``` is probably what you are looking for
Python: TypeError: cannot concatenate 'str' and 'int' objects
11,844,072
69
2012-08-07T10:35:24Z
11,844,123
10
2012-08-07T10:37:34Z
[ "python", "string", "printing", "integer" ]
I have this python program that adds strings to integers: ``` a = raw_input("Enter a: ") b = raw_input("Enter b: ") print "a + b as strings: " + a + b a = int(a) b = int(b) c = a + b str(c) print "a + b as integers: " + c ``` I get this error: ``` Python: TypeError: cannot concatenate 'str' and 'int' objects ``` Ho...
If you want to concatenate int or floats to a string you must use this: ``` i = 123 a = "foobar" s = a + str(i) ```
Python: TypeError: cannot concatenate 'str' and 'int' objects
11,844,072
69
2012-08-07T10:35:24Z
11,844,131
92
2012-08-07T10:38:04Z
[ "python", "string", "printing", "integer" ]
I have this python program that adds strings to integers: ``` a = raw_input("Enter a: ") b = raw_input("Enter b: ") print "a + b as strings: " + a + b a = int(a) b = int(b) c = a + b str(c) print "a + b as integers: " + c ``` I get this error: ``` Python: TypeError: cannot concatenate 'str' and 'int' objects ``` Ho...
There are two ways to fix the problem which is caused by the last `print` statement. You can assign the result of the `str(c)` call to `c` as correctly shown by @jamylak and then concatenate all of the strings, or you can replace the last `print` simply with this: ``` print "a + b as integers: ", c # note the comma ...
python encoding error only when called as external process
11,844,835
4
2012-08-07T11:20:31Z
11,845,065
7
2012-08-07T11:33:32Z
[ "python", "bash", "encoding", "invocation" ]
A simple file like ``` $ cat x.py x = u'Gen\xe8ve' print x ``` when run will give me: ``` $ python x.py Genève ``` however, when run as a "command substitution" will give: ``` $ echo $(python x.py) ... UnicodeEncodeError: 'ascii' codec... ``` I've tried with different terminal emulators (xterm, gnome-term) and t...
The problem here is that in the second call you are basically writing to a pipe that only accepts bytestrings (file-like object). The same happens if you try to execute this: ``` python x.py > my_file Traceback (most recent call last): File "x.py", line 2, in <module> print x UnicodeEncodeError: 'ascii' codec can'...
Tkinter OpenGL context in Python
11,844,882
21
2012-08-07T11:22:37Z
13,750,666
7
2012-12-06T19:03:34Z
[ "python", "opengl", "tkinter", "tk" ]
I need to create an OpenGL context in Tkinker, for using it with PyOpenGL Python module. Tkinker doesn't natively support OpenGL context, but I found this page on PyOpenGL docs, explaining how to use a wrapper included in the module for this: <http://pyopengl.sourceforge.net/documentation/context/> I tried to run the...
PyOpenGL provides Python bindings for the Tk OpenGL widget (Togl) but not Togl itself, that is why you had to download it. Now, to install Togl is easy but there isn't a tool ready to perform the task. Since the Python bindings will use Tcl to load the Togl module, the widget needs to live in one of the directories pre...
Predicting from previous date:value data
11,845,055
7
2012-08-07T11:32:53Z
13,409,899
9
2012-11-16T03:23:32Z
[ "python", "algorithm", "statistics", "prediction" ]
I have a few data sets from similar periods of time. It's a presentation of people at that day, the period being about a year. The data hasn't been gathered in regular intervals, it is rather quite random: 15-30 entries for each year, from 5 different years. The graph drawn from the data for each year looks roughly li...
In your case, the data is changing fast, and you have immediate observations of new data. A quick prediction can be implemented using [Holt-winter](http://en.wikipedia.org/wiki/Exponential_smoothing) exponential smoothing. The update equations: ![enter image description here](http://i.stack.imgur.com/EtKz1.png) `m_t...
Utilizing %r within raw_input in python
11,845,238
4
2012-08-07T11:43:56Z
11,845,289
7
2012-08-07T11:47:34Z
[ "python", "raw-input" ]
Is it feasible to utilize %r within raw\_input in python? For context, I'm working on Zed Shaw's [Exercise 12](http://learnpythonthehardway.org/book/ex12.html). (Great resource! The lessons are very helpful, and well paced.) I'm playing around in the extra credit, trying to get raw\_input to repeat what I typed in. I...
Your line should read ``` raw_input("Hello %r, what is your age? " % firstname) ``` instead of ``` raw_input("Hello %r, what is your age? ") % firstname ``` --- Otherwise, you would not format your `"Hello %r, ..."` string, but the resulting string of the call to `raw_input`.
Is Python's time.time() timezone specific?
11,845,803
23
2012-08-07T12:18:40Z
11,845,878
15
2012-08-07T12:22:57Z
[ "python", "datetime", "time", "timezone" ]
Apologies for asking too basic question but I couldn't get it cleared after reading docs. It just seems that I am missing or have misunderstood something too basic here. Does calling `time.time()` from different timezones, at the same time produce different results? This maybe comes down to definition of `epoch`, whic...
Yes, [`time.time()`](http://docs.python.org/library/time.html#time.time) returns the number of seconds since an unspecified *epoch*. Note that on most systems, this does **not** include leap seconds, although it is [possible to configure your system clock to include them](http://support.ntp.org/bin/view/Support/TimeSca...
Detect mouseover an image in Pygame
11,846,032
4
2012-08-07T12:30:01Z
11,858,933
9
2012-08-08T06:36:29Z
[ "python", "pygame", "game-engine" ]
I have an image: ``` newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha() ``` I then display it on the screen: ``` screen.blit(newGameButton, (0,0)) ``` How do I detect if the mouse is touching the image?
Use [`Surface.get_rect`](http://www.pygame.org/docs/ref/surface.html#Surface.get_rect) to get a [`Rect`](http://www.pygame.org/docs/ref/rect.html) describing the bounds of your [`Surface`](http://www.pygame.org/docs/ref/surface.html), then use [`.collidepoint()`](http://www.pygame.org/docs/ref/rect.html#Rect.collidepoi...
Handling directories with spaces Python subprocess.call()
11,846,232
6
2012-08-07T12:40:26Z
11,846,310
9
2012-08-07T12:44:29Z
[ "python", "subprocess", "directory" ]
I'm trying to create a program that scans a text file and passes arguments to subprocess. Everything works fine until I get directories with spaces in the path. My split method, which breaks down the arguments trips up over the spaces: ``` s = "svn move folder/hello\ world anotherfolder/hello\ world" task = s.split(...
Use a list instead: ``` task = ["svn", "move", "folder/hello world anotherfolder/hello world"] subprocess.check_call(task) ``` If your file contains whole commands, not just paths then you could try [shlex.split()](http://docs.python.org/library/shlex): ``` task = shlex.split(s) subprocess.check_call(task) ```
Strings and the and operator: best practice, differences with +
11,846,287
12
2012-08-07T12:43:14Z
11,846,411
13
2012-08-07T12:49:19Z
[ "python" ]
For one of my sites, I need to check if several class attributes are defined and not empty. So far, I've happily used `if self.attr:`, which in my mind is the shorthand for `if self.attr is not None and self.attr is not '':`, or whatever the undefined value of the attribute is. This works fine, but yields to surprisin...
`and` never typecasts to bool. Rather, `if` calls `bool()` on the result of expressions. An expression using `and` (and `or`, for that matter), short-circuits when it can determine that the expression will not evaluate to True or False based on the first operand, and returns the last evaluated value: ``` >>> 0 and 's...
python if statement with variable mathematical operator
11,847,359
15
2012-08-07T13:44:20Z
11,847,385
16
2012-08-07T13:45:58Z
[ "python", "if-statement", "operators", "mathematical-expressions" ]
Hi, I'm trying to insert a variable mathematical operator into a if statement, an example of what I'm trying to achieve:- ``` maths_operator = "==" if "test" maths_operator "test": print "match found" maths_operator = "!=" if "test" maths_operator "test": print "match found" else: print "match ...
Use the [`operator`](http://docs.python.org/library/operator) module: ``` import operator op = operator.eq if op("test", "test"): print "match found" ```
python if statement with variable mathematical operator
11,847,359
15
2012-08-07T13:44:20Z
11,847,476
17
2012-08-07T13:50:20Z
[ "python", "if-statement", "operators", "mathematical-expressions" ]
Hi, I'm trying to insert a variable mathematical operator into a if statement, an example of what I'm trying to achieve:- ``` maths_operator = "==" if "test" maths_operator "test": print "match found" maths_operator = "!=" if "test" maths_operator "test": print "match found" else: print "match ...
Use the operator package together with a dictionary to look up the operators according to their text equivalents. All of these must be either unary or binary operators to work consistently. ``` import operator ops = {'==' : operator.eq, '!=' : operator.ne, '<=' : operator.le, '>=' : operator.ge, ...
Python: filtering lists by indices
11,847,491
16
2012-08-07T13:51:14Z
11,847,525
34
2012-08-07T13:52:58Z
[ "python", "list", "filter", "indexing" ]
In Python I have a list of elements `aList` and a list of indices `myIndices`. Is there any way I can retrieve all at once those items in `aList` having as indices the values in `myIndices`? Example: ``` >>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> myIndices = [0, 3, 4] >>> aList.A_FUNCTION(myIndices) ['a', 'd...
I don't know any method to do it. But you could use a [list comprehension](http://www.python.org/dev/peps/pep-0202/): ``` >>> [aList[i] for i in myIndices] ```
Python: filtering lists by indices
11,847,491
16
2012-08-07T13:51:14Z
11,847,748
7
2012-08-07T14:05:17Z
[ "python", "list", "filter", "indexing" ]
In Python I have a list of elements `aList` and a list of indices `myIndices`. Is there any way I can retrieve all at once those items in `aList` having as indices the values in `myIndices`? Example: ``` >>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> myIndices = [0, 3, 4] >>> aList.A_FUNCTION(myIndices) ['a', 'd...
Definitely use a list comprehension but here is a function that does it (there are no methods of `list` that do this). This is however bad use of `itemgetter` but just for the sake of knowledge I have posted this. ``` >>> from operator import itemgetter >>> a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> my_indices =...
Python - curious/unexpected behaviour - precedence of operators
11,847,848
7
2012-08-07T14:10:12Z
11,847,897
20
2012-08-07T14:12:19Z
[ "python", "order", "precedence" ]
I have recently been experimenting with python generators a bit, and I came across the following curious behaviour, and I am curious to understand why this happens and what is going on: ``` def generating_test(n): for a in range(n): yield "a squared is %s" % a*a # Notice instead of a**2 we have written a...
This doesn't have anything to do with generators: ``` >>> a = 2 >>> "a squared is %s" % a 'a squared is 2' >>> ("a squared is %s" % a)*a 'a squared is 2a squared is 2' >>> "a squared is %s" % a*a 'a squared is 2a squared is 2' >>> "a squared is %s" % (a*a) 'a squared is 4' ``` The `%` op is performed before the multi...
Python - curious/unexpected behaviour - precedence of operators
11,847,848
7
2012-08-07T14:10:12Z
11,848,063
8
2012-08-07T14:21:29Z
[ "python", "order", "precedence" ]
I have recently been experimenting with python generators a bit, and I came across the following curious behaviour, and I am curious to understand why this happens and what is going on: ``` def generating_test(n): for a in range(n): yield "a squared is %s" % a*a # Notice instead of a**2 we have written a...
[Python's order of operations](http://docs.python.org/reference/expressions.html#evaluation-order) is from left-to-right except where PEMDAS applies. The string interpolation operator apparently has the same precedence as modulo and multiplication, because if you reverse the order, making the multiplication left of the...
How include static files to setuptools - python package
11,848,030
31
2012-08-07T14:19:51Z
11,848,281
35
2012-08-07T14:34:26Z
[ "python", "package", "setuptools" ]
It's impossible to include static files! I tried everything that I've found in tutorials and the documentation, but all in vain... I want to include the ./static/data.txt, there is my code: ``` # setup.py import os,glob from setuptools import setup,find_packages setup( name = "PotatoProject", version = "0.1....
Just added a `MANIFEST.in` in the same directory of `setup.py`, that looks like this: ``` include src/static/* include src/Potato/*.txt ``` and It worked (: I do not know if this is the best way out, looks like that the `setup.py` should do this by itself, but worked anyway...
How include static files to setuptools - python package
11,848,030
31
2012-08-07T14:19:51Z
20,242,010
15
2013-11-27T12:04:26Z
[ "python", "package", "setuptools" ]
It's impossible to include static files! I tried everything that I've found in tutorials and the documentation, but all in vain... I want to include the ./static/data.txt, there is my code: ``` # setup.py import os,glob from setuptools import setup,find_packages setup( name = "PotatoProject", version = "0.1....
Include all files recursively: ``` recursive-include project_name/templates * recursive-include project_name/static * ``` where `project_name` is a folder in the same line where you have `setup.py` file.
Python equivalent for PHP's usort()?
11,848,773
4
2012-08-07T15:01:47Z
11,848,830
7
2012-08-07T15:05:47Z
[ "python", "sorting" ]
My data structure is a list of tuples in Python, and I'd like to be able to sort the list items by a value contained in their tuples. In PHP, I'd normally create my own sorting function with usort(). Is there an equivalent in Python I could use?
Give the `sort()` method a `key` function: ``` >>> my_list = [(1, 2), (3, 4), (2, 1), (3, 2)] >>> my_list.sort(key=lambda x: x[1]) >>> my_list [(2, 1), (1, 2), (3, 2), (3, 4)] >>> ``` If you need to get a sorted list, instead of sorting *in place*, use the built\_in [`sorted()`](https://docs.python.org/2/library/func...
Formatting a nan float in python
11,849,158
5
2012-08-07T15:26:36Z
11,849,257
7
2012-08-07T15:32:11Z
[ "python", "string-formatting" ]
I'm trying to use string.format on a 'nan' float. Here's the description of the 'g' option from the [python documentation](http://docs.python.org/release/2.6/library/string.html). > General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponen...
`repr(float)` was fixed in Python 2.6 and Python 3.0; see <http://bugs.python.org/issue1635>; however `str.format` was not fixed until the 2.7 branch; see <http://hg.python.org/cpython/rev/c5e0d9beebf9> and <http://bugs.python.org/issue1580>. I'd recommend seeing if `"{0!r}"` works for you; that *should* call into the...
add a number to all odd or even indexed elements in numpy array without loops
11,849,778
6
2012-08-07T15:59:56Z
11,849,835
13
2012-08-07T16:03:35Z
[ "python", "arrays", "numpy" ]
Lets say your numpy array is: ``` A = [1,1,2,3,4] ``` You can simply do: > A + .1 to add a number to that every element numpy array I am looking for a way to add a number to just the odd or even indexed numbers `A[::2] +1` while keeping the entire array intact. Is it possible to add a number to all the odd or...
``` In [43]: A = np.array([1,1,2,3,4], dtype = 'float') In [44]: A[::2] += 0.1 In [45]: A Out[45]: array([ 1.1, 1. , 2.1, 3. , 4.1]) ``` Note that this modifies `A`. If you wish to leave `A` unmodified, copy `A` first: ``` In [46]: A = np.array([1,1,2,3,4], dtype = 'float') In [47]: B = A.copy() In [48]: B[:...
Python: Unexpected behavior using contextmanager on class method
11,849,844
3
2012-08-07T16:04:07Z
11,849,948
9
2012-08-07T16:09:49Z
[ "python", "with-statement", "contextmanager" ]
I'm trying to use the with..as contruct in Python to make writing "reversible computing" code easier. However, using `@contextmanager` on a class method seems to change the default initialization of future class instances. Python 2.6 and 3.1 have the same behavior. Here is a simple example exhibiting this behavior: ``...
This behavior is due to how [mutable default arguments](http://stackoverflow.com/q/1132941/505154) work in Python. Try changing `SymList.__init__()` to the following: ``` def __init__(self, L=None): if L is None: self.L = [] else: self.L = L ``` As you modify `self.L` in...
Using Python gdata to clear the rows in worksheet before adding data
11,850,257
4
2012-08-07T16:28:15Z
12,734,997
11
2012-10-04T20:04:00Z
[ "python", "gdata-api" ]
I have a Google Spreadsheet which I'm populating with values using a python script and the gdata library. If i run the script more than once, it appends new rows to the worksheet, I'd like the script to first clear all the data from the rows before populating it, that way I have a fresh set of data every time I run the...
Not sure if you got this sorted out or not, but regarding speeding up the clearing out of current data, try using a [batch request](http://code.google.com/p/gdata-python-client/wiki/UsingBatchOperations). For instance, to clear out every single cell in the sheet, you could do: ``` cells = client.GetCellsFeed(key, wks_...
Using python lxml.etree for huge XML files
11,850,345
2
2012-08-07T16:34:25Z
11,850,445
11
2012-08-07T16:41:07Z
[ "python", "lxml" ]
I would like to parse a huge xml (>200MB) using `lxml.etree` in Python. I tried to use `etree.parse` to load the XML file, but this does not work due to the filesize: ``` etree.parse('file.xml')Traceback (most recent call last): File "<stdin>", line 1, in <module> File "lxml.etree.pyx", line 2706, in lxml.etree.pars...
Try to create a custom `XMLParser` instance: ``` from lxml.etree import XMLParser, parse p = XMLParser(huge_tree=True) tree = parse('file.xml', parser=p) ```
Custom Python list sorting
11,850,425
24
2012-08-07T16:39:42Z
11,850,492
21
2012-08-07T16:44:47Z
[ "python", "list", "sorting" ]
I was refactoring some old code of mine and came across of this: ``` alist.sort(cmp_items) def cmp_items(a, b): if a.foo > b.foo: return 1 elif a.foo == b.foo: return 0 else: return -1 ``` The code works (and I wrote it some 3 years ago!) but I cannot find this thing documented an...
It's documented [here](http://docs.python.org/library/stdtypes.html#mutable-sequence-types). > The sort() method takes optional arguments for controlling the > comparisons. > > cmp specifies a custom comparison function of two arguments (list > items) which should return a negative, zero or positive number > depending...
Custom Python list sorting
11,850,425
24
2012-08-07T16:39:42Z
11,850,552
36
2012-08-07T16:49:06Z
[ "python", "list", "sorting" ]
I was refactoring some old code of mine and came across of this: ``` alist.sort(cmp_items) def cmp_items(a, b): if a.foo > b.foo: return 1 elif a.foo == b.foo: return 0 else: return -1 ``` The code works (and I wrote it some 3 years ago!) but I cannot find this thing documented an...
As a side note, here is a better alternative to implement the same sorting: ``` alist.sort(key=lambda x: x.foo) ``` Or alternatively: ``` import operator alist.sort(key=operator.attrgetter('foo')) ``` Check out the [Sorting How To](http://wiki.python.org/moin/HowTo/Sorting/), it is very useful.
Spline Interpolation with Python
11,851,770
9
2012-08-07T18:18:25Z
11,852,192
12
2012-08-07T18:47:51Z
[ "python", "interpolation", "spline", "cubic" ]
I wrote the following code to perform a spline interpolation: ``` import numpy as np import scipy as sp x1 = [1., 0.88, 0.67, 0.50, 0.35, 0.27, 0.18, 0.11, 0.08, 0.04, 0.04, 0.02] y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95] x = np.array(x1) y = np.array(y1) ne...
From the [scipy documentation on scipy.interpolate.interp1d](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html): > scipy.interpolate.interp1d(x, y, kind='linear', axis=-1, copy=True, bounds\_error=True, fill\_value=np.nan) > > x : array\_like. A 1-D array of monotonically increasing r...
Spline Interpolation with Python
11,851,770
9
2012-08-07T18:18:25Z
24,123,361
7
2014-06-09T15:18:11Z
[ "python", "interpolation", "spline", "cubic" ]
I wrote the following code to perform a spline interpolation: ``` import numpy as np import scipy as sp x1 = [1., 0.88, 0.67, 0.50, 0.35, 0.27, 0.18, 0.11, 0.08, 0.04, 0.04, 0.02] y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95] x = np.array(x1) y = np.array(y1) ne...
You can get this in the following way: ``` import numpy as np import scipy as sp from scipy.interpolate import interp1d x1 = [1., 0.88, 0.67, 0.50, 0.35, 0.27, 0.18, 0.11, 0.08, 0.04, 0.04, 0.02] y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95] # Combine lists into ...
itertools.takewhile within a generator function - why is it evaluated once only?
11,852,579
9
2012-08-07T19:15:51Z
11,852,709
24
2012-08-07T19:24:56Z
[ "python", "generator", "itertools" ]
I have a text file like this: ``` 11 2 3 4 11 111 ``` Using Python 2.7, I want to turn it into a list of lists of lines, where line breaks divide items in the inner list and empty lines divide items in the outer list. Like so: ``` [["11","2","3","4"],["11"],["111"]] ``` And for this purpose, I wrote a generator f...
What you're trying to do is a perfect job for [`groupby`](http://docs.python.org/library/itertools.html#itertools.groupby): ``` from itertools import groupby def read_parag(filename): with open(filename) as f: for k,g in groupby((line.strip() for line in f), bool): if k: yield ...
Foo.objects.get(id=None) returns Foo instance, sometimes
11,853,141
9
2012-08-07T19:57:05Z
11,908,154
13
2012-08-10T19:37:22Z
[ "python", "mysql", "django", "django-models", "innodb" ]
I have this code: ``` try: parent_comment = models.Comment.all_objects.get(id=parent_comment_id) except models.Comment.DoesNotExist: parent_comment = None if parent_comment is not None and parent_comment_id is None: raise Exception("WTF django/mysql") ``` ... and sometimes, the exception somehow gets rai...
This behaviour is caused by deeply strange (in this coder's humble opinion) MySQL behaviour, controlled [by the `SQL_AUTO_IS_NULL` variable](http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_sql_auto_is_null) (which is `1` by default in MySQL < 5.5.3): > If this variable is set to 1, then afte...
parameter unsupported when inserting int in sqlite
11,853,167
16
2012-08-07T19:58:42Z
21,082,534
31
2014-01-13T01:19:47Z
[ "python", "datetime", "sqlite3" ]
I have been going around and around with storing date and time in SQLite3 with the intention of retrieving the records using comparisons later e.g. SELECT \* WHERE date1 < date2 I finally gave up trying to store datetime.datetime objects and decided to use a UNIX timestamp instead as they are just an int and easy to ma...
Note the added comma after "temp" below: ``` cur.execute('insert into new_test (curent_dt) values (?)', (temp,)) ``` The reason this happens is that `(temp)` is an integer but `(temp,)` is a tuple of length one containing `temp`.
python cross platform apps
11,853,430
2
2012-08-07T20:16:00Z
11,907,022
7
2012-08-10T18:08:39Z
[ "python", "webkit", "cross-platform", "packaging", "py2exe" ]
I'm trying to make an app in CPython that should work on both linux and windows. I'm using the webkit library, witch works fine on linux (Ubuntu 12.04), but I can't get it to work on Windows. I know that I can compile my app into a Windows executable *(.exe)* with `py2exe`, but to do that it must work on my Windows ma...
Ok, so i couldn't get webkit to work on windows with GTK, but i found out that Qt provides an integrated WebKit module, so I donwloaded PySide (the Qt wrapper for python) and I tested it with this script: ``` import sys from PySide import QtCore from PySide import QtGui from PySide import QtWebKit class MainWindow (Q...
How to make sys.argv arguments optional? (Python)
11,853,508
6
2012-08-07T20:21:01Z
11,853,536
9
2012-08-07T20:22:50Z
[ "python", "command-line-arguments", "sys" ]
`sys.argv` takes arguments at the shell command line when running a program. How do I make these arguments optional? I know I can use `try` - `except`. But this forces you to insert either no extra arguments or all extra arguments, unless you nest more `try` - `except` which makes the code look much less readable. ##...
You can use more high-level libraries: [argparse](http://docs.python.org/dev/library/argparse.html), [optparse](http://docs.python.org/library/optparse.html), [opster](http://opster.readthedocs.org/en/latest/index.html). All of them supports optional arguments.
Python Multiple users append to the same file at the same time
11,853,551
9
2012-08-07T20:23:47Z
11,853,621
11
2012-08-07T20:27:12Z
[ "python" ]
I'm working on a python script that will be accessed via the web, so there will be multiple users trying to append to the same file at the same time. My worry is that this might cause a race condition where if multiple users wrote to the same file at the same time and it just might corrupt the file. For example: ``` ...
You can use [file locking](http://docs.python.org/library/fcntl.html#fcntl.flock): ``` import fcntl new_entry = "foobar" with open("/somepath/somefile.txt", "a") as g: fcntl.flock(g, fcntl.LOCK_EX) g.write(new_entry) fcntl.flock(g, fcntl.LOCK_UN) ``` Note that on some systems, locking is **not** needed if...
How to change ancestor of an NDB record?
11,854,137
4
2012-08-07T21:04:54Z
11,855,209
8
2012-08-07T22:47:07Z
[ "python", "google-app-engine", "gae-datastore" ]
In the High-Replication Datastore (I'm using NDB), the consistency is eventual. In order to get a guaranteed complete set, ancestor queries can be used. Ancestor queries also provide a great way to get all the "children" of a particular ancestor with kindless queries. In short, being able to leverage the ancestor model...
The only way to change the ancestor of an entity is to delete the old one and create a new one with a new key. This must be done for all child (and grand child, etc) entities in the ancestor path. If this isn't possible, then your listed solution works. This is required because the ancestor path of an entity is part o...
python multiprocessing: some functions do not return when they are complete (queue material too big)
11,854,519
19
2012-08-07T21:39:30Z
11,855,207
14
2012-08-07T22:46:56Z
[ "python", "queue", "multiprocessing" ]
I am using multiprocessing's Process and Queue. I start several functions in parallel and most behave nicely: they finish, their output goes to their Queue, and they show up as .is\_alive() == False. But for some reason a couple of functions are not behaving. They always show .is\_alive() == True, even after the last l...
Alright, it seems that the pipe used to fill the Queue gets plugged when the output of a function is too big (my crude understanding? This is an unresolved/closed bug? <http://bugs.python.org/issue8237>). I have modified the code in my question so that there is some buffering (queues are regularly emptied while process...
How to tell if a string contains valid Python code
11,854,745
15
2012-08-07T22:03:08Z
11,854,793
14
2012-08-07T22:06:08Z
[ "python", "syntax", "python-3.x" ]
If I have a string of Python code, how do I tell if it is valid, i.e., if entered at the Python prompt, it would raise a SyntaxError or not? I thought that using `compiler.parse` would work, but apparently that module has been removed in Python 3. Is there a way to do it that also works in Python 3. Obviously, I don't ...
Use [`ast.parse`](http://docs.python.org/library/ast.html#ast.parse): ``` import ast def is_valid_python(code): try: ast.parse(code) except SyntaxError: return False return True ``` ``` >>> is_valid_python('1 // 2') True >>> is_valid_python('1 /// 2') False ```
Display an image from a file in an IPython Notebook
11,854,847
66
2012-08-07T22:11:04Z
11,855,133
120
2012-08-07T22:37:17Z
[ "python", "ipython", "biopython" ]
I would like to use an [IPython notebook](http://ipython.org/notebook.html) as a way to interactively analyze some genome charts I am making with Biopython's [`GenomeDiagram`](http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec329) module. While there is extensive documentation on how to use `matplotlib` to get g...
Courtesy of [this post](http://python.6.n6.nabble.com/IPython-User-ipython-notebook-how-to-display-image-not-from-pylab-td4497427.html), you can do the following: ``` from IPython.display import Image Image(filename='test.png') ```
Display an image from a file in an IPython Notebook
11,854,847
66
2012-08-07T22:11:04Z
35,061,341
50
2016-01-28T12:20:52Z
[ "python", "ipython", "biopython" ]
I would like to use an [IPython notebook](http://ipython.org/notebook.html) as a way to interactively analyze some genome charts I am making with Biopython's [`GenomeDiagram`](http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec329) module. While there is extensive documentation on how to use `matplotlib` to get g...
If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method. ``` from IPython.display import Image, display listOfImageNames = ['/path/to/images/1.png', '/path/to/images/2.png'] for imageName in listOfImageNames: display(Ima...
Display an image from a file in an IPython Notebook
11,854,847
66
2012-08-07T22:11:04Z
35,313,233
8
2016-02-10T10:55:18Z
[ "python", "ipython", "biopython" ]
I would like to use an [IPython notebook](http://ipython.org/notebook.html) as a way to interactively analyze some genome charts I am making with Biopython's [`GenomeDiagram`](http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec329) module. While there is extensive documentation on how to use `matplotlib` to get g...
Note, until now posted solutions only work for png and jpg! If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack! ``` ![alt text](tes...
How to remove relative shift in matplotlib axis
11,855,363
20
2012-08-07T23:06:00Z
11,858,063
21
2012-08-08T05:18:19Z
[ "python", "matplotlib", "axis" ]
When I try to do a plot against a range with big enough numbers I get an axis with relative shift for all the ticks. For example: ``` plot([1000, 1001, 1002], [1, 2, 3]) ``` I get these ticks on axis of abscissas: ``` 0.0 0.5 1.0 1.5 2.0 +1e3 ``` The question is how to...
``` plot([1000, 1001, 1002], [1, 2, 3]) gca().get_xaxis().get_major_formatter().set_useOffset(False) draw() ``` This grabs the current `axes`, gets the x-axis `axis` object and then the major formatter object and sets useOffset to false ([doc](http://matplotlib.sourceforge.net/api/ticker_api.html#matplotlib.ticker.Sca...
Multivariate (polynomial) best fit curve in python?
11,856,206
17
2012-08-08T00:53:07Z
11,856,451
22
2012-08-08T01:26:40Z
[ "python", "matplotlib", "machine-learning", "regression", "scatter-plot" ]
How do you calculate a best fit line in python, and then plot it on a scatterplot in matplotlib? I was I calculate the linear best-fit line using Ordinary Least Squares Regression as follows: ``` from sklearn import linear_model clf = linear_model.LinearRegression() x = [[t.x1,t.x2,t.x3,t.x4,t.x5] for t in self.train...
The accepted answer to [this question](http://stackoverflow.com/questions/10988082/multivariate-polynomial-regression-with-numpy) provides **[a small multi poly fit library](https://github.com/mrocklin/multipolyfit)** which will do exactly what you need using numpy, and you can plug the result into the plotting as I've...