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
dict.get() method returns a pointer
7,153,893
9
2011-08-22T21:35:05Z
7,153,971
7
2011-08-22T21:44:01Z
[ "python", "dictionary", "pass-by-reference" ]
Let's say I have this code: ``` my_dict = {} default_value = {'surname': '', 'age': 0} # get info about john, or a default dict item = my_dict.get('john', default_value) # edit the data item[surname] = 'smith' item[age] = 68 my_dict['john'] = item ``` The problem becomes clear, if we now check the value of default...
In Python dicts are both objects (so they are always passed as references) and mutable (meaning they can be changed without being recreated). You can copy your dictionary each time you use it: ``` my_dict.get('john', default_value.copy()) ``` You can also use the defaultdict collection: ``` from collections import ...
dict.get() method returns a pointer
7,153,893
9
2011-08-22T21:35:05Z
7,153,980
7
2011-08-22T21:45:00Z
[ "python", "dictionary", "pass-by-reference" ]
Let's say I have this code: ``` my_dict = {} default_value = {'surname': '', 'age': 0} # get info about john, or a default dict item = my_dict.get('john', default_value) # edit the data item[surname] = 'smith' item[age] = 68 my_dict['john'] = item ``` The problem becomes clear, if we now check the value of default...
Don't use get. You could do: ``` item = my_dict.get('john', default_value.copy()) ``` But this requires a dictionary to be copied *even if the dictionary entry exists*. Instead, consider just checking if the value is there. ``` item = my_dict['john'] if 'john' in my_dict else default_value.copy() ``` The only probl...
How do I remove entries within a Counter object with a loop without invoking a RuntimeError?
7,154,312
4
2011-08-22T22:23:49Z
7,154,680
9
2011-08-22T23:12:30Z
[ "python", "collections", "containers", "counter" ]
``` from collections import * ignore = ['the','a','if','in','it','of','or'] ArtofWarCounter = Counter(ArtofWarLIST) for word in ArtofWarCounter: if word in ignore: del ArtofWarCounter[word] ``` ArtofWarCounter is a Counter object containing all the words from the Art of War. I'm trying to have words in `ig...
Don't loop over all words of a dict to find a entry, dicts are much better at lookups. You loop over the `ignore` list and remove the entries that exist: ``` ignore = ['the','a','if','in','it','of','or'] for word in ignore: if word in ArtofWarCounter: del ArtofWarCounter[word] ```
How can I get an array of alternating values in python?
7,154,739
6
2011-08-22T23:22:55Z
7,154,925
7
2011-08-22T23:56:39Z
[ "python", "numpy" ]
Simple question here: I'm trying to get an array that alternates values (1, -1, 1, -1.....) for a given length. np.repeat just gives me (1, 1, 1, 1,-1, -1,-1, -1). Thoughts?
I like @Benjamin's solution. An alternative though is: ``` import numpy as np a = np.empty((15,)) a[::2] = 1 a[1::2] = -1 ``` This also allows for odd-length lists. **EDIT:** Also just to note speeds, for a array of 10000 elements ``` import numpy as np from timeit import Timer if __name__ == '__main__': setu...
How can I get an array of alternating values in python?
7,154,739
6
2011-08-22T23:22:55Z
7,155,748
7
2011-08-23T02:39:39Z
[ "python", "numpy" ]
Simple question here: I'm trying to get an array that alternates values (1, -1, 1, -1.....) for a given length. np.repeat just gives me (1, 1, 1, 1,-1, -1,-1, -1). Thoughts?
use resize(): ``` In [38]: np.resize([1,-1], 10) # 10 is the length of result array Out[38]: array([ 1, -1, 1, -1, 1, -1, 1, -1, 1, -1]) ``` it can produce odd-length array: ``` In [39]: np.resize([1,-1], 11) Out[39]: array([ 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1]) ```
How can I highlight regex matches in Python?
7,154,972
2
2011-08-23T00:05:56Z
7,155,015
8
2011-08-23T00:13:21Z
[ "python", "editor" ]
How might I highlight the matches in regex in the sentence? I figure that I could use the locations of the matches like I would get from this: ``` s = "This is a sentence where I talk about interesting stuff like sencha tea." spans = [m.span() for m in re.finditer(r'sen\w+', s)] ``` But how do I force the terminal to...
There are several terminal color packages available such as [termstyle](https://github.com/gfxmonk/termstyle) or [termcolor](http://pypi.python.org/pypi/termcolor). I like [colorama](http://pypi.python.org/pypi/colorama), which works on Windows as well. Here's an example of doing what you want with colorama: ``` from...
matplotlib backends - do I care?
7,156,058
29
2011-08-23T03:47:36Z
7,158,256
28
2011-08-23T08:36:21Z
[ "python", "backend", "matplotlib" ]
``` >>> import matplotlib >>> print matplotlib.rcsetup.all_backends [u'GTK', u'GTKAgg', u'GTKCairo', u'MacOSX', u'Qt4Agg', u'Qt5Agg', u'TkAgg', u'WX', u'WXAgg', u'CocoaAgg', u'GTK3Cairo', u'GTK3Agg', u'WebAgg', u'nbAgg', u'agg', u'cairo', u'emf', u'gdk', u'pdf', u'pgf', u'ps', u'svg', u'template'] ``` Look at all thos...
The backend mainly matters if you're embedding matplotlib in an application, in which case you need to use a backend (GTK, Qt, TkInter, WxWindows) which matches the toolkit you're using to build your application. If you're also using matplotlib in a simple interactive way, you'll also want to use a backend which matche...
packaging a python application
7,156,333
10
2011-08-23T04:38:20Z
7,156,418
7
2011-08-23T04:54:17Z
[ "python", "packaging" ]
If I have a python application consisting of multiple files, how can I pack and distribute it? My application has a configuration file which has to filled in by the user. So what is the best way to manage? I guess I am looking for steps similar to configure/make/make install/make documentation that I use on my Linux ma...
You can read up on packaging your projects on the official [Python site](http://docs.python.org/distutils/index.html#distutils-index) or check out [setuptools](http://docs.python.org/distutils/index.html#distutils-index).
packaging a python application
7,156,333
10
2011-08-23T04:38:20Z
7,157,786
7
2011-08-23T07:50:31Z
[ "python", "packaging" ]
If I have a python application consisting of multiple files, how can I pack and distribute it? My application has a configuration file which has to filled in by the user. So what is the best way to manage? I guess I am looking for steps similar to configure/make/make install/make documentation that I use on my Linux ma...
Also take a look at [5 tips for packaging your Python projects](http://tarekziade.wordpress.com/2011/08/19/5-tips-for-packaging-your-python-projects/).
Monitoring Rsync Progress
7,157,973
11
2011-08-23T08:07:35Z
7,272,339
20
2011-09-01T15:07:44Z
[ "python", "progress", "rsync" ]
I'm trying to write a Python script which will monitor an rsync transfer, and provide a (rough) estimate of percentage progress. For my first attempt, I looked at an `rsync --progress` command and saw that it prints messages such as: ``` 1614 100% 1.54MB/s 0:00:00 (xfer#5, to-check=4/10) ``` I wrote a parser fo...
The current version of rsync (at the time of editing 3.1.2) has an option `--info=progress2` which will show you progress of the entire transfer instead of individual files. From [the man page](https://download.samba.org/pub/rsync/rsync.html): > There is also a --info=progress2 option that outputs statistics based on...
Do not want images to load and CSS to render on Firefox in Selenium WebDriver tests with Python
7,157,994
23
2011-08-23T08:09:23Z
7,606,238
45
2011-09-30T05:20:59Z
[ "python", "css", "firefox", "selenium-webdriver" ]
I am using Selenium 2 with python bindings to fetch some data from our partner's site. But on an average it's taking me around 13 secs to perform this operation. I was looking for a way to disable the images css and flash etc. I am using Firefox 3.6 and also using pyvirtualdisplay to to prevent opening of firefox win...
I have figured out a way to prevent Firefox from loading CSS, images and Flash. ``` from selenium.webdriver.firefox.firefox_profile import FirefoxProfile def disableImages(self): ## get the Firefox profile object firefoxProfile = FirefoxProfile() ## Disable CSS firefoxProfile.set_preference('permissio...
Do not want images to load and CSS to render on Firefox in Selenium WebDriver tests with Python
7,157,994
23
2011-08-23T08:09:23Z
31,576,782
8
2015-07-23T01:35:21Z
[ "python", "css", "firefox", "selenium-webdriver" ]
I am using Selenium 2 with python bindings to fetch some data from our partner's site. But on an average it's taking me around 13 secs to perform this operation. I was looking for a way to disable the images css and flash etc. I am using Firefox 3.6 and also using pyvirtualdisplay to to prevent opening of firefox win...
Unfortunately the option `firefox_profile.set_preference('permissions.default.image', 2)` no longer seems to work to disable images with the latest version of Firefox - [for reason see Alecxe's answer to my question [Can't turn off images in Selenium / Firefox](http://stackoverflow.com/questions/31571726/cant-turn-off-...
Diagonal stacking in numpy?
7,158,098
4
2011-08-23T08:21:01Z
7,158,370
7
2011-08-23T08:47:05Z
[ "python", "numpy" ]
So numpy has some convenience functions for combining several arrays into one, e.g. hstack and vstack. I'm wondering if there's something similar but for stacking the component arrays diagonally? Say I have N arrays of shape (n\_i, m\_i), and I want to combine them into a single array of size (sum\_{1,N}n\_i, sum\_{1,...
It does seem `block_diag` does exactly what you want. So if for some reason you can't update scipy, then here is the source from `v0.8.0` if you wish to simply define it! ``` def block_diag(*arrs): """Create a block diagonal matrix from the provided arrays. Given the inputs `A`, `B` and `C`, the output will h...
Best python style for complex one-liners
7,158,141
12
2011-08-23T08:25:49Z
7,158,401
18
2011-08-23T08:50:19Z
[ "python", "coding-style" ]
I recently wrote a rather ugly looking one-liner, and was wondering if it is better python style to break it up into multiple lines, or leave it as a commented one-liner. I looked in PEP 8, but it did not mention anything about this This is the code I wrote: ``` def getlink(url): return(urllib.urlopen(url).readli...
My vote would be based on readability. I find your one-liner quicker to digest than the multi-line example. One-liners are great as long as it fits in one *eye-ful*, and collectively they perform one distinct task. Personally, I would write that as: ``` def getlink(url): content = urllib.urlopen(url).readlines()...
What's best Python open source library to draw chart?
7,158,809
6
2011-08-23T09:24:46Z
7,158,958
12
2011-08-23T09:36:48Z
[ "python", "charts" ]
What's best open source library in Python to draw chart/diagram? 2D is necessary, and 3D is good if provided together. and it has to accept simple input data format like csv. I googled one called: `matplotlib`, how is it and any others? It should be best in terms of the reliability, performance, simple use and easy i...
From the official python wiki: > Over the years many different plotting modules and packages have been > developed for Python. For most of that time there was no clear > favorite package, but recently matplotlib has become the most widely > used. matplotlib highlights for me: * easy to learn (based on matlab traditi...
Creating simple form with qt-designer and pyqt
7,159,003
5
2011-08-23T09:40:36Z
7,159,260
10
2011-08-23T09:59:41Z
[ "python", "user-interface", "pyqt", "designer", "qt-designer" ]
I'm trying to run my first application in pyqt. My form looks fine when I'm doing preview in designer: <http://imageshack.us/photo/my-images/171/screenshotuw.png/> But if I'm showing it from my script I got: <http://imageshack.us/photo/my-images/268/screenshot1hwn.png/> And information in terminal: QLayout: Attempt...
I would say that you have designed a `QWidget` in the designer, and you create a `QMainWindow`. Replace ``` class MyForm(QtGui.QMainWindow) ``` by ``` class MyForm(QtGui.QWidget) ```
List directories with a specified depth in Python
7,159,607
18
2011-08-23T10:28:06Z
7,159,726
35
2011-08-23T10:37:11Z
[ "python" ]
I'm want a function to return a list with directories with a specified path and a fixed depth and soon realized there a few alternatives. I'm using os.walk quite a lot but the code started to look ugly when counting the depth etc. What is really the most "neat" implementation?
If the depth is fixed, [`glob`](http://docs.python.org/library/glob.html) is a good idea: ``` import glob,os.path filesDepth3 = glob.glob('*/*/*') dirsDepth3 = filter(lambda f: os.path.isdir(f), filesDepth3) ``` Otherwise, it shouldn't be too hard to use `os.walk`: ``` import os,string path = '.' path = os.path.norm...
Does paramiko close ssh connection on a non-paramiko exception
7,159,644
6
2011-08-23T10:31:21Z
8,293,225
7
2011-11-28T08:32:00Z
[ "python", "ssh", "paramiko" ]
I'm debugging some code, which is going to result in me constantly logging in / out of some external sftp servers. Does anyone know if paramiko automatically closes a ssh / sftp session on the external server if a non-paramiko exception is raised in the code? I can't find it in the docs and as the connections have to b...
No, paramiko will not automatically close the ssh / sftp session. It doesn't matter if the exception was generated by paramiko code or otherwise; there is nothing in the paramiko code that catches any exceptions and automatically closes them, so you have to do it yourself. You can ensure that it gets closed by wrappin...
Left Matrix Division and Numpy Solve
7,160,162
7
2011-08-23T11:17:23Z
7,160,356
8
2011-08-23T11:33:44Z
[ "python", "matlab", "numpy", "octave", "linear-algebra" ]
I am trying to convert code that contains the \ operator from Matlab (Octave) to Python. Sample code ``` B = [2;4] b = [4;4] B \ b ``` This works and produces 1.2 as an answer. Using this web page <http://mathesaurus.sourceforge.net/matlab-numpy.html> I translated that as: ``` import numpy as np import numpy.linal...
From [MathWorks documentation](http://www.mathworks.com/help/techdoc/ref/mldivide.html) for left matrix division: > If A is an m-by-n matrix with m ~= n and B is a column vector with m > components, or a matrix with several such columns, then X = A\B is the > solution in the least squares sense to the under- or overde...
Python - How to validate a url in python ? (Malformed or not)
7,160,737
28
2011-08-23T12:02:31Z
7,160,778
29
2011-08-23T12:06:48Z
[ "python", "url", "malformedurlexception" ]
I have `url` from the user and I have to reply with the fetched HTML. How can I check for the URL to be malformed or not ? For Example : ``` url='google' // Malformed url='google.com' // Malformed url='http://google.com' // Valid url='http://google' // Malformed ``` How can we achieve this ?
# django url validation regex: ``` regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::...
Python - How to validate a url in python ? (Malformed or not)
7,160,737
28
2011-08-23T12:02:31Z
7,160,819
68
2011-08-23T12:10:16Z
[ "python", "url", "malformedurlexception" ]
I have `url` from the user and I have to reply with the fetched HTML. How can I check for the URL to be malformed or not ? For Example : ``` url='google' // Malformed url='google.com' // Malformed url='http://google.com' // Valid url='http://google' // Malformed ``` How can we achieve this ?
Actually, I think this is the best way. ``` from django.core.validators import URLValidator from django.core.exceptions import ValidationError val = URLValidator(verify_exists=False) try: val('http://www.google.com') except ValidationError, e: print e ``` If you set `verify_exists` to `True`, it will actuall...
Python - How to validate a url in python ? (Malformed or not)
7,160,737
28
2011-08-23T12:02:31Z
32,171,869
28
2015-08-23T21:46:01Z
[ "python", "url", "malformedurlexception" ]
I have `url` from the user and I have to reply with the fetched HTML. How can I check for the URL to be malformed or not ? For Example : ``` url='google' // Malformed url='google.com' // Malformed url='http://google.com' // Valid url='http://google' // Malformed ``` How can we achieve this ?
Use the [validators](http://validators.readthedocs.org/en/latest/#) package: ``` >>> import validators >>> validators.url("http://google.com") True >>> validators.url("http://google") ValidationFailure(func=url, args={'value': 'http://google', 'require_tld': True}) >>> if not validators.url("http://google"): ... p...
Catching all exceptions in Python
7,160,983
17
2011-08-23T12:23:50Z
7,161,030
17
2011-08-23T12:28:27Z
[ "python", "multithreading", "exception-handling", "python-3.x", "catch-all" ]
In Python, what's the best way to catch "all" exceptions? ``` except: # do stuff with sys.exc_info()[1] except BaseException as exc: except Exception as exc: ``` The catch may be executing in a thread. My aim is to log any exception that might be thrown by normal code without masking any special Python exceptions,...
If you need to catch all exceptions and do the same stuff for all, I'll suggest you this : ``` try: #stuff except: # do some stuff ``` If you don't want to mask "special" python exceptions, use the Exception base class ``` try: #stuff except Exception: # do some stuff ``` for some exceptions related man...
Catching all exceptions in Python
7,160,983
17
2011-08-23T12:23:50Z
7,161,517
23
2011-08-23T13:09:27Z
[ "python", "multithreading", "exception-handling", "python-3.x", "catch-all" ]
In Python, what's the best way to catch "all" exceptions? ``` except: # do stuff with sys.exc_info()[1] except BaseException as exc: except Exception as exc: ``` The catch may be executing in a thread. My aim is to log any exception that might be thrown by normal code without masking any special Python exceptions,...
* `except Exception:` vs `except BaseException:`: The difference between catching `Exception` and `BaseException` is that according to the [exception hierarchy](http://docs.python.org/library/exceptions.html#exception-hierarchy) exception like SystemExit, KeyboardInterrupt and GeneratorExit will not be caught when u...
what is statically typed in RPython?
7,161,856
13
2011-08-23T13:36:49Z
7,162,308
13
2011-08-23T14:06:55Z
[ "python", "static-typing", "pypy", "rpython" ]
It is often stated that [RPython](http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html#id1) (a subset of Python) is statically typed. (E.g. on [Wikipedia](http://en.wikipedia.org/wiki/PyPy).) Initially, I wondered how they would add that to Python and thought that they might have added the requirement to add stat...
> So, do function arguments also count as variables? Of course they do. They always do in pretty much every language. > Or in what sense is RPython statically typed? Or is this actually misstated? The statement is correct. **RPython is not Python.** Well, it's a subset of it and can be run as Python code. But when y...
Get location of the .py source file
7,162,366
26
2011-08-23T14:10:22Z
7,162,404
44
2011-08-23T14:12:49Z
[ "python" ]
Say I have a python file in directory **e** like this: */a/b/c/d/e/file.py* Under directory **e** I have a few folders I want to access but if file.py is executed from anywhere else rather than from folder **e** the relative path won't work for me. Also folder **e** could be located anywhere but always with the a set...
``` # in /a/b/c/d/e/file.py import os os.path.dirname(os.path.abspath(__file__)) # /a/b/c/d/e ```
pass session cookies in http header with python urllib2?
7,162,850
7
2011-08-23T14:42:21Z
7,163,087
14
2011-08-23T14:57:46Z
[ "python", "http", "cookies", "wikipedia-api" ]
I'm trying to write a simple script to log into Wikipedia and perform some actions on my user page, using the Mediawiki api. However, I never seem to get past the first login request (from this page: <https://secure.wikimedia.org/wikipedia/en/wiki/Wikipedia:Creating_a_bot#Logging_in>). I don't think the session cookie ...
The latest version of [`requests`](http://docs.python-requests.org/en/latest/index.html) has support for [sessions](http://docs.python-requests.org/en/latest/user/advanced/#session-objects) (as well as being really simple to use and generally great): ``` with requests.session() as s: s.post(url, data=user_data) ...
Python Imports, Paths, Directories & Modules
7,163,204
6
2011-08-23T15:05:08Z
7,163,609
8
2011-08-23T15:31:26Z
[ "python", "module", "package" ]
Let me start by saying I've done extensive research over the course of the past week and have not yet found actual answers to these questions - just some fuzzy answers that don't really explain what is going on. If that's just cause I missed what I was looking for, I'm sorry - please just point me in the correct direct...
First off, you will find all the information you need in [section 6 of The Python Tutorial](http://docs.python.org/tutorial/modules.html). --- > (1) Does python deal differently with imports on packages & modules that exist in the pythonpath than when you are trying to import from your current directory? No, it does...
What is the default order of a list returned from a Django filter call?
7,163,640
18
2011-08-23T15:33:51Z
7,164,126
29
2011-08-23T16:10:50Z
[ "python", "django", "postgresql" ]
**Short Question** What is the default order of a list returned from a Django filter call when connected to a PostgreSQL database? **Background** By my own admission, I *had* made a poor assumption at the application layer in that the order in which a list is returned will be constant, that is without using 'order...
There is **NO DEFAULT ORDER**, a point that can not be emphasized enough because everyone does it wrong. A table in a database is not an ordinary html table, it is an unordered set of tuples. It often surprises programmers only used to MySQL because in that particular database the order of the rows are often predictab...
Getting stdout from a tcpdump subprocess after terminating it
7,163,877
6
2011-08-23T15:53:28Z
7,163,965
7
2011-08-23T16:00:05Z
[ "python", "subprocess", "tcpdump" ]
I am running `tcpdump` in a subprocess like this: ``` pcap_process = subprocess.Popen(['tcpdump', '-s 0', '-w -', 'tcp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ``` The `-w -` argument is important: it tells `tcpdump` to print the resulting .pcap file to `stdout`. I then g...
Instead of using tcpdump, it's often advisable to use [PCAP directly](http://code.google.com/p/pypcap/), or [Scapy](http://www.secdev.org/projects/scapy/doc/usage.html#sniffing). If that isn't an option, simply call `communicate` after `terminate` - killing a process does not kill data in the pipes to it. However, don...
Nested for loops in Python
7,164,162
6
2011-08-23T16:14:04Z
7,164,180
9
2011-08-23T16:15:16Z
[ "python", "loops" ]
I want to do something like ``` for a in [0..1]: for b in [0..1]: for c in [0..1]: do something ``` But, I might have 15 different variables. Is there a simpler way like ``` for a, b, c in [0..1]: do something ``` Thanks for any help
[`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product): ``` import itertools for a,b,c in itertools.product([0, 1], repeat=3): # do something ```
Any difference between these 2 imports?
7,164,234
5
2011-08-23T16:19:42Z
7,164,274
12
2011-08-23T16:22:29Z
[ "python" ]
Do the below 2 import statements have some difference? Or just the same thing? ``` from package import * import package ```
`from package import *` imports everything from package into the local namespace; this is not recommended because it may introduce unwanted things (like a function that overwrites a local one). This is a quick and handy import tool, but if things get serious, you should use the `from package import X,Y,Z`, or `import p...
Find the min/max excluding zeros in a numpy array (or a tuple) in python
7,164,397
14
2011-08-23T16:33:37Z
7,164,425
27
2011-08-23T16:36:35Z
[ "python", "numpy" ]
I have an array. The valid values are not zero (either positive or negetive). I want to find the minimum and maximum within the array which should not take zeros into account. For example if the numbers are only negative. Zeros will be problematic.
How about: ``` import numpy as np minval = np.min(a[np.nonzero(a)]) maxval = np.max(a[np.nonzero(a)]) ``` where `a` is your array.
Find the min/max excluding zeros in a numpy array (or a tuple) in python
7,164,397
14
2011-08-23T16:33:37Z
7,164,681
12
2011-08-23T16:57:48Z
[ "python", "numpy" ]
I have an array. The valid values are not zero (either positive or negetive). I want to find the minimum and maximum within the array which should not take zeros into account. For example if the numbers are only negative. Zeros will be problematic.
If you can choose the "invalid" value in your array, it is better to use `nan` instead of `0`: ``` >>> a = numpy.array([1.0, numpy.nan, 2.0]) >>> numpy.nanmax(a) 2.0 >>> numpy.nanmin(a) 1.0 ``` If this is not possible, you can use an array mask: ``` >>> a = numpy.array([1.0, 0.0, 2.0]) >>> ma = numpy.ma.masked_equal...
How to send cookies in a post request with the Python Requests library?
7,164,679
34
2011-08-23T16:57:24Z
7,164,897
62
2011-08-23T17:12:50Z
[ "python", "cookies", "http-request", "python-requests" ]
I'm trying to use the [Requests](http://docs.python-requests.org/en/latest/user/quickstart/#cookies) library to send cookies with a post request, but I'm not sure how to actually set up the cookies based on its documentation. The script is for use on Wikipedia, and the cookie(s) that need to be sent are of this form: ...
The latest release of Requests will build CookieJars for you from simple dictionaries. ``` import requests cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'} r = requests.post('http://wikipedia.org', cookies=cookie) ``` Enjoy :)
How to send cookies in a post request with the Python Requests library?
7,164,679
34
2011-08-23T16:57:24Z
8,977,165
40
2012-01-23T19:06:09Z
[ "python", "cookies", "http-request", "python-requests" ]
I'm trying to use the [Requests](http://docs.python-requests.org/en/latest/user/quickstart/#cookies) library to send cookies with a post request, but I'm not sure how to actually set up the cookies based on its documentation. The script is for use on Wikipedia, and the cookie(s) that need to be sent are of this form: ...
Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do: ``` import requests r1 = requests.post('http://www.yourapp.com/login') r2 = requests.post('ht...
In Python, how do you determine whether the kernel is running in 32-bit or 64-bit mode?
7,164,843
9
2011-08-23T17:08:37Z
7,171,315
9
2011-08-24T06:29:55Z
[ "python" ]
I'm running python 2.6 on Linux, Mac OS, and Windows, and need to determine whether the kernel is running in 32-bit or 64-bit mode. Is there an easy way to do this? I've looked at platform.machine(), but this doesn't work properly on Windows. I've also looked at platform.architecture(), and this doesn't work when run...
How about working around [issue7860](http://bugs.python.org/issue7860) ``` import os import sys import platform def machine(): """Return type of machine.""" if os.name == 'nt' and sys.version_info[:2] < (2,7): return os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get('PROCESSOR_AR...
python nonlinear least squares fitting
7,165,201
12
2011-08-23T17:37:33Z
7,165,877
31
2011-08-23T18:34:10Z
[ "python", "scipy", "nonlinear-optimization" ]
I am a little out of my depth in terms of the math involved in my problem, so I apologise for any incorrect nomenclature. I was looking at using the scipy function leastsq, but am not sure if it is the correct function. I have the following equation: ``` eq = lambda PLP,p0,l0,kd : 0.5*(-1-((p0+l0)/kd) + np.sqrt(4*(l0...
This is a bare-bones example of how to use `scipy.optimize.leastsq`: ``` import numpy as np import scipy.optimize as optimize import matplotlib.pylab as plt def func(kd,p0,l0): return 0.5*(-1-((p0+l0)/kd) + np.sqrt(4*(l0/kd)+(((l0-p0)/kd)-1)**2)) ``` The sum of the squares of the `residuals` is the function of `...
How to restore a 2-dimensional numpy.array from a bytestring?
7,165,367
5
2011-08-23T17:52:05Z
7,166,844
10
2011-08-23T20:01:39Z
[ "python", "numpy" ]
`numpy.array` has a handy `.tostring()` method which produces a compact representation of the array as a bytestring. But how do I restore the original array from the bytestring? `numpy.fromstring()` only produces a 1-dimensional array, and there is no `numpy.array.fromstring()`. Seems like I ought to be able to provide...
``` >>> x array([[ 0. , 0.125, 0.25 ], [ 0.375, 0.5 , 0.625], [ 0.75 , 0.875, 1. ]]) >>> s = x.tostring() >>> numpy.fromstring(s) array([ 0. , 0.125, 0.25 , 0.375, 0.5 , 0.625, 0.75 , 0.875, 1. ]) >>> y = numpy.fromstring(s).reshape((3, 3)) >>> y array([[ 0. , 0.125, 0.25 ], ...
How to get Python interactive console in current namespace?
7,165,493
10
2011-08-23T18:02:28Z
7,165,575
8
2011-08-23T18:09:12Z
[ "python", "variables", "namespaces", "console", "read-eval-print-loop" ]
I would like to have my Python code start a Python interactive console (REPL) in the middle of running code using something like code.interact(). But the console that code.interact() starts doesn't see the variables in the current namespace. How do I do something like: mystring="hello" code.interact() ... and then i...
Try: ``` code.interact(local=locals()) ``` (found here: <http://aymanh.com/python-debugging-techniques>)
Passing objects from Django to Javascript DOM
7,165,656
17
2011-08-23T18:16:45Z
7,167,875
16
2011-08-23T21:36:35Z
[ "javascript", "python", "django", "json", "dom" ]
I'm trying to pass a Query Set from Django to a template with javascript. I've tried different approaches to solve this: **1. Normal Approach - Javascript gets all messed up with trying to parse the object because of the nomenclature [ &gt Object:ID &lt, &gt Object:ID &lt,... ]** Django View ``` django_list = list(...
Ok, I found the solution! Mostly it was because of not quoting the results. When Javascript was trying to parse the object this wasn't recognized as string. So, first step is: ``` var js_list = {{django_list}}; ``` changed to: ``` var js_list = "{{django_list}}"; ``` After this I realized that Django was escaping...
Passing objects from Django to Javascript DOM
7,165,656
17
2011-08-23T18:16:45Z
18,219,246
12
2013-08-13T21:07:48Z
[ "javascript", "python", "django", "json", "dom" ]
I'm trying to pass a Query Set from Django to a template with javascript. I've tried different approaches to solve this: **1. Normal Approach - Javascript gets all messed up with trying to parse the object because of the nomenclature [ &gt Object:ID &lt, &gt Object:ID &lt,... ]** Django View ``` django_list = list(...
## Same Question, "Better"(*more recent*) answer: [Django Queryset to dict for use in json](http://stackoverflow.com/questions/10502135/django-queryset-to-dict-for-use-in-json) Answer by [vashishtha-jogi](http://stackoverflow.com/users/462216/vashishtha-jogi): > A better approach is to use DjangoJSONEncoder. It has s...
Open file in a relative location in Python
7,165,749
32
2011-08-23T18:24:02Z
7,166,139
55
2011-08-23T18:59:31Z
[ "python", "file", "path" ]
Suppose python code is executed in not known by prior windows directory say 'main' , and wherever code is installed when it runs it needs to access to directory 'main/2091/data.txt' . how should I use open(location) function? what should be location ? Edit : I found that below simple code will work..does it have any...
With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself. If you are sure the file you want is in a subdirectory beneath where the script is actually locate...
How to do an upsert with SqlAlchemy?
7,165,998
25
2011-08-23T18:46:34Z
7,166,559
18
2011-08-23T19:37:00Z
[ "python", "sqlalchemy", "upsert" ]
I have a record that I want to exist in the database if it is not there, and if it is there already (primary key exists) I want the fields to be updated to the current state. This is often called an [upsert](http://en.wikipedia.org/wiki/Upsert). The following incomplete code snippet demonstrates what will work, but it...
SQLAlchemy does have a "save-or-update" behavior, which in recent versions has been built into `session.add`, but previously was the separate `session.saveorupdate` call. This is not an "upsert" but it may be good enough for your needs. It is good that you are asking about a class with multiple unique keys; I believe ...
pymongo + gevent: throw me a banana and just monkey_patch?
7,166,998
12
2011-08-23T20:15:07Z
7,169,174
18
2011-08-24T00:39:52Z
[ "python", "mongodb", "pymongo", "monkeypatching", "gevent" ]
Quickie here that needs more domain expertise on pymongo than I have right now: Are the "right" parts of the pymongo driver written in python for me to call gevent monkey\_patch() and successfully alter pymongo's blocking behavior on r/w within gevent "asynchronous" greenlets? If this will require a little more leg w...
I have used PyMongo with Gevent and here are a few things you need to watch out for: 1. Instantiate only one `pymongo.Connection` object, preferrably as a global or module-level variable. This is important because `Connection` has within itself a pool! 2. Monkey patch everything, or at least BOTH socket and threading....
Efficiently finding the last line in a text file
7,167,008
11
2011-08-23T20:16:13Z
7,167,069
9
2011-08-23T20:21:13Z
[ "python", "text" ]
I need to extract the last line from a number of very large (several hundred megabyte) text files to get certain data. Currently, I am using python to cycle through all the lines until the file is empty and then I process the last line returned, but I am certain there is a more efficient way to do this. What is the be...
Not the straight forward way, but probably much faster than a simple Python implementation: ``` line = subprocess.check_output(['tail', '-1', filename]) ```
Efficiently finding the last line in a text file
7,167,008
11
2011-08-23T20:16:13Z
7,167,136
8
2011-08-23T20:27:30Z
[ "python", "text" ]
I need to extract the last line from a number of very large (several hundred megabyte) text files to get certain data. Currently, I am using python to cycle through all the lines until the file is empty and then I process the last line returned, but I am certain there is a more efficient way to do this. What is the be...
You could take a look at: [Get last n lines of a file with Python, similar to tail](http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail) It is really close to what you need.
Is there a Java equivalent of Python's 'enumerate' function?
7,167,253
45
2011-08-23T20:39:33Z
7,167,266
42
2011-08-23T20:41:27Z
[ "java", "python", "iterator" ]
In Python, the [`enumerate`](http://docs.python.org/library/functions.html#enumerate) function allows you to iterate over a sequence of (index, value) pairs. For example: ``` >>> numbers = ["zero", "one", "two"] >>> for i, s in enumerate(numbers): ... print i, s ... 0 zero 1 one 2 two ``` Is there any way of doi...
For collections that implement the [`List`](http://download.oracle.com/javase/7/docs/api/java/util/List.html) interface, you can call the [`listIterator()`](http://download.oracle.com/javase/7/docs/api/java/util/List.html#listIterator%28%29) method to get a [`ListIterator`](http://download.oracle.com/javase/7/docs/api/...
Python list greater than number
7,167,657
14
2011-08-23T21:16:12Z
7,167,722
21
2011-08-23T21:21:52Z
[ "python", "python-2.7" ]
I have discovered the a list is greater than a number. ``` >>> [1,2,3] > 1000 True ``` Is there some reason why this works? I can't convert a list to an int with `int([1,2,3])`. The int can't be converted to a list with `list(1000)`. So how is python comparing the two?
In this case of "mismatched" types, the types are listed lexicographically by type name: a "list" comes after an "int" in alphabetical ordering, so it is greater. > CPython implementation detail: Objects of different types except > numbers are ordered by their type names; objects of the same types > that don’t suppo...
Python list greater than number
7,167,657
14
2011-08-23T21:16:12Z
7,167,740
9
2011-08-23T21:23:55Z
[ "python", "python-2.7" ]
I have discovered the a list is greater than a number. ``` >>> [1,2,3] > 1000 True ``` Is there some reason why this works? I can't convert a list to an int with `int([1,2,3])`. The int can't be converted to a list with `list(1000)`. So how is python comparing the two?
According to the [Python Reference Manual](http://docs.python.org/reference/expressions.html#notin), > Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one exe...
background function in Python
7,168,508
29
2011-08-23T22:56:18Z
7,168,647
43
2011-08-23T23:14:52Z
[ "python", "multithreading" ]
I've got a Python script that sometimes displays images to the user. The images can, at times, be quite large, and they are reused often. Displaying them is not critical, but displaying the message associated with them is. I've got a function that downloads the image needed and saves it locally. Right now it's run inli...
Do something like this: ``` def function_that_downloads(my_args): # do some long download here ``` then inline, do something like this: ``` import threading def my_inline_function(some_args): #do some stuff download_thread = threading.Thread(target=function_that_downloads, args=my_args) download_thre...
Suppress newline in Python logging module
7,168,790
14
2011-08-23T23:37:22Z
13,373,364
10
2012-11-14T05:10:01Z
[ "python", "logging" ]
I'm trying to replace an ad-hoc logging system with Python's logging module. I'm using the logging system to output progress information for a long task on a single line so you can `tail` the log or watch it in a console. I've done this by having a flag on my logging function which suppresses the newline for that log m...
The new line, `\n`, is inserted inside the `StreamHandler` class. If you're really set on *fixing* this behaviour, then here's an example of how I solved this by [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch) the `emit(self, record)` method inside the logging.StreamHandler class. > A monkey patch is a w...
Suppress newline in Python logging module
7,168,790
14
2011-08-23T23:37:22Z
33,132,165
7
2015-10-14T17:45:34Z
[ "python", "logging" ]
I'm trying to replace an ad-hoc logging system with Python's logging module. I'm using the logging system to output progress information for a long task on a single line so you can `tail` the log or watch it in a console. I've done this by having a flag on my logging function which suppresses the newline for that log m...
If you wanted to do this you can change the logging handler terminator. Python 3.4 ``` handler = logging.StreamHandler() handler.terminator = "" ``` When the StreamHandler writes it writes the terminator last.
Using Python, how can I access a shared folder on windows network?
7,169,845
18
2011-08-24T02:34:31Z
7,170,008
24
2011-08-24T03:09:55Z
[ "python", "windows", "networking" ]
I have a file that I would like to copy from a shared folder which is in a shared folder on a different system, but on the same network. How can I access the folder/file? The usual open() method does not seem to work?
Use forward slashes to specify the [UNC](http://en.wikipedia.org/wiki/Path_%28computing%29#Uniform_Naming_Convention) Path: ``` open('//HOST/share/path/to/file') ``` (if your Python client code is also running under Windows)
Using Python, how can I access a shared folder on windows network?
7,169,845
18
2011-08-24T02:34:31Z
7,170,763
9
2011-08-24T05:19:19Z
[ "python", "windows", "networking" ]
I have a file that I would like to copy from a shared folder which is in a shared folder on a different system, but on the same network. How can I access the folder/file? The usual open() method does not seem to work?
How did you try it? Maybe you are working with `\` and omit proper escaping. Instead of ``` open('\\HOST\share\path\to\file') ``` use either Johnsyweb's solution with the `/`s, or try one of ``` open(r'\\HOST\share\path\to\file') ``` or ``` open('\\\\HOST\\share\\path\\to\\file') ``` .
Using Python Iterparse For Large XML Files
7,171,140
29
2011-08-24T06:07:57Z
7,171,543
42
2011-08-24T06:52:20Z
[ "python", "xml", "lxml", "large-files", "elementtree" ]
I need to write a parser in Python that can process some extremely large files ( > 2 GB ) on a computer without much memory (only 2 GB). I wanted to use iterparse in lxml to do it. My file is of the format: ``` <item> <title>Item 1</title> <desc>Description 1</desc> </item> <item> <title>Item 2</title> <desc>...
Try [Liza Daly's fast\_iter](http://www.ibm.com/developerworks/xml/library/x-hiperfparse/). After processing an element, `elem`, it calls `elem.clear()` to remove descendants and also removes preceding siblings. ``` def fast_iter(context, func, *args, **kwargs): """ http://lxml.de/parsing.html#modifying-the-tr...
Python - calculating trendlines with errors
7,171,356
8
2011-08-24T06:33:53Z
7,187,687
11
2011-08-25T09:03:55Z
[ "python", "numpy", "trendline" ]
So I've got some data stored as two lists, and plotted them using ``` plot(datasetx, datasety) ``` Then I set a trendline ``` trend = polyfit(datasetx, datasety) trendx = [] trendy = [] for a in range(datasetx[0], (datasetx[-1]+1)): trendx.append(a) trendy.append(trend[0]*a**2 + trend[1]*a + trend[2]) plot...
I think you can use the function **`curve_fit`** of `scipy.optimize` ([documentation](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html)). A basic example of the usage: ``` import numpy as np from scipy.optimize import curve_fit def func(x, a, b, c): return a*x**2 + b*x + c x = np...
Override python logging for test efficiency
7,172,290
5
2011-08-24T08:04:13Z
7,172,562
12
2011-08-24T08:29:00Z
[ "python", "performance", "unit-testing", "logging" ]
In many cases unit-tests are significantly slowed down by the use of python's `logging` package. Assuming logging isn't essential to the test, how would you cleanly override `logging` per-test, so that log commands would be effectively skipped. Assume the use of multiple loggers such as in: ``` logger1 = logging.getL...
**Option 1:** Logging can be [disabled](http://docs.python.org/library/logging.html#logging.disable) by calling ``` logging.disable(logging.CRITICAL) ``` and turned back on with ``` logging.disable(logging.NOTSET) ``` However, even after disabling logging, a logging statement such as `logger.info` would still caus...
Calculate difference between adjacent items in a python list
7,172,933
7
2011-08-24T09:03:36Z
7,172,970
7
2011-08-24T09:08:06Z
[ "python", "list" ]
I have a list of millions of numbers. I want to find out if the difference between each number in the ordered list is the same for the entire list. list\_example = [ 0, 5, 10, 15, 20, 25, 30, 35, 40, ..etc etc etc] What's the best way to do this? My try: ``` import collections list_example = [ 0, 5, 10, 15, 20, 25...
Using pure Python: ``` >>> x = [0,5,10,15,20] >>> xdiff = [x[n]-x[n-1] for n in range(1,len(x))] >>> xdiff [5, 5, 5, 5] >>> all([xdiff[0] == xdiff[n] for n in range(1,len(xdiff))]) True ``` It's a little easier, and probably faster, if you use NumPy: ``` >>> import numpy as np >>> xdiff = np.diff(x) >>> np.all(xdiff...
Calculate difference between adjacent items in a python list
7,172,933
7
2011-08-24T09:03:36Z
7,173,025
9
2011-08-24T09:13:45Z
[ "python", "list" ]
I have a list of millions of numbers. I want to find out if the difference between each number in the ordered list is the same for the entire list. list\_example = [ 0, 5, 10, 15, 20, 25, 30, 35, 40, ..etc etc etc] What's the best way to do this? My try: ``` import collections list_example = [ 0, 5, 10, 15, 20, 25...
The straight approach here is the best: ``` x = s[1] - s[0] for i in range(2, len(s)): if s[i] - s[i-1] != x: break else: #do some work here... ```
Calculate difference between adjacent items in a python list
7,172,933
7
2011-08-24T09:03:36Z
7,173,267
7
2011-08-24T09:35:15Z
[ "python", "list" ]
I have a list of millions of numbers. I want to find out if the difference between each number in the ordered list is the same for the entire list. list\_example = [ 0, 5, 10, 15, 20, 25, 30, 35, 40, ..etc etc etc] What's the best way to do this? My try: ``` import collections list_example = [ 0, 5, 10, 15, 20, 25...
Need notice that the list may have millions of numbers. So ideally, we shouldn't iterate over the entire list unless it's necessary. Also we need avoid construct new list, which may have significant memory consumption. Using all and a generator will solve the problem ``` >>> x = [5, 10, 15, 20, 25] >>> all(x[i] - x[...
Duplicate log output when using Python logging module
7,173,033
30
2011-08-24T09:14:18Z
7,175,288
29
2011-08-24T12:19:36Z
[ "python" ]
I am using python logger. The following is my code: ``` import os import time import datetime import logging class Logger : def myLogger(self): logger = logging.getLogger('ProvisioningPython') logger.setLevel(logging.DEBUG) now = datetime.datetime.now() handler=logging.FileHandler('/root/cre...
The `logging.getLogger()` is already a singleton. ([Documentation](http://docs.python.org/release/2.6.7/library/logging.html?highlight=logging#logging.getLogger)) The problem is that every time you call `myLogger()`, it's adding another handler to the instance, which causes the duplicate logs. Perhaps something like ...
Duplicate log output when using Python logging module
7,173,033
30
2011-08-24T09:14:18Z
7,672,941
15
2011-10-06T10:17:09Z
[ "python" ]
I am using python logger. The following is my code: ``` import os import time import datetime import logging class Logger : def myLogger(self): logger = logging.getLogger('ProvisioningPython') logger.setLevel(logging.DEBUG) now = datetime.datetime.now() handler=logging.FileHandler('/root/cre...
``` import datetime import logging class Logger : def myLogger(self): logger=logging.getLogger('ProvisioningPython') if not len(logger.handlers): logger.setLevel(logging.DEBUG) now = datetime.datetime.now() handler=logging.FileHandler('/root/credentials/Logs/ProvisioningP...
Bottle.py error routing
7,174,886
13
2011-08-24T11:46:57Z
7,175,125
7
2011-08-24T12:05:56Z
[ "python", "bottle" ]
Bottle.py ships with an import to handle throwing HTTPErrors and route to a function. Firstly, the documentation claims I can (and so do several examples): ``` from bottle import error @error(500) def custom500(error): return 'my custom message' ``` however, when importing this statement error is unresolved but...
This works for me: ``` from bottle import error, run, route, abort @error(500) def custom500(error): return 'my custom message' @route("/") def index(): abort("Boo!") run() ```
Bottle.py error routing
7,174,886
13
2011-08-24T11:46:57Z
7,175,152
22
2011-08-24T12:08:31Z
[ "python", "bottle" ]
Bottle.py ships with an import to handle throwing HTTPErrors and route to a function. Firstly, the documentation claims I can (and so do several examples): ``` from bottle import error @error(500) def custom500(error): return 'my custom message' ``` however, when importing this statement error is unresolved but...
If you want to embed your errors in another module, you could do something like this: *error.py* ``` def custom500(error): return 'my custom message' handler = { 500: custom500, } ``` *app.py* ``` from bottle import * import error app = Bottle() app.error_handler = error.handler @app.route('/') def divze...
When does socket.recv(recv_size) return?
7,174,927
23
2011-08-24T11:49:51Z
7,180,671
13
2011-08-24T18:49:01Z
[ "python", "sockets" ]
From test, I concluded that in following three cases the `socket.recv(recv_size)` will return. 1. After the connection was closed. For example, the client side called socket.close() or any socket error occurred, it would return empty string. 2. Some data come, the size of data is more than `recv_size`. 3. Some d...
Yes, your conclusion is correct. `socket.recv` is a blocking call. `socket.recv(1024)` will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to `socket.recv` won't block. `socket.recv` will also end with an empty string if the connection is closed or there ...
Python efficient way to check if very large string contains a substring
7,175,020
4
2011-08-24T11:57:18Z
7,175,496
7
2011-08-24T12:35:49Z
[ "python", "performance" ]
Python is not my best language, and so I'm not all that good at finding the most efficient solutions to some of my problems. I have a very large string (coming from a 30 MB file) and I need to check if that file contains a smaller substring (this string is only a few dozen characters). The way I am currently doing it i...
Is it really slow? You're talking about 30MB string; let's try it with even bigger string: ``` In [12]: string="agu82934u"*50*1024*1024+"string to be found" In [13]: len(string) Out[13]: 471859218 In [14]: %timeit "string to be found" in string 1 loops, best of 3: 335 ms per loop In [15]: %timeit "string not to be ...
Generating python CLI man page
7,176,560
9
2011-08-24T13:50:41Z
7,179,569
11
2011-08-24T17:16:08Z
[ "python", "command-line-interface", "man" ]
I am developing a python CLI tool (using [optparse](https://docs.python.org/2.6/library/optparse.html) in python2.6, but hope to switch soon to python2.7) and I am about to write the man page. I have some experience on generating dynamic man pages by: * creating a dedicated method that composes a string in [pod format...
The usual way to generate documentation in Python is to use [Sphinx](http://sphinx.pocoo.org/). For example, that's what's used in the official Python documentation. Once you have a Sphinx documentation project set up (see [this tutorial](http://sphinx.pocoo.org/tutorial.html)), you can generate man pages from your Sph...
How to calculate relative path between 2 directory path?
7,178,001
6
2011-08-24T15:21:55Z
7,178,050
13
2011-08-24T15:24:52Z
[ "python" ]
I have 2 directory: ``` subdir1 = live/events/livepkgr/events/_definst_/ subdir2 = live/streams/livepkgr/streams/_definst_/ ``` result must be: ``` diff_subdir = ../../../../streams/livepkgr/streams/_definst_/ ```
``` >>> subdir1 = "live/events/livepkgr/events/_definst_/" >>> subdir2 = "live/streams/livepkgr/streams/_definst_/" >>> import os >>> os.path.relpath(subdir2, subdir1) '../../../../streams/livepkgr/streams/_definst_' >>> ```
How to calculate relative path between 2 directory path?
7,178,001
6
2011-08-24T15:21:55Z
7,178,070
11
2011-08-24T15:25:57Z
[ "python" ]
I have 2 directory: ``` subdir1 = live/events/livepkgr/events/_definst_/ subdir2 = live/streams/livepkgr/streams/_definst_/ ``` result must be: ``` diff_subdir = ../../../../streams/livepkgr/streams/_definst_/ ```
<http://docs.python.org/library/os.path.html> > os.path.relpath(path[, start]) Return a relative filepath to path > either from the current directory or from an optional start point. > > start defaults to os.curdir. > > Availability: Windows, Unix. > > New in version 2.6.
Why can't generators be pickled?
7,180,212
19
2011-08-24T18:11:36Z
7,180,424
29
2011-08-24T18:29:08Z
[ "python", "generator", "pickle", "python-stackless" ]
Python's pickle (I'm talking standard Python 2.5/2.6/2.7 here) cannot pickle locks, file objects etc. It also cannot pickle generators and lambda expressions (or any other anonymous code), because the pickle really only stores name references. In case of locks and OS-dependent features, the reason *why* you cannot pi...
There is lots of information about this available. For the "official word" on the issue, read the [(closed) Python bugtracker issue](http://bugs.python.org/issue1092962). The core reasoning, by one of the people who made the decision, is detailed on [this blog](http://peadrop.com/blog/2009/12/29/why-you-cannot-pickle-...
Why can't generators be pickled?
7,180,212
19
2011-08-24T18:11:36Z
7,180,448
15
2011-08-24T18:31:31Z
[ "python", "generator", "pickle", "python-stackless" ]
Python's pickle (I'm talking standard Python 2.5/2.6/2.7 here) cannot pickle locks, file objects etc. It also cannot pickle generators and lambda expressions (or any other anonymous code), because the pickle really only stores name references. In case of locks and OS-dependent features, the reason *why* you cannot pi...
You actually can, depending on the implementation. [PyPy](http://pypy.org) and [Stackless Python](http://stackless.com) both allow this (to some degree anyway): ``` Python 2.7.1 (dcae7aed462b, Aug 17 2011, 09:46:15) [PyPy 1.6.0 with GCC 4.0.1] on darwin Type "help", "copyright", "credits" or "license" for more informa...
Python lxml changes tag hierarchy?
7,180,919
2
2011-08-24T19:07:59Z
7,180,990
11
2011-08-24T19:14:58Z
[ "python", "html", "xml", "lxml" ]
I'm having a small issue with lxml. I'm converting an XML doc into an HTML doc. The original XML looks like this (it looks like HTML, but it's in the XML doc): ``` <p>Localization - Eiffel tower? Paris or Vegas <p>Bayes theorem p(A|B)</p></p> ``` When I do this (item is the string above) ``` lxml.html.tostring(lxml....
lxml is doing this because it doesn't store invalid HTML, and `<p>` elements [can't be nested](http://www.w3.org/TR/html401/struct/text.html#h-9.3.1) in HTML: > The P element represents a paragraph. It cannot contain block-level elements (including P itself).
Running South migrations for all apps
7,181,255
7
2011-08-24T19:38:19Z
7,181,351
18
2011-08-24T19:46:19Z
[ "python", "django", "django-models", "migration", "django-south" ]
I've just begun using South and am still in the process of figuring it out. Let's say I have the initial migration script of a model. Then i go add a column to the model and create a migration script for it. I then add another column to another model and create another migration script for it. I'm creating the migratio...
To bring all apps up to date on all their migrations, run: ``` ./manage.py migrate ``` Simple. :)
How to implement division with round-towards-infinity in Python
7,181,757
7
2011-08-24T20:20:14Z
7,181,952
16
2011-08-24T20:36:38Z
[ "python", "math", "floating-point", "rounding", "division" ]
I want 3/2 to equal 2 not 1.5 I know there's a mathematical term for that operation(not called rounding up), but I can't recall it right now. Anyway, how do i do that without having to do two functions? ex of what I do NOT want: ``` answer = 3/2 then math.ceil(answer)=2 (why does math.ceil(3/2)=1?) ``` ex of what I...
*To give a short answer...* Python only offers native operators for two types of division: "true" division, and "round down" division. So what you want isn't available as a single function. However, it is possible to easily implement a number of different types of division-with-rounding using some short expressions. ...
Why do I get a ASCII encoding error with Unicode data in Python 2.4 but not in 2.7?
7,182,384
4
2011-08-24T21:17:14Z
7,183,618
7
2011-08-24T23:43:15Z
[ "python", "exception", "unicode", "encoding" ]
I have a program that, when run in Python 2.7, produces proper Unicode output to the standard output. When run in Python 2.4, I get `UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)`. What changed between version 2.4 and 2.7 that this works now?
Although I could not find any mention of it elswhere, it appears that Python 2.7 is automatically converting text to the terminal encoding, instead of throwing an error as expected. **Python 2.7:** ``` > echo $LANG en_US.UTF-8 > python -c 'import sys; print sys.getdefaultencoding()' ascii > python -c 'import sys; sy...
Extracting href with Beautiful Soup
7,183,922
5
2011-08-25T00:42:31Z
7,183,953
8
2011-08-25T00:49:46Z
[ "python", "beautifulsoup", "href" ]
I use this code to get acces to my link : ``` links = soup.find("span", { "class" : "hsmall" }) links.findNextSiblings('a') for link in links: print link['href'] print link.string ``` Link have no ID or class or whatever, it's just a classic link with a href attribute. The response of my script is : ``` print l...
Links is still referring to your soup.find. So you could do something like: ``` links = soup.find("span", { "class" : "hsmall" }).findNextSiblings('a') for link in links: print link['href'] print link.string ```
Collections and Stream classes equivalences between Smalltalk, Perl, Python and Ruby
7,184,240
7
2011-08-25T01:43:29Z
7,184,369
7
2011-08-25T02:08:05Z
[ "python", "ruby", "perl", "programming-languages", "smalltalk" ]
I have few experience with languages like Python, Perl and Ruby, but I have developed in Smalltalk from some time. There are some pretty basic Smalltalk classes which are very popular and cross-Smalltalk implementation: ``` FileStream ReadWriteStream Set Dictionary OrderedCollection SortedCollection Bag Interval Array...
# Perl I'll answer for Perl, since I'm fluent in both Perl and Smalltalk. Smalltalk's Dictionary is fairly close to Perl's hash type. A Dictionary uses object equivalence for the keys. Perl uses simple strings for keys, so the flexibility is somewhat limited. Smalltalk's OrderedCollection is fairly close to Perl's a...
jquery.ajax post request to get data from app engine server
7,184,450
2
2011-08-25T02:24:46Z
7,185,256
9
2011-08-25T04:46:19Z
[ "jquery", "python", "ajax", "google-app-engine" ]
Apologies up front for the noob question... Hello, how do I get data from the Python end of an appengine server using jQuery.ajax? I know how to send data to the server using ajax and an appropriate handler, but I was wondering if someone could tell me what the ajax request for getting values from the server looks lik...
The mechanism is exactly the same either way the data is flowing. Use the `success` parameter on the ajax call to operate on the data after the request successfully finishes. This is generally called a **callback**. Other callbacks exist. See <http://api.jquery.com/jQuery.ajax/> for the complete information. ``` $.aja...
Has anyone been able to write out UTF-8 characters using python's xlwt?
7,184,454
5
2011-08-25T02:25:16Z
7,265,898
10
2011-09-01T03:39:14Z
[ "python", "utf-8", "multibyte", "xlwt" ]
I'm trying to write data to an excel file that includes Japanese characters. I'm using codec.open() to get the data, and that seems to work fine, but I run into this error when I try to write the data: ``` UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-17: ordinal not in range(128) ``` I don...
In an Excel 97-2003 XLS file, each piece of text is encoded in `latin1` if that is possible, otherwise `UTF-16LE`, with a flag to show which. To do that, xlwt nees a `unicode` object. If the caller supplies a `str` object, xlwt will attempt to decode it using the encoding specified in the Workbook() call (default is `a...
python range() with duplicates?
7,185,495
4
2011-08-25T05:23:34Z
7,185,565
11
2011-08-25T05:32:23Z
[ "python", "list", "range", "generator" ]
So everybody knows that I can get a list of numbers with `range` like so: ``` >>> range(5) [0, 1, 2, 3, 4] ``` And if I want, say, 3 copies of each number I could use: ``` >>> range(5)*3 [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4] ``` But suppose I wanted them like this instead? ``` [0, 0, 0, 1, 1, 1, 2, 2, 2, 3...
You can do: ``` >>> [i for i in range(5) for _ in range(3)] [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] ``` the `range(3)` part should be replaced with your number of repetitions... BTW, you should use generators --- Just to make it clearer, the `_` is a variable name for something you don't care about (any name...
Applying the Sobel filter using scipy
7,185,655
10
2011-08-25T05:43:39Z
7,186,582
18
2011-08-25T07:30:18Z
[ "python", "scipy", "edge-detection" ]
I'm trying to apply the Sobel filter on an image to detect edges using scipy. I'm using Python 3.2 (64 bit) and scipy 0.9.0 on Windows 7 Ultimate (64 bit). Currently my code is as follows: ``` import scipy from scipy import ndimage im = scipy.misc.imread('bike.jpg') processed = ndimage.sobel(im, 0) scipy.misc.imsave(...
1) Use a higher precision. 2) You are only calculating the approximation of the derivative along the zero axis. The 2D Sobel operator is explained on [Wikipedia](http://en.wikipedia.org/wiki/Sobel_operator). Try this code: ``` import numpy import scipy from scipy import ndimage im = scipy.misc.imread('bike.jpg') im =...
Why doesn't this Haskell I translated to Python work properly?
7,186,081
5
2011-08-25T06:40:53Z
7,186,110
11
2011-08-25T06:44:13Z
[ "python", "math", "haskell" ]
Haskell: ``` average x y = (x + y) / 2 sqrt' :: (Ord a, Fractional a) => a -> Int -> a sqrt' 0 _ = 0.0 sqrt' 1 _ = 1.0 sqrt' s approximations = (infsqr' s) !! approximations infsqr' n = unfoldr acc 1 where acc guess | guess < 0 = Nothing | otherwise = Just (newguess', newguess') where ...
If you called unfold again, your generator will regenerate again, so you need to assign it to variable. ``` >>> res = unfold(acc, 1) >>> print res.next() 5.0 >>> print res.next() 3.4 >>> ```
Unbounded xrange()
7,186,336
27
2011-08-25T07:05:49Z
7,186,348
43
2011-08-25T07:07:04Z
[ "python", "generator", "xrange" ]
Is there an unbounded version of `xrange` that I can use, or do I have to define it myself? For example ``` squares = (x*x for x in xrange(n)) ``` can only give me a generator for the squares up to `(n-1)**2`, and I can't see any obvious way to call `xrange(infinity)` so that it just keeps on truckin'.
You're describing the basic use of [`itertools.count`](http://docs.python.org/library/itertools.html#itertools.count): ``` import itertools squares = (x*x for x in itertools.count()) ```
Function with varying number of For Loops (python)
7,186,518
17
2011-08-25T07:23:37Z
7,186,570
8
2011-08-25T07:28:47Z
[ "python", "recursion", "for-loop", "nested", "fractals" ]
My problem is difficult to explain. I want to create a function that contains nested for loops, the amount of which is proportional to an argument passed to the function. Here's a hypothetical example: ``` Function(2) ``` ...would involve... ``` for x in range (y): for x in range (y): do_whatever() `...
I'm not clear why you can't use the product of the bounds and do ``` for x in range(y exp n) ``` where n is the # of loops.... You say y exp n will be huge, but I'm sure python can handle it. However, that being said, what about some sort of recursive algorithm? ``` def loop_rec(y, n): if n >= 1: for x ...
Function with varying number of For Loops (python)
7,186,518
17
2011-08-25T07:23:37Z
7,186,607
13
2011-08-25T07:32:11Z
[ "python", "recursion", "for-loop", "nested", "fractals" ]
My problem is difficult to explain. I want to create a function that contains nested for loops, the amount of which is proportional to an argument passed to the function. Here's a hypothetical example: ``` Function(2) ``` ...would involve... ``` for x in range (y): for x in range (y): do_whatever() `...
This problem can be solved by recursion. I am just writing an algorithm here, since I believe this can be a general problem. ``` function Recurse (y, number) if (number > 1) Recurse ( y, number - 1 ) else for x in range (y) whatever() ```
Function with varying number of For Loops (python)
7,186,518
17
2011-08-25T07:23:37Z
7,186,693
8
2011-08-25T07:38:58Z
[ "python", "recursion", "for-loop", "nested", "fractals" ]
My problem is difficult to explain. I want to create a function that contains nested for loops, the amount of which is proportional to an argument passed to the function. Here's a hypothetical example: ``` Function(2) ``` ...would involve... ``` for x in range (y): for x in range (y): do_whatever() `...
this can be done without recursion using `itertools.product` ``` import itertools def function(n): for x in itertools.product(range(n),repeat=n): whatever() ```
set_data and autoscale_view matplotlib
7,187,504
20
2011-08-25T08:50:07Z
7,198,623
28
2011-08-26T00:01:07Z
[ "python", "matplotlib" ]
I have multiple lines to be drawn on the same axes, and each of them are dynamically updated (I use set\_data), The issue being that i am not aware of the x and y limits of each of the lines. And axes.autoscale\_view(True,True,True) / axes.set\_autoscale\_on(True) are not doing what they are supposed to. How do i auto ...
From the [matplotlib docs for autoscale\_view](http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.autoscale_view): > The data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. In that case, use matplotlib.axes.Axes.relim() prior...
BeautifulSoup parser appends semicolons to naked ampersands, mangling URLs?
7,187,744
7
2011-08-25T09:07:37Z
7,188,419
7
2011-08-25T09:59:05Z
[ "python", "beautifulsoup" ]
I am trying to parse some site in python that has links in it to other sites, but in plain text, not in "a" tag. Using BeautifulSoup I get the wrong answer. Consider this code: ``` import BeautifulSoup html = """<html> <head> <title>Test html</title> </head> <body> ...
Apparently BS has an underdocumented [issue parsing ampersands inside URL](http://groups.google.com/group/beautifulsoup/browse_thread/thread/f591f8c795afdd61/ea9b73b423c1032f?lnk=gst&q=semicolon#), I just searched their discussion forum for 'semicolon'. According to that discussion from 2009, naked `&` is strictly not ...
Python re.sub replace with matched content
7,191,209
16
2011-08-25T13:28:42Z
7,191,251
8
2011-08-25T13:31:55Z
[ "python", "regex" ]
Trying to get to grips with regular expressions in Python, I'm trying to output some HTML highlighted in part of a URL. My input is ``` images/:id/size ``` my output should be ``` images/<span>:id</span>/size ``` If I do this in Javascript ``` method = 'images/:id/size'; method = method.replace(/\:([a-z]+)/, '<spa...
Use `\1` instead of `$1`. > \number Matches the contents of the group of the same number. <http://docs.python.org/library/re.html#regular-expression-syntax>
Python re.sub replace with matched content
7,191,209
16
2011-08-25T13:28:42Z
7,191,254
30
2011-08-25T13:32:01Z
[ "python", "regex" ]
Trying to get to grips with regular expressions in Python, I'm trying to output some HTML highlighted in part of a URL. My input is ``` images/:id/size ``` my output should be ``` images/<span>:id</span>/size ``` If I do this in Javascript ``` method = 'images/:id/size'; method = method.replace(/\:([a-z]+)/, '<spa...
Simply use [`\1`](http://docs.python.org/library/re.html#regular-expression-syntax) instead of `$1`: ``` In [1]: import re In [2]: method = 'images/:id/huge' In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method) Out[3]: 'images/<span>:id</span>/huge' ``` Also note the use of [raw strings](http://docs.python.org/...
How can I set the PATH for supervisord so it finds the executables
7,191,613
5
2011-08-25T13:54:56Z
19,965,816
9
2013-11-13T22:32:01Z
[ "python", "shell", "environment-variables", "supervisord" ]
I'm trying to setup `supervisor.conf`. One of my apps requires node.js, but node is not installed system wise. Also, because it needs to bind to port 80 it need to run as root. How can I modify the `PATH` variable so that supervisord can find the `node` executable (which is located in a directory) and run the node.js a...
You can add it in the command using env: ``` [program:web] command=env PATH="/path/to/where/node/executable/is" node web.js -c config.json ``` It seems environment does not work on some cases.
how to format a shell command line from a list of arguments in python
7,192,104
4
2011-08-25T14:27:03Z
7,192,300
11
2011-08-25T14:38:02Z
[ "python", "shell", "command-line", "formatting", "command-line-arguments" ]
I have a list of arguments, e.g. `["hello", "bobbity bob", "bye"]`. How would I format these so they would be passed appropriately to a shell? **Wrong**: ``` >>> " ".join(args) hello bobbity bob bye ``` **Correct**: ``` >>> magic(args) hello "bobbity bob" bye ```
You could use the undocumented but long-stable (at least [since Oct 2004](http://svn.python.org/view/python/trunk/Lib/subprocess.py?revision=37587&view=markup)) `subprocess.list2cmdline`: ``` In [26]: import subprocess In [34]: args=["hello", "bobbity bob", "bye"] In [36]: subprocess.list2cmdline(args) Out[36]: 'hell...
Concatenation of tuples
7,192,391
6
2011-08-25T14:43:46Z
7,192,409
24
2011-08-25T14:45:11Z
[ "python-3.x", "tuples", "python" ]
1. Normal text: * I'm having some problems with coding on python 3.2.1. Actually I'm taking online lectures that are on python 2.5. 2. Here is the code: ``` x = 100 divisors = () for i in range(1,x): if x%i == 0: divisors = divisors + (i) ``` 3. on running the program, following er...
`(1)` is not a tuple, its just a parenthesized expression. To make it a tuple, add a trailing comma, `(1,)`
South appears to be loading initial_data.json twice
7,192,675
3
2011-08-25T15:01:25Z
7,193,402
7
2011-08-25T15:50:56Z
[ "python", "django", "django-south" ]
I've been working with South on a new Django project. I've just added a new model `Client`, and I'd like to make ensure that any of the tests that get run, or any new database setups, always get populated with an instance of `Client`, so I've added a new instance into the project's `initial_data.json`. Now whenever I...
The recommended solution is not to use initial data fixtures with South at all, but to call loaddata from inside a migration instead: See this discussion on Google Groups - [link](http://groups.google.com/group/south-users/browse_thread/thread/3d6a509fad540e62?pli=1)
Python: How does "IN" (for lists) works?
7,192,900
5
2011-08-25T15:16:15Z
7,192,946
7
2011-08-25T15:20:06Z
[ "python", "list", "data-structures" ]
I have this code ``` list = ['a','b','c'] if 'b' in list: return "found it" return "not found" ``` Now, how does this work? Does it traverse the whole list comparing the element? Does it use some kind of hash function? Also, is it the same for this code? ``` list.index('b') ```
Python Wiki [states](http://wiki.python.org/moin/TimeComplexity) that `val in list` has `O(n)` average time complexity. This implies linear search. I expect `list.index(val)` to be the same. After all, `list` is, well, a list. If you want hash tables, consider using `set` or `dict`.
Python: How does "IN" (for lists) works?
7,192,900
5
2011-08-25T15:16:15Z
7,192,950
16
2011-08-25T15:20:23Z
[ "python", "list", "data-structures" ]
I have this code ``` list = ['a','b','c'] if 'b' in list: return "found it" return "not found" ``` Now, how does this work? Does it traverse the whole list comparing the element? Does it use some kind of hash function? Also, is it the same for this code? ``` list.index('b') ```
`in` uses the method `__contains__`. Each container type implements it differently. For a list, it uses linear search. For a dict, it uses a hash lookup.
Run External Python Programs with Eclipse PyDev
7,194,424
7
2011-08-25T17:10:20Z
7,203,663
8
2011-08-26T10:57:44Z
[ "python", "eclipse", "aptana", "pydev" ]
I want to use the refactoring enabled by PyDev but think it is a little ridiculous to create a project folder in my Eclipse workspace for every single little python script I create. I'm able to get refactoring by editing the file in Eclipse using `File > Open File...`. However, I still have to go to the Terminal to ru...
The latest PyDev already has improved things a bit... the workflow for the use-case of dealing with external files is the following (checking on PyDev 2.2.2 and Eclipse 3.7): 1. Drag file from filesystem to Eclipse (should open the file to edit it). 2. Press F9 with the editor open to run the file... It'll still ask y...
Read in file - change contents - write out to same file
7,194,665
6
2011-08-25T17:32:25Z
7,195,120
10
2011-08-25T18:07:22Z
[ "python" ]
I have to read in a file, change a sections of the text here and there, and then write out to the same file. Currently I do: ``` f = open(file) file_str = f.read() # read it in as a string, Not line by line f.close() # # do_actions_on_file_str # f = open(file, 'w') # to clear the file f.write(file_str) f.close() ``` ...
That looks straightforward, and clear already. Any suggestion depends on how big the files are. If not really huge that looks fine. If really large, you could process in chunks. But you could use a context manager, to avoid the explicit closes. ``` with open(filename) as f: file_str = f.read() # do stuff with fi...
Assigning return value of function to a variable, with multiprocessing? And a problem about IDLE?
7,194,884
10
2011-08-25T17:48:19Z
7,216,618
9
2011-08-27T18:51:49Z
[ "python", "return-value", "multiprocessing" ]
I'm trying to understand multiprocessing in python. ``` from multiprocessing import Process def multiply(a,b): print(a*b) return a*b if __name__ == '__main__': p = Process(target= multiply, args= (5,4)) p.start() p.join() print("ok.") ``` In this codeblock, for example, if there was an varia...
Ok, i somehow managed this. I looked to python documentation, and i learnt that: with using Queue class, we can get return values from a function. And final version of my code is like this: ``` from multiprocessing import Process, Queue def multiply(a,b,que): #add a argument to function for assigning a queue que....