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 |
|---|---|---|---|---|---|---|---|---|---|
Python3 error: "Import error: No module name urllib2" | 2,792,650 | 115 | 2010-05-08T01:58:52Z | 17,510,727 | 40 | 2013-07-07T09:12:13Z | [
"python",
"python-3.x",
"urllib2"
] | Here's my code:
```
import urllib2.request
response = urllib2.urlopen("http://www.google.com")
html = response.read()
print(html)
```
Any help? | For a script working with Python 2 (tested versions 2.7.3 and 2.6.8) and Python 3 (3.2.3 and 3.3.2+) try:
```
#! /usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
html = urlopen("htt... |
Python code formatting | 2,792,887 | 4 | 2010-05-08T03:58:35Z | 2,792,916 | 13 | 2010-05-08T04:17:36Z | [
"python"
] | In response to another question of mine, someone suggested that I avoid long lines in the code and to use PEP-8 rules when writing Python code. One of the PEP-8 rules suggested avoiding lines which are longer than 80 characters. I changed a lot of my code to comply with this requirement without any problems. However, c... | A multiline string would be more readable:
```
def __str__(self):
return '''\
Car Type
mpg: %.1f
hp: %.2f
pc: %i
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price)
```
To maintain visually meaningful indentation levels, use `textwrap.dedent`:
```
import textwrap
def __str__(self)... |
Is there a simple way to delete a list element by value in python? | 2,793,324 | 338 | 2010-05-08T07:48:28Z | 2,793,341 | 563 | 2010-05-08T07:56:03Z | [
"python",
"list"
] | ```
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
```
The above shows the following error:
```
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list
```
So I have to do this:
```
a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
... | To remove an element's first occurrence in a list, simply use `list.remove`:
```
>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']
```
Mind that it does not remove all occurrences of your element. Use a list comprehension for that.
```
>>> a = [1, 2, 3, 4, 2, 3, 4, 2, 7, 2]
>>> a = [x for x ... |
Is there a simple way to delete a list element by value in python? | 2,793,324 | 338 | 2010-05-08T07:48:28Z | 2,793,345 | 40 | 2010-05-08T07:57:26Z | [
"python",
"list"
] | ```
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
```
The above shows the following error:
```
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list
```
So I have to do this:
```
a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
... | You can do
```
a=[1,2,3,4]
if 6 in a:
a.remove(6)
```
but above need to search 6 in list a 2 times, so try except would be faster
```
try:
a.remove(6)
except:
pass
``` |
Is there a simple way to delete a list element by value in python? | 2,793,324 | 338 | 2010-05-08T07:48:28Z | 2,793,348 | 7 | 2010-05-08T07:58:35Z | [
"python",
"list"
] | ```
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
```
The above shows the following error:
```
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list
```
So I have to do this:
```
a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
... | Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:
```
>>> a = [1, 2, 3, 4]
>>> try:
... a.remove(6)
... except ValueError:
... pass
...
>>> print a
[1, 2, 3, 4]
>>> try:
... a.remove(3)
... except ValueError:
... pass
...
>>> print a
[1, ... |
Is there a simple way to delete a list element by value in python? | 2,793,324 | 338 | 2010-05-08T07:48:28Z | 2,793,356 | 80 | 2010-05-08T08:02:03Z | [
"python",
"list"
] | ```
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
```
The above shows the following error:
```
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list
```
So I have to do this:
```
a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
... | Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:
```
if c in a:
a.remove(c)
```
or:
```
try:
a.remove(c)
except ValueError:
pass
```
An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly. |
Is there a simple way to delete a list element by value in python? | 2,793,324 | 338 | 2010-05-08T07:48:28Z | 2,794,519 | 7 | 2010-05-08T14:57:38Z | [
"python",
"list"
] | ```
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
```
The above shows the following error:
```
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list
```
So I have to do this:
```
a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
... | Here's how to do it inplace (without list comprehension):
```
def remove_all(seq, value):
pos = 0
for item in seq:
if item != value:
seq[pos] = item
pos += 1
del seq[pos:]
``` |
Is there a simple way to delete a list element by value in python? | 2,793,324 | 338 | 2010-05-08T07:48:28Z | 15,692,408 | 7 | 2013-03-28T21:20:35Z | [
"python",
"list"
] | ```
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
```
The above shows the following error:
```
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list
```
So I have to do this:
```
a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
... | If you know what value to delete, here's a simple way (as simple as I can think of, anyway):
```
a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
a.remove(1)
```
You'll get
`[0, 0, 2, 3, 4]` |
Is there a simple way to delete a list element by value in python? | 2,793,324 | 338 | 2010-05-08T07:48:28Z | 25,251,306 | 17 | 2014-08-11T19:55:25Z | [
"python",
"list"
] | ```
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
```
The above shows the following error:
```
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list
```
So I have to do this:
```
a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
... | Consider:
```
a = [1,2,2,3,4,5]
```
To take out all occurrences, you could use the filter function in python.
For example, it would look like:
```
a = list(filter(lambda x: x!= 2, a))
```
So, it would keep all elements of a != 2.
To just take out one of the items use
```
a.remove(2)
``` |
Python: User-Defined Exception That Proves The Rule | 2,793,783 | 13 | 2010-05-08T10:59:15Z | 2,793,806 | 19 | 2010-05-08T11:05:09Z | [
"python",
"exception"
] | Python documentations [states](http://docs.python.org/tutorial/errors.html#user-defined-exceptions):
> Exceptions should typically be derived from the Exception class,
> either directly or indirectly.
the word `'typically'` leaves me in an ambiguous state.
consider the code:
```
class good(Exception): pass
class ba... | There are other valid classes you can inherit from apart from `Exception`, for example `BaseException`.
See the documentation for the [exception hierarchy](http://docs.python.org/library/exceptions.html#exception-hierarchy).
```
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
... |
Python: User-Defined Exception That Proves The Rule | 2,793,783 | 13 | 2010-05-08T10:59:15Z | 2,793,972 | 9 | 2010-05-08T12:02:47Z | [
"python",
"exception"
] | Python documentations [states](http://docs.python.org/tutorial/errors.html#user-defined-exceptions):
> Exceptions should typically be derived from the Exception class,
> either directly or indirectly.
the word `'typically'` leaves me in an ambiguous state.
consider the code:
```
class good(Exception): pass
class ba... | > "so when reading the python docs,
> should i change 'typically' with ''?"
No.
Typically, you inherit from Exception. Period. That's what it says.
Sometimes, you might inherit from BaseException. That's what it doesn't say. You might extend BaseExcetion because you want to defeat `except Exception` handlers.
> Wha... |
create destination path for shutil.copy files | 2,793,789 | 3 | 2010-05-08T11:00:24Z | 2,793,824 | 8 | 2010-05-08T11:11:00Z | [
"python"
] | If a path such as `b/c/` does not exist in `./a/b/c` , `shutil.copy("./blah.txt", "./a/b/c/blah.txt")` will complain that the destination does not exist. What is the best way to create both the destination path and copy the file to this path? | Use `os.makedirs` to create the directory tree. |
create destination path for shutil.copy files | 2,793,789 | 3 | 2010-05-08T11:00:24Z | 3,284,204 | 7 | 2010-07-19T19:12:59Z | [
"python"
] | If a path such as `b/c/` does not exist in `./a/b/c` , `shutil.copy("./blah.txt", "./a/b/c/blah.txt")` will complain that the destination does not exist. What is the best way to create both the destination path and copy the file to this path? | I use something similar to this to check if the directory exists before doing things with it.
```
if not os.path.exists('a/b/c/'):
os.mkdir('a/b/c')
``` |
How do I assign functions in a dictionary? | 2,794,631 | 3 | 2010-05-08T15:34:07Z | 2,794,635 | 10 | 2010-05-08T15:35:06Z | [
"python"
] | I'm having a problem with a simple program I wrote, I want to perform a certain function according to the users input. I've already used a dictionary as a replacement for a switch to do assignment but when I try to assign functions to the dictionary it doesn't execute them...
The code:
```
def PrintValuesArea():
#... | You forgot to call it.
```
PrintTables.get(ans.lower())()
```
or
```
PrintTables[ans.lower()]()
``` |
How to generate random html document | 2,795,134 | 8 | 2010-05-08T18:15:44Z | 2,795,450 | 7 | 2010-05-08T20:07:07Z | [
"python",
"html",
"random",
"grammar"
] | I'd like to generate completely random piece of html source, possibly from a grammar. I want to do this in python but I'm not sure how to proceed -- is there a library that takes a grammar and just randomly follows its rules, printing the path?
Ideas? | ```
import urllib
html = urllib.urlopen('http://random.yahoo.com/bin/ryl').read()
```
I think that pulling a random page is much easier to implement and will be far more random than anything you could program yourself. Any program designed to produce random pages will still have to adhere to whatever rules defining t... |
Best way to detect IronPython | 2,795,240 | 7 | 2010-05-08T18:54:44Z | 2,795,250 | 10 | 2010-05-08T18:59:26Z | [
"python",
"ironpython",
"version",
"detection"
] | I need to write a module which will be used from both CPython and IronPython. What's the best way to detect IronPython, since I need a slightly different behaviour in that case?
I noticed that sys.platform is "win32" on CPython, but "cli" on IronPython.
Is there another preferred/standard way of detecting it? | New in Python 2.6 is [`platform.python_implementation`](http://docs.python.org/library/platform.html#platform.python_implementation):
> Returns a string identifying the Python implementation. Possible return values are: âCPythonâ, âIronPythonâ, âJythonâ.
That's probably the cleanest way to do it, and that... |
Get node name with minidom | 2,795,462 | 8 | 2010-05-08T20:11:33Z | 2,795,489 | 10 | 2010-05-08T20:21:47Z | [
"python",
"minidom"
] | Is it possible to get the name of a node using minidom?
For example I have a node:
```
<heading><![CDATA[5 year]]></heading>
```
What I'm trying to do, is store the value `heading` so that I can use it as a key in a dictionary.
The closest I can get is something like:
```
[<DOM Element: heading at 0x11e6d28>]
```
... | Is this what you mean?
```
tag= node.tagName
d[tag]= node
```
`tagName` is [defined](http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-745549614) in DOM Level 1 Core, the basic standard that minidom (mostly) implements. |
getting Ceil() of Decimal in python? | 2,795,946 | 6 | 2010-05-08T22:51:39Z | 2,797,269 | 14 | 2010-05-09T09:58:07Z | [
"python",
"decimal",
"rounding",
"ceil"
] | Is there a way to get the ceil of a high precision Decimal in python?
```
>>> import decimal;
>>> decimal.Decimal(800000000000000000001)/100000000000000000000
Decimal('8.00000000000000000001')
>>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000)
8.0
```
math rounds the value and returns non pre... | The most direct way to take the ceiling of a Decimal instance `x` is to use `x.to_integral_exact(rounding=ROUND_CEILING)`. There's no need to mess with the context here. Note that this sets the `Inexact` and `Rounded` flags where appropriate; if you don't want the flags touched, use `x.to_integral_value(rounding=ROUND_... |
Python Closures Example Code | 2,796,855 | 12 | 2010-05-09T06:44:15Z | 2,796,916 | 15 | 2010-05-09T07:11:21Z | [
"python",
"python-3.x",
"closures"
] | I am learning Python using [Dive Into Python 3](http://getpython3.com/diveintopython3/) book. I like it, but I don't understand the [example used to introduce Closures](http://getpython3.com/diveintopython3/generators.html#a-file-of-patterns) in Section 6.5.
I mean, I see how it works, and I think it's really cool. Bu... | Decorators are an example of closures. For example,
```
def decorate(f):
def wrapped_function():
print("Function is being called")
f()
print("Function call is finished")
return wrapped_function
@decorate
def my_function():
print("Hello world")
my_function()
```
The function `wrap... |
Automating Etrade | 2,796,952 | 7 | 2010-05-09T07:31:08Z | 2,798,292 | 7 | 2010-05-09T16:19:51Z | [
"python",
"automation",
"stocks",
"trading",
"broker"
] | Hey everyone, I was wondering how would I start programming an interface to trading stocks in Etrade in python. I am attempting to make an automated trading bot, but there is no api publicly available for automated trading with Etrade. Thanks in advance. ^^ | For E-trade I could only find this: <http://code.google.com/p/pyetrade/> . It uses urllib2 to access the site like a user would. But because of lack of an official API there is no guarantee that anything will keep working.
Interactive Brokers has an extensive API for automatic trading, also from Python. I can confirm ... |
Python references | 2,797,114 | 13 | 2010-05-09T08:55:04Z | 2,797,120 | 7 | 2010-05-09T08:58:30Z | [
"python",
"immutability"
] | Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
```
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
``` | Because integers are immutable, while list are mutable. You can see from the syntax. In `x = x + 1` you are actually assigning a new value to `x` (it is alone on the LHS). In `x[0] = 4`, you're calling the index operator on the list and giving it a parameter - it's actually equivalent to `x.__setitem__(0, 4)`, which is... |
Python references | 2,797,114 | 13 | 2010-05-09T08:55:04Z | 2,797,128 | 8 | 2010-05-09T09:02:34Z | [
"python",
"immutability"
] | Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
```
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
``` | The best explanation I ever read is here:
<http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables> |
Python using methods from other classes | 2,797,139 | 15 | 2010-05-09T09:07:56Z | 2,797,151 | 18 | 2010-05-09T09:13:43Z | [
"python",
"design",
"class",
"methods"
] | If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function? | There are two options:
* instanciate an object in your class, then call the desired method on it
* use [@classmethod](http://docs.python.org/library/functions.html#classmethod) to turn a function into a class method
Example:
```
class A(object):
def a1(self):
""" This is an instance method. """
p... |
Python using methods from other classes | 2,797,139 | 15 | 2010-05-09T09:07:56Z | 2,797,332 | 14 | 2010-05-09T10:25:14Z | [
"python",
"design",
"class",
"methods"
] | If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function? | There are several approaches:
* Inheritance
* Delegation
* Super-sneaky delegation
The following examples use each for sharing a function that prints a member.
**Inheritance**
```
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(Common)... |
Why is Python 3.1 throwing a SyntaxError when printing after loop? | 2,797,364 | 4 | 2010-05-09T10:41:04Z | 2,797,375 | 9 | 2010-05-09T10:46:28Z | [
"python",
"syntax-error"
] | I'm trying to run this snippet in Python 3.1 console and I'm getting SyntaxError:
```
>>> while True:
... a=5
... if a<6:
... break
... print("hello")
File "<stdin>", line 5
print("hello")
^
SyntaxError: invalid syntax
>>>
```
(This is just shortened code to make a point.)
Am I miss... | You have to input an empty line into the REPL to complete the current block before you can enter a new, unindented line of code. |
Why is Python 3.1 throwing a SyntaxError when printing after loop? | 2,797,364 | 4 | 2010-05-09T10:41:04Z | 2,797,378 | 7 | 2010-05-09T10:46:46Z | [
"python",
"syntax-error"
] | I'm trying to run this snippet in Python 3.1 console and I'm getting SyntaxError:
```
>>> while True:
... a=5
... if a<6:
... break
... print("hello")
File "<stdin>", line 5
print("hello")
^
SyntaxError: invalid syntax
>>>
```
(This is just shortened code to make a point.)
Am I miss... | It's working, if you put the whole thing in a function:
```
def test():
while True:
a=5
if a<6:
break
print("hello")
```
If you try to do it outside a function (just in the interpreter), it does not know how to evaulate the whole thing, since it can only handle one statement at a t... |
Matplotlib PDF export uses wrong font | 2,797,525 | 13 | 2010-05-09T11:46:16Z | 2,798,758 | 7 | 2010-05-09T18:53:45Z | [
"python",
"osx",
"matplotlib",
"cairo"
] | I want to generate high-quality diagrams for a presentation. Iâm using Pythonâs matplotlib to generate the graphics. Unfortunately, the PDF export seems to ignore my font settings.
I tried setting the font both by passing a `FontProperties` object to the text drawing functions and by setting the option globally. F... | Basically, @Jouniâs is the right answer but since I still had some trouble getting it to work, hereâs my final solution:
```
#!/usr/bin/env python2.6
import scipy
import matplotlib
matplotlib.use('cairo')
import matplotlib.pylab as pylab
import matplotlib.font_manager as fm
font = fm.FontProperties(
fami... |
Python: Why do some packages get installed as eggs and some as "egg folders"? | 2,798,451 | 20 | 2010-05-09T17:09:23Z | 2,798,497 | 21 | 2010-05-09T17:29:04Z | [
"python",
"packaging",
"setuptools",
"egg"
] | I maintain a few Python packages. I have a very similar `setup.py` file for each of them. However, when doing `setup.py install`, one of my packages gets installed as an egg, while the others get installed as "egg folders", i.e. folders with an extension of "egg".
What is the difference between them that causes this d... | [The Internal Structure of Python Eggs, Zip Support Metadata](http://peak.telecommunity.com/DevCenter/EggFormats#zip-safe-and-not-zip-safe) :
> If `zip-safe` exists, it means that the project will work properly when installed as an `.egg` zipfile, and conversely the existence of `not-zip-safe` means the project should... |
How can I detect DOS line breaks in a file? | 2,798,627 | 7 | 2010-05-09T18:16:58Z | 2,800,981 | 20 | 2010-05-10T07:26:06Z | [
"python",
"bash",
"file",
"line-breaks",
"line-endings"
] | I have a bunch of files. Some are Unix line endings, many are DOS. I'd like to test each file to see if if is dos formatted, before I switch the line endings.
How would I do this? Is there a flag I can test for? Something similar? | Python can *automatically detect what newline convention is used in a file*, thanks to the "universal newline mode" (`U`), and you can access Python's guess through the `newlines` attribute of file objects:
```
f = open('myfile.txt', 'U')
f.readline() # Reads a line
# The following now contains the newline ending of ... |
Installing PygraphViz on Windows, Python 2.6 | 2,798,858 | 18 | 2010-05-09T19:24:07Z | 15,830,674 | 17 | 2013-04-05T09:43:57Z | [
"python",
"c",
"windows",
"installation",
"graphviz"
] | Anybody out there has successfully installed PygraphViz on Windows?
Since there is not an official [release for Windows](http://pypi.python.org/pypi/pygraphviz/), I'm trying to build it myself, but it fails to compile. I'm not the [first one](https://networkx.lanl.gov/trac/ticket/117) to [face this issue](http://group... | I appreciate this may be an obsolete thread by now, but to update it for others currently hitting this wall, the installer at Christoph Gohlke's [Unofficial Windows Binaries for Python Extension Packages](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygraphviz) has just worked for me.. |
How do I merge dictionaries together in Python? | 2,799,064 | 70 | 2010-05-09T20:31:12Z | 2,799,075 | 117 | 2010-05-09T20:34:59Z | [
"python",
"dictionary"
] | ```
d3 = dict(d1, **d2)
```
I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I would like d1 and d2 to be merged, but d1 has priority if there is duplicate key. | You can use the [`.update()`](http://docs.python.org/library/stdtypes.html#dict.update) method if you don't need the original `d2` any more:
> Update the dictionary with the key/value pairs from other, **overwriting existing keys**. Return `None`.
E.g.:
```
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'b': 1, 'c': 3}
>>> d2... |
How do I merge dictionaries together in Python? | 2,799,064 | 70 | 2010-05-09T20:31:12Z | 2,799,082 | 31 | 2010-05-09T20:36:05Z | [
"python",
"dictionary"
] | ```
d3 = dict(d1, **d2)
```
I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I would like d1 and d2 to be merged, but d1 has priority if there is duplicate key. | In Python2,
```
d1={'a':1,'b':2}
d2={'a':10,'c':3}
```
d1 overrides d2:
```
dict(d2,**d1)
# {'a': 1, 'c': 3, 'b': 2}
```
d2 overrides d1:
```
dict(d1,**d2)
# {'a': 10, 'c': 3, 'b': 2}
```
This behavior is not just a fluke of implementation; it is guaranteed [in the documentation](http://docs.python.org/library/st... |
How do I merge dictionaries together in Python? | 2,799,064 | 70 | 2010-05-09T20:31:12Z | 2,799,110 | 9 | 2010-05-09T20:44:02Z | [
"python",
"dictionary"
] | ```
d3 = dict(d1, **d2)
```
I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I would like d1 and d2 to be merged, but d1 has priority if there is duplicate key. | If you want `d1` to have priority in the conflicts, do:
```
d3 = d2.copy()
d3.update(d1)
```
Otherwise, reverse `d2` and `d1`. |
cd Terminal at a given directory after running a Python script? | 2,799,256 | 5 | 2010-05-09T21:30:51Z | 2,799,281 | 10 | 2010-05-09T21:35:19Z | [
"python",
"bash",
"shell",
"directory",
"terminal"
] | I'm working on a simple Python script that can use `subprocess` and/or `os` to execute some commands, which is working fine.
However, when the script exits I'd like to `cd` the actual Terminal (in this case OS X) so on exit, the new files are ready to use in the directory where the have been created. All the following... | Sadly, no. Processes are not allowed to change the environment of their parent process, and in this case your Python script is a child process of the shell. You could "fake" it by having your Python process set up a new shell - call subprocess to open a shell process and present it to the user, inheriting the modified ... |
is this a correct way to generate rsa keys? | 2,799,503 | 9 | 2010-05-09T23:01:39Z | 2,802,304 | 16 | 2010-05-10T11:45:48Z | [
"python",
"cryptography",
"rsa",
"public-key"
] | is this code going to give me correct values for RSA keys (assuming that the other functions are correct)? im having trouble getting my program to decrypt properly, as in certain blocks are not decrypting properly
this is in python:
```
import random
def keygen(bits):
p = q = 3
while p == q:
p = rando... | Mathematically, your *n*, *e* and *d* appear to respect the RSA rules (i.e. for every prime *r* which divides *n*, *r2* does not divide *n*, and *d* is an inverse of *e* modulo *r-1*). However, RSA is a bit more than that; it also mandates some padding rules, which govern how a message (a sequence of bytes) is to be tr... |
Wait for a single RabbitMQ message with a timeout | 2,799,731 | 5 | 2010-05-10T00:26:43Z | 2,803,126 | 7 | 2010-05-10T13:57:34Z | [
".net",
"python",
"rabbitmq",
"amqp",
"py-amqplib"
] | I'd like to send a message to a RabbitMQ server and then wait for a reply message (on a "reply-to" queue). Of course, I don't want to wait forever in case the application processing these messages is down - there needs to be a timeout. It sounds like a very basic task, yet I can't find a way to do this. I've now run in... | I just added timeout support for `amqplib` in `carrot`.
This is a subclass of `amqplib.client0_8.Connection`:
<http://github.com/ask/carrot/blob/master/carrot/backends/pyamqplib.py#L19-97>
`wait_multi` is a version of `channel.wait` able to receive on an arbitrary number
of channels.
I guess this could be merged up... |
Remove certain keys from a dictionary in python | 2,800,373 | 12 | 2010-05-10T04:50:18Z | 2,800,385 | 22 | 2010-05-10T04:53:22Z | [
"python",
"dictionary",
"python-3.x"
] | I'm trying to construct a dictionary that contains a series of sets:
```
{Field1:{Value1, Value2, Value3}, Field2{Value4}}
```
The trouble is, I then wish to delete any fields from the dictionary that only have one value in the set. I have been writing code like this:
```
for field in FieldSet:
if len(FieldSet[f... | Iterate over the return value from [`.keys()`](http://docs.python.org/library/stdtypes.html#dict.keys) instead. Since you get a list of keys back, it won't be affected by changing the dictionary after you've called it. |
Remove certain keys from a dictionary in python | 2,800,373 | 12 | 2010-05-10T04:50:18Z | 2,800,427 | 14 | 2010-05-10T05:04:45Z | [
"python",
"dictionary",
"python-3.x"
] | I'm trying to construct a dictionary that contains a series of sets:
```
{Field1:{Value1, Value2, Value3}, Field2{Value4}}
```
The trouble is, I then wish to delete any fields from the dictionary that only have one value in the set. I have been writing code like this:
```
for field in FieldSet:
if len(FieldSet[f... | A sometimes-preferable alternative to changing `FieldSet` in place is sometimes (depending on the amount of alterations performed) to build a new one and bind it to the existing name:
```
FieldSet = dict((k, v) for k, v in FieldSet.iteritems()
if len(v) != 1)
``` |
mongodb: insert if not exists | 2,801,008 | 81 | 2010-05-10T07:33:32Z | 2,923,719 | 91 | 2010-05-27T18:17:44Z | [
"python",
"mongodb",
"bulkinsert",
"mongodb-query"
] | Every day, I receive a stock of documents (an update). What I want to do is insert each item that does not already exist.
* I also want to keep track of the first time I inserted them, and the last time I saw them in an update.
* I don't want to have duplicate documents.
* I don't want to remove a document which has p... | Sounds like you want to do an "upsert". MongoDB has built-in support for this. Pass an extra parameter to your update() call: {upsert:true}. For example:
```
key = {'key':'value'}
data = {'key2':'value2', 'key3':'value3'};
coll.update(key, data, {upsert:true});
```
This replaces your if-find-else-update block entirel... |
mongodb: insert if not exists | 2,801,008 | 81 | 2010-05-10T07:33:32Z | 13,847,788 | 10 | 2012-12-12T20:10:47Z | [
"python",
"mongodb",
"bulkinsert",
"mongodb-query"
] | Every day, I receive a stock of documents (an update). What I want to do is insert each item that does not already exist.
* I also want to keep track of the first time I inserted them, and the last time I saw them in an update.
* I don't want to have duplicate documents.
* I don't want to remove a document which has p... | You could always make a unique index, which causes MongoDB to reject a conflicting save. Consider the following done using the mongodb shell:
```
> db.getCollection("test").insert ({a:1, b:2, c:3})
> db.getCollection("test").find()
{ "_id" : ObjectId("50c8e35adde18a44f284e7ac"), "a" : 1, "b" : 2, "c" : 3 }
> db.getCol... |
mongodb: insert if not exists | 2,801,008 | 81 | 2010-05-10T07:33:32Z | 17,533,368 | 18 | 2013-07-08T18:18:36Z | [
"python",
"mongodb",
"bulkinsert",
"mongodb-query"
] | Every day, I receive a stock of documents (an update). What I want to do is insert each item that does not already exist.
* I also want to keep track of the first time I inserted them, and the last time I saw them in an update.
* I don't want to have duplicate documents.
* I don't want to remove a document which has p... | As of MongoDB 2.4, you can use $setOnInsert (<http://docs.mongodb.org/manual/reference/operator/setOnInsert/>)
Set 'insertion\_date' using $setOnInsert and 'last\_update\_date' using $set in your upsert command. |
Python: Is there a way to split a string of numbers into every 3rd number? | 2,801,085 | 5 | 2010-05-10T07:48:17Z | 2,801,117 | 9 | 2010-05-10T07:55:04Z | [
"python",
"list"
] | For example, if I have a string a=123456789876567543 could i have a list like...
123
456
789
876
567
543 | ```
>>> a="123456789"
>>> [int(a[i:i+3]) for i in range(0, len(a), 3)]
[123, 456, 789]
``` |
Generating a PNG with matplotlib when DISPLAY is undefined | 2,801,882 | 153 | 2010-05-10T10:22:33Z | 3,054,314 | 270 | 2010-06-16T14:41:22Z | [
"python",
"matplotlib",
"graph"
] | I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
```
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz... | The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers. The solution for me was to add the following code in a place that gets read *before* any other pylab/matplotlib/**pyplot** import:
```
import matplotlib
# Force matplotlib to no... |
Generating a PNG with matplotlib when DISPLAY is undefined | 2,801,882 | 153 | 2010-05-10T10:22:33Z | 9,303,165 | 10 | 2012-02-15T23:25:17Z | [
"python",
"matplotlib",
"graph"
] | I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
```
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz... | When signing into the server to execute the code
use this instead:
```
ssh -X username@servername
```
the `-X` will get rid of the no display name and no $DISPLAY environment variable
error
:) |
Generating a PNG with matplotlib when DISPLAY is undefined | 2,801,882 | 153 | 2010-05-10T10:22:33Z | 13,435,682 | 42 | 2012-11-17T23:07:04Z | [
"python",
"matplotlib",
"graph"
] | I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
```
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz... | Just as a complement of Reinout's answer.
The permanent way to solve this kind of problem is to edit .matplotlibrc file. Find it via
```
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
# This is the file location in Ubuntu
'/etc/matplotlibrc'
```
Then modify the backend in that file to Agg. That is it. |
Generating a PNG with matplotlib when DISPLAY is undefined | 2,801,882 | 153 | 2010-05-10T10:22:33Z | 21,071,208 | 21 | 2014-01-12T04:09:59Z | [
"python",
"matplotlib",
"graph"
] | I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
```
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz... | I will just repeat what @Ivo Bosticky said which can be overlooked. Put these lines at the **VERY** start of the py file.
```
import matplotlib
matplotlib.use('Agg')
```
Or one would get error
```
*/usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning: This call to matplotlib.use() has no effect
be... |
Generating a PNG with matplotlib when DISPLAY is undefined | 2,801,882 | 153 | 2010-05-10T10:22:33Z | 36,271,874 | 7 | 2016-03-28T21:53:44Z | [
"python",
"matplotlib",
"graph"
] | I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
```
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz... | The clean answer is to take a little bit of time correctly prepare your execution environment.
The first technique you have to prepare your execution environment is to use a `matplotlibrc` file, [as wisely recommended by Chris Q.](http://stackoverflow.com/a/13435682/38140), setting
```
backend : Agg
```
in that file... |
Find last match with python regular expression | 2,802,168 | 10 | 2010-05-10T11:20:12Z | 2,802,195 | 16 | 2010-05-10T11:25:04Z | [
"python",
"regex"
] | I wanto to match the last occurence of a simple pattern in a string, e.g.
```
list = re.findall(r"\w+ AAAA \w+", "foo bar AAAA foo2 AAAA bar2")
print "last match: ", list[len(list)-1]
```
however, if the string is *very* long, a huge list of matches is generated. Is there a more direct way to match the second occuren... | you could use `$` that denotes end of the line character:
```
>>> s = """foo bar AAAA
foo2 AAAA bar2"""
>>> re.findall(r"\w+ AAAA \w+$", s)
['foo2 AAAA bar2']
```
Also, note that `list` is a bad name for your variable, as it shadows built-in type. To access the last element of a list you could just use `[-1]` index:
... |
Find last match with python regular expression | 2,802,168 | 10 | 2010-05-10T11:20:12Z | 2,988,680 | 17 | 2010-06-07T10:28:38Z | [
"python",
"regex"
] | I wanto to match the last occurence of a simple pattern in a string, e.g.
```
list = re.findall(r"\w+ AAAA \w+", "foo bar AAAA foo2 AAAA bar2")
print "last match: ", list[len(list)-1]
```
however, if the string is *very* long, a huge list of matches is generated. Is there a more direct way to match the second occuren... | You can avoid the building of a list just by iterating over all matches and keeping the last match:
```
for match in re.finditer(r"\w+ AAAA \w+", "foo bar AAAA foo2 AAAA bar2"):
pass
```
After this, `match` holds the last match, and works for all combinations of *pattern* and *searched string*. You might want to ... |
python-like Java IO library? | 2,802,711 | 18 | 2010-05-10T12:55:00Z | 2,802,737 | 11 | 2010-05-10T12:58:50Z | [
"java",
"python",
"file-io"
] | Java is not my main programming language so I might be asking the obvious.
But is there a simple file-handling library in Java, like in [python](http://docs.python.org/release/3.0.1/tutorial/inputoutput.html#methods-of-file-objects)?
For example I just want to say:
```
File f = Open('file.txt', 'w')
for(String line:... | Reading a file line by line in Java:
```
BufferedReader in = new BufferedReader(new FileReader("myfile.txt"));
String line;
while ((line = in.readLine()) != null) {
// Do something with this line
System.out.println(line);
}
in.close();
```
Most of the classes for I/O are in the package `java.io`. See the AP... |
python-like Java IO library? | 2,802,711 | 18 | 2010-05-10T12:55:00Z | 2,803,424 | 19 | 2010-05-10T14:32:51Z | [
"java",
"python",
"file-io"
] | Java is not my main programming language so I might be asking the obvious.
But is there a simple file-handling library in Java, like in [python](http://docs.python.org/release/3.0.1/tutorial/inputoutput.html#methods-of-file-objects)?
For example I just want to say:
```
File f = Open('file.txt', 'w')
for(String line:... | I was thinking something more along the lines of:
```
File f = File.open("C:/Users/File.txt");
for(String s : f){
System.out.println(s);
}
```
Here is my source code for it:
```
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOEx... |
Python date string to date object | 2,803,852 | 146 | 2010-05-10T15:22:12Z | 2,803,866 | 40 | 2010-05-10T15:23:43Z | [
"python",
"date"
] | How do I convert a string to a date object in python?
The string would be: `"24052010"` (corresponding to the format: `"%d%m%Y"`)
I **don't** want a datetime.datetime object, but rather a datetime.date | ```
import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()
``` |
Python date string to date object | 2,803,852 | 146 | 2010-05-10T15:22:12Z | 2,803,877 | 264 | 2010-05-10T15:24:45Z | [
"python",
"date"
] | How do I convert a string to a date object in python?
The string would be: `"24052010"` (corresponding to the format: `"%d%m%Y"`)
I **don't** want a datetime.datetime object, but rather a datetime.date | You can use [`strptime`](http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior) in the [`datetime`](http://docs.python.org/library/datetime.html) package of Python:
```
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)
``` |
Python date string to date object | 2,803,852 | 146 | 2010-05-10T15:22:12Z | 29,161,018 | 18 | 2015-03-20T06:53:59Z | [
"python",
"date"
] | How do I convert a string to a date object in python?
The string would be: `"24052010"` (corresponding to the format: `"%d%m%Y"`)
I **don't** want a datetime.datetime object, but rather a datetime.date | # Directly related question:
## What if you have
```
datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()
```
## and you get:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
f... |
How to add http headers in suds 0.3.6? | 2,804,062 | 4 | 2010-05-10T15:43:48Z | 7,589,497 | 9 | 2011-09-28T20:57:22Z | [
"python",
"http",
"header",
"suds"
] | I have an application in python 2.5 which sends data through suds 0.3.6.
The problem is that the data contains non-ascii characters, so I need the following header to exist in the soap message:
**Content-Type="text/html; charset="utf-8"**
and the header that exists in the SOAP message is just:
**Content-Type="text/... | At least in suds 0.4 (maybe earlier?) HTTP headers can also be passed in to the constructor or via the `set_options` method:
```
client = suds.client.Client(url, headers={'key': 'value'})
client.set_options(headers={'key2': 'value'})
``` |
How do I retrieve program output in Python? | 2,804,194 | 3 | 2010-05-10T16:00:51Z | 2,804,233 | 7 | 2010-05-10T16:05:35Z | [
"c++",
"python",
"perl"
] | I'm not a Perl user, but from [this question](http://stackoverflow.com/questions/2803909/how-do-i-find-out-which-version-of-java-i-am-using-perl) deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to:
```
$version = `java -version`;
```
... | For python 2.5: sadly, no. You need to use subprocess:
```
import subprocess
proc = subprocess.Popen(['java', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
```
Docs are at <http://docs.python.org/library/subprocess.html> |
Pausing a process? | 2,804,287 | 8 | 2010-05-10T16:10:54Z | 4,230,243 | 9 | 2010-11-19T23:15:09Z | [
"python",
"process",
"signals"
] | Is there a way to pause a process (running from an executable) so that it stops the cpu load while it's paused, and waits till it's unpaused to go on with its work? Possibly in python, or in some way accessible by python. | By using psutil ( <https://github.com/giampaolo/psutil> ):
```
>>> import psutil
>>> somepid = 1023
>>> p = psutil.Process(somepid)
>>> p.suspend()
>>> p.resume()
``` |
read subprocess stdout line by line | 2,804,543 | 120 | 2010-05-10T16:47:31Z | 2,813,530 | 88 | 2010-05-11T18:48:31Z | [
"python",
"subprocess"
] | My python script uses subprocess to call a linux utility that is very noisy. I want to store all of the output to a log file and show some of it to the user. I thought the following would work, but the output doesn't show up in my application until the utility has produced a significant amount of output.
```
#fake_uti... | It's been a long time since I last worked with Python, but I think the problem is with the statement `for line in proc.stdout`, which reads the entire input before iterating over it. The solution is to use `readline()` instead:
```
#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],... |
read subprocess stdout line by line | 2,804,543 | 120 | 2010-05-10T16:47:31Z | 25,572,491 | 8 | 2014-08-29T16:36:03Z | [
"python",
"subprocess"
] | My python script uses subprocess to call a linux utility that is very noisy. I want to store all of the output to a log file and show some of it to the user. I thought the following would work, but the output doesn't show up in my application until the utility has produced a significant amount of output.
```
#fake_uti... | Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.
```
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
```
becomes
```
proc = subprocess.Popen(['python','-u', 'fake_utility.py'],stdout=su... |
How can I do DNS lookups in Python, including referring to /etc/hosts? | 2,805,231 | 59 | 2010-05-10T18:14:42Z | 2,805,413 | 61 | 2010-05-10T18:36:52Z | [
"python",
"dns"
] | [dnspython](http://www.dnspython.org) will do my DNS lookups very nicely, but it entirely ignores the contents of `/etc/hosts`.
Is there a python library call which will do the right thing? ie check first in `etc/hosts`, and only fall back to DNS lookups otherwise? | I'm not really sure if you want to do DNS lookups *yourself* or if you just want a host's ip. In case you want the latter,
```
import socket
print socket.gethostbyname('localhost') # result from hosts file
print socket.gethostbyname('google.com') # your os sends out a dns query
``` |
How can I do DNS lookups in Python, including referring to /etc/hosts? | 2,805,231 | 59 | 2010-05-10T18:14:42Z | 2,816,838 | 69 | 2010-05-12T07:44:48Z | [
"python",
"dns"
] | [dnspython](http://www.dnspython.org) will do my DNS lookups very nicely, but it entirely ignores the contents of `/etc/hosts`.
Is there a python library call which will do the right thing? ie check first in `etc/hosts`, and only fall back to DNS lookups otherwise? | The normal name resolution in Python works fine. Why do you need DNSpython for that. Just use [socket](http://docs.python.org/library/socket.html)'s `getaddrinfo` which follows the rules configured for your operating system (on Debian, it follows `/etc/nsswitch.conf`:
```
>>> print socket.getaddrinfo('google.com', 80)... |
What's the best way to aggregate the boolean values of a Python dictionary? | 2,806,611 | 6 | 2010-05-10T21:34:39Z | 2,806,640 | 21 | 2010-05-10T21:38:36Z | [
"python"
] | For the following Python dictionary:
```
dict = {
'stackoverflow': True,
'superuser': False,
'serverfault': False,
'meta': True,
}
```
I want to aggregate the boolean values above into the following boolean expression:
```
dict['stackoverflow'] and dict['superuser'] and dict['serverfault'] and dict['... | in python 2.5+:
```
all(dict.itervalues())
```
in python 3+
```
all(dict.values())
```
`dict` is a bad variable name, though, because it is the name of a builtin type
Edit: add syntax for python 3 version. `values()` constructs a view in python 3, unlike 2.x where it builds the list in memory. |
Huge Graph Structure | 2,806,806 | 5 | 2010-05-10T22:10:32Z | 2,806,868 | 14 | 2010-05-10T22:23:10Z | [
"python",
"memory",
"data-structures",
"graph"
] | I'm developing an application in which I need a structure to represent a huge graph (between 1000000 and 6000000 nodes and 100 or 600 edges) in memory. The edges representation will contain some attributes of the relation.
I have tried a memory map representation, arrays, dictionaries and strings to represent that str... | 1. If that is 100-600 edges/node, then you are talking about 3.6 billion edges.
2. Why does this have to be all in memory?
3. Can you show us the structures you are currently using?
4. How much memory are we allowed (what is the memory limit you are hitting?)
If the only reason you need this in memory is because you n... |
What is the best practices for checking if the user of a Python script has root-like privileges? | 2,806,897 | 35 | 2010-05-10T22:31:05Z | 2,806,923 | 28 | 2010-05-10T22:39:20Z | [
"python",
"root",
"privileges"
] | I have a Python script that will be doing a lot of things that would require root-level privileges, such as moving files in /etc, installing with apt-get, and so on. I currently have:
```
if os.geteuid() != 0:
exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exi... | `os.geteuid` gets the effective user id, which is exactly what you want, so I can't think of any better way to perform such a check. The one bit that's uncertain is that "root-like' in the title: your code checks for *exactly* `root`, no "like" about it, and indeed I wouldn't know what "root-like but not root" would me... |
What is the best practices for checking if the user of a Python script has root-like privileges? | 2,806,897 | 35 | 2010-05-10T22:31:05Z | 2,806,932 | 23 | 2010-05-10T22:41:07Z | [
"python",
"root",
"privileges"
] | I have a Python script that will be doing a lot of things that would require root-level privileges, such as moving files in /etc, installing with apt-get, and so on. I currently have:
```
if os.geteuid() != 0:
exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exi... | Under the "Easier to Ask Forgiveness than Permission" principle:
```
try:
os.rename('/etc/foo', '/etc/bar')
except IOError as e:
if (e[0] == errno.EPERM):
print >> sys.stderr, "You need root permissions to do this, laterz!"
sys.exit(1)
```
If you are concerned about the non-portability of `os.ge... |
How to get a html elements with python lxml | 2,807,209 | 4 | 2010-05-10T23:50:03Z | 2,807,665 | 7 | 2010-05-11T02:13:07Z | [
"python",
"xml",
"lxml"
] | I have this html code:
```
<table>
<tr>
<td class="test"><b><a href="">aaa</a></b></td>
<td class="test">bbb</td>
<td class="test">ccc</td>
<td class="test"><small>ddd</small></td>
</tr>
<tr>
<td class="test"><b><a href="">eee</a></b></td>
<td class="test">fff</td>
<td class="test">ggg</td>
<td clas... | If you do `el.text_content()` you'll strip all the tag stuff from each element, i.e.:
```
result = [el.text_content() for el in result]
``` |
super function doesn't work inside a maya python module | 2,808,010 | 4 | 2010-05-11T04:08:02Z | 5,872,660 | 20 | 2011-05-03T16:30:13Z | [
"python",
"class",
"maya"
] | Somehow, this works fine in the Maya/Python script editor, but fails when it's inside of my module code. Anyone have any ideas?
```
class ControlShape(object):
def __init__(self, *args, **kwargs):
print 'Inside ControlShape...'
class Cross(ControlShape):
def __init__(self, *args, **kwargs):
pr... | It has to do with reloading modules. Reloading a module often changes the internal object in memory which makes the isinstance test of super return False.
<http://thingspython.wordpress.com/2010/09/27/another-super-wrinkle-raising-typeerror/> |
Whats the best way to extend Anonymous User in Django? | 2,808,723 | 5 | 2010-05-11T07:15:37Z | 2,809,873 | 7 | 2010-05-11T10:31:43Z | [
"python",
"django",
"authentication",
"user"
] | I want to make my User objects all have the same base behaviour and to do so I need to add a couple of methods / properties to Anonymous User.
I've already subclassed User to make richer user objects but I was wondering if anyone has done the same for Anonymous User? And if there are any preferred ways of doing it! | Your middleware suggestion got me thinking, and I now think the best idea is to overwrite the standard `AuthenticationMiddleware`. That class assigns a `LazyUser` object to the request, which is resolved to the correct user, when accessed, by calling `contrib.auth.get_user`. This is probably the right place to override... |
Problems with sys.stdout.write() with time.sleep() in a function | 2,808,832 | 5 | 2010-05-11T07:38:51Z | 2,808,845 | 8 | 2010-05-11T07:40:57Z | [
"python",
"buffering"
] | What I wanted is printing out 5 dots that a dot printed per a second using time.sleep(), but the result was 5 dots were printed at once after 5 seconds delay.
Tried both print and sys.stdout.write, same result.
Thanks for any advices.
```
import time
import sys
def wait_for(n):
"""Wait for {n} seconds. {n} sho... | You need to flush after writing.
```
sys.stdout.write('foo')
sys.stdout.flush()
wastetime()
sys.stdout.write('bar')
sys.stdout.flush()
``` |
How to show raw_id value of a ManyToMany relation in the Django admin? | 2,809,122 | 4 | 2010-05-11T08:36:03Z | 3,023,530 | 7 | 2010-06-11T14:20:05Z | [
"python",
"django",
"django-admin"
] | I have an app using raw\_id on both ForeignKeyField and ManyToManyField. The admin displays the value of the foreign key on the right of the edit box.
Unfortunatey, it doesn't work with ManyToMany. I've checked the code and I think that it is the normal behavior. However I would like to know if someone has an easy tip... | Finally I succeed to make it working.
```
from django.contrib.admin.widgets import ManyToManyRawIdWidget
class VerboseManyToManyRawIdWidget(ManyToManyRawIdWidget):
def __init__(self, rel, attrs=None):
super(VerboseManyToManyRawIdWidget, self).__init__(rel, attrs)
def label_for_value(self, value):
... |
sort a list of percentages | 2,809,415 | 3 | 2010-05-11T09:21:53Z | 2,809,451 | 15 | 2010-05-11T09:26:57Z | [
"python",
"list",
"sorting"
] | I have the following list:
```
l = ['50%','12.5%','6.25%','25%']
```
Which I would like to sort in the following order:
```
['6.25%','12.5%','25%','50%']
```
Using l.sort() yields:
```
['12.5%','25%','50%','6.25%']
```
Any cool tricks to sort these lists easily in Python? | You can sort with a custom key
```
b =['52.5%', '62.4%', '91.8%', '21.5%']
b.sort(key = lambda a: float(a[:-1]))
```
This resorts the set, but uses the numerical value as the key (i.e. chops of the '%' in the string and converts to float. |
Making a CharField use a PasswordInput in the admin | 2,810,996 | 7 | 2010-05-11T13:20:27Z | 2,811,012 | 16 | 2010-05-11T13:22:38Z | [
"python",
"django",
"django-admin"
] | I have a Django site in which the site admin inputs their Twitter Username/Password in order to use the Twitter API. The Model is set up like this:
```
class TwitterUser(models.Model):
screen_name = models.CharField(max_length=100)
password = models.CharField(max_length=255)
def __unicode__(self):
return self.scre... | From [the docs](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets), you can build your own form, something like this:
```
from django.forms import ModelForm, PasswordInput
class TwitterUserForm(ModelForm):
class Meta:
model = TwitterUser
wi... |
Model Django Poll | 2,811,075 | 8 | 2010-05-11T13:29:49Z | 2,811,103 | 10 | 2010-05-11T13:34:16Z | [
"python",
"django",
"django-models"
] | I am working through the [Django tutorials](http://docs.djangoproject.com/en/dev/intro/tutorial01/), and now I am at creating a poll.
The code below works fine until I want to create choices, where for some reason I always get this error message:
```
line 22, in __unicode__
return self.question
AttributeError: 'Choi... | The `__unicode__` method on the `Choice` model should look something like:
```
def __unicode__(self):
return self.poll.question
```
`question` attribute does not exist on the `Choice` model, you need to reach for it over the `poll` foreign key field.
Don't forget to check out Django's great documentation that sh... |
Model Django Poll | 2,811,075 | 8 | 2010-05-11T13:29:49Z | 4,894,293 | 7 | 2011-02-04T03:31:02Z | [
"python",
"django",
"django-models"
] | I am working through the [Django tutorials](http://docs.djangoproject.com/en/dev/intro/tutorial01/), and now I am at creating a poll.
The code below works fine until I want to create choices, where for some reason I always get this error message:
```
line 22, in __unicode__
return self.question
AttributeError: 'Choi... | To follow up on rebus's answer, the tutorial actually says to add different returns to each model:
```
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
```
You had 'self.question' as... |
Python file input string: how to handle escaped unicode characters? | 2,811,174 | 3 | 2010-05-11T13:44:18Z | 2,811,398 | 7 | 2010-05-11T14:11:33Z | [
"python",
"unicode",
"utf-8",
"decode"
] | In a text file (test.txt), my string looks like this:
```
Gro\u00DFbritannien
```
Reading it, python escapes the backslash:
```
>>> file = open('test.txt', 'r')
>>> input = file.readline()
>>> input
'Gro\\u00DFbritannien'
```
How can I have this interpreted as unicode? `decode()` and `unicode()` won't do the job.
... | You want to use the `unicode_escape` codec:
```
>>> x = 'Gro\\u00DFbritannien'
>>> y = unicode(x, 'unicode_escape')
>>> print y
GroÃbritannien
```
See [the docs](http://docs.python.org/library/codecs.html?highlight=codecs#standard-encodings) for the vast number of standard encodings that come as part of the Python s... |
Problem with sys.argv[1] when unittest module is in a script | 2,812,218 | 7 | 2010-05-11T15:57:01Z | 2,839,010 | 11 | 2010-05-15T05:19:23Z | [
"python",
"unit-testing",
"argv",
"sys"
] | I have a script that does various things and access paramenters using sys.argv but when the script gets to the unittest part of the code it says there is no module for this. The script that I have is:
```
class MyScript():
def __init__(self):
self.value = sys.argv[1]
def hello(self):
print se... | The problem is that `unittest.main()` wants your precious argv for its own use! It uses either the argv you give it as a function parameter, or `sys.argv` if you don't give it argv explicitly, and tries to load tests named the arguments you give. In this case, this means it's looking for either a submodule called `Hell... |
Is there a python equivalent of Ruby's 'rvm'? | 2,812,471 | 111 | 2010-05-11T16:25:35Z | 2,812,484 | 61 | 2010-05-11T16:27:02Z | [
"python",
"egg",
"equivalent",
"rvm"
] | **Q:** Do we have anything functionally equivalent in Python to the [Ruby version manager 'rvm'](http://rvm.beginrescueend.com/workflow/rvmrc/)?
---
(*RVM* lets you easily switch **completely** between different versions of the ruby interpreter **and** different sets of gems (modules). Everything concerning download-... | Yes, it is [virtualenv](http://pypi.python.org/pypi/virtualenv) along with [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/).
update: you may install both at once with [virtualenv burrito](https://github.com/brainsik/virtualenv-burrito).
**Update**: the correct answer is now probably [pyenv... |
Is there a python equivalent of Ruby's 'rvm'? | 2,812,471 | 111 | 2010-05-11T16:25:35Z | 3,953,221 | 79 | 2010-10-17T12:32:11Z | [
"python",
"egg",
"equivalent",
"rvm"
] | **Q:** Do we have anything functionally equivalent in Python to the [Ruby version manager 'rvm'](http://rvm.beginrescueend.com/workflow/rvmrc/)?
---
(*RVM* lets you easily switch **completely** between different versions of the ruby interpreter **and** different sets of gems (modules). Everything concerning download-... | ## Pythonbrew is no longer under development. The former maintainer suggests to use "PyEnv" instead (see below)".
pythonbrew has come!
<http://github.com/utahta/pythonbrew>
pyenv: <https://github.com/yyuu/pyenv> |
Is there a python equivalent of Ruby's 'rvm'? | 2,812,471 | 111 | 2010-05-11T16:25:35Z | 12,701,715 | 33 | 2012-10-03T04:02:55Z | [
"python",
"egg",
"equivalent",
"rvm"
] | **Q:** Do we have anything functionally equivalent in Python to the [Ruby version manager 'rvm'](http://rvm.beginrescueend.com/workflow/rvmrc/)?
---
(*RVM* lets you easily switch **completely** between different versions of the ruby interpreter **and** different sets of gems (modules). Everything concerning download-... | I created [pyenv](https://github.com/yyuu/pyenv) which is a fork of Ruby's [rbenv](https://github.com/sstephenson/rbenv) and modified for Python. Like pythonz, pyenv also supports Stackless, PyPy, and Jython. |
pip: dealing with multiple Python versions? | 2,812,520 | 149 | 2010-05-11T16:32:18Z | 2,812,627 | 51 | 2010-05-11T16:43:15Z | [
"python",
"pip"
] | Is there any way to make `pip` play well with multiple versions of Python? For example, I want to use `pip` to explicitly install things to either my site 2.5 installation or my site 2.6 installation.
For example, with `easy_install`, I use `easy_install-2.{5,6}`.
And, yes â I know about virtualenv, and no â it's... | `/path/to/python2.{5,6} /path/to/pip install PackageName` doesn't work?
For this to work on any python version that doesn't have pip already installed you need to download pip and do `python*version* setup.py install`. For example `python3.3 setup.py install`. This resolves the import error in the comments. (As sugges... |
pip: dealing with multiple Python versions? | 2,812,520 | 149 | 2010-05-11T16:32:18Z | 4,910,393 | 156 | 2011-02-05T23:24:41Z | [
"python",
"pip"
] | Is there any way to make `pip` play well with multiple versions of Python? For example, I want to use `pip` to explicitly install things to either my site 2.5 installation or my site 2.6 installation.
For example, with `easy_install`, I use `easy_install-2.{5,6}`.
And, yes â I know about virtualenv, and no â it's... | Since version 0.8, Pip supports `pip-{version}`. You can use it the same as `easy_install-{version}`:
```
$ pip-2.5 install myfoopackage
$ pip-2.6 install otherpackage
$ pip-2.7 install mybarpackage
```
---
**EDIT**: pip changed its schema to use `pipVERSION` instead of `pip-VERSION` in version 1.5. You should use t... |
pip: dealing with multiple Python versions? | 2,812,520 | 149 | 2010-05-11T16:32:18Z | 15,878,602 | 8 | 2013-04-08T12:05:24Z | [
"python",
"pip"
] | Is there any way to make `pip` play well with multiple versions of Python? For example, I want to use `pip` to explicitly install things to either my site 2.5 installation or my site 2.6 installation.
For example, with `easy_install`, I use `easy_install-2.{5,6}`.
And, yes â I know about virtualenv, and no â it's... | So apparently there are multiple versions of `easy_install` *and* `pip`. It seems to be a big mess. Anyway, this is what I did to install Django for Python 2.7 on Ubuntu 12.10:
```
$ sudo easy_install-2.7 pip
Searching for pip
Best match: pip 1.1
Adding pip 1.1 to easy-install.pth file
Installing pip-2.7 script to /us... |
pip: dealing with multiple Python versions? | 2,812,520 | 149 | 2010-05-11T16:32:18Z | 25,474,222 | 24 | 2014-08-24T17:12:26Z | [
"python",
"pip"
] | Is there any way to make `pip` play well with multiple versions of Python? For example, I want to use `pip` to explicitly install things to either my site 2.5 installation or my site 2.6 installation.
For example, with `easy_install`, I use `easy_install-2.{5,6}`.
And, yes â I know about virtualenv, and no â it's... | I had python 2.6 installed by default (Amazon EC2 AMI), but needed python2.7 plus some external packages for my application. Assuming you already installed python2.7 alongside with default python (2.6 in my case). Here is how to install pip and packages for non-default python2.7
Install pip for your python version:
`... |
pip: dealing with multiple Python versions? | 2,812,520 | 149 | 2010-05-11T16:32:18Z | 37,251,956 | 12 | 2016-05-16T10:40:12Z | [
"python",
"pip"
] | Is there any way to make `pip` play well with multiple versions of Python? For example, I want to use `pip` to explicitly install things to either my site 2.5 installation or my site 2.6 installation.
For example, with `easy_install`, I use `easy_install-2.{5,6}`.
And, yes â I know about virtualenv, and no â it's... | In Windows, you can execute the pip module by mentioning the python version ( You need to ensure that the launcher is on your path )
py -3.4 -m pip install pyfora
py -2.7 -m pip install pyfora |
Python proper use of __str__ and __repr__ | 2,812,809 | 9 | 2010-05-11T17:06:28Z | 2,812,895 | 12 | 2010-05-11T17:19:40Z | [
"python",
"bit-manipulation",
"conventions",
"representation"
] | My current project requires extensive use of bit fields. I found a simple, functional [recipe for bit a field class](http://code.activestate.com/recipes/113799/) but it was lacking a few features I needed, so I decided to extend it. I've just got to implementing `__str__` and `__repr__` and I want to make sure I'm foll... | The `__repr__` should preferably be a string that could be used to recreate the object, for example if you use `eval` on it - see the docs [here](http://docs.python.org/library/functions.html#repr). This isn't an exact science, as it can depend on how the user of your module imported it, for example.
I would have the ... |
Lisp vs Python -- Static Compilation | 2,812,954 | 13 | 2010-05-11T17:27:49Z | 2,813,126 | 13 | 2010-05-11T17:52:09Z | [
"python",
"lisp",
"compilation",
"dynamic-languages"
] | Why can Lisp with all its dynamic features be statically compiled but Python cannot (without losing all its dynamic features)? | There is nothing that prevents static compilation of Python. It's a bit less efficient because Python reveals more mutable local scope, also, to retain some of the dynamic properties (e.g. eval) you need to include the compiler with the compiled program but nothing prevents that too.
That said, research shows that mos... |
Printing Variable names and contents as debugging tool; looking for emacs/Python shortcut | 2,813,227 | 9 | 2010-05-11T18:04:40Z | 2,813,384 | 7 | 2010-05-11T18:28:07Z | [
"python",
"debugging",
"emacs",
"variables",
"printing"
] | I find myself adding debugging "print" statements quite often -- stuff like this:
```
print("a_variable_name: %s" % a_variable_name)
```
How do you all do that? Am I being neurotic in trying to find a way to optimize this? I may be working on a function and put in a half-dozen or so of those lines, figure out why it'... | Sometimes a debugger is great, but sometimes using print statements is quicker, and easier to setup and use repeatedly.
This may only be suitable for debugging with CPython (since not all Pythons implement `inspect.currentframe` and `inspect.getouterframes`), but I find this useful for cutting down on typing:
In util... |
How to pack python files and its dependencies in a single executable file? | 2,813,229 | 7 | 2010-05-11T18:04:53Z | 2,813,252 | 9 | 2010-05-11T18:08:07Z | [
"python",
"executable",
"archive",
"libraries"
] | I've got a piece of software which consists of several python sources and a couple of c++ libraries. I'd like to pack them in a executable single file, just like java does with .jar files. Is there a way to do that? | You may want to have a look at [py2exe](http://www.py2exe.org), [pyInstaller](http://www.pyinstaller.org/) or [others](http://www.freehackers.org/Packaging_a_python_program). |
How do you check the presence of many keys in a Python dictinary? | 2,813,806 | 8 | 2010-05-11T19:24:45Z | 2,813,820 | 9 | 2010-05-11T19:26:53Z | [
"python"
] | I have the following dictionary:
```
sites = {
'stackoverflow': 1,
'superuser': 2,
'meta': 3,
'serverfault': 4,
'mathoverflow': 5
}
```
To check if there are more than one key available in the above dictionary, I will do something like:
```
'stackoverflow' in sites and 'serverfault' in sites
```
... | You could use `all`:
```
print( all(site in sites for site in ('stackoverflow','meta')) )
# True
print( all(site in sites for site in ('stackoverflow','meta','roger')) )
# False
``` |
How do you check the presence of many keys in a Python dictinary? | 2,813,806 | 8 | 2010-05-11T19:24:45Z | 2,813,836 | 12 | 2010-05-11T19:29:39Z | [
"python"
] | I have the following dictionary:
```
sites = {
'stackoverflow': 1,
'superuser': 2,
'meta': 3,
'serverfault': 4,
'mathoverflow': 5
}
```
To check if there are more than one key available in the above dictionary, I will do something like:
```
'stackoverflow' in sites and 'serverfault' in sites
```
... | You can pretend the keys of the dict are a set, and then use set.issubset:
```
set(['stackoverflow', 'serverfault']).issubset(sites) # ==> True
set(['stackoverflow', 'google']).issubset(sites) # ==> False
``` |
How do I coalesce a sequence of identical characters into just one? | 2,813,829 | 4 | 2010-05-11T19:28:36Z | 2,813,846 | 13 | 2010-05-11T19:31:23Z | [
"python",
"regex",
"string"
] | Suppose I have this:
My---sun--is------very-big---.
I want to replace all multiple hyphens with just one hyphen. | ```
import re
astr='My---sun--is------very-big---.'
print(re.sub('-+','-',astr))
# My-sun-is-very-big-.
``` |
How do I coalesce a sequence of identical characters into just one? | 2,813,829 | 4 | 2010-05-11T19:28:36Z | 2,814,090 | 12 | 2010-05-11T20:10:57Z | [
"python",
"regex",
"string"
] | Suppose I have this:
My---sun--is------very-big---.
I want to replace all multiple hyphens with just one hyphen. | If you want to replace *any* run of consecutive characters, you can use
```
>>> import re
>>> a = "AA---BC++++DDDD-EE$$$$FF"
>>> print(re.sub(r"(.)\1+",r"\1",a))
A-BC+D-E$F
```
If you only want to coalesce non-word-characters, use
```
>>> print(re.sub(r"(\W)\1+",r"\1",a))
AA-BC+DDDD-EE$FF
```
If it's really just hy... |
Python Error: "ValueError: need more than 1 value to unpack" | 2,814,128 | 26 | 2010-05-11T20:16:39Z | 2,814,150 | 28 | 2010-05-11T20:20:17Z | [
"python",
"arguments"
] | In Python, when I run this code:
```
from sys import argv
script, user_name =argv
prompt = '>'
print "Hi %s, I'm the %s script." % (user_name, script)
```
I get this error:
```
Traceback (most recent call last):
script, user_name =argv
ValueError: need more than 1 value to unpack
```
What does that error mean... | Probably you didn't provide an argument on the command line. In that case, `sys.argv` only contains one value, but it would have to have two in order to provide values for both `user_name` and `script`. |
Python and urllib2: how to make a GET request with parameters | 2,814,898 | 33 | 2010-05-11T22:33:10Z | 2,814,929 | 17 | 2010-05-11T22:39:18Z | [
"python",
"urllib2"
] | I'm building an "API API", it's basically a wrapper for a in house REST web service that the web app will be making a lot of requests to.
Some of the web service calls need to be GET rather than post, but passing parameters.
Is there a "best practice" way to encode a dictionary into a query string? e.g.: `?foo=bar&bla... | [urllib.urlencode](http://docs.python.org/library/urllib.html#urllib.urlencode)
And yes, the `urllib` / `urllib2` division of labor is a little confusing in Python 2.x. |
Python and urllib2: how to make a GET request with parameters | 2,814,898 | 33 | 2010-05-11T22:33:10Z | 2,814,978 | 29 | 2010-05-11T22:50:12Z | [
"python",
"urllib2"
] | I'm building an "API API", it's basically a wrapper for a in house REST web service that the web app will be making a lot of requests to.
Some of the web service calls need to be GET rather than post, but passing parameters.
Is there a "best practice" way to encode a dictionary into a query string? e.g.: `?foo=bar&bla... | Is [urllib.urlencode()](http://docs.python.org/library/urllib.html#urllib.urlencode) not enough?
```
>>> import urllib
>>> urllib.urlencode({'foo': 'bar', 'bla': 'blah'})
foo=bar&bla=blah
```
EDIT:
You can also update the existing url:
```
>>> import urlparse, urlencode
>>> url_dict = urlparse.parse_qs('a=b&c=d... |
PyDev and Django: Autocomplete not detecting Django? | 2,815,094 | 3 | 2010-05-11T23:15:46Z | 2,816,189 | 8 | 2010-05-12T05:11:15Z | [
"python",
"django",
"eclipse",
"ide",
"pydev"
] | I'm using PyDev with Django. The autocomplete works nicely in the shell - I start typing, and it suggests completions. However, this doesn't work in the main code editor window. How can I fix this?
I'm using:
Eclipse build #20100218-1602
PyDev 1.5.6
Eclipse IDE for Java Devs 1.2.2 | You might need to set the editor code completion settings. They are under:
`Window->Preferences->PyDev->Editor->Code Completion`
You might also need to add the Django install or your Django project to your path. You can set this under:
`Window->Preferences->PyDev->Interpreter - Python`
Hope this helps. |
Is there a php function like python's zip? | 2,815,162 | 41 | 2010-05-11T23:31:46Z | 2,815,190 | 10 | 2010-05-11T23:41:05Z | [
"php",
"python"
] | Python has a nice [`zip()`](http://docs.python.org/library/functions.html#zip) function. Is there a PHP equivalent? | [`array_combine`](http://php.net/manual/en/function.array-combine.php) comes close.
Otherwise nothing like coding it yourself:
```
function array_zip($a1, $a2) {
for($i = 0, $i < min(length($a1), length($a2)); $i++) {
$out[$i] = [$a1[$i], $a2[$i]];
}
return $out;
}
``` |
Is there a php function like python's zip? | 2,815,162 | 41 | 2010-05-11T23:31:46Z | 2,815,250 | 11 | 2010-05-11T23:57:29Z | [
"php",
"python"
] | Python has a nice [`zip()`](http://docs.python.org/library/functions.html#zip) function. Is there a PHP equivalent? | Try this function to create an array of arrays similar to Pythonâs `zip`:
```
function zip() {
$args = func_get_args();
$zipped = array();
$n = count($args);
for ($i=0; $i<$n; ++$i) {
reset($args[$i]);
}
while ($n) {
$tmp = array();
for ($i=0; $i<$n; ++$i) {
... |
Is there a php function like python's zip? | 2,815,162 | 41 | 2010-05-11T23:31:46Z | 2,815,567 | 54 | 2010-05-12T01:17:15Z | [
"php",
"python"
] | Python has a nice [`zip()`](http://docs.python.org/library/functions.html#zip) function. Is there a PHP equivalent? | As long as all the arrays are the same length, you can use [`array_map`](http://php.net/manual/en/function.array-map.php) with `null` as the first argument.
```
array_map(null, $a, $b, $c, ...);
```
If some of the arrays are shorter, they will be padded with nulls to the length of the longest, unlike python where the... |
Is there a php function like python's zip? | 2,815,162 | 41 | 2010-05-11T23:31:46Z | 8,375,865 | 7 | 2011-12-04T14:10:26Z | [
"php",
"python"
] | Python has a nice [`zip()`](http://docs.python.org/library/functions.html#zip) function. Is there a PHP equivalent? | This **works exactly as Python's `zip()` function**, and is compatible also with PHP < 5.3:
```
function zip() {
$params = func_get_args();
if (count($params) === 1){ // this case could be probably cleaner
// single iterable passed
$result = array();
foreach ($params[0] as $item){
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.