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 |
|---|---|---|---|---|---|---|---|---|---|
Python using enumerate inside list comprehension | 10,777,271 | 62 | 2012-05-27T21:03:37Z | 10,777,408 | 29 | 2012-05-27T21:27:34Z | [
"python",
"list",
"iteration",
"list-comprehension"
] | Lets suppose I have a list like this:
```
mylist = ["a","b","c","d"]
```
To get the values printed along with their index I can use Python's `enumerate` function like this
```
>>> for i,j in enumerate(mylist):
... print i,j
...
0 a
1 b
2 c
3 d
>>>
```
Now, when I try to use it inside a `list comprehension` it g... | Just to be really clear, this has nothing to do with `enumerate` and everything to do with list comprehension syntax.
This list comprehension returns a list of tuples:
```
[(i,j) for i in range(3) for j in 'abc']
```
this a list of dicts:
```
[{i:j} for i in range(3) for j in 'abc']
```
a list of lists:
```
[[i,j... |
Python using enumerate inside list comprehension | 10,777,271 | 62 | 2012-05-27T21:03:37Z | 10,777,810 | 9 | 2012-05-27T22:46:28Z | [
"python",
"list",
"iteration",
"list-comprehension"
] | Lets suppose I have a list like this:
```
mylist = ["a","b","c","d"]
```
To get the values printed along with their index I can use Python's `enumerate` function like this
```
>>> for i,j in enumerate(mylist):
... print i,j
...
0 a
1 b
2 c
3 d
>>>
```
Now, when I try to use it inside a `list comprehension` it g... | If you're using long lists, it appears the list comprehension's faster, not to mention more readable.
```
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))"
1000000 loops, best of 3: 1.61 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]"
1... |
My first web app (Python): use CGI, or a framework like Django? | 10,777,502 | 5 | 2012-05-27T21:43:27Z | 10,777,923 | 7 | 2012-05-27T23:11:43Z | [
"python",
"django",
"apache",
"google-app-engine",
"cgi"
] | I donât want to burden you all with the details, but basically Iâm a 2nd year compsci student with no Web dev experience.
Basically I want to create a small âweb appâ that takes in input from a html form, have a python script perform some calculations, and re-display those results in your browser.
As of right... | Django, while being nice, all-encompassing and well-supported, is sometimes too much for a small web application. Django wants you to play by its rules from the beginning, you'll have to avoid things like the database and admin panels if you don't need them. It's also easier, with Django, to follow its project layout, ... |
Accessing Facebook API Data with Python | 10,778,018 | 7 | 2012-05-27T23:37:32Z | 10,778,328 | 8 | 2012-05-28T00:53:22Z | [
"python",
"facebook"
] | What is the best library to access Facebook Graph API data for python 2.7 or python 3.0?
I'm new to the Facebook Graph API. Doing some research, in the past people used pyfacebook and the Facebook Python SDK, but it seems neither are being updated / supported anymore. What are people currently using to access the data... | People use SDKs. It's the most manageable way to do it.
The Python SDK (facebook) is up to date and has a repo at <https://github.com/pythonforfacebook/facebook-sdk>. It's not official because Facebook doesn't officially support anymore *but* it is maintained (last commit 12 days ago) *and* people do use it.
facepy a... |
Recursively creating hardlinks using python | 10,778,229 | 7 | 2012-05-28T00:28:11Z | 10,778,930 | 11 | 2012-05-28T03:07:03Z | [
"python",
"directory",
"directory-structure",
"hardlink"
] | What I basically would like to do is `cp -Rl dir1 dir2`. But as I understand it, python only provides `shutils.copytree(src,dst)` which actually copies the files, but has no possibility of hardlinking the files instead.
I know that I could invoke the `cp` command using the `subprocess` module, but I'd rather like to f... | You just have to call `os.system("cp -Rl dir1 dir2")`, no need hand write your own function.
**Edited**: Since you want do this in python.
You are right: It **IS** available in module `shutil`
```
shutil.copytree(src, dst, copy_function=os.link)
``` |
Multiple URL segment in Flask and other Python frameowrks | 10,778,346 | 2 | 2012-05-28T00:57:42Z | 10,782,775 | 8 | 2012-05-28T10:03:47Z | [
"python",
"frameworks",
"flask"
] | I'm building an application in both Bottle and Flask to see which I am more comfortable with as Django is too much 'batteries included'.
I have read through the routing documentation of both, which is very clear and understandable but I am struggling to find a way of dealing with an unknown, possibly unlimited number ... | I'm fairly new to Flask myself, but from what I've worked out so far, I'm pretty sure that the idea is that you have lots of small route/view methods, rather than one massive great switching beast.
For example, if you have urls like this:
```
http://example.com/unit/57/
http://example.com/unit/57/page/23/
http://exam... |
python pyplot annotations | 10,778,733 | 3 | 2012-05-28T02:23:35Z | 10,778,967 | 9 | 2012-05-28T03:13:36Z | [
"python",
"marker",
"matplotlib"
] | I am currently using the following code to plot a graph using python pyplot:
```
plt.plot([row[2] for row in data],[row[1] for row in data], type, marker='o', label=name)
```
However, instead of the default marker of `'o'` I want the marker at the points to be the data in `row[1]`
Can someone explain how to do thi... | So you want to annotate the y-values of the points along your line?
Use `annotate` for each point. For example:
```
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots()
# Plot the line connecting the points
ax.plot(x, y)
# At each point, plot the y-value with a white box behind it
... |
Python "OverflowError" | 10,778,764 | 8 | 2012-05-28T02:30:25Z | 10,778,815 | 15 | 2012-05-28T02:40:45Z | [
"python",
"overflow"
] | I am just starting to learn to code in Python. I am trying to write some code to answer this Project Euler Question:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My program works with the test case of 13195, but when I try to enter 600851475143, I get ... | The `range` function creates a list and tries to store it in memory. Creating a list many numbers long is what's causing the OverflowError. You can use `xrange` instead to get a generator which produces the numbers on demand.
That said, I think you'll find that your algorithm is way too slow for calculating large prim... |
Lock mutable objects as immutable in python | 10,778,824 | 11 | 2012-05-28T02:42:31Z | 10,778,940 | 13 | 2012-05-28T03:08:39Z | [
"python",
"immutability"
] | How do I "lock" an object in Python?
Say I have:
```
class Foo:
def __init__(self):
self.bar = []
self.qnx = 10
```
I'd modify foo as much as I want:
```
foo = Foo()
foo.bar.append('blah')
foo.qnx = 20
```
But then I'd like to be able to "lock" it such that when I try
```
lock(foo)
foo.bar.append('blah'... | Here is a simple way of doing this.
```
class Foo(object):
def __init__(self):
self._bar = []
self._qnx = 10
self._locked= False
@property
def locked(self):
return self._locked
def lock(self):
self._locked = True
@property
def bar(self):
if sel... |
How can I change urlencode to python dictionary | 10,778,828 | 2 | 2012-05-28T02:43:10Z | 10,778,894 | 7 | 2012-05-28T02:58:58Z | [
"python",
"django",
"urlencode"
] | I have got data from POST like
```
first_name=jon&nick_name=harry
```
How can I change this to a python dictionary, like :
```
{
"first_name":"jon",
"nick_name":"harry"
}
``` | ```
>>> urlparse.parse_qs("first_name=jon&nick_name=harry")
{'nick_name': ['harry'], 'first_name': ['jon']}
``` |
python split function -avoids last empy space | 10,780,423 | 9 | 2012-05-28T06:45:58Z | 10,780,447 | 18 | 2012-05-28T06:47:46Z | [
"python",
"split"
] | I have a simple doubt in using split function.
```
str = 'James;Joseph;Arun;'
str.split(';')
```
I got the result `['James', 'Joseph', 'Arun', '']`
I need the output as `['James', 'Joseph', 'Arun']`
What is the best way to do it. Thanks all in advance | To remove all empty strings you can use a list comprehension:
```
>>> [x for x in my_str.split(';') if x]
```
Or the filter/bool trick:
```
>>> filter(bool, my_str.split(';'))
```
Note that this will also remove empty strings at the start or in the middle of the list, not just at the end.
* [Remove empty strings f... |
python split function -avoids last empy space | 10,780,423 | 9 | 2012-05-28T06:45:58Z | 10,780,463 | 13 | 2012-05-28T06:48:51Z | [
"python",
"split"
] | I have a simple doubt in using split function.
```
str = 'James;Joseph;Arun;'
str.split(';')
```
I got the result `['James', 'Joseph', 'Arun', '']`
I need the output as `['James', 'Joseph', 'Arun']`
What is the best way to do it. Thanks all in advance | First remove `;` from the right edge of the string:
```
s.rstrip(';').split(';')
```
You can also use `filter()` (which will filter off also empty elements that weren't found at the end of the string). But the above is really the cleanest approach in my opinion, when you want to avoid empty element at the end, result... |
How to disable the minor ticks of log-plot in Matplotlib? | 10,781,077 | 9 | 2012-05-28T07:46:43Z | 10,781,270 | 12 | 2012-05-28T08:03:38Z | [
"python",
"matplotlib"
] | Here is a simple plot:

1) How to disable the ticks?
2) How to reduce their number?
Here is a sample code:
```
from pylab import *
import numpy as np
x = [5e-05, 5e-06, 5e-07, 5e-08, 5e-09, 5e-10]
y = [-13, 14, 100, 120, 105, 93]
def myfunc(x,p):
... | ```
plt.minorticks_off()
```
Turns em off!
To change the number of them/position them, you can use the `subsx` parameter. like this:
```
plt.xscale('log', subsx=[2, 3, 4, 5, 6, 7, 8, 9])
```
From the [docs](http://matplotlib.sourceforge.net/api/pyplot_api.html?highlight=tick#matplotlib.pyplot.xscale):
> subsx/subs... |
Network clustering and python | 10,782,345 | 3 | 2012-05-28T09:32:51Z | 10,782,397 | 7 | 2012-05-28T09:36:44Z | [
"python",
"graph",
"cluster-analysis",
"data-visualization"
] | I have a network graph data and want to divide the nodes into clusters based on the distances between the nodes. Is there any python library or some other tool to which I can give the input by python script and can query which cluster a node belongs to. | scikit-learn includes various [clustering algorithms](http://scikit-learn.org/stable/modules/clustering.html), including a few that accept distance matrices as input.
[Disclaimer: I'm involved in the scikit-learn project.] |
Doing the ls output magic in python | 10,783,971 | 3 | 2012-05-28T11:31:47Z | 10,784,024 | 8 | 2012-05-28T11:35:11Z | [
"python",
"linux",
"bash",
"shell"
] | I want to have the same output as ls creates in a bash or python script.
I don't mean listing directories, but the thing ls does to be able to be "loopable". Example:
```
# ls
a b c d
# ls | head -n 1
a
# for i in $(ls); do echo "file: $i"; done
file: a
file: b
file: c
file: d
```
How can ls be like that and still ... | The trick is to detect whether the output is a terminal, in which case `ls` uses columns, or not, in which case it outputs in a simpler format.
In Unix, you should be able to use Python's `os.isatty()` function to get this information.
From the shell, you can use the `tty(1)` program: `tty -s <&1`. This will exit tru... |
Non-blocking ORM for Tornado? | 10,784,254 | 23 | 2012-05-28T11:54:25Z | 26,663,553 | 10 | 2014-10-30T21:22:37Z | [
"python",
"database",
"orm",
"tornado"
] | Is there any asynchronous Python ORM other than [Twistar](http://findingscience.com/twistar/)?
I'm looking for lightweight ORM for non-blocking API, built on top of tornado. Of course, I can write raw SQL queries using momoko, but I'd like to work with objects. | Sure, it is! Look at [peewee](https://github.com/coleifer/peewee) and [peewee-async](https://github.com/05bit/peewee-async) extension. Disclaimer: extension is only for PostgreSQL at the moment and I'm an author of extension :)
It's not specifically for Tornado, but Tornado can run on asyncio event loop. |
Can I delay a decorator to happen until I call the function? | 10,784,699 | 2 | 2012-05-28T12:30:10Z | 10,784,778 | 7 | 2012-05-28T12:36:00Z | [
"python",
"decorator"
] | First I've learned what Python decorators are and how they work. And I'd like it to do something like this:
```
def age_over_18(go_enjoy_yourself):
def go_home_and_rethink_your_life():
return 'So you should go home and rethink your life.'
return go_enjoy_yourself if age_stored_somewhere > 18 else go... | The trick is just to ensure that the check happens in your inner function, not the outer one. In your case:
```
def age_over_18(go_enjoy_yourself):
def are_you_over_18():
if age > 18:
return go_enjoy_yourself()
else:
return 'So you should go home and rethink your life.'
... |
for(i=0;True;i++) in python? | 10,785,218 | 3 | 2012-05-28T13:09:49Z | 10,785,286 | 7 | 2012-05-28T13:14:13Z | [
"python"
] | Is there a more pythonic way, or at least a shorter and simpler way, to do this:
```
i = 1
while True:
res = lookup(i) # returns a value or None
if res is None:
break
else:
i += 1
yield res
``` | You could make use of [`itertools`](http://docs.python.org/library/itertools.html):
```
from itertools import takewhile, count
# ...
def myfunc():
return takewhile(lambda x: x is not None, (lookup(i) for i in count(1)))
```
If you don't like `takewhile` for whatever reason:
```
for i in count(1):
res = loo... |
How can I identify numbers with space separator for thousands in a string with Python? | 10,786,118 | 3 | 2012-05-28T14:16:04Z | 10,786,150 | 8 | 2012-05-28T14:17:57Z | [
"python",
"regex"
] | I'm working with text that uses spaces as thousands separators, e.g. 400 or 40 000 or 40 000 000 or 4 000 000 000. I need to identify the number in the string. Once identified, there are many options to re-format the number. I'm a rookie at regex. This doesn't work:
```
import re
line = '40) He had 120 hours to increa... | The following will do it:
```
regex = re.compile(r"(\d+(?:\s+\d+)*)")
```
This uses a non-capturing group `(?:)` that matches one or more spaces (`\s+`) followed by at least one digit (`\d+`). The entire non-capture group can appear zero or more times (`*`).
It is worth pointing out that it's generally a good idea t... |
2d hsv color space in matplotlib | 10,787,103 | 7 | 2012-05-28T15:34:09Z | 10,791,901 | 11 | 2012-05-29T00:51:51Z | [
"python",
"numpy",
"matplotlib"
] | I'm trying to reproduce this graph in matplotlib (taken from wikipedia)
<http://i.imgur.com/To0BO.png>
basically a 2d hsv color space where saturation is set to 1.0. here's what I have done so far
```
from pylab import *
from numpy import outer
x = outer(arange(0, 1, 0.01), ones(100))
imshow(transpose(x), cmap=cm.... | You need to create the HSV array and convert it to RGB, here is an example:
```
import numpy as np
import pylab as pl
from matplotlib.colors import hsv_to_rgb
V, H = np.mgrid[0:1:100j, 0:1:300j]
S = np.ones_like(V)
HSV = np.dstack((H,S,V))
RGB = hsv_to_rgb(HSV)
pl.imshow(RGB, origin="lower", extent=[0, 360, 0, 1], as... |
How to handle a long SQL statement string in Python | 10,787,163 | 3 | 2012-05-28T15:39:01Z | 10,787,251 | 7 | 2012-05-28T15:46:02Z | [
"python",
"sql"
] | I am trying get information from an SQL database using python
I was able to connect and retrieve data when the SQL statement was simple such as
```
#cursor.execute("SELECT * FROM Client WHERE UsesTimesheet = 1 ORDER BY ClientName")
```
However when I move to a more complex statement I get the error shown below
```
... | Your python string is being joined together without newlines, thus there is no space before the `where` keyword. Better use triple-quoted strings when working with multi-line string literals:
```
cursor.execute("""\
SELECT PJI.*, PJO.*,
CST.ABCGS
FROM dbo.Traverse AS TRE
LEFT OUTER JOIN dbo.T... |
Optimizing numpy.dot with Cython | 10,788,267 | 8 | 2012-05-28T17:15:34Z | 10,791,730 | 10 | 2012-05-29T00:20:57Z | [
"python",
"numpy",
"cython",
"dot-product"
] | I have the following piece of code which I'd like to optimize using Cython:
```
sim = numpy.dot(v1, v2) / (sqrt(numpy.dot(v1, v1)) * sqrt(numpy.dot(v2, v2)))
dist = 1-sim
return dist
```
I have written and compiled the .pyx file and when I ran the code I do not see any significant improvement in performance. Accordi... | As a general note, if you are calling numpy functions from within cython and doing little else, you generally will see only marginal gains if any at all. You generally only get massive speed-ups if you are statically typing code that makes use of an explicit for loop at the python level (not in something that is callin... |
python defaultdict: 0 vs. int and [] vs list | 10,788,378 | 21 | 2012-05-28T17:26:39Z | 10,788,464 | 27 | 2012-05-28T17:35:04Z | [
"python",
"collections",
"defaultdict"
] | Is there any difference between passing `int` and `lambda: 0` as arguments? Or between `list` and `lambda: []`?
It looks like they do the same thing:
```
from collections import defaultdict
dint1 = defaultdict(lambda: 0)
dint2 = defaultdict(int)
dlist1 = defaultdict(lambda: [])
dlist2 = defaultdict(list)
for ch in '... | All that `defaultdict` requires is a callable object that will return what should be used as a default value when called with no parameters.
If you were to call the `int` constructor, it would return `0` and if you were to call `lambda: 0`, it would return `0`. Same with the lists. The only difference here is that the... |
NodeJS String format like Python? | 10,788,408 | 6 | 2012-05-28T17:29:52Z | 18,363,666 | 9 | 2013-08-21T17:10:26Z | [
"javascript",
"python",
"node.js",
"v8"
] | In python, I can do the following:
```
name = "bob"
print("Hey, %s!" % name)
```
Is there anything similar to that (or Python's `.format()`) in JavaScript/NodeJS? | You can use [util.format](http://nodejs.org/api/util.html#util_util_format_format), it's `printf` like function. |
Google App Engine vs WebFaction | 10,788,661 | 5 | 2012-05-28T17:54:50Z | 10,788,794 | 9 | 2012-05-28T18:08:26Z | [
"python",
"google-app-engine",
"webfaction"
] | Possible duplicates:
[GAE + Python vs Webfaction + Python + django - for a relative new dev](http://stackoverflow.com/questions/3326308/gae-python-vs-webfaction-python-django-for-a-relative-new-dev)
Hello,
I am developing one of my hobby project using django-nonrel on google app engine. The basic part of the applicati... | Google App Engine and webfaction/linode are unrelated beyond the point that they both ultimately host your application.
GAE is a cloud platform-as-service for hosting an app, which usually conforms to an API they expose to you for the individual services you would like to use. They give you the free tier and then make... |
Shopping list in Python | 10,789,501 | 2 | 2012-05-28T19:22:12Z | 10,789,803 | 7 | 2012-05-28T19:53:13Z | [
"python"
] | I'm learning Python (and programming in general) by making small programs. Below is a basic shopping program which will return a list of items to buy based on the selected food.
I'd like to improve it and allow user to select several foods at once (e.g. user input would be "1, 2, 3") and return a list of ingredients b... | There are some common problems with your code, so let's begin by fixing those.
You have multiple items you want to present at the user, and you are hard-coding those values. This makes a lot of effort for you as you have to repeat yourself a lot. Look at your choice lines, they all come to basically the same thing. Yo... |
Python 3 utf-8 encoding seem to be wrong? | 10,789,568 | 2 | 2012-05-28T19:28:47Z | 10,789,676 | 8 | 2012-05-28T19:39:35Z | [
"python",
"unicode",
"python-3.x"
] | I've messed in the past with Python 3.2 but now I face a somewhat confusing situation about utf-8 encoding in python.
For example, say I have this piece of code:
```
'×'.encode()
```
The result is `b'\xd7\x90'` (or `0xD790`), this, however, is wrong: the utf-8 encoding of the Hebrew character Alef is supposed to b... | The [unicode *codepoint* of × is U+05D0](http://www.fileformat.info/info/unicode/char/05D0/index.htm), or `101 1101 0000` in binary. The UTF-8 encoding of an 11-bit codepoint ABCDEFGHIJK [is](http://en.wikipedia.org/wiki/UTF-8#Description)
```
110A BCDE 10FG HIJK
# i.e.
1101 0111 1001 0000 # binary
d 7 9 ... |
No cv.Point in Python OpenCV on latest stable Debian | 10,790,116 | 7 | 2012-05-28T20:28:25Z | 10,790,310 | 7 | 2012-05-28T20:52:48Z | [
"python",
"opencv",
"debian"
] | When trying to draw a circle on an image using cv.Circle, I realized that there is no cv.Point function to create a cvPoint in Python OpenCV. I'm using the latest stable version of Debian and I installed all the Python OpenCV packages with Synaptic. How do I create a cvPoint to use with the cv.Circle function? | Use tuples. Here is example of filled green circle:
```
cv2.circle(img, (x1, y1), 3, (0, 255, 0), -1)
``` |
Numpy: Check array for string data type | 10,790,312 | 11 | 2012-05-28T20:52:57Z | 10,790,620 | 10 | 2012-05-28T21:31:50Z | [
"python",
"arrays",
"string"
] | how can I determine if a Numpy array contains a string? The array `a` in
```
a = np.array('hi world')
```
has data type `dtype('|S8')`, where `8` refers to the number of characters in the string.
I don't see how regular expressions (such as `re.match('\|S\d+', a.dtype)`) would work here as the data type isn't simply... | ```
a.dtype.char == 'S'
```
or
```
a.dtype.type is np.string_
```
See [NumPy docs, Data type objects, Attributes](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#attributes). |
Order a list by all item's digits in Python | 10,790,645 | 5 | 2012-05-28T21:34:54Z | 10,790,714 | 7 | 2012-05-28T21:43:30Z | [
"python",
"sorting"
] | # I want to sort a list by each item's digit.
Example:
```
myCmpItem = '511'
myList = ['111','222','333','444','555','123']
(some magic)
mySortedList = ['111', '222', '333', '123', '444', '555']
```
# How the algorithm should work:
* Compare each digit of current item in myList with myCmpItem
+ For the first it... | First, make a list of integers from `myCmpItem` to make subtraction possible.
```
myCmpItem = map(int, myCmpItem)
```
Then, define a function that calculates the distance between an item and `myCmpItem`. We need to map the items to lists of integers as well. The rest is just the vanilla formula for [L1 distance](http... |
Getting container/parent object from within python | 10,791,588 | 10 | 2012-05-28T23:52:05Z | 10,791,613 | 17 | 2012-05-28T23:56:42Z | [
"python",
"class",
"object",
"containers"
] | In Python, is it possible to get the object, say Foo, that contains another object, Bar, from within Bar itself? Here is an example of what I mean
```
class Foo(object):
def __init__(self):
self.bar = Bar()
self.text = "Hello World"
class Bar(object):
def __init__(self):
self.newText =... | Pass a reference to the Bar object, like so:
```
class Foo(object):
def __init__(self):
self.text = "Hello World" # has to be created first, so Bar.__init__ can reference it
self.bar = Bar(self)
class Bar(object):
def __init__(self, parent):
self.parent = parent
self.newText =... |
How do I discretize values in a pandas DataFrame and convert to a binary matrix? | 10,791,661 | 6 | 2012-05-29T00:06:52Z | 11,005,432 | 25 | 2012-06-12T21:52:56Z | [
"python",
"pandas",
"dataframe"
] | I mean something like this:
I have a DataFrame with columns that may be categorical or nominal. For each observation (row), I want to generate a new row where every possible value for the variables is now its own binary variable. For example, this matrix (first row is column labels)
```
'a' 'b' 'c'
one 0.... | Note that I have implemented new `cut` and `qcut` functions for discretizing continuous data:
<http://pandas-docs.github.io/pandas-docs-travis/basics.html#discretization-and-quantiling> |
Python dictionary that defaults to key? | 10,791,738 | 20 | 2012-05-29T00:22:04Z | 10,791,777 | 25 | 2012-05-29T00:28:39Z | [
"python",
"dictionary",
"defaultdict"
] | Is there a way to get a defaultdict to return the key by default? Or some data structure with equivalent behavior? I.e., after initializing dictionary `d`,
```
>>> d['a'] = 1
>>> d['a']
1
>>> d['b']
'b'
>>> d['c']
'c'
```
I've only seen default dictionaries take functions that don't take parameters, so I'm not sure i... | I'd override the `__missing__` method of `dict`:
```
>>> class MyDefaultDict(dict):
... def __missing__(self, key):
... self[key] = key
... return key
...
>>> d = MyDefaultDict()
>>> d['joe']
'joe'
>>> d
{'joe': 'joe'}
``` |
Python dictionary that defaults to key? | 10,791,738 | 20 | 2012-05-29T00:22:04Z | 10,791,812 | 7 | 2012-05-29T00:36:54Z | [
"python",
"dictionary",
"defaultdict"
] | Is there a way to get a defaultdict to return the key by default? Or some data structure with equivalent behavior? I.e., after initializing dictionary `d`,
```
>>> d['a'] = 1
>>> d['a']
1
>>> d['b']
'b'
>>> d['c']
'c'
```
I've only seen default dictionaries take functions that don't take parameters, so I'm not sure i... | **Edit:** Oops, I just realized that code in my file originally came from another stackoverflow answer! <http://stackoverflow.com/a/2912455/456876>, go upvote that one.
This is what I use - it's a defaultdict variant that passes the key as an argument to the default-value factory function that's passed as an argument ... |
What scripts would go into a bin folder of a Python package? | 10,792,588 | 13 | 2012-05-29T02:58:42Z | 11,747,169 | 17 | 2012-07-31T19:04:25Z | [
"python",
"folder",
"packages",
"bin"
] | I'm learning about Python Packages from Learn Python the Hard Way and one of the exercises it says:
> Put a script in the bin directory that you can run
To me, it seems kind of vague. I'm not exactly sure what kind of scripts would go into the bin folder. [The Hitchhiker's Guide to Packaging](http://guide.python-dist... | I just recently got through Ex46 in LPTHW myself. Like you, I was confused by the scripts. In case the other answer was too advanced for you, I ended up just putting in a simple "hello world" script:
```
#!/usr/bin/env python
from test3 import printstring
printstring.printstring("test script working")
print "test ove... |
Troubleshoot TemplateNotFound error from Flask under Gunicorn | 10,792,755 | 12 | 2012-05-29T03:31:42Z | 11,055,096 | 26 | 2012-06-15T16:57:18Z | [
"python",
"nginx",
"installation",
"flask",
"gunicorn"
] | I've got a Flask app that I'm trying to deploy using Gunicorn and nginx. However, although it works fine locally, it throws a TemplateNotFound error when I run in with Gunicorn on my remote server.
I'm not sure how to even start debugging this, let alone why it's failing...would love help on the former, if not the lat... | Are your templates in [app root]/templates/?
If so, check to be sure your path is correct. Put this as the first line in the view that handles your homepage:
```
return app.root_path
```
If that's what you expect to see - or if you're using Blueprints or another method that changes the default Jinja Environment some... |
Python missing or unusable error while cross compiling GDB | 10,792,844 | 6 | 2012-05-29T03:49:26Z | 11,600,411 | 8 | 2012-07-22T12:46:26Z | [
"python",
"gdb"
] | I get this error while attempting to cross-compile GDB (using the `--with-python` flag):
```
checking for python: /usr/bin/python
checking for python2.7: no
configure: error: python is missing or unusable
```
I made sure I had python2.7 installed in `/usr/bin`. I even removed the package and installed it again. I tri... | I had the same problem with gdb 7.4 and finally made it worked after spending some time debugging.
By checking the file `<gdb-source-path>/gdb/config.log`, you will notice one line:
```
configure:11031: gcc -o conftest -g -O2 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Library/Framework... |
Python missing or unusable error while cross compiling GDB | 10,792,844 | 6 | 2012-05-29T03:49:26Z | 11,614,395 | 13 | 2012-07-23T14:19:38Z | [
"python",
"gdb"
] | I get this error while attempting to cross-compile GDB (using the `--with-python` flag):
```
checking for python: /usr/bin/python
checking for python2.7: no
configure: error: python is missing or unusable
```
I made sure I had python2.7 installed in `/usr/bin`. I even removed the package and installed it again. I tri... | I had the same problem on Debian 6.0 when compiling GDB 7.4.1
The solution was to install python headers
```
sudo apt-get install python2.6-dev
```
and then configure with the right flag
```
./configure --with-python
``` |
Python star unpacking for version 2.7 | 10,792,970 | 19 | 2012-05-29T04:12:55Z | 10,792,997 | 21 | 2012-05-29T04:16:45Z | [
"python",
"iterable-unpacking"
] | As mentioned [here](http://stackoverflow.com/a/431959/386279), you can use the star for unpacking an unknown number of variables (like in functions), but only in python 3:
```
>>> a, *b = (1, 2, 3)
>>> b
[2, 3]
>>> a, *b = (1,)
>>> b
[]
```
In python 2.7, the best I can come up with is (not terrible, but annoying):
... | in python 2.X, you can do:
```
c = (1, 2, 3)
a, b = c[0], c[1:]
```
as long as `c` has at east one member it will work because if `c` only has 1 thing in it `c[1:]` is `[]`.
You should probably make sure there is at least one thing in `c` though, or else `c[0]` will raise an exception.
You could do something like:
... |
Needed advice to automate REST services test | 10,793,154 | 10 | 2012-05-29T04:41:41Z | 10,803,350 | 18 | 2012-05-29T16:45:45Z | [
"python",
"api",
"rest",
"testing",
"automated-tests"
] | I am kind of newbie to REST and testing dept. I needed to write automation scripts to test our REST services.We are planning to run these scripts from a Jenkins CI job regularly. I prefer writing these in python as we already have UI functionality testing scripts in python generated by selenium IDE, but I am open to an... | I usually use [Cucumber](https://github.com/cucumber/cucumber) to test my restful APIs. The following example is in Ruby, but could easily be translated to python using either [the rubypy gem](https://github.com/cucumber/cucumber/tree/master/examples/python) or [lettuce](http://lettuce.it/).
Start with a set of RESTfu... |
Python dictionary search values for keys using regular expression | 10,795,973 | 17 | 2012-05-29T08:56:22Z | 10,796,073 | 21 | 2012-05-29T09:03:28Z | [
"python"
] | I am trying to implement to search for a value in Python dictionary for specific key values (using regular expression as a key).
Example:
I have a Python dictionary which has values like:
```
{'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
```
I need to search... | If you only need to check keys that are starting with `"seller_account"`, you don't need regex, just use [startswith()](http://docs.python.org/library/stdtypes.html#str.startswith)
```
my_dict={'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
for key, value in my_... |
Difference between calling sys.exit() and throwing exception | 10,796,821 | 4 | 2012-05-29T09:56:22Z | 10,796,924 | 10 | 2012-05-29T10:02:10Z | [
"python",
"exception-handling"
] | What is the difference between calling `sys.exit()` and throwing an exception in Python?
Let's say I have a Python script which does the following:
1. open a file
2. read lines
3. close it
If the file doesn't exist or an `IOException` gets thrown at runtime, which of the options below makes more sense?
1. no except... | `sys.exit` raises a `SystemExit` itself so from a purely technical point of view there's no difference between raising that exception yourself or using `sys.exit`. And yes you can catch `SystemExit` exceptions like any other exception and ignore it.
So it's just a matter of documenting your intent better.
PS: Note th... |
How to retrieve multiple values returned of a function called through multiprocessing.Process | 10,797,484 | 4 | 2012-05-29T10:38:54Z | 10,799,628 | 10 | 2012-05-29T12:55:41Z | [
"python",
"multiprocessing"
] | I have a scenario like this :
```
for each in content :
pdf_output,job_id=createpdf(each)
if pdf_output :
pdf_output = pdf_output + pdf_output
```
I am trying to parallelize the whole process .Something like this
```
jobs=[]
for each in content :
jobs.append(multiprocessing.Process(ta... | You do not need queues for such a simple task. I would recommend to use pools. The `Pool.map` method can apply a function to a series of values in parallel:
```
import multiprocessing
def createpdf(data):
return ("This is my pdf data: %s\n" % data, 0)
data = [ "My data", "includes", "strings and", "numbers like"... |
Finding the mode of a list | 10,797,819 | 42 | 2012-05-29T11:00:14Z | 10,797,913 | 55 | 2012-05-29T11:07:16Z | [
"python",
"mode"
] | Given a list of items, recall that the *mode* of the list is the item that occurs most often.
I would like to know how to create a function that can find the mode of a list but that displays a message if the list does not have a mode (i.e. all the items in the list only appear once). I want to make this function witho... | You can use the [`Counter`](http://docs.python.org/library/collections.html#collections.Counter) supplied in the [`collections`](http://docs.python.org/library/collections.html) package which has a `mode`-esque function
```
from collections import Counter
data = Counter(your_list_in_here)
data.most_common() # Return... |
Finding the mode of a list | 10,797,819 | 42 | 2012-05-29T11:00:14Z | 10,797,984 | 13 | 2012-05-29T11:12:01Z | [
"python",
"mode"
] | Given a list of items, recall that the *mode* of the list is the item that occurs most often.
I would like to know how to create a function that can find the mode of a list but that displays a message if the list does not have a mode (i.e. all the items in the list only appear once). I want to make this function witho... | Taking a leaf from some statistics software, namely [SciPy](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mode.html) and [MATLAB](http://www.mathworks.co.uk/help/techdoc/ref/mode.html), these just return the smallest most common value, so if two values occur equally often, the smallest of these are re... |
Finding the mode of a list | 10,797,819 | 42 | 2012-05-29T11:00:14Z | 22,458,203 | 14 | 2014-03-17T15:19:11Z | [
"python",
"mode"
] | Given a list of items, recall that the *mode* of the list is the item that occurs most often.
I would like to know how to create a function that can find the mode of a list but that displays a message if the list does not have a mode (i.e. all the items in the list only appear once). I want to make this function witho... | Python 3.4 includes the method [`statistics.mode`](http://docs.python.org/3.4/library/statistics.html#statistics.mode), so it is straightforward:
```
>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
```
You can have any type of elements in the list, not just numeric:
```
>>> mode(["red", "blue",... |
Finding the mode of a list | 10,797,819 | 42 | 2012-05-29T11:00:14Z | 28,129,716 | 39 | 2015-01-24T20:08:44Z | [
"python",
"mode"
] | Given a list of items, recall that the *mode* of the list is the item that occurs most often.
I would like to know how to create a function that can find the mode of a list but that displays a message if the list does not have a mode (i.e. all the items in the list only appear once). I want to make this function witho... | You can use the `max` function and a key. Have a look at [python max function using 'key' and lambda expression](http://stackoverflow.com/questions/18296755/python-max-function-using-key-and-lambda-expression).
```
max(set(list), key=list.count)
``` |
Is it possible to multiprocess a function that returns something in Python? | 10,797,998 | 12 | 2012-05-29T11:12:59Z | 10,798,031 | 10 | 2012-05-29T11:15:28Z | [
"python",
"multiprocessing"
] | In Python I have seen many examples where multiprocessing is called but the target just prints something. I have a scenario where the target returns 2 variables, which I need to use later. For example:
```
def foo(some args):
a = someObject
b = someObject
return a,b
p1=multiprocess(target=foo,args(some args)... | Yes, sure - you can use a number of methods. One of the easiest ones is a shared `Queue`. See an example here: <http://eli.thegreenplace.net/2012/01/16/python-parallelizing-cpu-bound-tasks-with-multiprocessing/> |
Is it possible to multiprocess a function that returns something in Python? | 10,797,998 | 12 | 2012-05-29T11:12:59Z | 10,798,103 | 7 | 2012-05-29T11:19:41Z | [
"python",
"multiprocessing"
] | In Python I have seen many examples where multiprocessing is called but the target just prints something. I have a scenario where the target returns 2 variables, which I need to use later. For example:
```
def foo(some args):
a = someObject
b = someObject
return a,b
p1=multiprocess(target=foo,args(some args)... | I'm copying this example straight from the docs because I can't give you a direct link to it. Note that it prints out the results from the done\_queue, but you can do whatever you like with it.
```
#
# Simple example which uses a pool of workers to carry out some tasks.
#
# Notice that the results will probably not co... |
Is it possible to multiprocess a function that returns something in Python? | 10,797,998 | 12 | 2012-05-29T11:12:59Z | 29,050,564 | 12 | 2015-03-14T15:22:32Z | [
"python",
"multiprocessing"
] | In Python I have seen many examples where multiprocessing is called but the target just prints something. I have a scenario where the target returns 2 variables, which I need to use later. For example:
```
def foo(some args):
a = someObject
b = someObject
return a,b
p1=multiprocess(target=foo,args(some args)... | You are looking to do some embarrassingly parallel work using multiple processes⦠so why not use a `Pool`? A `Pool` will take care of starting up the processes, retrieving the results, and returning the results to you.
Here I use `pathos`, which has a fork of `multiprocessing`, because it has much better serializatio... |
Combining base url with resultant href in scrapy | 10,798,118 | 7 | 2012-05-29T11:20:29Z | 10,798,853 | 8 | 2012-05-29T12:07:50Z | [
"python",
"url",
"scrapy"
] | below is my spider code,
```
class Blurb2Spider(BaseSpider):
name = "blurb2"
allowed_domains = ["www.domain.com"]
def start_requests(self):
yield self.make_requests_from_url("http://www.domain.com/bookstore/new")
def parse(self, response):
hxs = HtmlXPathSelector(response)
urls... | It is because you didn't add the scheme, eg http:// in your base url.
Try: `urlparse.urljoin('http://www.domain.com/', i[1:])`
Or even more easy: `urlparse.urljoin(response.url, i[1:])` as urlparse.urljoin will sort out the base URL itself. |
Warning raised by inserting 4-byte unicode to mysql | 10,798,605 | 5 | 2012-05-29T11:53:30Z | 10,799,465 | 8 | 2012-05-29T12:46:50Z | [
"python",
"mysql",
"regex",
"astral-plane"
] | Look at the following:
```
/home/kinka/workspace/py/tutorial/tutorial/pipelines.py:33: Warning: Incorrect string
value: '\xF0\x9F\x91\x8A\xF0\x9F...' for column 't_content' at row 1
n = self.cursor.execute(self.sql, (item['topic'], item['url'], item['content']))
```
The string `'\xF0\x9F\x91\x8A`, actually is a 4-by... | If MySQL cannot handle UTF-8 codes of 4 bytes or more then you'll have to filter out all unicode characters over codepoint `\U00010000`; UTF-8 encodes codepoints below that threshold in 3 bytes or fewer.
You could use a regular expression for that:
```
>>> import re
>>> highpoints = re.compile(u'[\U00010000-\U0010fff... |
Does anyone have any examples of using OpenCV with python for descriptor extraction? | 10,799,625 | 15 | 2012-05-29T12:55:26Z | 10,804,059 | 13 | 2012-05-29T17:41:27Z | [
"python",
"image-processing",
"opencv",
"surf"
] | I'm trying to use OpenCV to extract SURF descriptors from an image. I'm using OpenCV 2.4 and Python 2.7, but am struggling to find any documentation that provides any information about how to use the functions. I've been able to use the following code to extract features, but I can't find any sensible way to extract de... | Here's an example of some code I've written for extracting SURF features using Python 2.7 and OpenCV 2.4.
```
im2 = cv2.imread(imgPath)
im = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)
surfDetector = cv2.FeatureDetector_create("SURF")
surfDescriptorExtractor = cv2.DescriptorExtractor_create("SURF")
keypoints = surfDetector.... |
How to profile django application with respect to execution time? | 10,799,982 | 10 | 2012-05-29T13:17:17Z | 10,810,670 | 10 | 2012-05-30T05:55:22Z | [
"python",
"django",
"performance",
"cpu-speed",
"django-debug-toolbar"
] | My Django application is insanely slow, I want to figure out what is taking time :
I tried `Django-debug-toolbar` but was unable to find a panel that can give me the break-up of the load time.
My requirements:
* A stack-trace type output with time of execution for each module called to render the page.
* I want to r... | Finally figured out a way to profile my django webapp :
Following 2 django snippets provide `middleware` that profile the whole flow and outputs if
request has `prof` in `GET keys` :
* <http://djangosnippets.org/snippets/727/> [ Uses cProfile ]
* <http://djangosnippets.org/snippets/186/> [ Uses hotshot ]
Plain and s... |
How to profile django application with respect to execution time? | 10,799,982 | 10 | 2012-05-29T13:17:17Z | 13,569,015 | 14 | 2012-11-26T16:30:30Z | [
"python",
"django",
"performance",
"cpu-speed",
"django-debug-toolbar"
] | My Django application is insanely slow, I want to figure out what is taking time :
I tried `Django-debug-toolbar` but was unable to find a panel that can give me the break-up of the load time.
My requirements:
* A stack-trace type output with time of execution for each module called to render the page.
* I want to r... | You can try the profiling panel of the django-debug-toolbar (make sure you use the application's latest version from [github](https://github.com/django-debug-toolbar/django-debug-toolbar)). Enable the panel like so in your settings.py:
```
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.version.VersionDebugPanel',
... |
Run multiple scrapy spiders at once using scrapyd | 10,801,093 | 7 | 2012-05-29T14:23:15Z | 10,804,324 | 19 | 2012-05-29T18:02:14Z | [
"python",
"screen-scraping",
"scrapy",
"scrapyd"
] | I'm using [scrapy](http://scrapy.org/) for a project where I want to scrape a number of sites - possibly hundreds - and I have to write a specific spider for each site. I can schedule *one* spider in a project deployed to scrapyd using:
```
curl http://localhost:6800/schedule.json -d project=myproject -d spider=spider... | My solution for running 200+ spiders at once has been to create a custom command for the project. See <http://doc.scrapy.org/en/latest/topics/commands.html#custom-project-commands> for more information about implementing custom commands.
**YOURPROJECTNAME/commands/allcrawl.py** :
```
from scrapy.command import Scrapy... |
Django - Change default locale | 10,801,397 | 9 | 2012-05-29T14:42:01Z | 10,801,903 | 19 | 2012-05-29T15:11:52Z | [
"python",
"django",
"localization",
"date-format"
] | Trying to understand L10N implementation into Django, Here are my settings
```
LANGUAGE_CODE = 'fr-FR'
USE_L10N = True
```
If I try
```
>>> datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M')
.strftime('%c')
```
It will give me `'Wed May 30 15:30:00 2012'` that is the *EN* locale. However the [do... | Django's localization works in the context of Django templates and forms, and can not travel up the chain to Python's internal datetime representations:
```
When using Django's formatting system, dates and numbers on templates
will be displayed using the format specified for the current locale.
...Django will also u... |
Comparing two large files | 10,801,760 | 3 | 2012-05-29T15:03:38Z | 10,801,819 | 7 | 2012-05-29T15:07:02Z | [
"python",
"algorithm",
"bash",
"grep",
"large-files"
] | I need to write a program that will write to a file the difference between two files.
The program has to loop through a 600 MB file with over 13.464.448 lines, check if a grep returns true on another file and then write the result onto another file.
I wrote a quick test with about 1.000.000 records and it took over an ... | You're probably looking in a list instead of a set, leading to an O(n²) performance. Try:
```
with open('b') as b:
blines = set(b)
with open('a') as a:
with open('result', 'w') as result:
for line in a:
if line not in blines:
result.write(line)
```
Assuming uniformly long (and not overly long l... |
How to save an Excel worksheet as CSV from Python (Unix)? | 10,802,417 | 7 | 2012-05-29T15:44:35Z | 10,803,229 | 21 | 2012-05-29T16:36:26Z | [
"python",
"excel",
"unix"
] | I want to write a Python script that reads in an Excel spreadsheet and saves some of its worksheets as CSV files.
How can I do this?
Thanks!
PS: I have found [third-party modules](http://www.python-excel.org/) for reading and writing Excel files from Python, but as far as I can tell, they can only save files in Exce... | The most basic exemples using the two libraries described line by line:
1. Open the xls workbook
2. Reference the first spreadsheet
3. Open in binary write the target csv file
4. Create the default csv writer object
5. Loop over all the rows of the first spreadsheet
6. Dump the rows into the csv
---
```
import xlrd
... |
Anisotropic diffusion 2d images | 10,802,611 | 3 | 2012-05-29T15:56:19Z | 12,254,999 | 8 | 2012-09-03T23:18:40Z | [
"python",
"c",
"image",
"matlab",
"filtering"
] | I want to use anisotropic diffusion on 2d images.
I'd like to use python but don't mind using matlab or c.
Are their any libraries I could use as a first step? I did a google search on the subject and found Panda3D and OpenGl.
Basically I want to give a set of images have it apply the filtering and then output t... | **[Here's](http://pastebin.com/sBsPX4Y7)** my Python/numpy implementation of 2D and 3D anisotropic (Perona-Malik) diffusion. It's not quite as fast as C-code, but it did the job nicely for me. |
Weighted choice short and simple | 10,803,135 | 15 | 2012-05-29T16:30:09Z | 10,803,136 | 9 | 2012-05-29T16:30:10Z | [
"python",
"numpy"
] | If I have a collection of items in a list. I want to choose from that list according to another list of weights.
For example my collection is `['one', 'two', 'three']` and the weights are `[0.2, 0.3, 0.5]`, the I would expect the method to give me 'three' in about half of all draws.
What is the easiest way to do so ? | This function takes two arguments: A list of weights and a list containing the objects to choose from:
```
from numpy import cumsum
from numpy.random import rand
def weightedChoice(weights, objects):
"""Return a random item from objects, with the weighting defined by weights
(which must sum to 1)."""
cs =... |
Weighted choice short and simple | 10,803,135 | 15 | 2012-05-29T16:30:09Z | 15,907,274 | 27 | 2013-04-09T16:21:04Z | [
"python",
"numpy"
] | If I have a collection of items in a list. I want to choose from that list according to another list of weights.
For example my collection is `['one', 'two', 'three']` and the weights are `[0.2, 0.3, 0.5]`, the I would expect the method to give me 'three' in about half of all draws.
What is the easiest way to do so ? | Since [numpy](/questions/tagged/numpy "show questions tagged 'numpy'") version 1.7 you can use [`numpy.random.choice()`](http://docs.scipy.org/doc/numpy-1.7.0/reference/generated/numpy.random.choice.html):
```
elements = ['one', 'two', 'three']
weights = [0.2, 0.3, 0.5]
from numpy.random import choice
print choice(e... |
List of all permutations but without opposite numbers | 10,803,186 | 3 | 2012-05-29T16:33:52Z | 10,803,731 | 7 | 2012-05-29T17:14:20Z | [
"python",
"list",
"permutation"
] | I need to create a list of all the permutation but excluding that ones where there is the same number changed of sign.
For example, from the sequence
```
[-2, -1, 1, 2]
```
I would obtain all permutations like these:
```
[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]
```
At the moment I use... | You are basically asking how to combine `permutation` and `product`. The following is much more efficient (and simpler) than rejection: You generate all permutations exactly once, and then twiddle the signs. It is asymptotically optimal in terms of time O(N!) and space O(1):
```
def plusAndMinusPermutations(items):
... |
ERROR collecting setup.py while trying to run py.test? | 10,804,268 | 11 | 2012-05-29T17:57:47Z | 10,806,575 | 16 | 2012-05-29T20:54:51Z | [
"python",
"setuptools",
"py.test",
"tox"
] | I am trying to run `py.test` on my package but it is trying to parse `setup.py` from the project root directory even if I tried to exclude it.
I need to collect the tests from \*.py files because the test classes are included in the modules.
```
# setup.cfg
[pytest]
norecursedirs = .svn _build tmp* lib/third lib *.eg... | You can configure the --ignore option to your pytest.ini configuration like this maybe:
```
addopts = --ignore=setup.py
```
which should help if you are in the root directory and want py.test to ignore the setup.py file. |
Proportional venn diagram for more than 3 sets | 10,804,432 | 7 | 2012-05-29T18:10:40Z | 10,814,476 | 10 | 2012-05-30T10:29:10Z | [
"python",
"matlab",
"plot",
"matplotlib"
] | I have a collection of documents in MongoDB where each has one or more categories in a list. Using map reduce, I can get the details of how many documents have each unique combination of categories:
```
['cat1'] = 523
['cat2'] = 231
['cat3'] = 102
['cat4'] = 72
[... | ## The Problem
We need to represent counts of multiple interconnected categories of object, and a Venn diagram would be unable to represent more than a trivial amount of categories and their overlap.
## A Solution
Consider each of the categories and their combinations as a node in a graph. Draw the graph such that t... |
Python: ++ operator | 10,804,592 | 3 | 2012-05-29T18:24:07Z | 10,804,617 | 10 | 2012-05-29T18:25:53Z | [
"python",
"operators",
"increment"
] | I often require doding a simple 1 unit incrementation (++) in Python.
I never seem to find a better solution than
```
x = x + 1
```
What am I doing wrong ? | Python doesn't have a `++` operator. You should use the `+=` operator:
```
x += 1
``` |
python dictionary count | 10,804,659 | 3 | 2012-05-29T18:28:36Z | 10,804,712 | 11 | 2012-05-29T18:32:57Z | [
"python",
"dictionary",
"count"
] | I need to count the number of times different values are listed in my dictionary. The problem is that I cant figure out how to count the values.
```
print dic
{'KLOI98': ['Martha Miller', '4563', 'Vet_Parking'], 'TY5678': ['Jane Miller', '8987', 'AgHort_Parking'], 'WER546': ['Olga Grey', '9898', 'Creche_Parking'], 'HU... | ```
from collections import Counter
items = Counter(val[2] for val in dic.values())
``` |
How to use WSGI to reroute a user from http to https | 10,804,873 | 7 | 2012-05-29T18:45:25Z | 10,813,798 | 8 | 2012-05-30T09:46:37Z | [
"python",
"google-app-engine",
"ssl",
"https",
"webapp2"
] | **Original Question**
---
App Engine SDK 1.6.5
Python 2.7
webapp2
I have implemented webapp2 schemes to secure pages to https. The issue is that when a user goes to say http:// site/login instead of https:// site/login they get a 404 error due to the schemes not recognising the route.
example main.py
```
# Li... | Set the URLs in app.yaml, rather than in code. See <https://developers.google.com/appengine/docs/python/config/appconfig#Secure_URLs>
For example:
```
handlers:
- url: /foo/.*
script: accounts.py
secure: always
```
This will redirect HTTP to HTTPS. |
Converting JSON date string to python datetime | 10,805,589 | 17 | 2012-05-29T19:40:21Z | 10,805,633 | 20 | 2012-05-29T19:44:34Z | [
"python",
"json",
"datetime",
"date",
"iso"
] | When translating dates to JSON, javascript is saving dates in this format:
```
2012-05-29T19:30:03.283Z
```
However, I am not sure how to get this into a python datetime object. I've tried these:
```
# Throws an error because the 'Z' isn't accounted for:
datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f')
... | Try the following format:
```
%Y-%m-%dT%H:%M:%S.%fZ
```
For example:
```
>>> datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2012, 5, 29, 19, 30, 3, 283000)
```
The `Z` in the date just means that it should be interpreted as a UTC time, so ignoring it won't cause an... |
Installation of Pyspatialite on Windows | 10,805,808 | 2 | 2012-05-29T19:56:29Z | 11,787,821 | 10 | 2012-08-03T00:46:49Z | [
"python",
"visual-c++",
"mingw",
"spatialite"
] | I'm using pyspatialite on ubuntu with no problemâit's perfect. But Windows is giving me a total headache. I've been trying to solve this issue for at least three days.
I'm using Visual Studio 2010 express with mingw (gcc) as the compiler. I encountered and solved a lot of problems: vcvarsall.bat, iconv.h, etc., but ... | After a great deal of trial-and-error, google searches, broken keyboards, various forum / chat Q&A
sessions, and head injuries - not to mention having to create my own fixes / workarounds for
several issues - I've finally succeeded in building and installing a 64-bit version of PySpatiaLite
3.0.1 for Windows x64. Woo-h... |
Split a string at a natural break | 10,806,037 | 4 | 2012-05-29T20:14:25Z | 10,806,131 | 11 | 2012-05-29T20:19:44Z | [
"python"
] | While rendering a title (using reportlab), I would like to split it between two lines if it is longer than 45 characters. So far I have this:
```
if len(Title) < 45:
drawString(200, 695, Title)
else:
drawString(200, 705, Title[:45])
drawString(200, 685, Title[45:])
```
The problem with this is that I only... | See this sample code :
```
import textwrap
print("\n".join(textwrap.wrap("This is my sooo long title", 10)))
```
The output :
```
This is my
sooo long
title
```
See full Python doc : <http://docs.python.org/library/textwrap.html#module-textwrap> |
Python: Create a global variable from a string? | 10,806,327 | 4 | 2012-05-29T20:33:52Z | 10,806,379 | 9 | 2012-05-29T20:37:54Z | [
"python"
] | Is there a way to create a global variable from a string? I know that you can make a variable from a string like so:
```
string = 'hello'
val = 10
vars()[string] = val
```
Thus making hello a variable equal to 10. I do not know how to make that user input variable global however, this does not work:
```
... | You can use the `globals()` function:
```
name = "hello"
globals()[name] = 10
``` |
python - is this a valid for in loop? | 10,806,669 | 2 | 2012-05-29T21:02:54Z | 10,806,699 | 7 | 2012-05-29T21:05:15Z | [
"python",
"loops",
"for-loop"
] | I want to access the object, i.e. array[i], as well as the interator count, i.
This is what I'm trying:
```
for i, pinName in allPorts[startIndex:endIndex]:
#do stuff
```
I get errors further down, just wondering if it's this part of the code.
New to python here. Cheers. | I guess you rather are looking for:
```
for i, pinName in enumerate(allPorts[startIndex:endIndex]):
...
```
the `enumerate()` builtin takes any list (tuple, iterable, ...) and yields tuples of (index, item) with index starting at 0. |
Generating Symmetric Matrices in Numpy | 10,806,790 | 7 | 2012-05-29T21:12:11Z | 10,806,947 | 12 | 2012-05-29T21:26:29Z | [
"python",
"random",
"matrix",
"numpy",
"adjacency-matrix"
] | I am trying to generate symmetric matrices in numpy. Specifically, these matrices are to have random places entries, and in each entry the contents can be random. Along the main diagonal we are not concerned with what enties are in there, so I have randomized those as well.
The approach I have taken is to first genera... | You could just do something like:
```
import numpy as np
N = 100
b = np.random.random_integers(-2000,2000,size=(N,N))
b_symm = (b + b.T)/2
```
Where you can choose from whatever distribution you want in the `np.random` or equivalent scipy module.
**Update:** If you are trying to build graph-like structures, definit... |
Counting each letter's frequency in a string | 10,806,866 | 8 | 2012-05-29T21:19:32Z | 10,806,904 | 11 | 2012-05-29T21:22:58Z | [
"python",
"dictionary"
] | This is a question from pyschools.
I did get it right, but I'm guessing that there would be a simpler method. Is this the simplest way to do this?
```
def countLetters(word):
letterdict={}
for letter in word:
letterdict[letter] = 0
for letter in word:
letterdict[letter] += 1
return let... | ```
>>> import collections
>>> print collections.Counter("google")
Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})
``` |
Counting each letter's frequency in a string | 10,806,866 | 8 | 2012-05-29T21:19:32Z | 10,806,913 | 28 | 2012-05-29T21:24:16Z | [
"python",
"dictionary"
] | This is a question from pyschools.
I did get it right, but I'm guessing that there would be a simpler method. Is this the simplest way to do this?
```
def countLetters(word):
letterdict={}
for letter in word:
letterdict[letter] = 0
for letter in word:
letterdict[letter] += 1
return let... | In 2.7+:
```
import collections
letters = collections.Counter('google')
```
Earlier (2.5+, that's ancient by now):
```
import collections
letters = collections.defaultdict(int)
for letter in word:
letters[letter] += 1
``` |
Python time formatting different in Windows | 10,807,164 | 12 | 2012-05-29T21:46:59Z | 10,807,204 | 10 | 2012-05-29T21:51:05Z | [
"python",
"cross-platform"
] | I'm probably missing an obvious platform difference that I should be accommodating but I'm getting this when trying to do a time format (Python2.7)...
in Linux env:
```
>>> import time
>>> time.strftime("%a, %d-%b-%Y %T GMT", time.gmtime())
'Tue, 29-May-2012 21:42:04 GMT'
```
in Windows:
```
>>> import time
>>> tim... | In general, you'll find that python `time.strftime()` supports the same set of format specifiers as the platform (or that platform's libc to be more specific) it runs on. However, only a subset of these is portable. See <http://docs.python.org/library/time.html> for a list. To quote the docs:
> Additional directives m... |
Is it safe to use pip with a git repo? | 10,807,246 | 6 | 2012-05-29T21:54:23Z | 10,807,359 | 7 | 2012-05-29T22:04:31Z | [
"python",
"github",
"pip"
] | It is possible to use pip to install from a git repo using command
`pip install git+https://github.com/...`
but is this safe for a production environment? Is there a way to protect from it being deleted without forking it, hosting myself, and merging any future updates? | No it is not 100% "safe", github can go down while you need to checkout the source, the author can delete the repository (or do some disrupting change to it) ecc. ecc.
With pip you can specify a revision or a tag together with the repository link
eg.
git+git://github.com/misterx/projectname.git@840d25bb9db9fbc801b9
... |
Is multiprocessing.Manager().dict().setdefault() broken? | 10,807,649 | 7 | 2012-05-29T22:31:35Z | 10,807,976 | 8 | 2012-05-29T23:09:12Z | [
"python",
"multiprocessing"
] | The its-late-and-im-probably-stupid department presents:
```
>>> import multiprocessing
>>> mgr = multiprocessing.Manager()
>>> d = mgr.dict()
>>> d.setdefault('foo', []).append({'bar': 'baz'})
>>> print d.items()
[('foo', [])] <-- Where did the dict go?
```
Whereas:
```
>>> e = mgr.dict()
>>> e['foo'] = [{'... | This is some pretty interesting behavior, I am not exactly sure how it works but I'll take a crack at why the behavior is the way it is.
First, note that `multiprocessing.Manager().dict()` is not a `dict`, it is a `DictProxy` object:
```
>>> d = multiprocessing.Manager().dict()
>>> d
<DictProxy object, typeid 'dict' ... |
Python parent class access to child private variables | 10,807,692 | 4 | 2012-05-29T22:35:38Z | 10,807,730 | 8 | 2012-05-29T22:39:04Z | [
"python",
"oop",
"class",
"inheritance"
] | The following code generates an error:
```
class A(object):
def say_something(self):
print (self.foo)
print(self.__bar)
class B(A):
def __init__(self):
self.foo='hello'
self.__something='world'
test=B()
test.say_something()
```
Printing of 'hello' is successful but 'world' ... | You can use `self._B__something` to access it. However, this is not what yuo should do. The proper solution is renaming `__bar` to `_bar`.
The idea behind the [double-underscore name mangling](http://docs.python.org/tutorial/classes.html#private-variables-and-class-local-references) is to avoid conflicts with subclass... |
How do you use OR,AND in conditionals? | 10,808,008 | 12 | 2012-05-29T23:13:12Z | 10,808,021 | 28 | 2012-05-29T23:16:02Z | [
"python",
"conditional"
] | I have found myself many times,with things that I need to be all or at least one equal to something,and I would write something like that:
```
if a==1 and b==1:
do something
```
or
```
if a==1 or b==1:
do something
```
If the number of things is small its ok,but it is still not elegant.So, is there a better w... | **Option 1: any / all**
For the general case, have a look at [`any`](http://docs.python.org/library/functions.html#any) and [`all`](http://docs.python.org/library/functions.html#all):
```
if all(x == 1 for x in a, b, c, d):
if any(x == 1 for x in a, b, c, d):
```
You can also use any iterable:
```
if any(x == 1 fo... |
variable scope of __init__ | 10,809,197 | 2 | 2012-05-30T02:20:05Z | 10,809,204 | 11 | 2012-05-30T02:21:40Z | [
"python"
] | I just wonder, why variable defined by `__init__` is not accessible from class? Should its executed during instantiation, so that its accessible from outside?
```
>>> class a:
... data = {}
...
>>> a.data
{}
>>> class a:
... def __init__(self):
... self.data = {}
...
>>> a.data
Traceback (most re... | Variables defined in `__init__` are *instance* variables, by definition they can't be accessed from a class scope. That's why this works:
```
a().data # data is a member of an instance of class `a`
```
... Whereas this won't work:
```
a.data # data is not a member of the `a` class
```
Notice that `__init__` (the ... |
Python: Why does the int class not have rich comparison operators like `__lt__()`? | 10,809,932 | 19 | 2012-05-30T04:19:13Z | 10,810,304 | 20 | 2012-05-30T05:09:59Z | [
"python",
"language-design",
"language-history"
] | Mostly curious.
I've noticed (at least in py 2.6 and 2.7) that a `float` has all the familiar rich comparison functions: `__lt__()`, `__gt__`, `__eq__`, etc.
```
>>> (5.0).__gt__(4.5)
True
```
but an `int` does not
```
>>> (5).__gt__(4)
Traceback (most recent call last):
File "<input>", line 1, in <module>
Attrib... | If we look at the [PEP 207 for Rich Comparisions](http://www.python.org/dev/peps/pep-0207/) there is this interesting sentence right at the end:
> The inlining already present which deals with integer comparisons would still apply, resulting in no performance cost for the most common cases.
So it seems that in 2.x th... |
django post_save call from within sending Model? | 10,810,202 | 2 | 2012-05-30T04:57:04Z | 10,811,963 | 9 | 2012-05-30T07:38:30Z | [
"python",
"django",
"django-models",
"django-signals"
] | I have a pretty simple model that works:
```
class Badge(models.Model):
name = models.CharField(max_length=16, help_text="Name for Badge")
category = models.ForeignKey(BadgeCategory, help_text="Category for badge")
description = models.CharField(max_length=32, help_text="A brief description")
file = m... | Just connect the signal with sender=Badge **after** Badge is defined, tested example:
```
from django.db import models
from django.db.models import signals
def create_badge(sender, instance, created, **kwargs):
print "Post save emited for", instance
class BadgeCategory(models.Model):
name = models.CharField(... |
Python super and setting parent class property | 10,810,369 | 13 | 2012-05-30T05:19:31Z | 10,810,545 | 12 | 2012-05-30T05:38:33Z | [
"python",
"super"
] | I'm having a really strange problem with Python super() and inheritance and properties. First, the code:
```
#!/usr/bin/env python3
import pyglet
import pygame
class Sprite(pyglet.sprite.Sprite):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rect = pygame.Rect(0, 0,... | I was trying to find the correct language to back up why this behavior is the way it is, so as not to give you a "because it just is" answer... But it seems this question has been asked more than once, and that it boils down to the behavior of `super()`. You can see a 2010 discussion about this exact behavior here: <ht... |
Can a python class return a new instance of its class? | 10,810,926 | 5 | 2012-05-30T06:19:25Z | 10,810,952 | 12 | 2012-05-30T06:23:00Z | [
"python",
"class"
] | Is the following python code valid?
```
class Test:
def __init__(self):
self.number = 5
def returnTest(self):
return Test()
``` | Yes it is valid. The class is defined by the time you create an object and call the `returnTest` method.
```
In [2]: x = Test()
In [3]: y = x.returnTest()
In [4]: y
Out[4]: <__main__.Test instance at 0x1e36ef0>
In [5]:
```
However, in cases where a method acts like a factory, you might want to consider using the [... |
Does easy_install provide search command? | 10,811,601 | 5 | 2012-05-30T07:14:04Z | 10,811,647 | 11 | 2012-05-30T07:16:48Z | [
"python",
"easy-install",
"package-managers"
] | Sometimes I need to guess the package name, is there any package search utilites such as the search command in apt/yum/port/brew... | No, but you can search online at [PyPi](http://pypi.python.org/pypi), which is the database that easy\_install, pip et al use. |
returning json output from multiple table in django tastypie | 10,812,271 | 2 | 2012-05-30T08:01:32Z | 10,813,563 | 8 | 2012-05-30T09:31:15Z | [
"python",
"django",
"orm",
"tastypie",
"django-queryset"
] | I have extended `django User` with my custom fields , now i need to return a json output from custom table along with `username` form parent table .
I tried select\_related in query set but it is not returning `username`
models
```
class ExProfile(models.Model):
user = models.ForeignKey(User, unique=True)
ce... | You don't need select related here.
If you just want the username not the user object add a attribute field and you can do the normal Django \_\_ relations e.g.
```
class ProfileResource(ModelResource):
uname = fields.CharField(attribute='user__username', readonly=True)
class Meta:
queryset =ExProfile... |
Modifying a list while iterating over it - why not? | 10,812,272 | 3 | 2012-05-30T08:01:35Z | 10,812,284 | 13 | 2012-05-30T08:02:24Z | [
"python",
"list"
] | Almost every tutorial and SO answer on this topic insists that you should never modify a list while iterating over it, but I can't see why this is such a bad thing if the code is valid. For example:
```
while len(mylist) > 0:
print mylist.pop()
```
Am I missing something? | ```
while len(mylist) > 0:
print mylist.pop()
```
You are not iterating over the list. You are each time checking an atomic condition.
Also:
```
while len(mylist) > 0:
```
can be rewritten as:
```
while len(mylist):
```
which can be rewritten as:
```
while mylist:
``` |
How can I access global variable inside class in Python | 10,814,452 | 18 | 2012-05-30T10:26:53Z | 10,814,468 | 40 | 2012-05-30T10:28:36Z | [
"python"
] | I have this:
```
g_c = 0
class TestClass():
global g_c
def run(self):
for i in range(10):
g_c = 1
print g_c
t = TestClass()
t.run()
print g_c
```
how can I actually modify my global variable g\_c? | By declaring it `global` inside the function that accesses it:
```
g_c = 0
class TestClass():
def run(self):
global g_c
for i in range(10):
g_c = 1
print g_c
```
The [Python documentation](http://docs.python.org/release/2.4/ref/global.html) says this, about the `global` st... |
How can I access global variable inside class in Python | 10,814,452 | 18 | 2012-05-30T10:26:53Z | 10,814,480 | 7 | 2012-05-30T10:29:29Z | [
"python"
] | I have this:
```
g_c = 0
class TestClass():
global g_c
def run(self):
for i in range(10):
g_c = 1
print g_c
t = TestClass()
t.run()
print g_c
```
how can I actually modify my global variable g\_c? | You need to move the `global` declaration inside your function:
```
class TestClass():
def run(self):
global g_c
for i in range(10):
g_c = 1
print g_c
``` |
Changing string to byte type in Python 2.7 | 10,814,483 | 9 | 2012-05-30T10:29:42Z | 10,814,498 | 11 | 2012-05-30T10:30:42Z | [
"python",
"types",
"version",
"byte"
] | In python 3.2, i can change the type of an object easily. For example :
```
x=0
print(type (x))
x=bytes(0)
print(type (x))
```
it will give me this :
```
<class 'int'>
<class 'bytes'>
```
But, in python 2.7, it seems that i can't use the same way to do it. If i do the same code, it give me this :
```
<type 'int'>
... | You are not changing types, you are assigning a different value to a variable.
You are also hitting on one of the fundamental differences between python 2.x and 3.x; grossly simplified the 2.x type `unicode` has replaced the `str` type, which itself has been renamed to `bytes`. It happens to work in your code as more ... |
Changing string to byte type in Python 2.7 | 10,814,483 | 9 | 2012-05-30T10:29:42Z | 10,814,849 | 7 | 2012-05-30T10:53:47Z | [
"python",
"types",
"version",
"byte"
] | In python 3.2, i can change the type of an object easily. For example :
```
x=0
print(type (x))
x=bytes(0)
print(type (x))
```
it will give me this :
```
<class 'int'>
<class 'bytes'>
```
But, in python 2.7, it seems that i can't use the same way to do it. If i do the same code, it give me this :
```
<type 'int'>
... | *What can i do to change the type into a bytes type?*
You can't, there is no such type as 'bytes' in Python 2.7.
From the Python 2.7 documentation (5.6 Sequence Types):
"There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects."
From the Python 3.2 documentatio... |
Can I iterate over a class in Python? | 10,814,535 | 18 | 2012-05-30T10:33:34Z | 10,814,662 | 23 | 2012-05-30T10:41:56Z | [
"python"
] | I have a class that keeps track of its instances in a class variable, something like this:
```
class Foo:
by_id = {}
def __init__(self, id):
self.id = id
self.by_id[id] = self
```
What I'd like to be able to do is iterate over the existing instances of the class. I can do this with:
```
for ... | If you want to iterate over the *class*, you have to define a metaclass which supports iteration.
x.py:
```
class it(type):
def __iter__(self):
# Wanna iterate over a class? Then ask that class for iterator.
return self.classiter()
class Foo:
__metaclass__ = it # We need that meta class...
... |
Can I iterate over a class in Python? | 10,814,535 | 18 | 2012-05-30T10:33:34Z | 10,814,720 | 7 | 2012-05-30T10:45:32Z | [
"python"
] | I have a class that keeps track of its instances in a class variable, something like this:
```
class Foo:
by_id = {}
def __init__(self, id):
self.id = id
self.by_id[id] = self
```
What I'd like to be able to do is iterate over the existing instances of the class. I can do this with:
```
for ... | Magic methods are always looked up on the class, so adding `__iter__` to the class won't make it iterable. However the class is an instance of its metaclass, so that is the correct place to define the `__init__` method.
```
class FooMeta(type):
def __iter__(self):
return self.by_id.iteritems()
class Foo:
... |
Python Redis interaction | 10,814,996 | 6 | 2012-05-30T11:04:22Z | 10,815,262 | 17 | 2012-05-30T11:20:45Z | [
"python",
"redis"
] | I want to write application in python which uses redis. I googled but I could not find any results for my question. Usually, I do this:
```
import redis
rs = redis.Redis('localhost')
```
then do all gets and sets. But can I in redis do something like this:
```
rs1 = redis.Redis('app1')
rs2 = redis.Redis('app2')
```... | As showed in the [getting started section of the docs](https://github.com/andymccurdy/redis-py#getting-started) `redis.Redis` and `redis.StrictRedis` both take an integer `db` argument as a constructor parameter. That will get you an effectively silo'ed instance.
You could do something like the following:
```
rs1 = r... |
Pylint showing invalid variable name in output | 10,815,549 | 30 | 2012-05-30T11:38:25Z | 10,815,647 | 29 | 2012-05-30T11:45:30Z | [
"python",
"pylint"
] | I made a simple python script to post data on a website.
```
#Imports
url_to_short = sys.argv[1]
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
headers = {'Content-Type': 'application/json'}
data = {'longUrl': url_to_short}
post_data = json.dumps(data)
req = urllib2.Request(post_url, post_data, header... | As your code is not contained in a class or function it is expecting those variables to be [constants](http://www.python.org/dev/peps/pep-0008/#constants) and as such they should be uppercase.
You can read [PEP8](http://www.python.org/dev/peps/pep-0008/) for further information. |
Pylint showing invalid variable name in output | 10,815,549 | 30 | 2012-05-30T11:38:25Z | 10,815,673 | 14 | 2012-05-30T11:47:17Z | [
"python",
"pylint"
] | I made a simple python script to post data on a website.
```
#Imports
url_to_short = sys.argv[1]
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
headers = {'Content-Type': 'application/json'}
data = {'longUrl': url_to_short}
post_data = json.dumps(data)
req = urllib2.Request(post_url, post_data, header... | EDIT: As others have mentioned, pylint expects that global variables should be UPPERCASE. If the warnings really bother you, you can circumvent them by wrapping small snippets like this in a `main()`-function and then use the `if __name__ == "__main__"`-convention. Or if you care, you can modify the regular expressions... |
most efficient way to substring path and file out of a string | 10,815,900 | 3 | 2012-05-30T12:03:41Z | 10,815,955 | 10 | 2012-05-30T12:07:21Z | [
"python",
"substring"
] | I am new to python, just wondering what's the best way for python to do the following:
```
file='/var/log/test.txt'
==action==
```
after ==action==, I want to get the path and the file separated like:
```
path='/var/log'
file_name='test.txt'
```
I am not asking how to do this, I am asking the most efficient way to ... | ```
file = '/var/log/test.txt'
path, file_name = os.path.split(file)
```
yields:
```
path
'/var/log'
file_name
'test.txt'
```
To use [os.path.split()](http://docs.python.org/library/os.path.html?highlight=os.path.split#os.path.split) requires `import os`. I'd have to think that the Python library is as efficient as... |
most efficient way to substring path and file out of a string | 10,815,900 | 3 | 2012-05-30T12:03:41Z | 10,815,956 | 7 | 2012-05-30T12:07:24Z | [
"python",
"substring"
] | I am new to python, just wondering what's the best way for python to do the following:
```
file='/var/log/test.txt'
==action==
```
after ==action==, I want to get the path and the file separated like:
```
path='/var/log'
file_name='test.txt'
```
I am not asking how to do this, I am asking the most efficient way to ... | You should look at the [documentation](http://docs.python.org/library/os.path.html) of `os.path` , there is a `split` function, for example:
```
path, file_name = os.path.split('/var/log/test/txt')
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.