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 |
|---|---|---|---|---|---|---|---|---|---|
PyQt4 File select widget | 3,196,353 | 9 | 2010-07-07T15:36:24Z | 3,219,438 | 19 | 2010-07-10T13:52:40Z | [
"python",
"qt4",
"pyqt4",
"filedialog",
"qfiledialog"
] | I want to make a QT4 (using QT designer) dialog, that contains a part where a file has to be selected.
Now, I know QFileDialog exists, and I can program something that does what I want.
But can I also just do it in QT designer?
Is there some way to get a "file select" widget in QT designer?
Or, I remember these butto... | There is no file dialog available from the Qt designer as far as I know. But you can easily do it with a few lines of code.
Assuming you have a simple button called pushButton and the path should be stored in lineEdit.
```
def selectFile():
lineEdit.setText(QFileDialog.getOpenFileName())
pushButton.clicked.conne... |
PyQt4 File select widget | 3,196,353 | 9 | 2010-07-07T15:36:24Z | 6,948,233 | 8 | 2011-08-04T20:39:51Z | [
"python",
"qt4",
"pyqt4",
"filedialog",
"qfiledialog"
] | I want to make a QT4 (using QT designer) dialog, that contains a part where a file has to be selected.
Now, I know QFileDialog exists, and I can program something that does what I want.
But can I also just do it in QT designer?
Is there some way to get a "file select" widget in QT designer?
Or, I remember these butto... | `QFileDialog` exists in `QtGui`. At least in my version 4.4 and probably much earlier too. I think the reason it is not in Designer is because it opens its own window instead of being a widget to place on another window.
The documentation from QTDesigner could be better and at least hint of its existence.
Instantiate... |
Python sorted list search | 3,196,610 | 12 | 2010-07-07T16:02:53Z | 3,196,660 | 19 | 2010-07-07T16:07:11Z | [
"python",
"search",
"sorting"
] | Are there any Python built-ins or widely used Python libraries to perform a search in a sorted sequence? | [`bisect`](http://docs.python.org/library/bisect.html) is part of the standard library - is that the sort of thing you're looking for? |
Python sorted list search | 3,196,610 | 12 | 2010-07-07T16:02:53Z | 23,141,708 | 8 | 2014-04-17T19:22:23Z | [
"python",
"search",
"sorting"
] | Are there any Python built-ins or widely used Python libraries to perform a search in a sorted sequence? | It's worth noting that there are a couple high-quality Python libraries for maintaining a sorted list which also implement fast searching: [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) and [blist](https://pypi.python.org/pypi/blist/). Using these depends of course on how often you're inserting/re... |
csrf error in django | 3,197,321 | 13 | 2010-07-07T17:32:42Z | 3,585,440 | 16 | 2010-08-27T14:58:25Z | [
"python",
"django",
"csrf",
"django-csrf"
] | I want to realize a login for my site. I basically copied and pasted the following bits from the Django Book together. However I still get an error (CSRF verification failed. Request aborted.), when submitting my registration form. Can somebody tell my what raised this error and how to fix it?
Here is my code:
views.... | I was having the exact same issue - and Blue Peppers' answer got me on the right track. Adding a RequestContext to your form view fixes the problem.
```
from django.template import RequestContext
```
and:
```
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is... |
csrf error in django | 3,197,321 | 13 | 2010-07-07T17:32:42Z | 4,707,639 | 7 | 2011-01-16T19:47:40Z | [
"python",
"django",
"csrf",
"django-csrf"
] | I want to realize a login for my site. I basically copied and pasted the following bits from the Django Book together. However I still get an error (CSRF verification failed. Request aborted.), when submitting my registration form. Can somebody tell my what raised this error and how to fix it?
Here is my code:
views.... | I'm using **Django 1.2.3**, I had a few intermittent problems:
Things to do:
**Ensure the csrf token is present in your template**:
```
<form action="" method="post">{% csrf_token %}
```
**Use a RequestContext**:
```
return render_to_response('search-results.html', {'results' : results}, context_instance=RequestCo... |
How to use list comprehension to add an element to copies of a dictionary? | 3,197,342 | 10 | 2010-07-07T17:35:05Z | 3,197,365 | 13 | 2010-07-07T17:39:38Z | [
"python",
"dictionary",
"list-comprehension"
] | given:
```
template = {'a': 'b', 'c': 'd'}
add = ['e', 'f']
k = 'z'
```
I want to use list comprehension to generate
```
[{'a': 'b', 'c': 'd', 'z': 'e'},
{'a': 'b', 'c': 'd', 'z': 'f'}]
```
I know I can do this:
```
out = []
for v in add:
t = template.copy()
t[k] = v
out.append(t)
```
but it is a little ve... | ```
[dict(template,z=value) for value in add]
```
or (to use `k`):
```
[dict(template,**{k:value}) for value in add]
``` |
Redirecting stdio from a command in os.system() in Python | 3,197,509 | 6 | 2010-07-07T17:59:59Z | 3,197,565 | 9 | 2010-07-07T18:07:38Z | [
"python",
"stdout",
"stdio",
"os.system"
] | Usually I can change stdout in Python by changing the value of `sys.stdout`. However, this only seems to affect `print` statements. So, is there any way I can suppress the output (to the console), of a program that is run via the `os.system()` command in Python? | On a unix system, you can redirect stderr and stdout to /dev/null as part of the command itself.
```
os.system(cmd + "> /dev/null 2>&1")
``` |
Redirecting stdio from a command in os.system() in Python | 3,197,509 | 6 | 2010-07-07T17:59:59Z | 3,197,585 | 14 | 2010-07-07T18:09:39Z | [
"python",
"stdout",
"stdio",
"os.system"
] | Usually I can change stdout in Python by changing the value of `sys.stdout`. However, this only seems to affect `print` statements. So, is there any way I can suppress the output (to the console), of a program that is run via the `os.system()` command in Python? | You could consider running the program via `subprocess.Popen`, with `subprocess.PIPE` communication, and then shove that output where ever you would like, but as is, `os.system` just runs the command, and nothing else.
```
from subprocess import Popen, PIPE
p = Popen(['command', 'and', 'args'], stdout=PIPE, stderr=PI... |
PyQt4 and pyuic4 | 3,197,609 | 4 | 2010-07-07T18:12:58Z | 3,197,642 | 9 | 2010-07-07T18:17:15Z | [
"python",
"pyqt"
] | I'm trying to compile my first .ui file using PyQt4 on a mac with osx 10.6. I'm getting a syntax error and I'm not sure what it means.
```
>>> import sys
>>> sys.path.append('/Users/womble/Dropbox/scratch/')
>>> from PyQt4 import QtCore, QtGui
>>> pyuic4 Urb.ui > Urb.py
File "<stdin>", line 1
pyuic4 Urb.ui > Urb.... | You're mixing Python and shell commands.
This is Python code and can be executed from an interactive Python session:
```
import sys
sys.path.append('/Users/womble/Dropbox/scratch/')
from PyQt4 import QtCore, QtGui
```
This is supposed to be run from a command prompt or terminal window. It's giving syntax errors in y... |
How can I explode a tuple so that it can be passed as a parameter list? | 3,198,218 | 13 | 2010-07-07T19:38:32Z | 3,198,227 | 28 | 2010-07-07T19:39:26Z | [
"python",
"parameters",
"tuples",
"iterable-unpacking"
] | Let's say I have a method definition like this:
```
def myMethod(a, b, c, d, e)
```
Then, I have a variable and a tuple like this:
```
myVariable = 1
myTuple = (2, 3, 4, 5)
```
Is there a way I can pass explode the tuple so that I can pass its members as parameters? Something like this (although I know this won't w... | You are looking for the [argument unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) operator `*`:
```
myMethod(myVariable, *myTuple)
``` |
How can I explode a tuple so that it can be passed as a parameter list? | 3,198,218 | 13 | 2010-07-07T19:38:32Z | 3,198,278 | 7 | 2010-07-07T19:46:43Z | [
"python",
"parameters",
"tuples",
"iterable-unpacking"
] | Let's say I have a method definition like this:
```
def myMethod(a, b, c, d, e)
```
Then, I have a variable and a tuple like this:
```
myVariable = 1
myTuple = (2, 3, 4, 5)
```
Is there a way I can pass explode the tuple so that I can pass its members as parameters? Something like this (although I know this won't w... | From the [Python documentation](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists):
> The reverse situation occurs when the
> arguments are already in a list or
> tuple but need to be unpacked for a
> function call requiring separate
> positional arguments. For instance,
> the built-in range() ... |
Can python open a mp3 file | 3,198,604 | 4 | 2010-07-07T20:40:13Z | 3,198,620 | 10 | 2010-07-07T20:42:13Z | [
"python",
"mp3",
"music",
"popen"
] | Is it possible to open a mp3 file in python (possible using POPEN) and i dont mean to run it in the program i mean as a separate window in media player or whatever just for it to open it when i call the function and if so how. thanks a lot. | Opening a file with its associated application (*Windows* only):
```
import os
os.startfile('my_mp3.mp3')
```
A link to the documentation [can be found here](http://docs.python.org/library/os.html#os.startfile). |
How to write Russian characters in file? | 3,198,765 | 5 | 2010-07-07T20:59:44Z | 3,204,861 | 8 | 2010-07-08T14:52:30Z | [
"python",
"windows",
"unicode",
"python-2.x",
"python-unicode"
] | In console when I'm trying output Russian characters It gives me ???????????????
Who know why?
I tried write to file - in this case the same situation.
for example
```
f=open('tets.txt','w')
f.write('some russian text')
f.close
```
inside file is - ?????????????????????????/
or
```
p="some russian text"
print p
... | Here is a worked-out example, please read the comments:
```
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8
from __future__ import with_statement # Not required in Python 2.6 any more
import codecs
p = u"абвгдежзийкл" # n... |
malformed start tag error - Python, BeautifulSoup, and Sipie - Ubuntu 10.04 | 3,198,874 | 9 | 2010-07-07T21:13:02Z | 9,232,766 | 8 | 2012-02-10T18:22:04Z | [
"python",
"beautifulsoup"
] | I just installed python, mplayer, beautifulsoup and sipie to run Sirius on my Ubuntu 10.04 machine. I followed some docs that seem straightforward, but am encountering some issues. I'm not that familiar with Python, so this may be out of my league.
I was able to get everything installed, but then running sipie gives t... | The issues you are encountering are pretty common, and they deal specifically with mal-formed HTML. In my case, there was an HTML element which had double quoted an attribute's value. I ran into this issue today actually, and in so doing so came across your post. I was FINALLY able to resolve this issue through parsing... |
malformed start tag error - Python, BeautifulSoup, and Sipie - Ubuntu 10.04 | 3,198,874 | 9 | 2010-07-07T21:13:02Z | 10,378,065 | 15 | 2012-04-30T03:11:10Z | [
"python",
"beautifulsoup"
] | I just installed python, mplayer, beautifulsoup and sipie to run Sirius on my Ubuntu 10.04 machine. I followed some docs that seem straightforward, but am encountering some issues. I'm not that familiar with Python, so this may be out of my league.
I was able to get everything installed, but then running sipie gives t... | Suppose you are using BeautifulSoup4, I found out something in the official document about this: <http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser>
> If youâre using a version of Python 2 earlier than 2.7.3, or a version
> of Python 3 earlier than 3.2.2, itâs essential that you install lxm... |
How to get out of a try/except inside a while? [Python] | 3,199,065 | 3 | 2010-07-07T21:38:46Z | 3,199,090 | 8 | 2010-07-07T21:41:48Z | [
"python",
"while-loop"
] | I'm trying this simple code, but the damn break doesn't work... what is wrong?
```
while True:
for proxy in proxylist:
try:
h = urllib.urlopen(website, proxies = {'http': proxy}).readlines()
print 'worked %s' % proxy
break
except:
print 'error %s' % p... | You just break out of `for` loop -- not `while` loop:
```
running = True
while running:
for proxy in proxylist:
try:
h = urllib.urlopen(website, proxies = {'http': proxy}).readlines()
print 'worked %s' % proxy
running = False
except:
print 'error %s' ... |
append multiple values for one key in Python dictionary | 3,199,171 | 57 | 2010-07-07T21:50:47Z | 3,199,196 | 43 | 2010-07-07T21:53:56Z | [
"python",
"dictionary",
"key-value"
] | I am new to python and I have a list of years and values for each year. What I want to do is check if the year already exists in a dictionary and if it does, append the value to that list of values for the specific key.
So for instance, I have a list of years and have one value for each year:
```
2010
2
2009
4 ... | You would be best off using [`collections.defaultdict`](http://docs.python.org/library/collections.html) (added in Python 2.5). This allows you to specify the default object type of a missing key (such as a `list`).
So instead of creating a key if it doesn't exist first and then appending to the value of the key, you ... |
append multiple values for one key in Python dictionary | 3,199,171 | 57 | 2010-07-07T21:50:47Z | 3,199,250 | 17 | 2010-07-07T22:00:17Z | [
"python",
"dictionary",
"key-value"
] | I am new to python and I have a list of years and values for each year. What I want to do is check if the year already exists in a dictionary and if it does, append the value to that list of values for the specific key.
So for instance, I have a list of years and have one value for each year:
```
2010
2
2009
4 ... | You can use `setdefault`.
```
for line in list:
d.setdefault(year, []).append(value)
```
This works because setdefault returns the list as well as setting it on the dictionary, and because a list is mutable, appending to the version returned by setdefault is the same as appending it to the version inside the di... |
append multiple values for one key in Python dictionary | 3,199,171 | 57 | 2010-07-07T21:50:47Z | 3,199,256 | 74 | 2010-07-07T22:00:52Z | [
"python",
"dictionary",
"key-value"
] | I am new to python and I have a list of years and values for each year. What I want to do is check if the year already exists in a dictionary and if it does, append the value to that list of values for the specific key.
So for instance, I have a list of years and have one value for each year:
```
2010
2
2009
4 ... | If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:
```
years_dict = dict()
for line in list:
if line[0] in years_dict:
# append the new number to the existing a... |
append multiple values for one key in Python dictionary | 3,199,171 | 57 | 2010-07-07T21:50:47Z | 3,212,718 | 7 | 2010-07-09T12:52:50Z | [
"python",
"dictionary",
"key-value"
] | I am new to python and I have a list of years and values for each year. What I want to do is check if the year already exists in a dictionary and if it does, append the value to that list of values for the specific key.
So for instance, I have a list of years and have one value for each year:
```
2010
2
2009
4 ... | ```
d = {}
# import list of year,value pairs
for year,value in mylist:
try:
d[year].append(value)
except KeyError:
d[year] = [value]
```
The Python way - it is easier to receive forgiveness than ask permission! |
Regex to match Domain.CCTLD | 3,199,343 | 7 | 2010-07-07T22:16:13Z | 3,199,371 | 8 | 2010-07-07T22:23:45Z | [
"python",
"regex",
"subdomain",
"dns",
"tld"
] | Does anyone know a regular expression to match Domain.CCTLD? I don't want subdomains, only the "atomic domain". For example, `docs.google.com` doesn't get matched, but `google.com` does. However, this gets complicated with stuff like `.co.uk`, CCTLDs. Does anyone know a solution? Thanks in advance.
**EDIT:** I've real... | It sounds like you are looking for the information available through the [Public Suffix List](http://publicsuffix.org/) project.
> A "public suffix" is one under which Internet users can directly register names. Some examples of public suffixes are ".com", ".co.uk" and "pvt.k12.wy.us". The Public Suffix List is a list... |
pydev and twisted framework | 3,199,702 | 5 | 2010-07-07T23:40:06Z | 3,199,728 | 12 | 2010-07-07T23:46:03Z | [
"python",
"eclipse",
"twisted",
"pydev"
] | It seems like my Eclipse PyDev does not recognize that Twisted is installed on my system. I can't make auto suggest working. Does anyone know how to solve it? | go to preferences->Pydev->Interpreter - Python and hit the apply button. That will rescan your modules directory and add any missing modules.
That should fix any normal import errors. Some modules do some runtime magic that PyDev cant follow. |
excess positional arguments, unpacking argument lists or tuples, and extended iterable unpacking | 3,200,120 | 5 | 2010-07-08T01:33:23Z | 3,200,496 | 7 | 2010-07-08T03:26:02Z | [
"python",
"list",
"tuples"
] | This question is going to be rather long, so I apologize preemptively.
In Python we can use \* in the following three cases:
**I.** When defining a function that we want to be callable with an arbitrary number of arguments, such as [in this example](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-... | > In Python we can use `*` in the
> following three cases:
You mean **prefix** `*` , of course -- **infix** `*` is used for multiplication.
> However, from a pedagogical
> perspective this lack of consistency
> is problematic, especially given that
> if you wanted to process the result,
> you could always say list(b)... |
excess positional arguments, unpacking argument lists or tuples, and extended iterable unpacking | 3,200,120 | 5 | 2010-07-08T01:33:23Z | 3,200,573 | 7 | 2010-07-08T03:58:45Z | [
"python",
"list",
"tuples"
] | This question is going to be rather long, so I apologize preemptively.
In Python we can use \* in the following three cases:
**I.** When defining a function that we want to be callable with an arbitrary number of arguments, such as [in this example](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-... | You missed one.
**IV.** Also, in Python 3, a bare `*` in the argument list marks the end of positional arguments, allowing for [keyword-only arguments](http://www.python.org/dev/peps/pep-3102/).
```
def foo(a, b, *, key = None):
pass
```
This can be called `foo(1, 2, key = 3)` but not `foo(1, 2, 3)`. |
Python: does calling a method 'directly' instantiate the object? | 3,200,309 | 6 | 2010-07-08T02:27:29Z | 3,200,311 | 9 | 2010-07-08T02:28:27Z | [
"python"
] | I am new to Python and while unit testing some methods on my object I noticed something 'weird'.
```
class Ape(object):
def __init__(self):
print 'ooook'
def say(self, s):
print s
def main():
Ape().say('eeek')
if __name__ == '__main__':
main()
```
I wrote this little example to illu... | Yes it does. That's what `Ape()` does: it creates an new `Ape` object, and as part of that process the `__init__` method gets run.
In your example, you then call the `say` method of that object. Note that there would be no way to call `say` if you didn't have an `Ape` object. |
Python: does calling a method 'directly' instantiate the object? | 3,200,309 | 6 | 2010-07-08T02:27:29Z | 3,200,531 | 11 | 2010-07-08T03:41:28Z | [
"python"
] | I am new to Python and while unit testing some methods on my object I noticed something 'weird'.
```
class Ape(object):
def __init__(self):
print 'ooook'
def say(self, s):
print s
def main():
Ape().say('eeek')
if __name__ == '__main__':
main()
```
I wrote this little example to illu... | If you want to call a method directly without creating an instance you can use the `staticmethod` decorator. Notice that there is no `self` when you use a static method
```
class Ape(object):
def __init__(self):
print 'ooook'
@staticmethod
def say(s):
print s
def main():
Ape.say('eeek... |
Python converting the values from dicts into a tuples | 3,202,089 | 4 | 2010-07-08T09:12:51Z | 3,202,096 | 11 | 2010-07-08T09:13:53Z | [
"python",
"dictionary",
"tuples"
] | I have a list of dictionaries that looks like this:
```
[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
```
I'd like to convert the values from each dict into a list of tuples like this:
```
[(1,'Foo'),(2,'Bar')]
```
How can I do this? | ```
>>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
>>> [tuple(d.values()) for d in l]
[(1, 'Foo'), (2, 'Bar')]
``` |
Python converting the values from dicts into a tuples | 3,202,089 | 4 | 2010-07-08T09:12:51Z | 3,202,304 | 10 | 2010-07-08T09:38:09Z | [
"python",
"dictionary",
"tuples"
] | I have a list of dictionaries that looks like this:
```
[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
```
I'd like to convert the values from each dict into a list of tuples like this:
```
[(1,'Foo'),(2,'Bar')]
```
How can I do this? | Note that the approach in SilentGhost's answer doesn't guarantee the order of each tuple, since dictionaries and their `values()` have no inherent order. So you might just as well get `('Foo', 1)` as `(1, 'Foo')`, in the general case.
If that's not acceptable and you definitely need the `id` first, you'll have to do t... |
Percentage chance to make action | 3,203,099 | 5 | 2010-07-08T11:37:31Z | 3,203,121 | 8 | 2010-07-08T11:40:11Z | [
"python"
] | Simple problem:
percentage\_chance = 0.36
```
if <don't know what>:
#action here has 36% chance to execute
pass
```
How can i solve this problem? | You could use [`random.random`](http://docs.python.org/library/random.html#random.random):
```
>>> import random
>>> if random.random() < percentage_chance:
print('aaa')
``` |
read file from server with some offset | 3,203,217 | 6 | 2010-07-08T11:52:59Z | 3,203,549 | 14 | 2010-07-08T12:30:58Z | [
"python",
"http"
] | How can I read file from server starting with some offset (Similar behavior to **wget -c**)? What headers I must send to server? What futures must server support? | You should use the `Range` header in the request. But you may use it only if the server informs you that it accept range request by `Accept-Ranges` response header.
This is an example session. Suppose we are interested in getting a part of [this picture](http://farm3.static.flickr.com/2238/2758537173_670161cac7_b.jpg)... |
How to create a read-only class property in Python? | 3,203,286 | 44 | 2010-07-08T12:00:12Z | 3,203,434 | 32 | 2010-07-08T12:18:48Z | [
"python",
"class",
"properties"
] | Essentially I want to do something like this:
```
class foo:
x = 4
@property
@classmethod
def number(cls):
return x
```
Then I would like the following to work:
```
>>> foo.number
4
```
Unfortunately, the above doesn't work. Instead of given me `4` it gives me `<property object at 0x101786c5... | This will make `Foo.number` a *read-only* property:
```
class MetaFoo(type):
@property
def number(cls):
return cls.x
class Foo(object, metaclass=MetaFoo):
x = 4
print(Foo.number)
# 4
Foo.number = 6
# AttributeError: can't set attribute
```
---
**Explanation**: The usual scenario when using @pr... |
How to create a read-only class property in Python? | 3,203,286 | 44 | 2010-07-08T12:00:12Z | 3,203,659 | 37 | 2010-07-08T12:43:54Z | [
"python",
"class",
"properties"
] | Essentially I want to do something like this:
```
class foo:
x = 4
@property
@classmethod
def number(cls):
return x
```
Then I would like the following to work:
```
>>> foo.number
4
```
Unfortunately, the above doesn't work. Instead of given me `4` it gives me `<property object at 0x101786c5... | The `property` descriptor always returns itself when accessed from a class (ie. when `instance` is `None` in its `__get__` method).
If that's not what you want, you can write a new descriptor that always uses the class object (`owner`) instead of the instance:
```
>>> class classproperty(object):
... def __init__... |
How to create a read-only class property in Python? | 3,203,286 | 44 | 2010-07-08T12:00:12Z | 26,634,248 | 8 | 2014-10-29T15:23:20Z | [
"python",
"class",
"properties"
] | Essentially I want to do something like this:
```
class foo:
x = 4
@property
@classmethod
def number(cls):
return x
```
Then I would like the following to work:
```
>>> foo.number
4
```
Unfortunately, the above doesn't work. Instead of given me `4` it gives me `<property object at 0x101786c5... | I agree with [unubtu's answer](http://stackoverflow.com/a/3203434/608191); it seems to work, however, it doesn't work with this precise syntax on **Python 3** (specifically, Python 3.4 is what I struggled with). Here's how one must form the pattern under Python 3.4 to make things work, it seems:
```
class MetaFoo(type... |
how to change any data type into a string in python | 3,204,614 | 25 | 2010-07-08T14:26:32Z | 3,204,622 | 32 | 2010-07-08T14:27:52Z | [
"python"
] | How can I change any data type into a string in Python? | ```
myvariable = 4
mystring = str(myvariable) # '4'
```
also, alternatively try repr:
```
mystring = repr(myvariable) # '4'
```
This is called "conversion" in python, and is quite common. |
how to change any data type into a string in python | 3,204,614 | 25 | 2010-07-08T14:26:32Z | 3,204,633 | 9 | 2010-07-08T14:28:43Z | [
"python"
] | How can I change any data type into a string in Python? | Use the [`str`](http://docs.python.org/library/functions.html#str) built-in:
```
x = str(something)
```
Examples:
```
>>> str(1)
'1'
>>> str(1.0)
'1.0'
>>> str([])
'[]'
>>> str({})
'{}'
...
```
From the documentation:
> Return a string containing a nicely printable representation of an object. For strings, this r... |
how to change any data type into a string in python | 3,204,614 | 25 | 2010-07-08T14:26:32Z | 3,205,525 | 15 | 2010-07-08T15:55:57Z | [
"python"
] | How can I change any data type into a string in Python? | `str` is meant to produce a string representation of the object's data. If you're writing your own class and you want `str` to work for you, add:
```
def __str__(self):
return ...
```
`print str(myObj)` will call `myObj.__str__()`.
`repr` is a similar method, which generally produces information on the class inf... |
combining two string variables | 3,205,532 | 18 | 2010-07-08T15:56:30Z | 3,205,551 | 25 | 2010-07-08T15:58:07Z | [
"python"
] | I'm a novice Python user trying to do something that I think should be simple but can't figure it out. I've got 2 variables defined:
```
a = 'lemon'
b = 'lime'
```
Can someone tell me how to combine these in a new variable?
If I try:
```
>>> soda = "a" + "b"
>>> soda
'ab'
```
I want soda to be `'lemonlime'`. How i... | you need to take out the quotes:
```
soda = a + b
```
(You want to refer to the *variables* `a` and `b`, not the *strings* "a" and "b") |
combining two string variables | 3,205,532 | 18 | 2010-07-08T15:56:30Z | 3,205,754 | 12 | 2010-07-08T16:17:56Z | [
"python"
] | I'm a novice Python user trying to do something that I think should be simple but can't figure it out. I've got 2 variables defined:
```
a = 'lemon'
b = 'lime'
```
Can someone tell me how to combine these in a new variable?
If I try:
```
>>> soda = "a" + "b"
>>> soda
'ab'
```
I want soda to be `'lemonlime'`. How i... | IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the [string join](http://docs.python.org/library/stdtypes.html#str.join) method seems to be preferred:
```
the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', '... |
How do I compare Rpm versions in python | 3,206,319 | 8 | 2010-07-08T17:31:15Z | 3,206,477 | 10 | 2010-07-08T17:51:27Z | [
"python",
"regex",
"rpm"
] | I'm trying to find out how I can compare 2 lists of RPMS (Currently installed) and (Available in local repository) and see which RPMS are out of date. I've been tinkering with regex but there are so many different naming standards for RPMS that i can't get a good list to work with. I don't have the actual RPMS on my dr... | In RPM parlance, `2.el5` is the release field; 2 and el5 are not separate fields. However, release need not have a `.` in it as your examples show. Drop the `\.(.*)` from the end to capture the release field in one shot.
So now you have a package name, version, and release. The easiest way to compare them is to use rp... |
Passing HTML to template using Flask/Jinja2 | 3,206,344 | 44 | 2010-07-08T17:34:36Z | 3,206,446 | 93 | 2010-07-08T17:48:14Z | [
"python",
"jinja2",
"flask"
] | I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using `render_template`. The templating framework seems to escape the html automatically, so all <"'> are converted to html entities. How can I disable that so that the HTML renders correctly? | the ideal way is to
```
{{ something|safe }}
```
than completely turning off auto escaping. |
Passing HTML to template using Flask/Jinja2 | 3,206,344 | 44 | 2010-07-08T17:34:36Z | 3,266,740 | 37 | 2010-07-16T16:00:19Z | [
"python",
"jinja2",
"flask"
] | I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using `render_template`. The templating framework seems to escape the html automatically, so all <"'> are converted to html entities. How can I disable that so that the HTML renders correctly? | You can also declare it HTML safe from the code:
```
from flask import Markup
value = Markup('<strong>The HTML String</strong>')
```
Then pass that value to the templates and they don't have to `|safe` it. |
Semantics of python loops and strings | 3,206,375 | 2 | 2010-07-08T17:39:04Z | 3,206,402 | 8 | 2010-07-08T17:42:48Z | [
"python",
"semantics"
] | Consider:
```
args = ['-sdfkj']
print args
for arg in args:
print arg.replace("-", '')
arg = arg.replace("-", '')
print args
```
This yields:
```
['-sdfkj']
sdfkj
['-sdfkj']
```
Where I expected it to be `['sdfkj']`.
Is `arg` in the loop a copy?
It behaves as if it is a copy (or perhaps an immutable thing... | > Is arg in the loop a copy?
Yes, it contains a copy of the reference.
When you reassign `arg` you aren't modifying the original array, nor the string inside it (strings are immutable). You modify only what the local variable `arg` points to.
```
Before assignment After assignment
args arg ... |
How to check if a library is 32bit/64bit built on Mac OS X? | 3,207,177 | 11 | 2010-07-08T19:26:41Z | 3,207,250 | 16 | 2010-07-08T19:35:21Z | [
"python",
"osx",
"64bit",
"python-sip"
] | I'm having some trouble in using PyQt/SIP. I guess the SIP is compiled into 64bit, but Python has some problem with finding it.
```
File "qtdemo.py", line 46, in
import sip
ImportError: dlopen(/Library/Python/2.6/site-packages/sip.so, 2): no suitable image found. Did find:
/Library/Python/2.6/site-pack... | The `file` tool can be used to identify executables.
Example:
```
> file /Applications/TextEdit.app/Contents/MacOS/TextEdit
/Applications/TextEdit.app/Contents/MacOS/TextEdit: Mach-O universal binary with 2 architectures
/Applications/TextEdit.app/Contents/MacOS/TextEdit (for architecture x86_64): Mach-O 64-bit ex... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 3,207,254 | 242 | 2010-07-08T19:35:33Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | ```
import os
os.listdir("somedirectory")
```
will return a list of all files and directories in "somedirectory". |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 3,207,973 | 1,633 | 2010-07-08T21:01:11Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | [`os.listdir()`](https://docs.python.org/2/library/os.html#os.listdir) will get you everything that's in a directory - files and directories.
If you want *just* files, you could either filter this down using [`os.path`](https://docs.python.org/2/library/os.path.html#module-os.path):
```
from os import listdir
from os... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 3,215,392 | 671 | 2010-07-09T18:13:37Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | I prefer using the [`glob`](https://docs.python.org/library/glob.html) module, as it does pattern matching and expansion.
```
import glob
print glob.glob("/home/adam/*.txt")
```
Will return a list with the queried files:
```
['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
``` |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 19,308,592 | 76 | 2013-10-11T00:55:16Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | **Getting Full File Paths From a Directory and All Its Subdirectories**
```
import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including t... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 21,207,590 | 98 | 2014-01-18T17:42:29Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | A one-line solution to get **only list of files** (no subdirectories):
```
filenames = next(os.walk(path))[2]
```
or absolute pathnames:
```
paths = [os.path.join(path,fn) for fn in next(os.walk(path))[2]]
``` |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 22,247,546 | 7 | 2014-03-07T10:28:17Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | ```
# -** coding: utf-8 -*-
import os
import traceback
print '\n\n'
def start():
address = "/home/ubuntu/Desktop"
try:
Folders = []
Id = 1
for item in os.listdir(address):
endaddress = address + "/" + item
Folders.append({'Id': Id, 'TopId': 0, 'Name': item, 'Add... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 22,990,477 | 17 | 2014-04-10T14:09:06Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | If you are looking for python implementation of **find**, this is a recipe I use rather frequently:
```
from findtools.find_files import (find_files, Match)
# Recursively find all *.sh files in **/usr/bin**
sh_files_pattern = Match(filetype='f', name='*.sh')
found_files = find_files(path='/usr/bin', match=sh_files_pa... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 24,145,985 | 29 | 2014-06-10T16:16:30Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | ```
def list_files(path):
# returns a list of names (with extension, without full path) of all files
# in folder path
files = []
for name in os.listdir(path):
if os.path.isfile(os.path.join(path, name)):
files.append(name)
return files
``` |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 24,209,884 | 12 | 2014-06-13T16:26:01Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | **Returning a list of absolute filepaths, does not recurse into subdirectories**
```
L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]
``` |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 24,652,788 | 38 | 2014-07-09T11:43:58Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | I really liked [adamk's answer](http://stackoverflow.com/a/3215392/901641), suggesting that you use `glob()`, from the module of the same name. This allows you to have pattern matching with `*`s.
But as other people pointed out in the comments, `glob()` can get tripped up over inconsistent slash directions. To help wi... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 30,925,692 | 18 | 2015-06-18T20:58:21Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | [pathlib](https://docs.python.org/3.4/library/pathlib.html): *New in version 3.4.*
```
>>> import pathlib
>>> [p for p in pathlib.Path('.').iterdir() if p.is_file()]
```
[os.scandir()](https://www.python.org/dev/peps/pep-0471/): *New in version 3.5.*
```
>>> import os
>>> [entry for entry in os.scandir('.') if entry... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 31,265,707 | 20 | 2015-07-07T10:12:33Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | ```
import os
lst=os.listdir(path)
```
os.listdir returns a list containing the names of the entries in the directory given by path. |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 32,289,024 | 10 | 2015-08-29T17:44:41Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | List all files in a directory:
```
import os
from os import path
files = [x for x in os.listdir(directory_path) if path.isfile(directory_path+os.sep+x)]
```
Here, you get list of all files in a directory. |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 34,841,882 | 12 | 2016-01-17T18:17:07Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | Python 3.5 introduced new, faster method for walking through the directory - [`os.scandir()`](https://www.python.org/dev/peps/pep-0471/).
Example:
```
for file in os.scandir('/usr/bin'):
line = ''
if file.is_file():
line += 'f'
elif file.is_dir():
line += 'd'
elif file.is_symlink():
... |
How to list all files of a directory in Python | 3,207,219 | 1,509 | 2010-07-08T19:31:22Z | 36,175,169 | 20 | 2016-03-23T10:09:45Z | [
"python",
"directory"
] | How can I list all files of a directory in python and add them to a list? | You should use `os` module for listing directory content.`os.listdir(".")` returns all the contents of the directory. We iterate over the result and append to the list.
```
import os
content_list = []
for content in os.listdir("."): # "." means current directory
content_list.append(content)
print content_list
`... |
"self" inside plain function? | 3,207,572 | 6 | 2010-07-08T20:12:54Z | 3,207,615 | 10 | 2010-07-08T20:17:31Z | [
"python"
] | I've got a bunch of functions (outside of any class) where I've set attributes on them, like `funcname.fields = 'xxx'`. I was hoping I could then access these variables from inside the function with `self.fields`, but of course it tells me:
> global name 'self' is not defined
So... what can I do? Is there some magic ... | `self` isn't a keyword in python, its just a normal variable name. When creating instance methods, you can name the first parameter whatever you want, self is just a convention.
You should almost always prefer passing arguments to functions over setting properties for input, but if you must, you can do so using the ac... |
Creating square subplots (of equal height and width) in matplotlib | 3,207,850 | 8 | 2010-07-08T20:44:00Z | 3,214,815 | 11 | 2010-07-09T16:51:59Z | [
"python",
"matplotlib"
] | When I run this code
```
from pylab import *
figure()
ax1 = subplot(121)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
```
I get two subplots which are "squished" in the X-dimension. How do I get these subplots such that the height of the Y-axis equals the w... | Your problem in setting the aspect of the plots is coming in when you're using sharex and sharey.
One workaround is to just not used shared axes. For example, you could do this:
```
from pylab import *
figure()
subplot(121, aspect='equal')
plot([1, 2, 3], [1, 2, 3])
subplot(122, aspect='equal')
plot([1, 2, 3], [1, 2... |
Nested exceptions? | 3,208,566 | 2 | 2010-07-08T22:47:46Z | 3,208,612 | 12 | 2010-07-08T22:55:04Z | [
"python"
] | Will this work?
```
try:
try:
field.value = filter(field.value, fields=self.fields, form=self, field=field)
except TypeError:
field.value = filter(field.value)
except ValidationError, e:
field.errors += e.args
field.value = revert
valid = False
break
```
Namely, if that first l... | If the filter statement in the inner try raises an exception, it will first get checked against the inner set of "except" statements and then if none of those catch it, it will be checked against the outer set of "except" statements.
You can convince yourself this is the case just by doing something simple like this (... |
using DictWriter in Python to write a subset of a dictionary's keys | 3,208,874 | 8 | 2010-07-08T23:46:33Z | 3,208,915 | 25 | 2010-07-08T23:54:40Z | [
"python",
"dictionary",
"csv",
"input"
] | I wrote a function that serializes a list of dictionaries as a CSV file using the CSV module. I sometimes want to write out to a file only a subset of each dictionary's keys however. I use the following code:
```
def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',
lineterminator='\n'):
out_f = ... | Simplest and most direct approach is to pass `extrasaction='ignore'` when you initialize your `DictWriter` instance, as documented [here](http://docs.python.org/library/csv.html?highlight=dictwriter#csv.DictWriter):
> If the dictionary passed to the
> `writerow()` method contains a key not
> found in fieldnames, the o... |
How to replace an instance in __init__() with a different object? | 3,209,233 | 11 | 2010-07-09T01:25:08Z | 3,209,240 | 25 | 2010-07-09T01:28:18Z | [
"python",
"oop"
] | I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to \_\_init\_\_() ('self' in the example below) *within* \_\_init\_\_() but it doesn't seem to do what I want.
in main:
```
import ClassA
... | You need `__new__()` for that. (And you also need to make it a new-style class, assuming you're using Python 2, by subclassing `object`.)
```
class ClassA(object):
def __new__(cls,theirnumber):
if theirnumber > 10:
# all big numbers should be ClassB objects:
return ClassB.ClassB(the... |
How to replace an instance in __init__() with a different object? | 3,209,233 | 11 | 2010-07-09T01:25:08Z | 3,209,245 | 9 | 2010-07-09T01:29:30Z | [
"python",
"oop"
] | I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to \_\_init\_\_() ('self' in the example below) *within* \_\_init\_\_() but it doesn't seem to do what I want.
in main:
```
import ClassA
... | Don't try to pervert the purpose of constructors: use a factory function. Calling a constructor for one class and being returned an instance of a different class is a sure way to cause confusion. |
How to replace an instance in __init__() with a different object? | 3,209,233 | 11 | 2010-07-09T01:25:08Z | 3,209,248 | 10 | 2010-07-09T01:30:51Z | [
"python",
"oop"
] | I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to \_\_init\_\_() ('self' in the example below) *within* \_\_init\_\_() but it doesn't seem to do what I want.
in main:
```
import ClassA
... | I would suggest using a **factory pattern** for this. For example:
```
def get_my_inst(the_number):
if the_number > 10:
return ClassB(the_number)
else:
return ClassA(the_number)
class_b_inst = get_my_inst(500)
class_a_inst = get_my_inst(5)
``` |
How to plot empirical cdf in matplotlib in Python? | 3,209,362 | 34 | 2010-07-09T02:14:18Z | 3,213,923 | 10 | 2010-07-09T15:07:20Z | [
"python",
"numpy",
"statistics",
"matplotlib",
"scipy"
] | How can I plot the empirical CDF of an array of numbers in matplotlib in Python? I'm looking for the cdf analog of pylab's "hist" function.
One thing I can think of is:
```
from scipy.stats import cumfreq
a = array([...]) # my array of numbers
num_bins = 20
b = cumfreq(a, num_bins)
plt.plot(b)
```
Is that correct t... | That looks to be (almost) exactly what you want. Two things:
First, the results are a tuple of four items. The third is the size of the bins. The second is the starting point of the smallest bin. The first is the number of points in the in or below each bin. (The last is the number of points outside the limits, but si... |
How to plot empirical cdf in matplotlib in Python? | 3,209,362 | 34 | 2010-07-09T02:14:18Z | 3,220,681 | 50 | 2010-07-10T20:09:16Z | [
"python",
"numpy",
"statistics",
"matplotlib",
"scipy"
] | How can I plot the empirical CDF of an array of numbers in matplotlib in Python? I'm looking for the cdf analog of pylab's "hist" function.
One thing I can think of is:
```
from scipy.stats import cumfreq
a = array([...]) # my array of numbers
num_bins = 20
b = cumfreq(a, num_bins)
plt.plot(b)
```
Is that correct t... | You can use the [`ECDF`](http://statsmodels.sourceforge.net/generated/scikits.statsmodels.tools.ECDF.html) function from the [scikits.statsmodels](http://scikits.appspot.com/statsmodels) library:
```
import numpy as np
import scikits.statsmodels as sm
import matplotlib.pyplot as plt
sample = np.random.uniform(0, 1, 5... |
How to plot empirical cdf in matplotlib in Python? | 3,209,362 | 34 | 2010-07-09T02:14:18Z | 5,814,277 | 10 | 2011-04-28T05:59:43Z | [
"python",
"numpy",
"statistics",
"matplotlib",
"scipy"
] | How can I plot the empirical CDF of an array of numbers in matplotlib in Python? I'm looking for the cdf analog of pylab's "hist" function.
One thing I can think of is:
```
from scipy.stats import cumfreq
a = array([...]) # my array of numbers
num_bins = 20
b = cumfreq(a, num_bins)
plt.plot(b)
```
Is that correct t... | Have you tried the cumulative=True argument to pyplot.hist? |
How to plot empirical cdf in matplotlib in Python? | 3,209,362 | 34 | 2010-07-09T02:14:18Z | 11,692,365 | 44 | 2012-07-27T17:02:31Z | [
"python",
"numpy",
"statistics",
"matplotlib",
"scipy"
] | How can I plot the empirical CDF of an array of numbers in matplotlib in Python? I'm looking for the cdf analog of pylab's "hist" function.
One thing I can think of is:
```
from scipy.stats import cumfreq
a = array([...]) # my array of numbers
num_bins = 20
b = cumfreq(a, num_bins)
plt.plot(b)
```
Is that correct t... | I almost always do:
```
# a is the data array
sorted = np.sort(a)
yvals = np.arange(len(sorted))/float(len(sorted))
plt.plot(sorted, yvals)
```
Which works for me even if there are `>O(1e6)` data values.
If you really need to down sample I'd set
```
sorted = np.sort(a)[::down_sampling_step]
```
**Edit** to respond ... |
What is the most pythonic way to have a generator expression executed? | 3,209,789 | 3 | 2010-07-09T04:17:21Z | 3,209,822 | 7 | 2010-07-09T04:25:48Z | [
"python",
"lazy-evaluation",
"generator"
] | More and more features of Python move to be "lazy executable", like generator
expressions and other kind of iterators.
Sometimes, however, I see myself wanting to roll a one liner "for" loop, just to perform some action.
What would be the most pythonic thing to get the loop actually executed?
For example:
```
a = op... | If I wanted to do this specific example, I'd write
```
for i in xrange(100): a.write('%d ' % i)
```
If I often needed to consume an iterator for its effect, I'd define
```
def for_effect(iterable):
for _ in iterable:
pass
``` |
What is the most pythonic way to have a generator expression executed? | 3,209,789 | 3 | 2010-07-09T04:17:21Z | 3,209,854 | 10 | 2010-07-09T04:34:13Z | [
"python",
"lazy-evaluation",
"generator"
] | More and more features of Python move to be "lazy executable", like generator
expressions and other kind of iterators.
Sometimes, however, I see myself wanting to roll a one liner "for" loop, just to perform some action.
What would be the most pythonic thing to get the loop actually executed?
For example:
```
a = op... | There is one obvious way to do it, and that is the way you should do it. There is no excuse for doing it a clever way.
```
a = open("numbers.txt", "w")
for i in xrange(100):
a.write("%d " % i)
d.close()
```
Lazy execution gives you a serious benefit: It allows you to pass a sequence to another piece of code witho... |
Java equivalent of Python's struct.pack? | 3,209,898 | 14 | 2010-07-09T04:44:50Z | 3,210,080 | 8 | 2010-07-09T05:39:02Z | [
"java",
"python",
"struct",
"pack"
] | Is there any function equivalent to Python's `struct.pack` in Java that allows me to pack and unpack values like this?
```
pump_on = struct.pack("IIHHI", 0, 0, 21, 96, 512)
``` | I think what you may be after is a [ByteBuffer](http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/nio/ByteBuffer.html):
```
ByteBuffer pump_on_buf = ...
pump_on_buf.putInt(0);
pump_on_buf.putInt(0);
pump_on_buf.putShort(21);
pump_on_buf.putShort(96);
pump_on_buf.putInt(512);
byte[] pump_on = pump_on_... |
Django return redirect() with parameters | 3,209,906 | 39 | 2010-07-09T04:46:07Z | 3,210,919 | 41 | 2010-07-09T08:12:50Z | [
"python",
"django",
"redirect",
"parameter-passing"
] | In my view function I want to call another view and pass data to it :
```
return redirect('some-view-name', backend, form.cleaned_data)
```
, where backend is of registration.backends object, and form.cleaned\_data is a dict of form data (but both must be either sent as \*args or \*\*kwargs to prevent raising `Don't ... | Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned\_data dictionary. Don't forget you can't redirect to a POST - this ... |
Django return redirect() with parameters | 3,209,906 | 39 | 2010-07-09T04:46:07Z | 23,932,182 | 12 | 2014-05-29T11:23:17Z | [
"python",
"django",
"redirect",
"parameter-passing"
] | In my view function I want to call another view and pass data to it :
```
return redirect('some-view-name', backend, form.cleaned_data)
```
, where backend is of registration.backends object, and form.cleaned\_data is a dict of form data (but both must be either sent as \*args or \*\*kwargs to prevent raising `Don't ... | urls.py:
```
#...
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),
```
views.py:
```
from django.shortcuts import redirect
from .models import Element
def element_info(request):
# ...
element = Element.object.get(pk=1)
return redirect('element_update', pk... |
Pythonic way to check if two dictionaries have the identical set of keys? | 3,210,832 | 6 | 2010-07-09T07:59:55Z | 3,210,876 | 17 | 2010-07-09T08:06:40Z | [
"python",
"dictionary"
] | For example, let's say I have to dictionaries:
```
d_1 = {'peter': 1, 'adam': 2, 'david': 3}
```
and
```
d_2 = {'peter': 14, 'adam': 44, 'david': 33, 'alan': 21}
```
What's the cleverest way to check whether the two dictionaries contain the same set of keys? In the example above it should return `False` because `d_... | In Python2,
```
set(d_1) == set(d_2)
```
In Python3, you can do this which may be a tiny bit more efficient than creating sets
```
d1.keys() == d2.keys()
```
although the Python2 way would work too |
Pythonic way to check if two dictionaries have the identical set of keys? | 3,210,832 | 6 | 2010-07-09T07:59:55Z | 3,210,884 | 12 | 2010-07-09T08:07:36Z | [
"python",
"dictionary"
] | For example, let's say I have to dictionaries:
```
d_1 = {'peter': 1, 'adam': 2, 'david': 3}
```
and
```
d_2 = {'peter': 14, 'adam': 44, 'david': 33, 'alan': 21}
```
What's the cleverest way to check whether the two dictionaries contain the same set of keys? In the example above it should return `False` because `d_... | You can get the keys for a dictionary with dict.keys().
You can turn this into a set with set(dict.keys())
You can compare sets with ==
To sum up:
```
set(d_1.keys()) == set(d_2.keys())
```
will give you what you want. |
Python: Why does os.getcwd() sometimes crash with OSError? | 3,210,902 | 15 | 2010-07-09T08:10:37Z | 3,210,928 | 7 | 2010-07-09T08:13:26Z | [
"python"
] | I have this program that at one point accesses os.getcwd(), but some times, depending on where the program has gone before getting to that line, it crashes with the message "OSError: [Errno 2] No such file or directory".
I cannot figure out what i can do wrong then calling os.getcwd(). There's no arguments, and there s... | You might get that error if the current working directory has been deleted. Programs that are working in a particular directory don't automatically notice if the directory gets deleted; as far as the program is concerned, the CWD is just a string, at least until you do something like `os.getcwd()` that actually accesse... |
Python: Why does os.getcwd() sometimes crash with OSError? | 3,210,902 | 15 | 2010-07-09T08:10:37Z | 3,210,929 | 17 | 2010-07-09T08:13:25Z | [
"python"
] | I have this program that at one point accesses os.getcwd(), but some times, depending on where the program has gone before getting to that line, it crashes with the message "OSError: [Errno 2] No such file or directory".
I cannot figure out what i can do wrong then calling os.getcwd(). There's no arguments, and there s... | The current directory may have been deleted by another process. |
python file read | 3,211,031 | 2 | 2010-07-09T08:27:23Z | 3,211,113 | 7 | 2010-07-09T08:41:19Z | [
"python",
"file"
] | ```
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
```
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output! | While your own answer *prints* the bytes read, it doesn't *return* them, so you won't be able to use the result somewhere else. Also, there's room for a few other improvements:
* `file_open` isn't a good name for the function, since it reads and returns bytes from a file rather than just opening it.
* You should make ... |
How to join two generators in Python? | 3,211,041 | 73 | 2010-07-09T08:29:05Z | 3,211,047 | 99 | 2010-07-09T08:30:28Z | [
"python",
"generator"
] | I want to change the following code
```
for directory, dirs, files in os.walk(directory_1):
do_something()
for directory, dirs, files in os.walk(directory_2):
do_something()
```
to this code:
```
for directory, dirs, files in os.walk(directory_1) + os.walk(directory_2):
do_something()
```
I get the err... | I think [`itertools.chain()`](http://docs.python.org/library/itertools.html#itertools.chain) should do it. |
How to join two generators in Python? | 3,211,041 | 73 | 2010-07-09T08:29:05Z | 29,398,596 | 15 | 2015-04-01T18:54:35Z | [
"python",
"generator"
] | I want to change the following code
```
for directory, dirs, files in os.walk(directory_1):
do_something()
for directory, dirs, files in os.walk(directory_2):
do_something()
```
to this code:
```
for directory, dirs, files in os.walk(directory_1) + os.walk(directory_2):
do_something()
```
I get the err... | A example of code:
```
from itertools import chain
def generator1():
for item in 'abcdef':
yield item
def generator2():
for item in '123456':
yield item
generator3 = chain(generator1(), generator2())
for item in generator3:
print item
``` |
How to deploy a python webapp with dependencies using virtualenv? | 3,211,080 | 5 | 2010-07-09T08:35:32Z | 3,211,304 | 9 | 2010-07-09T09:16:02Z | [
"python",
"virtualenv"
] | I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use *virtualenv* to have a clean environment for this application.
However, **I am wondering how to manage dependencies when deploying to the server ?**
In development, I have a *virtualenv* in which I inst... | With pip you can create a requirements file:
```
$ pip freeze > requirements.txt
```
Then in the server to install all of these you do:
```
$ pip install -r requirements.txt
```
And with this (if the server has everything necessary to build the binary packages that you might have included) all is ready. |
Two processes reading/writing to the same file Python | 3,211,292 | 11 | 2010-07-09T09:14:15Z | 3,211,357 | 10 | 2010-07-09T09:24:03Z | [
"python",
"file-io",
"process"
] | I have one process who's reading from a file (using `file.read()`) and one process who's writing to the same file (`file.write()`). The problem is it doesn't work - I get no errors but they can't operate at the same time. I've tried making the read and write operations none-blocking and then flushing the stream, as fol... | test1.py
```
import os
f = open('txt.txt', 'a', os.O_NONBLOCK)
while 1:
f.write('asd')
f.flush()
```
test2.py
```
import os
f = open('txt.txt', 'r', os.O_NONBLOCK)
while 1:
print f.read(3)
```
This works fine for me. |
sparse file usage in python | 3,211,999 | 8 | 2010-07-09T11:06:38Z | 3,212,102 | 9 | 2010-07-09T11:20:05Z | [
"python",
"file",
"filesize",
"sparse-file"
] | I'm creating sparse files in python as follows:
```
>>> f = open('testfile', 'ab')
>>> f.truncate(1024000)
>>> f.close()
```
when the file is done, it takes up 0 disk space, but its inode size is set to my truncated value (1000K):
```
igor47@piglet:~/test$ ls -lh testfile
-rw-r--r-- 1 igor47 igor47 1000K 2010-07-09... | ```
>>> os.stat('testfile').st_blocks*512
0
```
Tadaa :)
`st_blocks` is the number of 512-byte blocks actually allocated to the file. Note that `st_blocks` is not guaranteed to be present in all operating systems, but those that support sparse files generally do. |
how to find target path of link if the file is a link file | 3,212,712 | 11 | 2010-07-09T12:51:51Z | 3,212,743 | 17 | 2010-07-09T12:56:34Z | [
"python",
"file",
"hyperlink"
] | how to find if the file is a link file, and find the path of the target file (actual file pointed by the link file) | [`os.path.islink`](http://docs.python.org/library/os.path.html#os.path.islink) (is it a link?) and [`os.path.realpath`](http://docs.python.org/library/os.path.html#os.path.realpath) (get ultimate pointed to path, regardless of whether it's a link).
If `os.path.islink` is True, and you only want to follow the first lin... |
Matlab equivalent of Numpy broadcasting? | 3,213,212 | 12 | 2010-07-09T13:49:14Z | 3,213,236 | 17 | 2010-07-09T13:51:36Z | [
"python",
"matlab",
"numpy",
"numpy-broadcasting"
] | I'm trying to find some way to substract a size 3 vector from each column of a 3\*(a big number) matrix in Matlab. Of course I could use a loop, but I'm trying to find some more efficient solution, a bit like numpy broadcasting. Oh, and I can't use repmat because I just don't have enough memory to use it (as it creates... | Loops aren't bad in MATLAB anymore thanks to compiler optimizations like [just-in-time acceleration (JITA)](http://www.mathworks.com/company/newsletters/news_notes/may03/profiler.html). etc. Most of the time, I've noticed that a solution with loops in current MATLAB versions is *much* faster than complicated (albeit, c... |
Lines of Code in Eclipse PyDev Projects | 3,214,245 | 9 | 2010-07-09T15:43:18Z | 3,215,869 | 15 | 2010-07-09T19:22:42Z | [
"python",
"eclipse",
"plugins",
"metrics",
"pydev"
] | I'm wondering if anyone has had any luck using the [Eclipse Metrics](http://metrics.sourceforge.net) Plugin with Projects that are not in Java (specifically I'm trying to generate code metrics for a couple of PyDev Projects). I've read through the walk-through for the Metrics project but it indicates that I should be i... | I don't know if it's doable to get the plugin to work with pydev projects, but if it's just the `lines-of-code` metric you are after, you could run this snippet in your project's root directory:
```
# prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints to... |
What is the fastest way to initialize an integer array in python? | 3,214,288 | 2 | 2010-07-09T15:49:06Z | 3,216,322 | 10 | 2010-07-09T20:27:40Z | [
"python",
"arrays",
"integer"
] | Say I wanted to create an array (NOT list) of 1,000,000 twos in python, like this:
`array = [2, 2, 2, ...... , 2]`
What would be a fast but simple way of doing it? | The currently-accepted answer is NOT the fastest way using `array.array`; at least it's not the slowest -- compare these:
```
[source: johncatfish (quoting chauncey), Bartek]
python -m timeit -s"import array" "arr = array.array('i', (2 for i in range(0,1000000)))"
10 loops, best of 3: 543 msec per loop
[source: g.d.d... |
Matplotlib autoscale | 3,214,576 | 7 | 2010-07-09T16:21:46Z | 3,215,060 | 8 | 2010-07-09T17:26:11Z | [
"python",
"visualization",
"matplotlib",
"plot"
] | I need to get a plot that fits the data automatically using matplotlib. This is the code I was given:
```
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
....
lines = LineCollection(mpl.line_holder, colors=mpl.colorholder , linestyle='solid')
plt.axes().add_collection(lines)
plt.axes(... | Not sure if this what you wanted, but I can change it if this was not what you were looking for.
```
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import pylab as p
fig = plt.figure()
pts1 = []
pts2 = []
for i in range(100):
pts1.append([i,i])
pts2.append([-i-3,-i])
lines ... |
How to get ° character in a string in python? | 3,215,168 | 34 | 2010-07-09T17:39:22Z | 3,215,178 | 23 | 2010-07-09T17:41:02Z | [
"python",
"string"
] | How can I get a `°` (degree) character into a string? | ```
>>> u"\u00b0"
u'\xb0'
>>> print _
°
```
BTW, all I did was search "unicode degree" on Google. This brings up two results:
"Degree sign U+00B0" and "Degree Celsius U+2103", which are actually different:
```
>>> u"\u2103"
u'\u2103'
>>> print _
â
``` |
How to get ° character in a string in python? | 3,215,168 | 34 | 2010-07-09T17:39:22Z | 3,215,827 | 21 | 2010-07-09T19:14:50Z | [
"python",
"string"
] | How can I get a `°` (degree) character into a string? | Put this line at the top of your source
```
# -*- coding: utf-8 -*-
```
If your editor uses a different encoding, substitute for utf-8
Then you can include utf-8 characters directly in the source |
How to get ° character in a string in python? | 3,215,168 | 34 | 2010-07-09T17:39:22Z | 3,216,630 | 38 | 2010-07-09T21:18:25Z | [
"python",
"string"
] | How can I get a `°` (degree) character into a string? | This is the most coder-friendly version of specifying a unicode character:
```
degree_sign= u'\N{DEGREE SIGN}'
```
Note: must be a capital N in the `\N` construct to avoid confusion with the '\n' newline character. The character name inside the curly braces can be any case.
It's easier to remember the [name](http://... |
Monitor Process in Python? | 3,215,262 | 4 | 2010-07-09T17:54:01Z | 3,215,404 | 14 | 2010-07-09T18:14:52Z | [
"python",
"process",
"monitor",
"restart"
] | I think this is a pretty basic question, but here it is anyway.
I need to write a python script that checks to make sure a process, say notepad.exe, is running. If the process is running, do nothing. If it is not, start it. How would this be done.
I am using Python 2.6 on Windows XP | The process creation functions of the `os` module are apparently deprecated in Python 2.6 and later, with the [`subprocess`](http://docs.python.org/release/2.6.5/library/subprocess.html) module being the module of choice now, so...
```
if 'notepad.exe' not in subprocess.Popen('tasklist', stdout=subprocess.PIPE).commun... |
How do I suppress "unused in wild import" warning in pydev? | 3,215,516 | 14 | 2010-07-09T18:31:47Z | 3,261,764 | 29 | 2010-07-16T03:36:09Z | [
"python",
"pydev"
] | How do I suppress "unused in wild import" warning in pydev? | Suppressing warning message for import / wild import
```
from django.db import connection #@UnusedImport
from django.db import * #@UnusedWildImport
``` |
Set cursor position in a Text widget | 3,215,549 | 6 | 2010-07-09T18:36:40Z | 3,215,718 | 7 | 2010-07-09T19:00:39Z | [
"python",
"tkinter",
"cursor-position"
] | Is it possible to set the cursor position in a Tkinter Text widget? I'm not finding anything terribly useful yet.
The best I've been able to do is emit a `<Button-1>` and `<ButtonRelease-1>` event at a certain x-y coordinate, but that is a pixel amount, not a letter amount. | If "text", "line", "column" are your text object, desired text line and desired column variables:
```
text.mark_set("insert", "%d.%d" % (line + 1, column + 1)
```
If you would not like to care about the line number...well, you have to.
Complete documentation at:
<http://effbot.org/tkinterbook/text.htm> |
paramiko SSH exec_command(shell script) returns before completion | 3,215,727 | 10 | 2010-07-09T19:02:15Z | 3,215,773 | 17 | 2010-07-09T19:07:57Z | [
"python",
"paramiko"
] | I launch a shell script from a remote Linux machine using paramiko. The shell script is launched and execute a command make -j8. However the exec\_command returns before the completion of the make.
If I launch the script on the local machine it executes correctly.
Could someone explain me this behaviour ? | You need to wait for application to finish, exec\_command isn't a blocking call.
```
print now(), "before call"
stdin, stdout, sterr = ssh.exec_command("sleep(10)")
print now(), "after call"
channel = stdout.channel
print now(), "before status"
status = channel.recv_exit_status()
print now(), "after status"
``` |
Extract Meta Keywords From Webpage? | 3,215,830 | 7 | 2010-07-09T19:15:39Z | 3,215,840 | 7 | 2010-07-09T19:17:55Z | [
"python",
"extract",
"webpage",
"keyword",
"urllib"
] | I need to extract the meta keywords from a web page using Python. I was thinking that this could be done using urllib or urllib2, but I'm not sure. Anyone have any ideas?
I am using Python 2.6 on Windows XP | BeautifulSoup is a great way to parse HTML with Python.
Particularly, check out the findAll method:
<http://www.crummy.com/software/BeautifulSoup/documentation.html> |
Extract Meta Keywords From Webpage? | 3,215,830 | 7 | 2010-07-09T19:15:39Z | 3,215,955 | 10 | 2010-07-09T19:34:10Z | [
"python",
"extract",
"webpage",
"keyword",
"urllib"
] | I need to extract the meta keywords from a web page using Python. I was thinking that this could be done using urllib or urllib2, but I'm not sure. Anyone have any ideas?
I am using Python 2.6 on Windows XP | [lxml](http://codespeak.net/lxml/index.html#documentation) is faster than BeautifulSoup (I think) and has much better functionality, while remaining relatively easy to use. Example:
```
52> from urllib import urlopen
53> from lxml import etree
54> f = urlopen( "http://www.google.com" ).read()
55> tree = etree.HTML( f... |
Sorting by arbitrary lambda | 3,216,398 | 25 | 2010-07-09T20:40:26Z | 3,216,416 | 7 | 2010-07-09T20:44:00Z | [
"python",
"sorting"
] | How can I sort a list by a key described by an arbitrary function? For example, if I have:
```
mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
```
I'd like to sort "mylist" by the second element of each member, e.g.
```
sort(mylist, key=lambda x: x[1])
```
how can I do this? | You have two options, very close to what you described, actually:
```
mylist.sort(key=lambda x: x[1]) # In place sort
new_list = sorted(mylist, key=lambda x: x[1])
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.