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 |
|---|---|---|---|---|---|---|---|---|---|
Why should I use operator.itemgetter(x) instead of [x]? | 11,287,207 | 17 | 2012-07-02T02:25:32Z | 11,287,231 | 8 | 2012-07-02T02:30:16Z | [
"python",
"operators"
] | There is a more general question here: [In what situation should the built-in `operator` module be used in python?](http://stackoverflow.com/questions/467920/in-what-situation-should-the-built-in-operator-module-be-used-in-python)
The top answer claims that `operator.itemgetter(x)` is "neater" than, presumably, than `... | There are benefits in some situations, here is a good example.
```
>>> data = [('a',3),('b',2),('c',1)]
>>> from operator import itemgetter
>>> sorted(data, key=itemgetter(1))
[('c', 1), ('b', 2), ('a', 3)]
```
This use of `itemgetter` is great because it makes everything clear while also being faster as all operatio... |
how to round_corner a logo without white background(transparent?) on it using pil? | 11,287,402 | 5 | 2012-07-02T03:09:45Z | 11,291,419 | 7 | 2012-07-02T09:58:50Z | [
"python",
"python-imaging-library",
"transparent",
"rounded-corners"
] | I got a square logo and I need to round\_corner it, searched for a while and got the follow code "working":
```
def round_corner_jpg(image, radius):
"""generate round corner for image"""
mask = Image.new('RGB', image.size)
#mask = Image.new('RGB', (image.size[0] - radius, image.size[1] - radius))
#mask... | First off, make sure you are saving your image in a format that supports transparency. `PNG` does, `JPG` does not... Below is some pretty nice code that will add transparent corners. It works like this:
1. Draws a circle with radius, `rad`, using `draw.ellipse()`
2. Create an image for the alpha channel the same size ... |
How do I avoid this pickling error, and what is the best way to parallelize this code in Python? | 11,287,455 | 6 | 2012-07-02T03:19:14Z | 11,287,550 | 11 | 2012-07-02T03:42:33Z | [
"python",
"multiprocessing",
"pickle"
] | I have the following code.
```
def main():
(minI, maxI, iStep, minJ, maxJ, jStep, a, b, numProcessors) = sys.argv
for i in range(minI, maxI, iStep):
for j in range(minJ, maxJ, jStep):
p = multiprocessing.Process(target=functionA, args=(minI, minJ))
p.start()
def functionB((a, b)):
su... | The reason you are most likely seeing this behavior is because of the order in which you define your pool, objects, and functions. `multiprocessing` is not quite the same as using threads. Each process will spawn and load a copy of the environment. If you create functions in scopes that may not be available to the proc... |
Installing lxml in virtualenv for windows | 11,287,585 | 6 | 2012-07-02T03:48:21Z | 17,631,171 | 8 | 2013-07-13T14:37:36Z | [
"python",
"lxml",
"virtualenv",
"pip"
] | I've recently started using virtualenv, and would like to install lxml in this isolated environment.
Normally I would use the windows binary installer, but I want to use lxml in this virtualenv (not globally). Pip install does not work for lxml, so I'm at a loss for what I can do.
I've read that creating symlinks may... | 1. Download lxml: <http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml>
2. Activate virtualenv
3. `easy_install /path/to/the/file/lxml-3.2.1.win32-py3.3.âexe` |
Python iterable Queue | 11,288,158 | 6 | 2012-07-02T05:26:46Z | 11,288,503 | 9 | 2012-07-02T06:08:34Z | [
"python",
"queue",
"iteration"
] | I need to know when a Queue is closed and wont have more items so I can end the iteration.
I did it by putting a sentinel in the queue:
```
from Queue import Queue
class IterableQueue(Queue):
_sentinel = object()
def __iter__(self):
return self
def close(self):
self.put(self._sentinel... | A sentinel is a reasonable way for a producer to send a message that no more queue tasks are forthcoming.
FWIW, your code can be simplified quite a bit with the two argument form of [*iter()*](http://docs.python.org/library/functions.html#iter):
```
from Queue import Queue
class IterableQueue(Queue):
_sentinel... |
Cannot install py2exe with Python 2.7 | 11,288,923 | 21 | 2012-07-02T06:48:49Z | 11,288,985 | 30 | 2012-07-02T06:54:11Z | [
"python",
"python-2.7",
"py2exe"
] | I am trying to install [py2exe](http://www.py2exe.org). I have Python 2.7 installed on my machine. Their [website](http://www.py2exe.org/old/) mentions that they have released support for 2.7, but when I try to install, it mentions that Python Version 2.6 required, which was not found in the registry. I have downloaded... | Try [this link](http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/py2exe-0.6.9.win32-py2.7.exe/download). It's py2exe for Python 2.7. |
How to find an index at which a new item can be inserted into sorted list and keep it sorted? | 11,290,767 | 13 | 2012-07-02T09:11:00Z | 11,290,793 | 19 | 2012-07-02T09:12:32Z | [
"python",
"sortedlist"
] | ```
a = 132
b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530]
```
I want to know that `a` should be in the 6th position in ordered list `b`.
What's the most pythonic way to do so? | Use [bisect](http://docs.python.org/py3k/library/bisect.html). It's not the most beautiful API, but it's exactly what you need.
You'll want to use `bisect.bisect`, which returns exactly what you want. |
How to find an index at which a new item can be inserted into sorted list and keep it sorted? | 11,290,767 | 13 | 2012-07-02T09:11:00Z | 11,290,852 | 16 | 2012-07-02T09:16:10Z | [
"python",
"sortedlist"
] | ```
a = 132
b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530]
```
I want to know that `a` should be in the 6th position in ordered list `b`.
What's the most pythonic way to do so? | [`bisect`](https://docs.python.org/3/library/bisect.html) is a module in the Python Standard Library that is perfect for this task. The function `bisect` in the module `bisect` will give you the index of the insertion point for the value.
Let me give a code example for `bisect`
```
from bisect import bisect
a = 132
b... |
Flask-SQLAlchemy: How to conditionally insert or update a row | 11,292,612 | 12 | 2012-07-02T11:19:32Z | 11,786,329 | 25 | 2012-08-02T21:50:07Z | [
"python",
"flask",
"flask-sqlalchemy",
"wtforms",
"flask-wtforms"
] | My application uses a combination of Flask, Flask-SQLAlchemy, Flask-WTF and Jinja2.
In its current incarnation, I have a settings table. The table will only have one record with one field. Initially the table contains zero records.
What I want to achieve is:
* Given that no entries exist in db, then show empty form ... | Once your form is validated etc,
To add a new record:
```
new_provider = Provider(form.rssfeed.data)
db.session.add(new_provider)
db.session.commit()
```
To update an existing record:
```
existing_provider = Provider.query.get(1) # or whatever
# update the rssfeed column
existing_provider.rssfeed = form.rssfeed.dat... |
Django: Catching Integrity Error and showing a customized message using template | 11,293,380 | 27 | 2012-07-02T12:07:15Z | 11,293,459 | 71 | 2012-07-02T12:12:12Z | [
"python",
"django",
"website"
] | In my django powered app there is only one obvious case where "IntegrityError" can arise.So,how can I catch that error and display a message using templates. | Just use try and catch.
```
from django.db import IntegrityError
from django.shortcuts import render_to_response
try:
# code that produces error
except IntegrityError as e:
return render_to_response("template.html", {"message": e.message})
```
If you want you can use the message in your template.
EDIT
Than... |
Why is the argument of os.umask() inverted? (umask 0o000 makes chmod 0o777) | 11,294,077 | 11 | 2012-07-02T12:52:38Z | 11,294,312 | 11 | 2012-07-02T13:05:57Z | [
"python",
"unix",
"filesystems",
"chmod",
"umask"
] | In most places, permissions are defined as an octal number in the format of `0777`. But UNIX's `umask` command (thus `os.umask()`) needs `0o000` to produce the permission bits of `0o777` and `0o022` equals to `0o755` in my understanding.
I heard that UNIX's `umask` is inverted for some reason and I do not understand t... | There is no real inconsistency, as the relation between `umask` and `chmod` can purely be written down with equations. Apparently, `umask` sets the opposite of `chmod`, it was created like this back in the old days.
Example: `022` (the default usual `umask`) creates `755`. It works like this:
* `7 - 0 = 7` becomes th... |
Why do I getting false for the isclass function? | 11,294,348 | 3 | 2012-07-02T13:08:13Z | 11,294,370 | 9 | 2012-07-02T13:09:22Z | [
"python",
"class"
] | I'm using the following code to determine whether the input parameter is a class or a variable:
```
class Trajectory():
...
print inspect.isclass( Trajectory() )
```
where the Trajectory is a class, but when I'm calling this function I'm receiving false. Why?
According the documentation this have to be true
```
... | Because `Trajectory()` is a class instance â `Trajectory` is a class.
```
print inspect.isclass(Trajectory)
```
will print `True`. |
Verify if a String is JSON in python? | 11,294,535 | 9 | 2012-07-02T13:19:09Z | 11,294,578 | 17 | 2012-07-02T13:21:47Z | [
"python",
"json",
"dictionary"
] | I have a string in Python, I want to know if it is valid JSON.
`json.loads(mystring)` will raise an error if the string is not JSON but I don't want to catch an exception.
I want something like this, but it doesn't work:
```
if type(mysrting) == dict:
myStrAfterLoading = json.loads(mystring)
else:
print "inv... | To verify the string would require parsing it - so if you checked then converted it would literally take twice as long.
Catching the exception is the best way.
Interestingly, you can still use an if-else style expression:
```
try:
json_object = json.loads(json_string)
except ValueError, e:
pass # invalid json
... |
Verify if a String is JSON in python? | 11,294,535 | 9 | 2012-07-02T13:19:09Z | 11,294,589 | 10 | 2012-07-02T13:22:18Z | [
"python",
"json",
"dictionary"
] | I have a string in Python, I want to know if it is valid JSON.
`json.loads(mystring)` will raise an error if the string is not JSON but I don't want to catch an exception.
I want something like this, but it doesn't work:
```
if type(mysrting) == dict:
myStrAfterLoading = json.loads(mystring)
else:
print "inv... | Is there any reason you don't want to catch the exception?
Keep in mind that testing and catching an exception can be blazingly fast in Python, and is often the Pythonic way of doing things, instead of testing for type (basically, trust duck typing and react accordingly).
To put your mind a bit more at ease, take a l... |
Verify if a String is JSON in python? | 11,294,535 | 9 | 2012-07-02T13:19:09Z | 11,294,685 | 22 | 2012-07-02T13:27:28Z | [
"python",
"json",
"dictionary"
] | I have a string in Python, I want to know if it is valid JSON.
`json.loads(mystring)` will raise an error if the string is not JSON but I don't want to catch an exception.
I want something like this, but it doesn't work:
```
if type(mysrting) == dict:
myStrAfterLoading = json.loads(mystring)
else:
print "inv... | The correct answer is: stop NOT wanting to catch the [`ValueError`](https://docs.python.org/2/library/exceptions.html#exceptions.ValueError).
**Example Python script returns a boolean if a string is valid json:**
```
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueE... |
Port forwarding with paramiko | 11,294,919 | 15 | 2012-07-02T13:41:47Z | 12,106,387 | 9 | 2012-08-24T09:12:39Z | [
"python",
"ssh",
"paramiko"
] | I'm trying to do some port forwarding from a python app using paramiko. I can set up the SSH connection just fine, but I'm a bit stumped as to how to use paramiko.transport. I've already found [this file](https://code.ros.org/trac/wg-ros-pkg/browser/pkg/trunk/paramiko/demos/forward.py?rev=30), but I can't work out what... | Please find some code using `paramiko-1.7.7.1`, `pycrypto-2.6` and the [forward.py script](https://code.ros.org/trac/wg-ros-pkg/browser/pkg/trunk/paramiko/demos/forward.py?rev=30) from which I did remove code from the line 115 to the end (to avoid options parsing).
```
import paramiko, sys
from forward import forward_... |
Read two textfile line by line simultaneously -python | 11,295,171 | 24 | 2012-07-02T13:56:47Z | 11,295,227 | 9 | 2012-07-02T14:00:02Z | [
"python",
"file",
"io",
"readfile"
] | I have 2 textfiles in two different languages and they are aligned line by line. I.e. the first line in the textfile1 should be equals to the first line in textfile2, and so on and so forth.
Is there a way to read both file line-by-line simultaneously?
Below is a sample of how the files should look like, imagine the ... | ```
with open(file1) as f1,open(fil2) as f2:
for x,y in zip(f1,f2):
print("{0}\t{1}".format(x.strip(),y.strip()))
```
**output:**
```
This is a the first line in English C'est la première ligne en Français
This is a the 2nd line in English C'est la deuxième ligne en Français
This is a the third line in E... |
Read two textfile line by line simultaneously -python | 11,295,171 | 24 | 2012-07-02T13:56:47Z | 11,295,232 | 51 | 2012-07-02T14:00:17Z | [
"python",
"file",
"io",
"readfile"
] | I have 2 textfiles in two different languages and they are aligned line by line. I.e. the first line in the textfile1 should be equals to the first line in textfile2, and so on and so forth.
Is there a way to read both file line-by-line simultaneously?
Below is a sample of how the files should look like, imagine the ... | ```
from itertools import izip
with open("textfile1") as textfile1, open("textfile2") as textfile2:
for x, y in izip(textfile1, textfile2):
x = x.strip()
y = y.strip()
print("{0}\t{1}".format(x, y))
```
In Python 3, replace `itertools.izip` with the built-in `zip`. |
python pexpect sendcontrol key characters | 11,295,550 | 3 | 2012-07-02T14:20:42Z | 11,299,721 | 7 | 2012-07-02T19:08:16Z | [
"python",
"key",
"character",
"pexpect"
] | I am working with pythons pexpect module to automate tasks, I need help in figuring out key characters to use with sendcontrol. how could one send the controlkey ENTER ? and for future reference how can we find the key characters?
here is the code i am working on.
```
#!/usr/bin/env python
import pexpect
id = pexpe... | **pexpect** has no `sendcontrol()` method. In your example you appear to be trying to send an empty line. To do that, use:
```
id.sendline('')
```
If you need to send real control characters then you can `send()` a string that contains the appropriate character value. For instance, to send a control-C you would:
... |
How can I check whether the numpy array is empty or not? | 11,295,609 | 44 | 2012-07-02T14:24:45Z | 11,295,857 | 65 | 2012-07-02T14:38:48Z | [
"python",
"numpy"
] | How can I check whether the numpy array is empty or not?
I used the following code, but this is fail if the array contains a zero.
```
if not self.Definition.all():
```
is this the solution?
```
if self.Definition == array( [] ):
``` | You can always take a look at the `.size` attribute:
```
import numpy as np
a = np.array([])
print a.size # 0
``` |
How to select a directory and store the location using tkinter in Python | 11,295,917 | 8 | 2012-07-02T14:42:03Z | 11,296,171 | 25 | 2012-07-02T14:58:16Z | [
"python",
"button",
"tkinter",
"directory",
"python-2.x"
] | I am creating a GUI with a browse button which I only want to return the path. I've been looking at solutions using code like below.
```
Tkinter.Button(subframe, text = "Browse", command = self.loadtemplate, width = 10).pack()
def loadtemplate(self):
filename = tkFileDialog.askopenfilename(filetypes = (("... | It appears that `tkFileDialog.askdirectory` should work. [documentation](http://tkinter.unpythonic.net/wiki/tkFileDialog) |
How to get the item currently pointed at by iterator without incrementing? | 11,295,937 | 8 | 2012-07-02T14:42:55Z | 11,296,012 | 7 | 2012-07-02T14:47:36Z | [
"python",
"iterator"
] | Is there a way to get the item pointed at by an iterator in python without incrementing the iterator itself? For example how would I implement the following with iterators:
```
looking_for = iter(when_to_change_the_mode)
for l in listA:
do_something(looking_for.current())
if l == looking_for.current():
... | Iterators don't have a way to get the current value. If you want that, keep a reference to it yourself, or wrap your iterator to hold onto it for you. |
Python NameError: global name 'NAME' is not not defined! (But it is defined) | 11,296,574 | 10 | 2012-07-02T15:22:35Z | 11,297,548 | 12 | 2012-07-02T16:25:23Z | [
"python",
"global",
"nameerror",
"defined"
] | This is my Python code:
```
import es, popuplib, cmdlib
info = es.AddonInfo()
info['name'] = "bilbodog Vaaben Menu"
info['version'] = "1.1"
info['author'] = "bilbodog"
info['url'] = ""
info['description'] = "En vaaben menu der kan give vaaben til spillere"
def load():
es.regclientcmd... | When you do:
```
global bilbodog
print bilbodog
```
You have this error:
```
Traceback (most recent call last):
File "D:\Documents and Settings\My Documents\StackOverflow\test.py", line 2, in <module>
print bilbodog
NameError: global name 'bilbodog' is not defined
```
Instead when you define your variables c... |
Matplotlib - Stepped histogram with already binned data | 11,297,030 | 11 | 2012-07-02T15:50:14Z | 11,297,568 | 8 | 2012-07-02T16:26:54Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | I am trying to get a histogram with already binned data. I have been trying to use `bar()` for this, but I can't seem to figure out how to make it a stepped histogram [like this one from the examples](http://matplotlib.org/mpl_examples/pylab_examples/histogram_demo_extended_02.png), instead of a filled histogram.
![en... | You could cheat, by offsetting your data and using `plot` instead:
```
from matplotlib import pyplot
import numpy as np
#sample data:
x = np.arange(30)
y = np.cumsum(np.arange(30))
#offset the x for horizontal, repeat the y for vertical:
x = np.ravel(zip(x,x+1))
y = np.ravel(zip(y,y))
pyplot.plot(x,y)
pyplot.savefig... |
What is the difference between a[:]=b and a=b[:] | 11,297,774 | 11 | 2012-07-02T16:41:55Z | 11,297,805 | 28 | 2012-07-02T16:43:50Z | [
"python",
"list",
"slice"
] | ```
a=[1,2,3]
b=[4,5,6]
c=[]
d=[]
```
Whats the difference between these two statements?
```
c[:]=a
d=b[:]
```
But both gives the same result.
c is [1,2,3] and d is [4,5,6]
And is there any difference functionality wise? | `c[:] = a` it means replace all the elements of c by elements of a
```
>>> l = [1,2,3,4,5]
>>> l[::2] = [0, 0, 0] #you can also replace only particular elements using this
>>> l
[0, 2, 0, 4, 0]
>>> k = [1,2,3,4,5]
>>> g = ['a','b','c','d']
>>> g[:2] = k[:2] # only replace first 2 elements
>>> g
[1, 2, 'c', 'd']
>>>... |
Saving a matplotlib/networkx figure without margins | 11,298,909 | 11 | 2012-07-02T18:10:14Z | 11,298,930 | 8 | 2012-07-02T18:11:46Z | [
"python",
"matplotlib",
"networkx"
] | When I draw a figure using `matplotlib` how do I save it without extra margins?
Usually when I save it as
```
plt.savefig("figure.png") # or .pdf
```
I get it with some margins:
> 
Example:
```
import matplotlib.pyplot as plt
import networkx as nx
... | Try `plt.savefig("figure.png", bbox_inches="tight")`.
Edit: Ah, you didn't mention you were using networkx (although now I see it's listed in a tag). `bbox_inches="tight"` is the way to crop the figure tightly. I don't know what networkx is doing, but I imagine it's setting some plot parameters that are adding extra s... |
Saving a matplotlib/networkx figure without margins | 11,298,909 | 11 | 2012-07-02T18:10:14Z | 11,300,289 | 7 | 2012-07-02T19:55:32Z | [
"python",
"matplotlib",
"networkx"
] | When I draw a figure using `matplotlib` how do I save it without extra margins?
Usually when I save it as
```
plt.savefig("figure.png") # or .pdf
```
I get it with some margins:
> 
Example:
```
import matplotlib.pyplot as plt
import networkx as nx
... | add the codes below to control plot limits before saving.
try different values of `cut`, like from 1.05 to 1.50, until you see fit.
```
# adjust the plot limits
cut = 1.05
xmax= cut*max(xx for xx,yy in pos.values())
ymax= cut*max(yy for xx,yy in pos.values())
plt.xlim(0,xmax)
plt.ylim(0,ymax)
``` |
What's the best way to obtain all the combinations (Cartesian product) of lists? | 11,299,236 | 3 | 2012-07-02T18:33:09Z | 11,299,258 | 11 | 2012-07-02T18:34:25Z | [
"python",
"multidimensional-array"
] | Suppose I have the following.
```
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]
```
How do I obtain the following?
```
[1,2,3,'a','b']
[1,2,3,'c','d']
[1,2,3,'e','f']
[4,5,6,'a','b']
[4,5,6,'c','d']
[4,5,6,'e','f']
[7,8,9,'a','b']
[7,8,9,'c','d']
[7,8,9,'e','f']
``` | ```
from itertools import product
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]
print [x+y for (x,y) in product(a,b)]
``` |
How to find the count of a word in a string? | 11,300,383 | 9 | 2012-07-02T20:02:55Z | 11,300,419 | 23 | 2012-07-02T20:05:03Z | [
"python"
] | I have a string "`Hello I am going to I with hello am`". I want to find how many times a word occur in the string. Example hello occurs 2 time. I tried this approach that only prints characters -
```
def countWord(input_string):
d = {}
for word in input_string:
try:
d[word] += 1
exc... | If you want to find the count of an individual word, just use `count`:
```
input_string.count("Hello")
```
Use `collections.Counter` and `split()` to tally up all the words:
```
from collections import Counter
words = input_string.split()
wordCount = Counter(words)
``` |
How to scale axes in mplot3d | 11,300,650 | 7 | 2012-07-02T20:24:10Z | 11,300,758 | 17 | 2012-07-02T20:32:20Z | [
"python",
"numpy",
"matplotlib"
] | I can't seem to find documentation regarding the ability to scale axes in a 3d image using matplotlib.
For example, I have the image:

And the axes have different scales. I would like them to be uniform. | Usually it is easiest for you to include some of the code that generated the image, so we can see what you've tried and also the general setup of your code. That being said, the inclusion of the following should work:
```
from mpl_toolkits.mplot3d import Axes3D
plt.clf()
fig = pylab.figure()
ax = Axes3D(fig)
ax.set_xl... |
How to check if variable is string with python 2 and 3 compatibility | 11,301,138 | 58 | 2012-07-02T21:03:29Z | 11,301,392 | 79 | 2012-07-02T21:23:46Z | [
"python",
"string",
"python-3.x",
"python-2.x"
] | I'm aware that I can use: `isinstance(x, str)` in python-3.x but I need to check if something is a string in python-2.x as well. Will `isinstance(x, str)` work as expected in python-2.x? Or will I need to check the version and use `isinstance(x, basestr)`?
Specifically, in python-2.x:
```
>>>isinstance(u"test", str)
... | If you're writing 2.x-and-3.x-compatible code, you'll probably want to use [six](http://packages.python.org/six/#six.string_types):
```
from six import string_types
isinstance(s, string_types)
``` |
How to check if variable is string with python 2 and 3 compatibility | 11,301,138 | 58 | 2012-07-02T21:03:29Z | 11,301,781 | 15 | 2012-07-02T22:01:44Z | [
"python",
"string",
"python-3.x",
"python-2.x"
] | I'm aware that I can use: `isinstance(x, str)` in python-3.x but I need to check if something is a string in python-2.x as well. Will `isinstance(x, str)` work as expected in python-2.x? Or will I need to check the version and use `isinstance(x, basestr)`?
Specifically, in python-2.x:
```
>>>isinstance(u"test", str)
... | This is @Lev Levitsky's answer, re-written a bit.
```
try:
isinstance("", basestring)
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
```
The `try`/`except` test is done once, and then defines a function that always works and is as f... |
How to check if variable is string with python 2 and 3 compatibility | 11,301,138 | 58 | 2012-07-02T21:03:29Z | 22,679,982 | 45 | 2014-03-27T06:35:05Z | [
"python",
"string",
"python-3.x",
"python-2.x"
] | I'm aware that I can use: `isinstance(x, str)` in python-3.x but I need to check if something is a string in python-2.x as well. Will `isinstance(x, str)` work as expected in python-2.x? Or will I need to check the version and use `isinstance(x, basestr)`?
Specifically, in python-2.x:
```
>>>isinstance(u"test", str)
... | The most terse approach I've found without relying on packages like six, is:
```
try:
basestring
except NameError:
basestring = str
```
then, assuming you've been checking for strings in Python 2 in the most generic manner,
```
isinstance(s, basestring)
```
will now also work for Python 3+. |
python regex first/shortest match | 11,301,387 | 22 | 2012-07-02T21:23:36Z | 11,301,418 | 44 | 2012-07-02T21:25:17Z | [
"python",
"regex"
] | trying to write an regex that can find all patterns
```
p = "q=http://.*\.doc" in
text = "q=http://11111.doc,q=http://22222.doc"
```
when I did finall on text,
I get the whole thing, i.e. `q=http://11111.doc,q=http://22222.doc`
but not `q=http://11111.doc` and `q=http://22222.doc`
how do I fix it? | That's because `*` is a greedy quantifier, trying to match as much as it can. Make it `*?`:
```
q=http://.*?\.doc
``` |
Integer out of range | 11,302,711 | 6 | 2012-07-02T23:47:46Z | 11,302,725 | 11 | 2012-07-02T23:50:04Z | [
"python",
"django"
] | I'm getting an `integer out of range` error when trying to migrate my database from SQLite to PostgreSQL.
I think I have pinpointed the problem: I have some huge integers in a `IntegerField` field in my model.
Basically on the order of 52675215334.
When I change this value to a small number like 1 and then try to mi... | Try using [BigIntegerField](https://docs.djangoproject.com/en/dev/ref/models/fields/#bigintegerfield) if you integers are *that* big. From the documentation:
> A 64 bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. The admin represents ... |
How to remove multiple indexes from a list at the same time? | 11,303,225 | 25 | 2012-07-03T01:06:52Z | 11,303,234 | 44 | 2012-07-03T01:08:08Z | [
"python"
] | Say I have this list here:
```
list = [a, b, c, d, e, f, g]
```
How would I delete say indexes `2, 3, 4`, and `5` at the same time?
pop doesn't accept multiple values. How else do I do this? | You need to do this in a loop, there is no built-in operation to remove a number of indexes at once.
Your example is actually a contiguous sequence of indexes, so you can do this:
```
del my_list[2:6]
```
which removes the slice starting at 2 and ending just before 6.
It isn't clear from your question whether in ge... |
How to remove multiple indexes from a list at the same time? | 11,303,225 | 25 | 2012-07-03T01:06:52Z | 11,303,241 | 10 | 2012-07-03T01:09:11Z | [
"python"
] | Say I have this list here:
```
list = [a, b, c, d, e, f, g]
```
How would I delete say indexes `2, 3, 4`, and `5` at the same time?
pop doesn't accept multiple values. How else do I do this? | ```
remove_indices = [1,2,3]
somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
```
Example:
```
In [9]: remove_indices = [1,2,3]
In [10]: somelist = range(10)
In [11]: somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
In [12]: somelist
Out[12]: [0, 4, 5, 6, 7, 8, 9]
... |
Python avoiding using a variable when using a value twice? | 11,303,596 | 4 | 2012-07-03T02:08:35Z | 11,303,663 | 12 | 2012-07-03T02:19:14Z | [
"python",
"variables"
] | I currently have:
```
tmp = myfunc()
mydict[mykey] = tmp
return tmp
```
..which seems a little too long. In javascript, I could just do:
```
return (mydict[mykey] = myfunc())
```
Is the above Python code the accepted way to do it, or is there something else?
edit: I'm aware of the possibility of doing:
```
mydict... | ```
tmp = mydict[mykey] = myfunc()
return tmp
``` |
What is the cross-platform method of enumerating serial ports in Python (including virtual ports)? | 11,303,850 | 28 | 2012-07-03T02:51:18Z | 11,398,450 | 7 | 2012-07-09T15:39:24Z | [
"python",
"cross-platform",
"serial-port",
"python-2.7",
"pyserial"
] | **Note:** I'm using Python 2.7, and pySerial for serial communications.
I found this article which lists two ways: <http://www.zaber.com/wiki/Software/Python#Displaying_a_list_of_available_serial_ports>
This method works on Windows and Linux, but sometimes misses virtual ports on Linux:
```
import serial
def scan()... | This is what I've been using. It's a mashup of the methods I posted above. I'd still like to see better solutions, though.
```
# A function that tries to list serial ports on most common platforms
def list_serial_ports():
system_name = platform.system()
if system_name == "Windows":
# Scan for available... |
What is the cross-platform method of enumerating serial ports in Python (including virtual ports)? | 11,303,850 | 28 | 2012-07-03T02:51:18Z | 12,528,704 | 7 | 2012-09-21T10:23:15Z | [
"python",
"cross-platform",
"serial-port",
"python-2.7",
"pyserial"
] | **Note:** I'm using Python 2.7, and pySerial for serial communications.
I found this article which lists two ways: <http://www.zaber.com/wiki/Software/Python#Displaying_a_list_of_available_serial_ports>
This method works on Windows and Linux, but sometimes misses virtual ports on Linux:
```
import serial
def scan()... | [bitpim](http://bitpim.sourceforge.net/) had quite a bit of code for comscan on multiple platforms. Probably useful to get some code out of there to build a cross platform serial port enumerator. You can run the detection code directly in command line to test it out.
[Link to source file comscan.py](http://bitpim.svn.... |
Python Sort Last Characters | 11,304,005 | 6 | 2012-07-03T03:16:30Z | 11,304,066 | 8 | 2012-07-03T03:27:20Z | [
"python",
"string",
"sorting",
"python-2.3"
] | In newer Python, I am able to use the sorted function and easily sorts out a list of string according to their last few chars as such:
```
lots_list=['anything']
print sorted(lots_list, key=returnlastchar)
def returnlastchar(s):
return s[10:]
```
How can I implement the above to `lots_list.sort()` which is... | The [Schwartzian transform](http://en.wikipedia.org/wiki/Schwartzian_transform) is usually more efficient than using the `cmp` argument (This is what newer versions of Python do when using the `key` argument)
```
lots_list=['anything']
def returnlastchar(s):
return s[10:]
decorated = [(returnlastchar(s), s... |
python interactive shell 16x faster than command line - what's wrong? | 11,304,348 | 7 | 2012-07-03T04:11:58Z | 11,304,423 | 9 | 2012-07-03T04:23:01Z | [
"python",
"command-line",
"interactive"
] | I'm using Enthought EPD-Free 7.3-1 on a small function, and when I cut/paste into an interactive session (PyLab) and run it, it takes less than a second. When I run the same code from the command line "`python probtest.py`" it takes over 16 seconds.
I've confirmed both are using the same python environment. Maybe rela... | Ah, this one seems familiar. If you're using a pylab interface, it's probably imported the numpy `sum` into scope, overriding the builtin. numpy's sum will be much faster (the only difference between the following two codes is that I've added `from numpy import sum` to the second):
```
localhost-2:coding $ time python... |
Regular expression for python syntax | 11,305,271 | 4 | 2012-07-03T06:00:36Z | 11,305,344 | 11 | 2012-07-03T06:07:37Z | [
"python",
"syntax"
] | I want to write a python code generator, and it would be helpful if I had the regular expression that describes all valid python programs.
Does such a regular expression exist? What is it? | Such a regular expression cannot exist, because regular expressions are, by definition, not powerful enough to recognize Turing complete languages (such as python). |
Pickle incompatability of numpy arrays between Python 2 and 3 | 11,305,790 | 37 | 2012-07-03T06:46:56Z | 11,314,602 | 25 | 2012-07-03T15:48:53Z | [
"python",
"python-3.x",
"pickle"
] | I am trying to load the MNIST dataset linked [here](http://deeplearning.net/tutorial/gettingstarted.html) in Python 3.2 using this program:
```
import pickle
import gzip
import numpy
with gzip.open('mnist.pkl.gz', 'rb') as f:
l = list(pickle.load(f))
print(l)
```
Unfortunately, it gives me the error:
```
T... | This seems like some sort of incompatibility. It's trying to load a "binstring" object, which is assumed to be ASCII, while in this case it is binary data. If this is a bug in the Python 3 unpickler, or a "misuse" of the pickler by numpy, I don't know.
Here is something of a workaround, but I don't know how meaningful... |
Python: Continue looping after exception | 11,306,908 | 7 | 2012-07-03T08:12:59Z | 11,307,035 | 9 | 2012-07-03T08:21:21Z | [
"python",
"exception",
"loops"
] | I have the following script (below). which will return the status code of URLs. It loops through a file and tries to connect to each host. Only problem is that it obviously stops looping when it reaches an exception.
I have tried numerous things to put the how of it in a loop, but to no avail. Any thoughts?
```
impor... | You could handle the exception where it is raised. Also, use a context manager when opening files, it makes for simpler code.
```
with open(hostsFile, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
epoch = str(time.time())
try:
conn = u... |
Computing stats on generators in single pass. Python | 11,308,146 | 2 | 2012-07-03T09:33:17Z | 11,308,254 | 7 | 2012-07-03T09:40:45Z | [
"python",
"statistics",
"generator"
] | When working with generators you can only pull out items on a single pass. An alternative is to load the generator into an list and do multiple passes but this involves a hit on performance and memory allocation.
Can anyone think of a better way of computing the following metrics from a generator in a single pass. Ide... | ```
def statistics(it):
"""Returns number of elements, sum, max, min"""
it = iter(it)
x0 = next(it)
maximum = minimum = total = x0
n = 1
for x in it:
maximum = max(maximum, x)
minimum = min(minimum, x)
total += x
n += 1
return n, total, maximum, minimum
``... |
Python import head ache | 11,309,196 | 2 | 2012-07-03T10:40:50Z | 11,309,252 | 8 | 2012-07-03T10:44:09Z | [
"python",
"import"
] | I have the following directory structure:
```
Main.py
A/
__init__.py
B/
__init__.py
C/
__init__.py
```
The file `Main.py` contains the code
```
from A import B
from B import C
```
The `__init__.py` files are empty.
When I run `Main.py` I get the error message
```
Traceback (most... | When processing `import` statements, Python doesn't look at what you have already imported; it simply looks whether the given module exists in the import path. So you need to write it like this:
```
from A import B
from A.B import C
``` |
Store different datatypes in one NumPy array? | 11,309,739 | 16 | 2012-07-03T11:13:49Z | 11,310,158 | 14 | 2012-07-03T11:41:50Z | [
"python",
"arrays",
"types",
"numpy"
] | I have two different arrays, one with strings and another with ints. I want to concatenate them, into one array where each column has the original datatype. My current solution for doing this (see below) converts the entire array into dtype = string, which seems very memory inefficient.
`combined_array = np.concatenat... | One approach might be to use a [record array](http://docs.scipy.org/doc/numpy/user/basics.rec.html). The "columns" won't be like the columns of standard numpy arrays, but for most use cases, this is sufficient:
```
>>> a = numpy.array(['a', 'b', 'c', 'd', 'e'])
>>> b = numpy.arange(5)
>>> records = numpy.rec.fromarray... |
Wtforms, add a class to a form dynamically | 11,309,779 | 12 | 2012-07-03T11:16:18Z | 11,331,512 | 23 | 2012-07-04T14:59:16Z | [
"python",
"css",
"flask",
"wtforms"
] | is there a way i could send a form's (css) class from python?
For example:
```
class Company(Form):
companyName = TextField('Company Name', [validators.Length(min=3, max = 60)])
```
This renders a simple text field, but i want that text field to have the css class of `.companyName`, is that possible directly from... | WTForms does not allow you to set display options (such as class name) in the field initialization. However, there are several ways to get around this:
1. If all of your fields should include a class name as well as an ID then just pass in each field's [`short_name`](http://wtforms.readthedocs.org/en/latest/fields.htm... |
Wtforms, add a class to a form dynamically | 11,309,779 | 12 | 2012-07-03T11:16:18Z | 12,643,257 | 41 | 2012-09-28T15:48:57Z | [
"python",
"css",
"flask",
"wtforms"
] | is there a way i could send a form's (css) class from python?
For example:
```
class Company(Form):
companyName = TextField('Company Name', [validators.Length(min=3, max = 60)])
```
This renders a simple text field, but i want that text field to have the css class of `.companyName`, is that possible directly from... | Alternatively you can add the class in your template like this for jinja2:
```
{{ form.name(size=20, class_='input-small') }}
``` |
Find number of columns in csv file | 11,310,248 | 16 | 2012-07-03T11:47:05Z | 11,310,329 | 17 | 2012-07-03T11:52:07Z | [
"python",
"csv"
] | My program needs to read csv files which may have 1,2 or 3 columns, and it needs to modify its behaviour accordingly. Is there a simple way to check the number of columns without "consuming" a row before the iterator runs? The following code is the most elegant I could manage, but I would prefer to run the check before... | You can use [itertools.tee](http://docs.python.org/library/itertools.html#itertools.tee)
> itertools.tee(iterable[, n=2])
> Return n independent iterators from a
> single iterable.
eg.
```
reader1, reader2 = itertools.tee(csv.reader(f, delimiter=d))
columns = len(next(reader1))
del reader1
for row in reader2:
... |
Creating a DLL from a wrapped cpp file with SWIG | 11,311,877 | 4 | 2012-07-03T13:21:47Z | 14,372,472 | 10 | 2013-01-17T05:01:53Z | [
"python",
"dll",
"swig"
] | I am in the process of learning how to use SWIG on Windows.
The following is my c++ code:
```
/* File : example.cxx */
#include "example.h"
#define M_PI 3.14159265358979323846
/* Move the shape to a new location */
void Shape::move(double dx, double dy) {
x += dx;
y += dy;
}
int Shape::nshapes = 0;
do... | add MS\_NO\_COREDLL definition at Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions;
or add #define MS\_NO\_COREDLL line before including python.h.
```
#define MS_NO_COREDLL
#include <Python.h>
``` |
Copying a list in python | 11,312,354 | 2 | 2012-07-03T13:47:16Z | 11,312,395 | 8 | 2012-07-03T13:49:25Z | [
"python",
"list",
"copy"
] | I'm looking for a way to do the following:
* I have a list composed of other lists:`TABLE=[table1,table2,table3]`
* I would like to duplicate this list but rename the sublists, such as:`TABLE_1=[table1_dup=list(table1),table2_dup=list(table2),table3_dup=list(table3)]` (this doesn't work; I'm just trying to explain my ... | I think, the `deepcopy` function suits fine in this occasion.
```
from copy import deepcopy
...
TABLE_1 = deepcopy(TABLE)
``` |
Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python | 11,312,525 | 49 | 2012-07-03T13:56:48Z | 11,312,948 | 26 | 2012-07-03T14:20:50Z | [
"python",
"multiprocessing",
"signals"
] | How do I catch a Ctrl+C in multiprocess python program and exit all processes gracefully, I need the solution to work both on unix and windows. I've tried the following:
```
import multiprocessing
import time
import signal
import sys
jobs = []
def worker():
signal.signal(signal.SIGINT, signal_handler)
while(... | The solution is based on [this link](http://noswap.com/blog/python-multiprocessing-keyboardinterrupt/) and [this link](https://github.com/jreese/multiprocessing-keyboardinterrupt/blob/master/example.py) and it solved the problem, I had to moved to `Pool` though:
```
import multiprocessing
import time
import signal
imp... |
Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python | 11,312,525 | 49 | 2012-07-03T13:56:48Z | 16,324,330 | 8 | 2013-05-01T18:44:29Z | [
"python",
"multiprocessing",
"signals"
] | How do I catch a Ctrl+C in multiprocess python program and exit all processes gracefully, I need the solution to work both on unix and windows. I've tried the following:
```
import multiprocessing
import time
import signal
import sys
jobs = []
def worker():
signal.signal(signal.SIGINT, signal_handler)
while(... | Just handle KeyboardInterrupt-SystemExit exceptions in your worker process:
```
def worker():
while(True):
try:
msg = self.msg_queue.get()
except (KeyboardInterrupt, SystemExit):
print "Exiting..."
break
``` |
Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python | 11,312,525 | 49 | 2012-07-03T13:56:48Z | 35,134,329 | 17 | 2016-02-01T15:33:35Z | [
"python",
"multiprocessing",
"signals"
] | How do I catch a Ctrl+C in multiprocess python program and exit all processes gracefully, I need the solution to work both on unix and windows. I've tried the following:
```
import multiprocessing
import time
import signal
import sys
jobs = []
def worker():
signal.signal(signal.SIGINT, signal_handler)
while(... | The accepted solution has race conditions and it does not work with `map` and `async` functions.
The correct way to handle Ctrl+C/`SIGINT` with `multiprocessing.Pool` is to:
1. Make the process ignore `SIGINT` before a process `Pool` is created. This way created child processes inherit `SIGINT` handler.
2. Restore th... |
networkx draw_networkx_edges capstyle | 11,312,579 | 6 | 2012-07-03T14:00:26Z | 11,330,044 | 7 | 2012-07-04T13:26:17Z | [
"python",
"matplotlib",
"networkx"
] | Does anyone know if it is possible to have fine-grained control over line properties when drawing networkx edges via (for example) `draw_networkx_edges`? I would like to control the line `solid_capstyle` and `solid_joinstyle`, which are (matplotlib) `Line2D` properties.
```
>>> import networkx as nx
>>> import matplot... | It looks like you can't set the capstyle on matplotlib line collections.
But you can make your own collection of edges using Line2D objects which allows you to control the capstyle:
```
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
G = nx.dodecahedral_graph()
pos = nx.sprin... |
Python: Convert a list of python dictionaries to an array of JSON objects | 11,312,733 | 6 | 2012-07-03T14:09:30Z | 11,312,799 | 21 | 2012-07-03T14:12:45Z | [
"python",
"json"
] | I'm trying to write a function to convert a python list into a JSON array of {"mpn":"list\_value"} objects, where "mpn" is the literal string value I need for every object but "list\_value" is the value from the python list. I'll use the output of this function for an API get request.
```
part_nums = ['ECA-1EHG102','C... | You are adding the exact same dictionary to the list. You should create a new dictionary for each item in the list:
```
json.dumps([dict(mpn=pn) for pn in lst])
``` |
Refactoring with python dictionary comprehension | 11,313,568 | 3 | 2012-07-03T14:53:14Z | 11,313,622 | 8 | 2012-07-03T14:55:51Z | [
"python",
"refactoring",
"dictionary-comprehension"
] | I have 2 dictionary which contain the same keys but the value pairs are different. Let's make dictA and dictB represent the two dictionaries in question.
```
dictA = {'key1':'Joe', 'key2':'Bob'}
dictB = {'key1':'Smith', 'key2':'Johnson'}
```
Currently, I am creating a new dictionary based the common occurring keys th... | Use sets or [key views (python 2.7)](http://docs.python.org/library/stdtypes.html#dict.viewkeys):
```
dictAB = {k: [dictA[k], dictB[k]] for k in dictA.viewkeys() & dictB.viewkeys()}
```
Before 2.7:
```
dictAB = dict((k, [dictA[k], dictB[k]]) for k in set(dictA) & set(dictB))
```
In python 3, you can use the `.keys`... |
Trying to catch integrity error with SQLAlchemy | 11,313,935 | 11 | 2012-07-03T15:12:20Z | 11,315,155 | 7 | 2012-07-03T16:23:02Z | [
"python",
"sqlalchemy",
"pyramid"
] | I'm having problems with trying to catch an error. I'm using Pyramid/SQLAlchemy and made a sign up form with email as the primary key. The problem is when a duplicate email is entered it raises a IntegrityError, so I'm trying to catch that error and provide a message but no matter what I do I can't catch it, the error ... | What you need to do is catch a general exception and output its class; then you can make the exception more specific.
```
except Exception as ex:
print ex.__class__
``` |
Trying to catch integrity error with SQLAlchemy | 11,313,935 | 11 | 2012-07-03T15:12:20Z | 11,316,086 | 19 | 2012-07-03T17:27:59Z | [
"python",
"sqlalchemy",
"pyramid"
] | I'm having problems with trying to catch an error. I'm using Pyramid/SQLAlchemy and made a sign up form with email as the primary key. The problem is when a duplicate email is entered it raises a IntegrityError, so I'm trying to catch that error and provide a message but no matter what I do I can't catch it, the error ... | In Pyramid, if you've configured your session (which the scaffold does for you automatically) to use the `ZopeTransactionExtension`, then session is not flushed/committed until after the view has executed. If you want to catch any SQL errors yourself in your view, you need to force a `flush` to send the SQL to the engi... |
What is the order of complexity of comparing two python lists? | 11,313,950 | 2 | 2012-07-03T15:13:15Z | 11,313,999 | 8 | 2012-07-03T15:15:44Z | [
"python",
"python-2.7"
] | Assume the lists contain hashable objects only.
BTW, I'm not sure if this question makes sense as I am a complete noob when it comes to complexity and academic stuff. | The complexity of comparing two lists is O(n) if both lists have length n, and O(1) if the lists have different lengths. |
Make column width take up available space in wxPython ListCtrl | 11,314,339 | 10 | 2012-07-03T15:33:30Z | 11,314,767 | 12 | 2012-07-03T15:57:52Z | [
"python",
"wxpython"
] | I have three columns in my `wx.ListCtrl(size=(-1,200))`. I would like the columns to fill up the width of the ListCtrl after its created. Ideally, the first column can expand to fill up the extra space available. The second and third columns don't need to expand, and preferably will not change in width (formatting ocd)... | You need to use the ListCtrlAutoWidthMixin mixin class. The wxPython demo application has an example in the ListCtrl demo. According to the [documentation](http://wxpython.org/docs/api/wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin-class.html), you can use its setResizeColumn method to tell it which column to resize. Th... |
request.user returns a SimpleLazyObject, how do I "wake" it? | 11,314,905 | 34 | 2012-07-03T16:06:29Z | 11,315,674 | 29 | 2012-07-03T17:00:00Z | [
"python",
"django",
"django-users",
"django-contrib"
] | I have the following method:
```
def _attempt(actor):
if actor.__class__ != User:
raise TypeError
```
Which is called from a view:
```
self.object.attempt(self.request.user)
```
As you can see, the \_attempt method expects actor to be type `django.contrib.auth.models.User`, however the object appears to... | See [my answer on a similar question](http://stackoverflow.com/a/10507200/654031).
Django lazy loads `request.user` so that it can be either `User` or `AnonymousUser` depending on the authentication state. It only "wakes up" and returns the appropriate class when an attribute is accessed on it. Unfortunately, `__class... |
request.user returns a SimpleLazyObject, how do I "wake" it? | 11,314,905 | 34 | 2012-07-03T16:06:29Z | 13,304,403 | 9 | 2012-11-09T08:14:44Z | [
"python",
"django",
"django-users",
"django-contrib"
] | I have the following method:
```
def _attempt(actor):
if actor.__class__ != User:
raise TypeError
```
Which is called from a view:
```
self.object.attempt(self.request.user)
```
As you can see, the \_attempt method expects actor to be type `django.contrib.auth.models.User`, however the object appears to... | This should do it:
```
# handle django 1.4 pickling bug
if hasattr(user, '_wrapped') and hasattr(user, '_setup'):
if user._wrapped.__class__ == object:
user._setup()
user = user._wrapped
```
I had to write this so I could add a user to the session dictionary. (SimpleLazyObjects are not picklable!) |
How to recursively call a macro in jinja2? | 11,314,980 | 10 | 2012-07-03T16:11:30Z | 11,316,764 | 11 | 2012-07-03T18:14:54Z | [
"python",
"code-generation",
"jinja2"
] | This is my jinja template to generate C# code from my data model
```
using System;
namespace {{ domain["ns"] }} {
{% for class in domain["content"] %}
public class {{ class["name"] }} {
#region Inners
{{ class["innerClass"] }}
#endregion
#region Props
{% for field in class["content"] %}
... | You can use [macros](http://jinja.pocoo.org/docs/templates/#macros), write a macro for class rendering, and then call it recursively:
```
{% macro render_class(class) -%}
class {{ class.name }}
{
{% for field in class.fields %}
int {{ field }};
{% endfor %}
{% for subclass in class.subclasses %}
{{ render_class(su... |
Find the biggest number formed by digits of input numer | 11,315,562 | 4 | 2012-07-03T16:52:32Z | 11,315,589 | 7 | 2012-07-03T16:54:25Z | [
"python"
] | I am trying to write a function that return the biggest number formed by the digits from an input integer number.
So if the input = 123584
output should be = 854321
My code is -
```
def maxNumber(inputNumber):
x = len(str(inputNumber))
max_number = []
result= []
while(x>0):
max_number.append(i... | The biggest number is formed by sorting the digits in descending order. This can be achived using the `rverse=True` parameter to `sorted()`:
```
def max_digit_permutation(n):
return int("".join(sorted(str(n), reverse=True)))
``` |
Find the biggest number formed by digits of input numer | 11,315,562 | 4 | 2012-07-03T16:52:32Z | 11,315,602 | 7 | 2012-07-03T16:54:57Z | [
"python"
] | I am trying to write a function that return the biggest number formed by the digits from an input integer number.
So if the input = 123584
output should be = 854321
My code is -
```
def maxNumber(inputNumber):
x = len(str(inputNumber))
max_number = []
result= []
while(x>0):
max_number.append(i... | ```
def maxNumber(inputNumber):
return int(''.join(sorted(str(inputNumber), reverse=True)))
``` |
python: plotting a histogram with a function line on top | 11,315,641 | 6 | 2012-07-03T16:57:40Z | 11,316,298 | 7 | 2012-07-03T17:43:08Z | [
"python",
"matplotlib",
"scipy"
] | I'm trying to do a little bit of distribution plotting and fitting in Python using SciPy for stats and matplotlib for the plotting. I'm having good luck with some things like creating a histogram:
```
seed(2)
alpha=5
loc=100
beta=22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=5000)
myHist = hist(data, 100, normed=... | just put both pieces together.
```
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
alpha, loc, beta=5, 100, 22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=5000)
myHist = plt.hist(data, 100, normed=True)
rv = ss.gamma(alpha,loc,beta)
x = np.linspace(0,600)
h = plt.plot(x, rv.pdf(x), lw=... |
Python IOError: File not open for writing and global name 'w' is not defined | 11,317,278 | 8 | 2012-07-03T18:50:54Z | 11,317,288 | 18 | 2012-07-03T18:51:52Z | [
"python",
"io",
"syntax-error"
] | I'm trying to write a little procedure that write (append would be even better) a line in a file with Python, like this:
```
def getNewNum(nlist):
newNum = ''
for i in nlist:
newNum += i+' '
return newNum
def writeDoc(st):
openfile = open("numbers.txt", w)
openfile.write(st)
newLine = [... | The problem is in the [open()](http://docs.python.org/library/functions.html?highlight=open#open) call in `writeDoc()` that file mode specification is not correct.
```
openfile = open("numbers.txt", w)
^
```
The `w` needs to have (a pair of single or double) quotes around it, i.e.,
```... |
How to get all dates (month, day and year) between two dates in python? | 11,317,378 | 2 | 2012-07-03T18:58:00Z | 11,317,428 | 17 | 2012-07-03T19:01:14Z | [
"python",
"datetime",
"date"
] | Situation:
I am trying to construct a simple method that accepts two different integers that represent two different dates. 20120525 for May 25, 2012 and 20120627 for June 26, 2012 as an example. I want this method to return a list of these integer types that represent all days between the two date parameters.
Questio... | You don't have to reinvent the wheel. Just parse the strings into datetime objects and let python do the math for you:
```
from dateutil import rrule
from datetime import datetime
a = '20120525'
b = '20120627'
for dt in rrule.rrule(rrule.DAILY,
dtstart=datetime.strptime(a, '%Y%m%d'),
... |
How to escape a pipe ( | ) symbol for url_encode in python | 11,317,588 | 5 | 2012-07-03T19:12:17Z | 11,317,674 | 9 | 2012-07-03T19:17:51Z | [
"python"
] | I am facing a problem with urllib.url\_encode in python. Bets explained with some code:
```
>>> from urllib import urlencode
>>> params = {'p' : '1 2 3 4 5&6', 'l' : 'ab|cd|ef'}
>>> urlencode(params)
'p=1+2+3+4+5%266&l=ab%7Ccd%7Cef'
```
I want to keep the pipes ('|') in to l parameter. can you please tell me how?
Th... | > Convert a mapping object or a sequence of two-element tuples to a
> âpercent-encodedâ string[...]
The [urlencode()](http://docs.python.org/library/urllib.html?highlight=urlencode#urllib.urlencode) method is acting as expected. If you want to prevent the encoding then you can first encode the entire object and th... |
Is it safe to use python's -S option? | 11,318,028 | 13 | 2012-07-03T19:42:00Z | 11,318,240 | 8 | 2012-07-03T19:57:00Z | [
"python"
] | The -S option to python is defined by the documentation as "Disable the import of the module site and the site-dependent manipulations of sys.path that it entails." I've found that python startup on my machine is more than twice as fast, sometimes *much* more, when I use this option. For example, on one (slow) machine:... | It's probably not a good idea. Among other things, it means that the site-packages directory won't be added to the path, so you won't be able to import anything but the standard lib modules:
```
python -Sc "import numpy"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module n... |
Is there a way to init a list without using square bracket in Python? | 11,318,592 | 3 | 2012-07-03T20:21:09Z | 11,318,614 | 10 | 2012-07-03T20:23:07Z | [
"python",
"functional-programming"
] | Is there a way to init a list without using square bracket in Python?
For example, is there a function like `list_cons` so that:
```
x = list_cons(1, 2, 3, 4)
```
is equivalent to:
```
x = [1, 2, 3, 4]
``` | ```
In [1]: def list_cons(*args):
...: return list(args)
...:
In [2]: list_cons(1,2,3,4)
Out[2]: [1, 2, 3, 4]
``` |
Zipping unequal lists in python in to a list which does not drop any element from longer list being zipped | 11,318,977 | 20 | 2012-07-03T20:51:31Z | 11,319,002 | 25 | 2012-07-03T20:53:23Z | [
"python",
"data-structures"
] | I have two lists
```
a = [1,2,3]
b = [9,10]
```
I want to combine (zip) these two lists into one list `c` such that
```
c = [(1,9), (2,10), (3, )]
```
Is there any function in standard library in Python to do this? | What you seek is [`itertools.izip_longest`](http://docs.python.org/library/itertools.html#itertools.izip_longest)
```
>>> a = [1,2,3]
>>> b = [9,10]
>>> for i in itertools.izip_longest(a,b): print i
...
(1, 9)
(2, 10)
(3, None)
```
**EDIT 1**: If you really want to get rid of the `None`s, then you could try:
```
>>... |
Does Ruby have something like Python's list comprehensions? | 11,319,429 | 10 | 2012-07-03T21:25:59Z | 11,319,866 | 10 | 2012-07-03T22:05:42Z | [
"python",
"ruby",
"programming-languages"
] | Python has a nice feature:
```
print([j**2 for j in [2, 3, 4, 5]]) # => [4, 9, 16, 25]
```
In Ruby it's even simpler:
```
puts [2, 3, 4, 5].map{|j| j**2}
```
but if it's about nested loops Python looks more convenient.
In Python we can do this:
```
digits = [1, 2, 3]
chars = ['a', 'b', 'c']
print([str(d)+ch f... | The common way in Ruby is to properly combine [Enumerable](http://ruby-doc.org/core-1.9.3/Enumerable.html) and [Array](http://www.ruby-doc.org/core-1.9.3/Array.html) methods to achieve the same:
```
digits.product(chars).select{ |d, ch| d >= 2 && ch == 'a' }.map(&:join)
```
This is only 4 or so characters longer than... |
Dealing with multiple python versions when python files have to use #!/bin/env python | 11,319,676 | 7 | 2012-07-03T21:47:39Z | 11,320,015 | 8 | 2012-07-03T22:21:24Z | [
"python",
"shebang"
] | I have this problem:
`System A` runs Ubuntu and needs `Python 2.6` for a bunch of different things.
I Installed `Python 2.7` separately on `System A`
`System B` has `Python 2.7` natively.
I have a python script `BLAH` which says `#!/bin/env python` up top.
Further down it executes another script `SIGH`, ... | If you have a script that needs a certain python version, for example 2.7, I'd change the first line to
```
#!/bin/env python2.7
```
And then ensure that `python2.7` is on your path (you may have to add symlinks as appropriate). In all the distributions I've used, these symlinks already exist.
(In fact, `python` is ... |
RE split multiple arguments | (or) returns none python | 11,320,231 | 3 | 2012-07-03T22:41:52Z | 11,320,285 | 7 | 2012-07-03T22:49:56Z | [
"python"
] | I'm using the RE expression in python and trying to split a chunk of text by period and by exclamation mark. However when I split it, I get a "None" in the result
```
a = "This is my text...I want it to split by periods. I also want it to split \
by exclamation marks! Is that so much to ask?"
```
This is my code:
``... | Try the following:
```
re.split(r'((?<=\w)\.(?!\..)|!)', a)
```
You get the `None` because you have two capturing groups, and all groups are included as a part of the `re.split()` result.
So any time you match a `.` the second capture group is `None`, and any time you match a `!` the first capture group is `None`.
... |
How to iterate through a python list of dictionaries | 11,321,220 | 2 | 2012-07-04T01:06:20Z | 11,321,291 | 9 | 2012-07-04T01:18:58Z | [
"python",
"django",
"dictionary"
] | This is my dictionary:
```
[{'entity': 'first entity', 'place': ['first', 'second', 'abc']}, {'entity': 'second entity', 'place': ['awe', 'ert']}]
```
and I want to print the values this way:
```
-first entity
-first, second, abc
-second entity
-awe, ert
```
I tried a lot of things but I don't know how to deal wit... | for python code,
```
a = [{'entity': 'first entity', 'place': ['first', 'second', 'abc']}, {'entity': 'second entity', 'place': ['awe', 'ert']}]
for x in a:
print '-', x['entity']
print '-', ','.join(x['place'])
```
for django template:
```
<p>
{% for x in a %}
{{x.entity}} <br/>
{% for y in x.place ... |
How can I display OSM tiles using Python? | 11,321,718 | 11 | 2012-07-04T02:35:36Z | 11,325,174 | 23 | 2012-07-04T08:22:52Z | [
"python",
"gis",
"openstreetmap"
] | I'm in the process of generating tiles with generate\_tiles.py and I'd like to write a Python app to display them instead of having a web interface. Does anything like that already exist or is there information somewhere on how to write such an app myself? | You can look/edit your map using a desktop application like Tilemill or QGIS (I can't really guess why are you generating tiles if it is not for a web application).
Tilestache has an internal webserver you can use for testing, it's easy to get it running just using config files.
A few pointers to get you started (or ... |
In django-taggit, how to get tags for objects that are associated with a specific user? | 11,321,906 | 3 | 2012-07-04T03:02:30Z | 11,790,127 | 12 | 2012-08-03T06:00:33Z | [
"python",
"django",
"django-models",
"tags",
"django-taggit"
] | I have a series of objects that are associated with specific users, like this:
```
from django.db import models
from django.contrib.auth.models import User
from taggit.managers import TaggableManager
class LibraryObject(models.Model):
title = models.CharField(max_length=255)
owner = models.ForeignKey(User)
... | I've came across a similar problem, and here is my solution:
```
tags = Tag.objects.filter(book__owner=me)
tags |= Tag.objects.filter(journalarticle__owner=me)
tags = tags.distinct()
```
hope it will help~ |
Python: How to send POST request? | 11,322,430 | 56 | 2012-07-04T04:30:02Z | 11,324,941 | 95 | 2012-07-04T08:08:46Z | [
"python",
"post",
"urllib",
"httplib"
] | I found this script online:
```
import httplib, urllib
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, he... | If you really want to handle with HTTP using Python, I highly recommend [Requests: HTTP for Humans](http://docs.python-requests.org/en/latest/index.html). The [POST quickstart](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) adapted to your question is:
```
>>> import request... |
Python: How to send POST request? | 11,322,430 | 56 | 2012-07-04T04:30:02Z | 36,678,494 | 16 | 2016-04-17T15:30:20Z | [
"python",
"post",
"urllib",
"httplib"
] | I found this script online:
```
import httplib, urllib
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, he... | Sometimes you want your script to be portable and you don't want to use 3rd party libraries. This is how you send POST request in Python 3.
```
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'} # ... |
Including a directory using Pyinstaller | 11,322,538 | 7 | 2012-07-04T04:44:50Z | 12,033,695 | 12 | 2012-08-20T07:24:37Z | [
"python",
"pyinstaller"
] | All of the documentation for Pyinstaller talks about including individual files.
Is it possible to include a directory, or should I write a function to create the include array by traversing my include directory? | Paste the following after `a = Analysis()` in the spec file to traverse a directory recursively and add all the files in it to the distribution.
```
##### include mydir in distribution #######
def extra_datas(mydir):
def rec_glob(p, files):
import os
import glob
for d in glob.glob(p):
... |
Generating heatmap using pylab | 11,324,267 | 7 | 2012-07-04T07:24:35Z | 11,325,707 | 16 | 2012-07-04T08:56:40Z | [
"python",
"ipython",
"matplotlib",
"heatmap"
] | I got a 2d array of data which i would like to plot as a heatmap using pylab. I only found solutions to use normal points to build a heatmap but not a way to map `f(x,y) = heat` onto a heatmap.
PS: ipython is awesome to do such stuff in combination with pylab :) | Turns out its fairly easy:
```
import pylab as pl
data = pl.random((25,25)) # 25x25 matrix of values
pl.pcolor(data)
pl.colorbar()
pl.show()
``` |
What is the default __hash__ in python? | 11,324,271 | 27 | 2012-07-04T07:24:47Z | 11,324,413 | 9 | 2012-07-04T07:33:56Z | [
"python"
] | I am quite often using funky stuff as keys for dictionaries, and therefore, I am wondering what is the right way to do it - and this goes through implementing good hash methods for my objects. I am aware of other questions asked here like [good way to implement **hash**](http://stackoverflow.com/questions/2909106/pytho... | The [documentation](http://docs.python.org/glossary.html#term-hashable) states that custom objects rely on [`id()`](http://docs.python.org/library/functions.html#id) as their `hash()` implementation:
> CPython implementation detail: This is the address of the object in memory.
If you mix custom objects with builtin t... |
What is the default __hash__ in python? | 11,324,271 | 27 | 2012-07-04T07:24:47Z | 11,324,771 | 17 | 2012-07-04T07:57:11Z | [
"python"
] | I am quite often using funky stuff as keys for dictionaries, and therefore, I am wondering what is the right way to do it - and this goes through implementing good hash methods for my objects. I am aware of other questions asked here like [good way to implement **hash**](http://stackoverflow.com/questions/2909106/pytho... | What you can rely on: custom objects have a default `hash()` that is based in some way on the identity of the object. i.e. any object using the default hash will have a constant value for that hash over its lifetime and different objects may or may not have a different hash value.
You cannot rely on any particular rel... |
AttributeError : Class Instance has no __call__ method | 11,324,589 | 3 | 2012-07-04T07:45:22Z | 11,324,675 | 14 | 2012-07-04T07:51:00Z | [
"python",
"oop",
"python-2.7",
"pygame",
"attributeerror"
] | I'm a bit new to python, but familiar with OOP. I'm trying to write a game using PyGame. Basically, my aim is to render trees every few seconds and move the tree rects across the screen.
So here is my code:
```
from collections import deque
import pygame,random,sys
pygame.init()
size = 800,600
screen = pygame.displa... | I guess it's because you have a variable name `tree` (used in `tree.render()`) which conflicts with your class name. Calling it `Tree` would be better (and more pythonic ^^). |
Output on the console and file using python | 11,325,019 | 24 | 2012-07-04T08:13:14Z | 11,325,249 | 21 | 2012-07-04T08:27:26Z | [
"python"
] | I'm trying to find out a way in python to redirect the script execution log to a file as well as stdout in pythonic way. Is there any easy way of acheiving this? | I came up with this [untested]
```
import sys
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush() # If you want the output to be visible immediately
def flush(self) :
for f in se... |
Output on the console and file using python | 11,325,019 | 24 | 2012-07-04T08:13:14Z | 11,327,339 | 41 | 2012-07-04T10:34:12Z | [
"python"
] | I'm trying to find out a way in python to redirect the script execution log to a file as well as stdout in pythonic way. Is there any easy way of acheiving this? | Use logging module (<http://docs.python.org/library/logging.html>):
```
import logging
logger = logging.getLogger('scope.name')
file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)
stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)
# nice output ... |
PyDev code analysis missing | 11,326,522 | 8 | 2012-07-04T09:45:02Z | 11,330,067 | 19 | 2012-07-04T13:27:54Z | [
"python",
"eclipse",
"pydev"
] | I have installed Eclipse 3.7.2 from APT in Ubuntu 12.04, and installed PyDev in Eclipse. First, it warns unused import and unused wild import, but it no longer displays them today. However, it can display errors like missing parenthesis.
I created a new user, and installed PyDev using that user, problem still happens.... | list all operations could solve it here, for others convenience, and make this question closed
* remove the project and recreated it, and this time the project dir is the the PYTHONPATH
* remove your python interpretor settings, and set it again in eclipse - window preference - pydev -interpreter Python, refresh the p... |
How to truncate all strings in a list to a same length, in some pythonic way? | 11,326,737 | 8 | 2012-07-04T09:58:59Z | 11,326,763 | 13 | 2012-07-04T10:00:21Z | [
"python"
] | Let's say we have a list such as:
```
g = ["123456789123456789123456",
"1234567894678945678978998879879898798797",
"6546546564656565656565655656565655656"]
```
I need the first twelve chars of each element :
```
["123456789123",
"123456789467",
"654654656465"]
```
Okay, I can build a second list in ... | Use a list comprehension:
```
g2 = [elem[:12] for elem in g]
```
If you prefer to edit `g` in-place, use the slice assignment syntax with a generator expression:
```
g[:] = (elem[:12] for elem in g)
```
Demo:
```
>>> g = ['abc', 'defg', 'lolololol']
>>> g[:] = (elem[:2] for elem in g)
>>> g
['ab', 'de', 'lo']
``` |
how to know if object gets deleted in python | 11,328,219 | 3 | 2012-07-04T11:29:19Z | 11,328,582 | 8 | 2012-07-04T11:54:17Z | [
"python",
"pyside"
] | I have an object in the heap and a reference to it. There are certain circumstances in which the object gets deleted but the reference that points to its location doesn't know that. How can i check if there is real data in the heap?
For example:
```
from PySide import *
a = QProgressBar()
b = QProgressBar()
self.setI... | For the `PySide` objects you'll need the `shiboken` module to perform object queries.
Visit the [shiboken module documention](http://shiboken.readthedocs.org/en/latest/shibokenmodule.html):
```
import shiboken
print shiboken.isValid(a)
``` |
Python bug - or my stupidity - EOL while scanning string literal | 11,328,335 | 6 | 2012-07-04T11:36:27Z | 11,328,385 | 9 | 2012-07-04T11:39:56Z | [
"python",
"string",
"syntax-error",
"eol"
] | I cannot see a significant difference between the two following lines.
Yet the first parses, and the latter, does not.
```
In [5]: n=""" \\"Axis of Awesome\\" """
In [6]: n="""\\"Axis of Awesome\\""""
File "<ipython-input-6-d691e511a27b>", line 1
n="""\\"Axis of Awesome\\""""
^
... | The last four quote marks in
```
"""\\"Axis of Awesome\\""""
```
are parsed as `"""`, i.e. end of string, followed by `"`, i.e. start of a new string literal. This new literal is never completed, though. Simple example:
```
>>> """foo""""bar"
'foobar'
>>> """foo""" "bar"
'foobar'
```
If you want to avoid this probl... |
Is Python strongly typed? | 11,328,920 | 134 | 2012-07-04T12:16:01Z | 11,328,962 | 22 | 2012-07-04T12:18:04Z | [
"python",
"strong-typing",
"weak-typing"
] | I've come across links that say Python is a strongly typed language.
However, I thought in strongly typed languages you couldn't do this :
```
bob = 1
bob = "bob"
```
I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplist) definition of strong/weak types.... | You are confusing ['strongly typed'](https://en.wikipedia.org/wiki/Strongly_typed) with ['dynamically typed'](https://en.wikipedia.org/wiki/Dynamically_typed).
I cannot change the type of `1` by adding the string `'12'`, but I can choose what types I store in a variable and change that during the program's run time.
... |
Is Python strongly typed? | 11,328,920 | 134 | 2012-07-04T12:16:01Z | 11,328,966 | 23 | 2012-07-04T12:18:28Z | [
"python",
"strong-typing",
"weak-typing"
] | I've come across links that say Python is a strongly typed language.
However, I thought in strongly typed languages you couldn't do this :
```
bob = 1
bob = "bob"
```
I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplist) definition of strong/weak types.... | According to this [wiki Python](http://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language) article Python is both dynamically and strongly typed (provides a good explanation too).
Perhaps you are thinking about *[statically typed](http://en.wikipedia.org/wiki... |
Is Python strongly typed? | 11,328,920 | 134 | 2012-07-04T12:16:01Z | 11,328,980 | 217 | 2012-07-04T12:19:26Z | [
"python",
"strong-typing",
"weak-typing"
] | I've come across links that say Python is a strongly typed language.
However, I thought in strongly typed languages you couldn't do this :
```
bob = 1
bob = "bob"
```
I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplist) definition of strong/weak types.... | Python is strongly, dynamically typed.
* **Strong** typing means that the type of a value doesn't suddenly change. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.
* **Dynamic** typing means that runtime objects (values) hav... |
Is Python strongly typed? | 11,328,920 | 134 | 2012-07-04T12:16:01Z | 11,329,223 | 8 | 2012-07-04T12:34:56Z | [
"python",
"strong-typing",
"weak-typing"
] | I've come across links that say Python is a strongly typed language.
However, I thought in strongly typed languages you couldn't do this :
```
bob = 1
bob = "bob"
```
I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplist) definition of strong/weak types.... | It's already been answered a few times, but Python is a strongly typed language:
```
>>> x = 3
>>> y = '4'
>>> print(x+y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
```
The following in JavaScript:
```
var x = 3
var y = '... |
Is Python strongly typed? | 11,328,920 | 134 | 2012-07-04T12:16:01Z | 25,231,621 | 18 | 2014-08-10T18:15:36Z | [
"python",
"strong-typing",
"weak-typing"
] | I've come across links that say Python is a strongly typed language.
However, I thought in strongly typed languages you couldn't do this :
```
bob = 1
bob = "bob"
```
I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplist) definition of strong/weak types.... | There are some important issues that I think all of the existing answers have missed.
---
Weak typing means allowing access to the underlying representation. In C, I can create a pointer to characters, then tell the compiler I want to use it as a pointer to integers:
```
char sz[] = "abcdefg";
int *i = (int *)sz;
``... |
Check if list item contains items from another list | 11,328,940 | 6 | 2012-07-04T12:16:52Z | 11,329,522 | 13 | 2012-07-04T12:52:29Z | [
"python",
"list"
] | I have a lists:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456', 'def-111', 'qwe-111']
bad = ['abc', 'def']
```
and want to search for items that contain the string 'abc' and 'def' (and others in bad). How can I do that?
Almost same question [here](http://stackoverflow.com/questions/4843158/check-in-pytho... | If you just want a test, join the target list into a string and test each element of `bad` like so:
```
>>> my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456', 'def-111', 'qwe-111']
>>> bad = ['abc', 'def']
>>> [e for e in bad if e in '\n'.join(my_list)]
['abc', 'def']
```
From your question, you can test each ele... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.