content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Copying files with unicode names
this was supposed to be a simple script
import shutil
files = os.listdir("C:\\")
for efile in files:
shutil.copy(efile, "D:\\")
It worked fine, until i tried it on a pc with files named with unicode characters!
python just converted these characters into question marks "????"... | Copying files with unicode names | this was supposed to be a simple script
import shutil
files = os.listdir("C:\\")
for efile in files:
shutil.copy(efile, "D:\\")
It worked fine, until i tried it on a pc with files named with unicode characters!
python just converted these characters into question marks "????" when getting the list from os.listdir... | [
"You need to use Unicode to access filenames which aren't in the ACP (ANSI codepage) of the Windows system you're running on. To do that, make sure you name directories as Unicode:\nimport shutil\n\nfiles = os.listdir(u\"C:\\\\\")\nfor efile in files:\n shutil.copy(efile, u\"D:\\\\\")\n\nPassing a Unicode strin... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004173477_python.txt |
Q:
wxPython: how to listen to EVT_KEY_DOWN on SearchCtrl?
In my application I want a search box, probably like the one provided by wx.SearchCtrl, with the search button and the cancel button included. I also want to know when the user presses Up or Down, so that I can browse through the search results. When I make a ... | wxPython: how to listen to EVT_KEY_DOWN on SearchCtrl? | In my application I want a search box, probably like the one provided by wx.SearchCtrl, with the search button and the cancel button included. I also want to know when the user presses Up or Down, so that I can browse through the search results. When I make a demo with wx.TextCtrl I can bind the event like this
self.te... | [
"A workaround seems to be using EVT_KEY_UP, i.e\nself.textbox.Bind(wx.EVT_KEY_UP, self.OnKeyUp, self.textbox)\n\nHowever, this way the key press is not repeatable (you have to release the key in order for the event to be fired). I'm still looking for better ways.\n",
"Use a different event, as per the docs.\nself... | [
1,
0
] | [] | [] | [
"python",
"search_box",
"wxpython"
] | stackoverflow_0004156329_python_search_box_wxpython.txt |
Q:
What abut this crazy sequence of loops and ifs? Ideas to improve this code?
This code is currently working, but it looks terrible - and probably can be much improved in terms of performance.
Any Suggestions?
def OnClick():
global Selection, touch, set_elsb, set_vreg, set_els, BAR_Items
A = viz.pick(0, viz.... | What abut this crazy sequence of loops and ifs? Ideas to improve this code? | This code is currently working, but it looks terrible - and probably can be much improved in terms of performance.
Any Suggestions?
def OnClick():
global Selection, touch, set_elsb, set_vreg, set_els, BAR_Items
A = viz.pick(0, viz.WORLD, all=False)
if touch != A: return
for i in BAR_Items:
if no... | [
"My normal approach to this would be to re-factor some of it out into small methods. This generally makes it more testable and easier to read.\n",
"It's a few more lines of code but I think it's clearer. \ndef OnClick():\n if not set_els: return\n\n # swap this with the line above if viz.pick has side eff... | [
1,
1,
0,
0
] | [] | [] | [
"if_statement",
"loops",
"optimization",
"python"
] | stackoverflow_0004170806_if_statement_loops_optimization_python.txt |
Q:
How to save pictures to document with Python win32com
I am making html to doc converter
from win32com.client import Dispatch
wrd=Dispatch('Word.Application')
doc=wrd.Documents.Open(inputfile)
doc.SaveAs(outputfile, FileFormat=0)
doc.Close
And I wand save picture to document: Prepare->Edit links t... | How to save pictures to document with Python win32com | I am making html to doc converter
from win32com.client import Dispatch
wrd=Dispatch('Word.Application')
doc=wrd.Documents.Open(inputfile)
doc.SaveAs(outputfile, FileFormat=0)
doc.Close
And I wand save picture to document: Prepare->Edit links to file->Save picture to document
What command I need?
htt... | [
"I believe you are looking for the AddPicture method in the InlineShapes collection.\n\nFileName\n\nRequired String. The path and file name of the picture.\nLinkToFile\n\nOptional Object. True to link the picture to the file from which it\n was created. False to make the picture\n an independent copy of the file.... | [
1
] | [] | [] | [
"ms_word",
"python",
"win32com"
] | stackoverflow_0004172337_ms_word_python_win32com.txt |
Q:
python easy_install failed because of wrong setuptools version
I tried to a library via easy_install like following:
$ sudo easy_install bbfreeze
Searching for bbfreeze
Reading http://pypi.python.org/simple/bbfreeze/
Reading http://systemexit.de/bbfreeze/
Best match: bbfreeze 0.97.2
Downloading http://pypi.python... | python easy_install failed because of wrong setuptools version | I tried to a library via easy_install like following:
$ sudo easy_install bbfreeze
Searching for bbfreeze
Reading http://pypi.python.org/simple/bbfreeze/
Reading http://systemexit.de/bbfreeze/
Best match: bbfreeze 0.97.2
Downloading http://pypi.python.org/packages/source/b/bbfreeze/bbfreeze-0.97.2.zip#md5=16e4981f4d8a... | [
"To use the newer version of setuptools, you need to use the newer version of easy_install installed by it. Note the line:\nInstalling easy_install script to /usr/local/bin\n\nTry this:\nsudo /usr/local/bin/easy_install bbfreeze\n\n"
] | [
2
] | [] | [] | [
"easy_install",
"python",
"setuptools"
] | stackoverflow_0004173354_easy_install_python_setuptools.txt |
Q:
Implementing Levenshtein distance in python
I have implemented the algorithm, but now I want to find the edit distance for the string which has the shortest edit distance to the others strings.
Here is the algorithm:
def lev(s1, s2):
return min(lev(a[1:], b[1:])+(a[0] != b[0]), lev(a[1:], b)+1, lev(a, b[1:])... | Implementing Levenshtein distance in python | I have implemented the algorithm, but now I want to find the edit distance for the string which has the shortest edit distance to the others strings.
Here is the algorithm:
def lev(s1, s2):
return min(lev(a[1:], b[1:])+(a[0] != b[0]), lev(a[1:], b)+1, lev(a, b[1:])+1)
| [
"Your \"implementation\" has several flaws:\n(1) It should start with def lev(a, b):, not def lev(s1, s2):. Please get into the good habits of (a) running your code before asking questions about it (b) quoting the code that you've actually run (by copy/paste, not by (error-prone) re-typing).\n(2) It has no terminat... | [
5,
0
] | [] | [] | [
"levenshtein_distance",
"python"
] | stackoverflow_0004173579_levenshtein_distance_python.txt |
Q:
Accessing a child class from another child class inside parent class
I really didn't know what title I should choose. Anyway, I have code like this (this is fixtures):
from fixture import DataSet
class CategoryData(DataSet):
class cat1:
name = 'Category 1'
class cat2:
name = 'Category 2'
... | Accessing a child class from another child class inside parent class | I really didn't know what title I should choose. Anyway, I have code like this (this is fixtures):
from fixture import DataSet
class CategoryData(DataSet):
class cat1:
name = 'Category 1'
class cat2:
name = 'Category 2'
parent = cat1
The problem is I can't reference cat1 in cat2 like t... | [
"There are two problems here.\nFirst, Python doesn't do nested scoping like that for you. To access CategoryData.cat1, you need to spell it out.\nSecond, and a bigger issue, is that there's no way to access CategoryData from there: the class hasn't been defined yet, since you're in the middle of defining it. If y... | [
3,
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0004173839_pylons_python.txt |
Q:
how to handle '../' in python?
i need to strip ../something/ from a url
eg. strip ../first/ from ../first/bit/of/the/url.html where first can be anything.
what's the best way to achieve this?
thanks :)
A:
You can simply split the path twice at the official path separator (os.sep, and not '/') and take the last b... | how to handle '../' in python? | i need to strip ../something/ from a url
eg. strip ../first/ from ../first/bit/of/the/url.html where first can be anything.
what's the best way to achieve this?
thanks :)
| [
"You can simply split the path twice at the official path separator (os.sep, and not '/') and take the last bit:\n>>> s = \"../first/bit/of/the/path.html\"\n>>> s.split(os.sep, 2)[-1]\n'bit/of/the/path.html'\n\nThis is also more efficient than splitting the path completely and stringing it back together.\nNote that... | [
5,
1
] | [] | [] | [
"path",
"python",
"string",
"url"
] | stackoverflow_0004172856_path_python_string_url.txt |
Q:
Where can I find Python code examples, or tutorials, of social networking style functions/components?
I am looking for tutorials and/or examples of certain components of a social network web app that may include Python code examples of:
user account auto-gen function(database)
friend/follow function (Twitter/Face... | Where can I find Python code examples, or tutorials, of social networking style functions/components? | I am looking for tutorials and/or examples of certain components of a social network web app that may include Python code examples of:
user account auto-gen function(database)
friend/follow function (Twitter/Facebook style)
messaging/reply function (Twitter style)
live chat function (Facebook style)
blog function
publ... | [
"So you're not interested in a fixed solution but want to program it yourself, do I get that correctly? If not: Go with a fixed solution. This will be a lot of programming effort, and whatever you want to do afterwards, doing it in another framework than you intended will be a much smaller problem.\nBut if you're a... | [
5
] | [] | [] | [
"get_satisfaction",
"pylons",
"python",
"social_networking"
] | stackoverflow_0004173883_get_satisfaction_pylons_python_social_networking.txt |
Q:
A question about Python script!
m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
def main():
if '01' in m:
n = m.replace('01','Janauary')
print n
elif '02' in m:
n = m.replace('02','February')
print n
elif '03' in m:
n = m.replace('03','March')
p... | A question about Python script! | m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
def main():
if '01' in m:
n = m.replace('01','Janauary')
print n
elif '02' in m:
n = m.replace('02','February')
print n
elif '03' in m:
n = m.replace('03','March')
print n
elif '04' in m:
n ... | [
"Please don't do it this way; it's already wrong, and can't be fixed without a lot of work. Use datetime.strptime() to turn it into a datetime, and then datetime.strftime() to output it in the correct format.\n",
"Take advantage of the datetime module:\nm = raw_input('Please enter a date(format:mm/dd/yyyy)')\n\n#... | [
11,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004174228_python.txt |
Q:
How to install python2.5.5 in Ubuntu10.10 with all libs bundled
I want to install python2.5.5 in Ubuntu10.10, since Ubuntu10.10 now just supports python>=2.6, so I download source file from python website and try to install it use
./configure && make && sudo make install, it seems that python2.5.5 has been instal... | How to install python2.5.5 in Ubuntu10.10 with all libs bundled | I want to install python2.5.5 in Ubuntu10.10, since Ubuntu10.10 now just supports python>=2.6, so I download source file from python website and try to install it use
./configure && make && sudo make install, it seems that python2.5.5 has been installed successfully, but when I want to use it, sometimes it says "no mo... | [
"Consider using Felix Krull's PPA which has pre-built Python 2.5 packages for Ubuntu.\n",
"You probably missing some libraries that are not bundled by default on Ubuntu with Python (I have no idea why they decided to split \"core\" python this way).\nYou can try running apt-get build-dep python python-dev and bui... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"ubuntu_10.04"
] | stackoverflow_0004173674_python_ubuntu_10.04.txt |
Q:
String coverage optimization in Python
I have this initial string.
'bananaappleorangestrawberryapplepear'
And also have a tuple with strings:
('apple', 'plepe', 'leoran', 'lemon')
I want a function so that from the initial string and the tuple with strings I obtain this:
'bananaxxxxxxxxxgestrawberryxxxxxxxar'
I... | String coverage optimization in Python | I have this initial string.
'bananaappleorangestrawberryapplepear'
And also have a tuple with strings:
('apple', 'plepe', 'leoran', 'lemon')
I want a function so that from the initial string and the tuple with strings I obtain this:
'bananaxxxxxxxxxgestrawberryxxxxxxxar'
I know how to do it imperatively by finding t... | [
"import re\n\nwords = ('apple', 'plepe', 'leoran', 'lemon')\ns = 'bananaappleorangestrawberryapplepear'\n\nx = set()\n\nfor w in words:\n for m in re.finditer(w, s):\n i = m.start()\n for j in range(i, i+len(w)):\n x.add(j)\n\nresult = ''.join(('x' if i in x else s[i]) for i in range(len... | [
3,
1,
1,
1,
0,
0
] | [] | [] | [
"functional_programming",
"optimization",
"python",
"python_itertools",
"string"
] | stackoverflow_0004173904_functional_programming_optimization_python_python_itertools_string.txt |
Q:
What does this Gtk error mean and how can I fix it?
**
Gtk:ERROR:/build/buildd/gtk+2.0-2.22.0/gtk/gtktoolbar.c:2248:logical_to_physical: assertion failed: (logical == 0)
Aborted
This is happening when I run code analogous to:
if condition:
self.insert(self.toolbutton, 0)
where self is an instance of a subcl... | What does this Gtk error mean and how can I fix it? | **
Gtk:ERROR:/build/buildd/gtk+2.0-2.22.0/gtk/gtktoolbar.c:2248:logical_to_physical: assertion failed: (logical == 0)
Aborted
This is happening when I run code analogous to:
if condition:
self.insert(self.toolbutton, 0)
where self is an instance of a subclass of gtk.Toolbar. The error only occurs when condition ... | [
"Is there an else, or elif clause, or is it just that single if clause that, when not satisfied, causes it to bomb out?\n",
"I discovered the cause of the problem. There was a number of similar statements. The problem was due to hard coding the index. Using this form:\nif condition:\n self.insert(self.toolbutt... | [
0,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004175035_gtk_pygtk_python.txt |
Q:
Calculating pi using a series in my book
I'm trying (yet again) to get better at programming, this time in python, and I've hit a roadblock. I've been trying to figure out why this doesn't work for a while now, so if I could have some help that would be really, really great. I have the instructions as a comment, b... | Calculating pi using a series in my book | I'm trying (yet again) to get better at programming, this time in python, and I've hit a roadblock. I've been trying to figure out why this doesn't work for a while now, so if I could have some help that would be really, really great. I have the instructions as a comment, but the series wouldn't copy to text, it's on w... | [
"Wrong starting point. Use sensible variable names (question says n, so use n, not p). Check upper bound ... to get n terms you need to do (n // 2) iterations, you are doing approx n iterations.\n>>> def pi(n):\n... tot = 0.0\n... for i in xrange(1, n * 4, 4):\n... tot += 4.0 / i - 4.0 / (i + 2)\n... ... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004175224_python.txt |
Q:
Mixing Python and PHP?
I have some Python scripts that I run on my desktop now for cutting up files. I want to put them on the web and write a simple front-end in PHP where a user uploads a file and it is passed as an argument to a python script on the web server and it is written out in chunks and the user can re... | Mixing Python and PHP? | I have some Python scripts that I run on my desktop now for cutting up files. I want to put them on the web and write a simple front-end in PHP where a user uploads a file and it is passed as an argument to a python script on the web server and it is written out in chunks and the user can re-download the chunks.
I know... | [
"\nFor http requests, you need to set your web server to hand over certain request to PHP and others to Python. From within PHP's scripts, if you need to call some Python executable scripts, use one of PHP's shell functions. e.g. exec()\nYes it is possible. The djangobook is a nice tutorial that covers this in one ... | [
10
] | [] | [] | [
"apache",
"php",
"python"
] | stackoverflow_0004175419_apache_php_python.txt |
Q:
Relative imports in Python
Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work.
My directory structure currently looks like this
src/
__init__.py
main.py
components/
... | Relative imports in Python | Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work.
My directory structure currently looks like this
src/
__init__.py
main.py
components/
__init__.py
expander.... | [
"Nevermind, I solved it:\nsrc/\n main.py\n mod/\n __init__.py\n components/\n __init__.py\n expander.py\n language_id.py\n utilities/\n __init__.py\n functions.py\n\nmain.py then refers to the subpackages as:\nfrom mod.components.expa... | [
21
] | [] | [] | [
"python",
"python_packaging"
] | stackoverflow_0004175534_python_python_packaging.txt |
Q:
Errors with python-openid and Google Apps Federated Login
UPDATE
I managed to get it working although I'm not quite sure why ;) It seems like python-openid uses a POST-request to issue the openid mode=associate and for some reason Google doesn't like that. When I patched python-openid to use a GET-request instead ... | Errors with python-openid and Google Apps Federated Login | UPDATE
I managed to get it working although I'm not quite sure why ;) It seems like python-openid uses a POST-request to issue the openid mode=associate and for some reason Google doesn't like that. When I patched python-openid to use a GET-request instead everything worked fine. I'll continue my investigation and upda... | [
"Okay. I don't have an Apps account so I can't test logging in, but I can successfully associate with an apps domain with python-openid 2.2.4. Here's a little debugging tool for making association requests: http://gist.github.com/288560\nYour patch should not have fixed things; associate requests are always POSTs... | [
2,
0
] | [] | [] | [
"google_apps",
"openid",
"python",
"python_openid",
"trac"
] | stackoverflow_0002148267_google_apps_openid_python_python_openid_trac.txt |
Q:
Using arguments in Python functions
I'm aware of mutuable vs immutable arguments in Python, and which is which, but here is a weird issue I ran into with mutable arguments. The simplified version is as follows:
def fun1a(tmp):
tmp.append(3)
tmp.append(2)
tmp.append(1)
return True
def fun1(a):
... | Using arguments in Python functions | I'm aware of mutuable vs immutable arguments in Python, and which is which, but here is a weird issue I ran into with mutable arguments. The simplified version is as follows:
def fun1a(tmp):
tmp.append(3)
tmp.append(2)
tmp.append(1)
return True
def fun1(a):
b = fun1a(a)
print a #prints [3,2,1]
... | [
"This isn't so much of a mutable/immutable issue as one of scope.\n\"b\" exists only in fun1 and fun2 bodies. It is not present in the main or global scope (at least intentionally)\n--EDIT--\n>>> def fun1(b):\n... b = b + 1\n... return b\n... \n>>> def fun2(a):\n... b = 1\n... return b\n... \n>>> f... | [
3,
1
] | [
"The problem may be related to the difference between lists and tuples. In fun2, don't put brackets around a,b.\nIn fun2a, return a tuple of the two objects and not a list. Python should write the varaibles correctly, if that's the problem that you're trying to solve.\nAlso, you called fun2 with argument b when b w... | [
-1
] | [
"python"
] | stackoverflow_0004175585_python.txt |
Q:
python: Is this a wrong way to remove an element from a dict?
I use this way to remove an emelment from a dict:
d["ele"] = data
...
d["ele"] = None
I think by this I can remove the reference on the original element so that the removed data can be freed, no memory leak.
Is it the right way to do this?
A:
... | python: Is this a wrong way to remove an element from a dict? | I use this way to remove an emelment from a dict:
d["ele"] = data
...
d["ele"] = None
I think by this I can remove the reference on the original element so that the removed data can be freed, no memory leak.
Is it the right way to do this?
| [
"You remove an element from a dictionary using del:\n>>> d={}\n>>> d['asdf']=3\n>>> d['ele']=90\n>>> d\n{'asdf': 3, 'ele': 90}\n>>> d['ele']=None\n>>> d\n{'asdf': 3, 'ele': None}\n>>> del d['ele']\n>>> d\n{'asdf': 3}\n>>> \n\n",
"That does not remove the key, just the value.\ndel d['ele']\n\n"
] | [
11,
3
] | [] | [] | [
"python"
] | stackoverflow_0004175686_python.txt |
Q:
Most efficient way to sort a Django QuerySet based on a form value
Working on a project with another fella. This is some code I wrote in view.py to sort a QuerySet based on some form data:
# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)
# Gather stops
stops = Stops.approv... | Most efficient way to sort a Django QuerySet based on a form value | Working on a project with another fella. This is some code I wrote in view.py to sort a QuerySet based on some form data:
# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)
# Gather stops
stops = Stops.approved_objects.filter(**query_attributes)
# Do neccessary sorting
if sort_b... | [
"Unnecessary optimization. Besides:\n# settings.py\nSORTS = {SORT_BY_PRICE: 'price'}\nDEFAULT_SORT = 'last_visited'\n\n# whatever.py\nsort_field = settings.SORTS.get(sort_by, settings.DEFAULT_SORT)\n\nstops = Stops.approved_objects.filter(**query_attributes).order_by(sort_field)\n\nThat's what you should be doing ;... | [
1,
1
] | [] | [] | [
"django_queryset",
"python"
] | stackoverflow_0004175643_django_queryset_python.txt |
Q:
Sorting a Django QuerySet by a property (not a field) of the Model
Some code and my goal
My (simplified) model:
class Stop(models.Model):
EXPRESS_STOP = 0
LOCAL_STOP = 1
STOP_TYPES = (
(EXPRESS_STOP, 'Express stop'),
(LOCAL_STOP, 'Local stop'),
)
name = models.CharField(max_... | Sorting a Django QuerySet by a property (not a field) of the Model | Some code and my goal
My (simplified) model:
class Stop(models.Model):
EXPRESS_STOP = 0
LOCAL_STOP = 1
STOP_TYPES = (
(EXPRESS_STOP, 'Express stop'),
(LOCAL_STOP, 'Local stop'),
)
name = models.CharField(max_length=32)
type = models.PositiveSmallIntegerField(choices=STOP_TYPE... | [
"Use QuerySet.extra() along with CASE ... END to define a new field, and sort on that.\nStops.objects.extra(select={'cost': 'CASE WHEN price=0 THEN 0 '\n 'WHEN type=:EXPRESS_STOP THEN price/2 WHEN type=:LOCAL_STOP THEN price*2'},\n order_by=['cost'])\n\nThat, or cast the QuerySet returned from the rest to a list,... | [
17
] | [] | [] | [
"django_models",
"django_templates",
"python"
] | stackoverflow_0004175749_django_models_django_templates_python.txt |
Q:
How to redirect python runtime errors?
I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit.
Is it possible for me to redirect such runtime error to a log file?
A:
It looks like you are ... | How to redirect python runtime errors? | I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit.
Is it possible for me to redirect such runtime error to a log file?
| [
"It looks like you are asking two questions.\nTo prevent your process from exiting on errors, you need to catch all exceptions that are raised using try...except...finally.\nYou also wish to redirect all output to a log. Happily, Python provides a comprehensive logging module for your convenience.\nAn example, for ... | [
5,
2
] | [] | [] | [
"error_logging",
"python"
] | stackoverflow_0004175697_error_logging_python.txt |
Q:
Outputting Tabs with Django
I'm trying to output lines from a .cpp file to a template in Django. I pass the lines in a tuple called file, and output it one line at a time.
{% for line in file %}
{{line}}<br />
{% endfor %}
Everything is very nicely autoescaped in the line, so that it is displayed correctly (like... | Outputting Tabs with Django | I'm trying to output lines from a .cpp file to a template in Django. I pass the lines in a tuple called file, and output it one line at a time.
{% for line in file %}
{{line}}<br />
{% endfor %}
Everything is very nicely autoescaped in the line, so that it is displayed correctly (like < and "), except for the \t char... | [
"Use u'\\xa0' instead.\nu'''def foo():\n\\xa0\\xa0return 42'''\n\n"
] | [
4
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0004176055_django_html_python.txt |
Q:
PyQT4: Drag and drop files into QListWidget
I've been coding a OCR book scanning thing (it renames pages by reading the page number), and have switched to a GUI from my basic CLI Python script.
I'm using PyQT4 and looked at a ton of documents on drag and drop, but no luck. It just refuses to take those files! I wa... | PyQT4: Drag and drop files into QListWidget | I've been coding a OCR book scanning thing (it renames pages by reading the page number), and have switched to a GUI from my basic CLI Python script.
I'm using PyQT4 and looked at a ton of documents on drag and drop, but no luck. It just refuses to take those files! I was using these to articles for my UI design:
http... | [
"The code you're using as an example seem to work fine and looks quite clean. According to your comment your list widget is not getting initialized; this should be the root cause of your issue. I've simplified your code a bit a tried it on my Ubuntu 10.04LTS and it worked fine. My code is listed below, see if it wo... | [
18
] | [] | [] | [
"drag_and_drop",
"pyqt",
"python"
] | stackoverflow_0004151637_drag_and_drop_pyqt_python.txt |
Q:
Turbogears tutorials , debugging tools
I successfully installed turbogears via virtualenv on ubuntu , loaded it with paster after quickstart. I was looking for a good ide with debugging for turbogears and paster. I need any good suggestion how to continue with , any good tutorials , links etc , ide information wou... | Turbogears tutorials , debugging tools | I successfully installed turbogears via virtualenv on ubuntu , loaded it with paster after quickstart. I was looking for a good ide with debugging for turbogears and paster. I need any good suggestion how to continue with , any good tutorials , links etc , ide information would be greatly appreciated.
Thank you for yo... | [
"Pydev - Eclipse can be setup for free and easy debugging\nhttp://pydev.blogspot.com/2006/07/configuring-pydev-to-work-with.html\n",
"I would checkout Wing IDE. The personal version runs 35 bucks.\n"
] | [
3,
1
] | [] | [] | [
"python",
"turbogears"
] | stackoverflow_0004145580_python_turbogears.txt |
Q:
Django - django-reversion - not working in inheritance
I have created a common class with it's admin class which should be inherited by all of my models. My common admin class inherited the VersionAdmin
from reversion.admin import VersionAdmin
class CommonAdmin(VersionAdmin):
pass
The problem is that, the... | Django - django-reversion - not working in inheritance | I have created a common class with it's admin class which should be inherited by all of my models. My common admin class inherited the VersionAdmin
from reversion.admin import VersionAdmin
class CommonAdmin(VersionAdmin):
pass
The problem is that, the model admins which inherited CommonAdmin is not showing th... | [
"The following didn't run properly. It works fine now.\nmanage.py createinitialrevisions\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_reversion",
"python"
] | stackoverflow_0004176194_django_django_models_django_reversion_python.txt |
Q:
Google App Engine - Admin Section
I am writing a web application with Google App Engine in Python that enables users to read books. I'd like to enable only administrators to add information about books and the contents of book pages to the website.
When restricting access to certain pages with the app.yaml config... | Google App Engine - Admin Section | I am writing a web application with Google App Engine in Python that enables users to read books. I'd like to enable only administrators to add information about books and the contents of book pages to the website.
When restricting access to certain pages with the app.yaml configuration, such as below, is it necessary... | [
"You can also use is_current_user_admin inside your request-handling code to check programmatically. \n",
"You've essentially got two options... one is what you've already got, which is to keep all the admin pages under /admin and apply blanket security on that path, which is what Adam has done. \nThe other is to... | [
5,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004175100_google_app_engine_python.txt |
Q:
Error while executing "paster shell example.ini" in reddit.com
Friends!!! I am frustated since last five days working on implementing
reddit.com on a ubuntu 9.10 machine.
Yes, I know that reddit.com has been tested on ubuntu intrepid. But
now i want to install it on U9.10
I have installed postgresql database, cre... | Error while executing "paster shell example.ini" in reddit.com | Friends!!! I am frustated since last five days working on implementing
reddit.com on a ubuntu 9.10 machine.
Yes, I know that reddit.com has been tested on ubuntu intrepid. But
now i want to install it on U9.10
I have installed postgresql database, created user copied the files,
and installed all the dependencies.
Ever... | [
"Newer version of python-webhelpers doesn't have asset_tag.py, you need to install an older version (0.6.4) for Pylons 0.9.6:\nwget http://pypi.python.org/packages/source/W/WebHelpers/WebHelpers-0.6.4.tar.gz && tar -xf WebHelpers-0.6.4.tar.gz && cd WebHelpers-0.6.4 && python setup.py build && sudo python setup.py i... | [
4
] | [] | [] | [
"pylons",
"python",
"reddit",
"web_applications"
] | stackoverflow_0002302470_pylons_python_reddit_web_applications.txt |
Q:
Any push back like function in python?
Sorry guys!!! pardon me. I'm a beginner in Python. I am writing the following code:
for line in file:
if StartingMarker in line:
# Here: I want to push back 'line' back in 'file'
for nextline in file:
if EndingMarker in line:
# Do some Operation
print "Don... | Any push back like function in python? | Sorry guys!!! pardon me. I'm a beginner in Python. I am writing the following code:
for line in file:
if StartingMarker in line:
# Here: I want to push back 'line' back in 'file'
for nextline in file:
if EndingMarker in line:
# Do some Operation
print "Done"
How can I push 'line' back in 'file'?
Th... | [
"Don't push back, yield.\ndef starttoend(it):\n for line in it:\n if 'START' in line:\n yield line\n break\n for line in it:\n yield line\n if 'END' in line:\n break\n\nl = ['asd', 'zxc', 'START123', '456789', 'qwertyEND', 'fgh', 'cvb']\n\ni = iter(l)\nfor line in starttoend(i):\n print l... | [
5,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004176033_python.txt |
Q:
What is the best way to control Twisted's reactor so that it is nonblocking?
Instead of running reactor.run(), I'd like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with twisted?
A:
Yes. The best practic... | What is the best way to control Twisted's reactor so that it is nonblocking? | Instead of running reactor.run(), I'd like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with twisted?
| [
"Yes. The best practice is that this is a bad idea, and that you never really need to do it. It doesn't work with all reactors, and you certainly can't have two different libraries which want to do this.\nWhy do you need to maintain your own main loop? Chances are, it's something like \"I want to work with PyGam... | [
11
] | [] | [] | [
"nonblocking",
"python",
"twisted"
] | stackoverflow_0004176405_nonblocking_python_twisted.txt |
Q:
Problems outputting an image over http using Python
I'm trying to load an image file from my local disk and output it over http when the script is accessed on my webserver via cgi.
For example I want http://example.com/getimage.py?imageid=foo to return the corresponding image. Just opening the file and printing im... | Problems outputting an image over http using Python | I'm trying to load an image file from my local disk and output it over http when the script is accessed on my webserver via cgi.
For example I want http://example.com/getimage.py?imageid=foo to return the corresponding image. Just opening the file and printing imgfile.read() after the appropriate content headers, howev... | [
"You probably have to open() your image files in binary mode:\nimgfile = open(\"%s.png\" % imageid, \"rb\")\nprint imgfile.read()\n\n\nOn Windows, you need to explicitly make stdout binary:\nimport sys\nif sys.platform == \"win32\":\n import os, msvcrt\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n\nYou... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004176693_python.txt |
Q:
How can I serve unbuffered CGI content from Apache 2?
I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending... | How can I serve unbuffered CGI content from Apache 2? | I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending the response to the client. This is on a Linux server runn... | [
"Randal Schwartz's article Watching long processes through CGI explains a different (and IMHO, better) way of watching a long running process.\n",
"Flushing STDOUT can help. For example, the following Perl program should work as intended:\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nlocal $| = 1;\n\nprint \"... | [
4,
2,
2,
1
] | [] | [] | [
"apache2",
"cgi",
"perl",
"python"
] | stackoverflow_0001181135_apache2_cgi_perl_python.txt |
Q:
Is there any way to get a better terminal in emacs?
I'm using emacs for python, and I'd like to have a nice useable shell in emacs to run an interpreter alongside my editing.
Is there any better emacs shell package out there? The default shell is awful.
A:
You say "terminal" in the title and "shell" in the que... | Is there any way to get a better terminal in emacs? | I'm using emacs for python, and I'd like to have a nice useable shell in emacs to run an interpreter alongside my editing.
Is there any better emacs shell package out there? The default shell is awful.
| [
"You say \"terminal\" in the title and \"shell\" in the question, yet you refer to an interpreter. It's all rather confusing.\nIf you want a better Python interpreter than the standard (although I'd suggest you explore the features of python-mode first); check out ipython.el which will give you an IPython interfac... | [
10,
4,
2,
1
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0004174633_emacs_python.txt |
Q:
Is `extend` faster than `+=`?
In python, we can concatenate lists in two ways:
lst.extend(another_lst)
lst += another_lst
I thought extend would be faster than using +=, because it reuses the list instead of creating a new one using the other two.
But when I test it out with timeit, it turns out that += is faste... | Is `extend` faster than `+=`? | In python, we can concatenate lists in two ways:
lst.extend(another_lst)
lst += another_lst
I thought extend would be faster than using +=, because it reuses the list instead of creating a new one using the other two.
But when I test it out with timeit, it turns out that += is faster,
>>> timeit('l.extend(x)', 'l = r... | [
"EDIT: I've tested the performance and I can't replicate the differences to any significant level.\n\nHere's the bytecode -- thanks to @John Machin for pointing out inconsistencies.\n>>> import dis\n>>> l = [1,2,3]\n>>> m = [4,5,6]\n>>> def f1(l, m):\n... l.extend(m)\n...\n>>> def f2(l,m):\n... l += m\n...\... | [
18
] | [] | [] | [
"list",
"performance",
"python"
] | stackoverflow_0004176980_list_performance_python.txt |
Q:
Can Java handle an Expando?
I'll synchronize the data from Google Contacts with a datastore in App Engine... i'm doing this in Python, and the datastore will be read later by a Java GAE instance.
Using Expando felt natural, but i'm not sure if the Java instance is going to be able to read it properly.
If the answ... | Can Java handle an Expando? | I'll synchronize the data from Google Contacts with a datastore in App Engine... i'm doing this in Python, and the datastore will be read later by a Java GAE instance.
Using Expando felt natural, but i'm not sure if the Java instance is going to be able to read it properly.
If the answer is 'no, Java won't read it', w... | [
"Edit: Once an Expando is compiled into a class file Java should be able to handle it... after all every Groovy object is an extension of the regular java Object class.\nCheck out this tutorial discussing mixing Groovy and Java for the gritty details.\n"
] | [
1
] | [] | [] | [
"expando",
"google_app_engine",
"google_cloud_datastore",
"java",
"python"
] | stackoverflow_0004175539_expando_google_app_engine_google_cloud_datastore_java_python.txt |
Q:
Extract audio from a video stream in python
Is there an easy way to do that? I'm tempted to call ffmpeg, but it sounds like a bad idea.
A:
Generally no. But it can be done with GStreamer.
| Extract audio from a video stream in python | Is there an easy way to do that? I'm tempted to call ffmpeg, but it sounds like a bad idea.
| [
"Generally no. But it can be done with GStreamer.\n"
] | [
3
] | [] | [] | [
"audio",
"python",
"video"
] | stackoverflow_0004176937_audio_python_video.txt |
Q:
Is serialization a must in order to transfer data across the wire?
Below is something I read and was wondering if the statement is true.
Serialization is the process of
converting a data structure or object
into a sequence of bits so that it can
be stored in a file or memory buffer,
or transmitted across ... | Is serialization a must in order to transfer data across the wire? | Below is something I read and was wondering if the statement is true.
Serialization is the process of
converting a data structure or object
into a sequence of bits so that it can
be stored in a file or memory buffer,
or transmitted across a network
connection link to be "resurrected"
later in the same or a... | [
"Serialization is just a fancy way of describing what you do when you want a certain data structure, class, etc to be transmitted.\nFor example, say I have a structure:\nstruct Color\n{\n int R, G, B;\n};\n\nWhen you transmit this over a network you don't say send Color. You create a line of bits and send it. I ... | [
8,
4,
3,
3,
2,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"c",
"c#",
"java",
"python"
] | stackoverflow_0004176087_c_c#_java_python.txt |
Q:
Any downside to overriding ConfigParser get() method to include an eval?
I'm creating a subclass of ConfigParser that is easier for me to use throughout my project:
class MyConfiguration(ConfigParser.ConfigParser):
def __init__(self, filename):
ConfigParser.ConfigParser.__init__(self)
self.rea... | Any downside to overriding ConfigParser get() method to include an eval? | I'm creating a subclass of ConfigParser that is easier for me to use throughout my project:
class MyConfiguration(ConfigParser.ConfigParser):
def __init__(self, filename):
ConfigParser.ConfigParser.__init__(self)
self.readfp(open(filename))
def get(self, section, option):
return eval(C... | [
"I am not sure if it is a good idea to eval an arbitary text that may be contained in the config file. A normal call to eval is usually considered unsafe.\nSee:\n\nSecurity of Python's eval() on untrusted strings?\nUse of eval in Python?\n\nIf you want to use python data types, then it is much better to store it as... | [
1,
1
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0004177734_configparser_python.txt |
Q:
Calling an inherited property in python
Possible Duplicate:
Polymorphism in Python
Hi
I'm trying to call a property in a class, that is inherited from my baseclass, but it doesn't work. I guess I'm missing something, but what?
Here is my code:
class Produkt:
def __init__(self,pID,pProdNavn,pNetto):
self._... | Calling an inherited property in python |
Possible Duplicate:
Polymorphism in Python
Hi
I'm trying to call a property in a class, that is inherited from my baseclass, but it doesn't work. I guess I'm missing something, but what?
Here is my code:
class Produkt:
def __init__(self,pID,pProdNavn,pNetto):
self.__produktId = pID #atributt for produkt n... | [
"It works fine if you don't use double underscore in attribute names\nclass Produkt:\n def __init__(self,pID,pProdNavn,pNetto):\n self.produktId = pID \n self.produktNavn = pProdNavn\n self.produktNetto = pNetto \n\n def getName(self): \n return self.__produktNavn\n\nclass Bok(Produkt):\n de... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0004177794_python.txt |
Q:
Using NLTK with Google App Engine
Is anyone using NLTK with GAE? From this thread it appears that GAE does not support NLTK (Special installation tricks needed.) Do you know any other lightweight similar Python module? Thanks.
A:
GAE supports pretty much any "pure" Python modules which don't try to access files ... | Using NLTK with Google App Engine | Is anyone using NLTK with GAE? From this thread it appears that GAE does not support NLTK (Special installation tricks needed.) Do you know any other lightweight similar Python module? Thanks.
| [
"GAE supports pretty much any \"pure\" Python modules which don't try to access files or sockets or other system level utilities. The poster from your link was mostly just trying to minimize the number of modules they included. They expressed a trial and error approach to figuring out which NLTK modules would be ne... | [
3
] | [] | [] | [
"google_app_engine",
"nltk",
"python"
] | stackoverflow_0004176350_google_app_engine_nltk_python.txt |
Q:
Combined Event Handling of widgets in TKinter
I am making a GUI Program in Tkinter and am running into problems.What I want to do is draw 2 checkboxes and a button. According to the user input next steps should take place. A part of my code has been shown below :-
CheckVar1 = IntVar()
CheckVar2 = IntVar()
self.C1... | Combined Event Handling of widgets in TKinter | I am making a GUI Program in Tkinter and am running into problems.What I want to do is draw 2 checkboxes and a button. According to the user input next steps should take place. A part of my code has been shown below :-
CheckVar1 = IntVar()
CheckVar2 = IntVar()
self.C1 = Checkbutton(root, text = "C Classifier", variabl... | [
"You're passing the value of self.proceed(CheckVar1.get(),CheckVar2.get()) to the Button constructor, but presumably what you want is for command to be set to a function which will call self.proceed(CheckVar1.get(),CheckVar2.get()) and return a new, possibly different value every time the button is pressed. You ca... | [
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004174768_python_tkinter.txt |
Q:
I'm not being able to access some GData Contacts properties, such as gender
Here's the code:
def fetch_feed(self):
client = gdata.contacts.service.ContactsService()
client.ClientLogin(username, password) #Will change to AuthSub later.
query = gdata.contacts.service.ContactsQuery()
q... | I'm not being able to access some GData Contacts properties, such as gender | Here's the code:
def fetch_feed(self):
client = gdata.contacts.service.ContactsService()
client.ClientLogin(username, password) #Will change to AuthSub later.
query = gdata.contacts.service.ContactsQuery()
query.max_results = 3000
feed = client.GetContactsFeed(query.ToUri())
... | [
"You can try the V3 client\nclient = gdata.contacts.client.ContactsClient()\nclient.client_login(usr, passwd, \"myscript\")\nqry = gdata.contacts.client.ContactsQuery(max_results=3000)\nfeed = client.get_contacts(query=qry)\n\nfor entry in feed.entry:\n # do something with entry\n\n"
] | [
6
] | [] | [] | [
"gdata_api",
"google_app_engine",
"google_contacts_api",
"python"
] | stackoverflow_0004177339_gdata_api_google_app_engine_google_contacts_api_python.txt |
Q:
alternative for pyhook in linux?
i want to know whether there exists an alternative for pyhook(available for windows not on linux) for linux to hook messages.
A:
Haven't needed but I have seen
http://sourceforge.net/projects/pykeylogger/
| alternative for pyhook in linux? | i want to know whether there exists an alternative for pyhook(available for windows not on linux) for linux to hook messages.
| [
"Haven't needed but I have seen\nhttp://sourceforge.net/projects/pykeylogger/\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004178191_python.txt |
Q:
How do I use SSH proxy in mechanize module in python? (Is is possible to do so?)
I couldn't find useful info on SSH proxy setting in mechanize, so I wonder if I can just set the proxy like this:
br = mechanize.Browser()
br.set_proxies{“SSH": "11.11.11.11:22"}
Anybody knows? If this won't work, how do I make SSH ... | How do I use SSH proxy in mechanize module in python? (Is is possible to do so?) | I couldn't find useful info on SSH proxy setting in mechanize, so I wonder if I can just set the proxy like this:
br = mechanize.Browser()
br.set_proxies{“SSH": "11.11.11.11:22"}
Anybody knows? If this won't work, how do I make SSH proxy work with mechanize Browser?
Thanks
| [
"Hope I understood what you want here:\nYou can set up a proxy on machine B (http://sourceforge.net/projects/tinyproxy/ is tiny) and then do SSH forwarding. \nFrom machine A:\nssh -aNL 7777:localhost:8888 B\n\nwould establish a proxy on port 7777 on machine A that connects to port 8888 on machine B. If machine B ha... | [
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0004178262_mechanize_python.txt |
Q:
Datetime and utctimetuple()
In this code mDATE0 for 3 items a, b, z is:
mUNIQUE: z | mDATE0: 2010-11-14 14:55:04.293000
mUNIQUE: b | mDATE0: 2010-11-14 14:53:34.824000
mUNIQUE: a | mDATE0: 2010-11-14 14:50:14.155000
But when I do
...
utc_tuple = rep.mDATE0.utctimetuple()
...
corresponding utc_tuples are:
utc_tup... | Datetime and utctimetuple() | In this code mDATE0 for 3 items a, b, z is:
mUNIQUE: z | mDATE0: 2010-11-14 14:55:04.293000
mUNIQUE: b | mDATE0: 2010-11-14 14:53:34.824000
mUNIQUE: a | mDATE0: 2010-11-14 14:50:14.155000
But when I do
...
utc_tuple = rep.mDATE0.utctimetuple()
...
corresponding utc_tuples are:
utc_tuple: time.struct_time(tm_hour=14, ... | [
"That isn't code! Please post short, complete example code to illustrate a problem. Below is what I think you are trying to do, but without seeing your code, there is no way for anyone to point your bug.\nfrom datetime import datetime\n# build up some datetime objects.\nz = datetime.strptime('2010-11-14 14:55:04.... | [
3
] | [] | [] | [
"datetime",
"google_app_engine",
"python"
] | stackoverflow_0004178125_datetime_google_app_engine_python.txt |
Q:
Python lambda optimization
I've just been learning lambda (About time) and I've figured some things out, I get the general idea.
I have a map() with a lambda here that can surely be made shorter, but I don't know how:
map(lambda x: [ x.split()[0], x.split()[2], x.split()[4] ] , y)
I hoped it would be possible to ... | Python lambda optimization | I've just been learning lambda (About time) and I've figured some things out, I get the general idea.
I have a map() with a lambda here that can surely be made shorter, but I don't know how:
map(lambda x: [ x.split()[0], x.split()[2], x.split()[4] ] , y)
I hoped it would be possible to get the 0, 2 and 4 elements of t... | [
"lambda x: operator.itemgetter(0, 2, 4)(x.split())\n\n",
"map(lambda x: x.split()[0:5:2] , y)\nMeaning - take x.split() and take the sublist [0:5] with each second item in it.\n",
"Just for variety's sake, featuring no itemgetter() call:\n map(lambda x: [x[i] for i in (0,2,4)], (s.split() for s in y))\n\nThe... | [
6,
4,
1
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0004177629_lambda_python.txt |
Q:
Python: memory usage statistics per object-types (or source code line)
I am doing some heavy calculations with Python (using OpenCV and Numpy) and in the end, I end up with a lot of memory usage (>1GB) whereby all refs should be gone and I only have the end-result (which should not be more than a few MB).
To debug... | Python: memory usage statistics per object-types (or source code line) | I am doing some heavy calculations with Python (using OpenCV and Numpy) and in the end, I end up with a lot of memory usage (>1GB) whereby all refs should be gone and I only have the end-result (which should not be more than a few MB).
To debug this, it would be nice if I could get some stats somehow which show me how ... | [
"I think you're searching for a python profiler ; \nyou have a bunch of them that you can use , like Heapy, profile or cprofile , Pysize ...\nexample using Heapy :\nyou have to include this snippet somewhere in your code:\nfrom guppy import hpy\nh = hpy()\nprint h.heap()\n\nand it will give you as output:\nPartitio... | [
11,
7
] | [] | [] | [
"debugging",
"memory",
"memory_leaks",
"python"
] | stackoverflow_0004178116_debugging_memory_memory_leaks_python.txt |
Q:
Which opensource web framework should a C# ASP.NET Guy Learn?
I am a web developer working mainly with C# on ASP.NET (Webforms and MVC)..
I have worked previously with PHP and Other Frameworks and languages of the sort..
I am currently looking and focusing all my development on 2 platforms..
One Proprietary and In... | Which opensource web framework should a C# ASP.NET Guy Learn? | I am a web developer working mainly with C# on ASP.NET (Webforms and MVC)..
I have worked previously with PHP and Other Frameworks and languages of the sort..
I am currently looking and focusing all my development on 2 platforms..
One Proprietary and Industry Class Framework (ASP.NET MVC)
and
One Opensource and Free Fr... | [
"I've been learning rails and loving it. The pain point with it is the documentation - version 3 of rails has just come out, and not all of the documentation you will come across will be up to date. However, you can pretty easily get by.\nThat said, I'm loving it. Ruby is a very elegant language. You can get a feel... | [
2,
2,
2,
1,
0
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0004175611_django_python_ruby_ruby_on_rails.txt |
Q:
OpenGL: Model doesn't look right when loaded in python
I have a blender model and below is a image of how my model renders when I load it into python. It looks like the normals are all messed up. I am using the correct normal for each vertex. I'm exporting them in the correct order. I test this in the blender cons... | OpenGL: Model doesn't look right when loaded in python | I have a blender model and below is a image of how my model renders when I load it into python. It looks like the normals are all messed up. I am using the correct normal for each vertex. I'm exporting them in the correct order. I test this in the blender console that the actual export file had the right data.
I know ... | [
"Right now you are specifying the normal after the vertex instead of before, so basically you're specifying the normal of vertex X for the vertex X+1. This is the most important flaw in the current code.\nAlso, what's that calculateVertexIntensity? First of all, lighting is enabled in your code so glColor is going ... | [
6,
0
] | [] | [] | [
"opengl",
"pyglet",
"python"
] | stackoverflow_0004178258_opengl_pyglet_python.txt |
Q:
wx Text with outline
I have a video player written in wxpython and am overlaying the current FPS onto the video.
My text is black, so if the video is sufficiently dark the FPS counter is not visible.
I am looking for a way to draw text with an outline so it will stand out no matter what the video is displaying. E.... | wx Text with outline | I have a video player written in wxpython and am overlaying the current FPS onto the video.
My text is black, so if the video is sufficiently dark the FPS counter is not visible.
I am looking for a way to draw text with an outline so it will stand out no matter what the video is displaying. E.g. I want black text with ... | [
"You are out of luck for any nice built in solution along the lines of options in font selection or pairs of fonts, one to draw the outline, one to draw the interior.\nIf you are only showing frame per second values and only using digits 0..9 and '.' then use small bitmaps for the numbers created yourself in an ima... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003661054_python_wxpython.txt |
Q:
move_uploaded_file function equivalent in django
I would like to upload some files from form to cloud server without redirecting there. So I've found this tutorial with php/ajax but a function that is not present in django is used there - move_uploaded_file. How can I achieve the same with django ? Currently I'm u... | move_uploaded_file function equivalent in django | I would like to upload some files from form to cloud server without redirecting there. So I've found this tutorial with php/ajax but a function that is not present in django is used there - move_uploaded_file. How can I achieve the same with django ? Currently I'm using a part of django-filetransfers, but after submitt... | [
"The django-storages plug-in has features that allows you to automatically store uploaded content to the repository of your choice. It has an annoying need to be linked to your MEDIA_URL, but that's just code and you can work around it.\nSource code can be found here: Django storages.\nI recommend rooting around t... | [
0
] | [] | [] | [
"cloud_hosting",
"django",
"file_upload",
"python",
"redirect"
] | stackoverflow_0004174376_cloud_hosting_django_file_upload_python_redirect.txt |
Q:
python/pylons - multiple controllers for template
I have a main page in Python/Pylons project, which have multiple different blocks (e.g. news/demo/(registration|private zone)/...).
My thought is that each block should be generated in a separate controller.
How can I call another controller method in a main page c... | python/pylons - multiple controllers for template | I have a main page in Python/Pylons project, which have multiple different blocks (e.g. news/demo/(registration|private zone)/...).
My thought is that each block should be generated in a separate controller.
How can I call another controller method in a main page controller?
| [
"What you want to do is HMVC. I'm not sure it is easily doable out of the box with Pylons, since it's MVC.\nIf you have code that is repeated in multiple controllers, you could move some of this code out of the controller (in the models, or another module).\nAlso, if you are using Mako templates, you can reuse part... | [
1,
0
] | [] | [] | [
"model_view_controller",
"pylons",
"python"
] | stackoverflow_0004171842_model_view_controller_pylons_python.txt |
Q:
Why would I want to reference cursor.fetchall() if I can use cursor.execute directly?
Why would I want to reference cursor.fetchall() if I can use cursor.execute directly?a
Thanks
A:
Because cursor.execute() doesn't actually return the data. Presumably you need that, so you need to run fetchall.
| Why would I want to reference cursor.fetchall() if I can use cursor.execute directly? | Why would I want to reference cursor.fetchall() if I can use cursor.execute directly?a
Thanks
| [
"Because cursor.execute() doesn't actually return the data. Presumably you need that, so you need to run fetchall.\n"
] | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004178828_python_sqlite.txt |
Q:
Python: Problems adding items to list in a class
I've got a class defined with a method to add items to it:
class ProdReg:
def __init__(self):
self.__PListe=[]
def addProdukt(self,pItem):
self.__Pliste.append(pItem)
When I instantiate a ProdReg object and try to add an object to it with t... | Python: Problems adding items to list in a class | I've got a class defined with a method to add items to it:
class ProdReg:
def __init__(self):
self.__PListe=[]
def addProdukt(self,pItem):
self.__Pliste.append(pItem)
When I instantiate a ProdReg object and try to add an object to it with the following code i gent an error:
pr.addProdukt(b)
I... | [
"Because in the __init__ you wrote: __PListe and in the the addProdukt method, you wrote __Pliste. Python is case sensitive.\n",
"It's a typo in your code I think, or a misunderstand of how names work. In Python names are case-sensitive.\nYou add the attribute as PListe then reference it as Pliste. In one in th... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0004179062_python.txt |
Q:
Python Named Argument is Keyword?
So an optional parameter expected in the web POST request of an API I'm using is actually a reserved word in python too. So how do I name the param in my method call:
example.webrequest(x=1,y=1,z=1,from=1)
this fails with a syntax error due to 'from' being a keyword. How can I pa... | Python Named Argument is Keyword? | So an optional parameter expected in the web POST request of an API I'm using is actually a reserved word in python too. So how do I name the param in my method call:
example.webrequest(x=1,y=1,z=1,from=1)
this fails with a syntax error due to 'from' being a keyword. How can I pass this in in such a way that no syntax... | [
"Pass it as a dict.\nfunc(**{'as': 'foo', 'from': 'bar'})\n\n",
"args = {'x':1, 'y':1, 'z':1, 'from':1}\nexample.webrequest(**args)\n\n// dont use that library\n"
] | [
16,
2
] | [] | [] | [
"keyword",
"named_parameters",
"python",
"reserved_words"
] | stackoverflow_0004179175_keyword_named_parameters_python_reserved_words.txt |
Q:
Unable to print content of list in python
I've made a class containing a list, with the following code:
class ProdReg:
def __init__(self):
self.__Pliste=[]
This works perfectly.
I've also added a method to print the contents of my list:
def printProdReg(self):
for produkt in self.__Pliste:
prin... | Unable to print content of list in python | I've made a class containing a list, with the following code:
class ProdReg:
def __init__(self):
self.__Pliste=[]
This works perfectly.
I've also added a method to print the contents of my list:
def printProdReg(self):
for produkt in self.__Pliste:
print(produkt)
This doesn't work all to great, Whe... | [
"The call to print calls __str__ on your object, which by default prints the type and memory address. If you want a more readable representation of your object you need to give your class a new implementation of __str__.\nclass Bok(object):\n def __str__(self):\n return 'This is a Bok!'\n\n # Other ... | [
6,
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004179308_python.txt |
Q:
Passing Django template variables into javascript in GAE
I'm trying to create a wordcloud with the Google's visualization sample:
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/... | Passing Django template variables into javascript in GAE | I'm trying to create a wordcloud with the Google's visualization sample:
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/svn/trunk/wordcloud/wc.js"></script>
<script type="text/javasc... | [
"I would suggest making a number of changes to your code. Instead of generating javascript calls (data.setCell), generate the table and let Google's DataTable process it.\nimport os\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext.webapp... | [
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0004179338_django_google_app_engine_javascript_python.txt |
Q:
How to query a Django model defining a IP range with two int fields (IP, mask)
I have:
class Range(models.Model):
ip = models.IntegerField() # as produced by socket.inet_aton + struct.unpack
mask = models.IntegerField()
Given a certain IP, how can I get all the ranges that match this specific IP using the... | How to query a Django model defining a IP range with two int fields (IP, mask) | I have:
class Range(models.Model):
ip = models.IntegerField() # as produced by socket.inet_aton + struct.unpack
mask = models.IntegerField()
Given a certain IP, how can I get all the ranges that match this specific IP using the Django models?
If I were using raw SQL, I would use the database's bitwise operator... | [
"The QuerySet API in Django 1.0 now includes the 'extra' method, described here in the Django docs. The extra method allows you to pass custom WHERE clauses to your QuerySet, which should allow you to use the bitwise comparison you need.\n",
"To do faster query fitting the range you'd better store lower and upper... | [
4,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001610227_django_django_models_python.txt |
Q:
Suggestions for developing a threaded tcp based admin interface
I've built a very simple TCP server (in python) that when queried, returns various system level statistics of the host OS running said script.
As part of my experimentation and goal to gain knowledge of python and its available libraries; i would lik... | Suggestions for developing a threaded tcp based admin interface | I've built a very simple TCP server (in python) that when queried, returns various system level statistics of the host OS running said script.
As part of my experimentation and goal to gain knowledge of python and its available libraries; i would like to build on an administration interface that a) binds to a separate... | [
"python includes some multi-threading servers (SocketServer, BaseHTTPServer, xmlrpclib). You might want to look at Twisted as well, it is a powerful framework for networking.\n",
"Probably the easiest starting point would involve Python's xmlrpclib.\nRegarding threading, all threads can read all data in a Python ... | [
1,
0,
0
] | [] | [] | [
"admin_interface",
"multithreading",
"python",
"sockets"
] | stackoverflow_0004179077_admin_interface_multithreading_python_sockets.txt |
Q:
What is the proper python way to write methods that only take a particular type?
I have a function that is supposed to take a string, append things to it where necessary, and return the result.
My natural inclination is to just return the result, which involved string concatenation, and if it failed, let the exce... | What is the proper python way to write methods that only take a particular type? | I have a function that is supposed to take a string, append things to it where necessary, and return the result.
My natural inclination is to just return the result, which involved string concatenation, and if it failed, let the exception float up to the caller. However, this function has a default value, which I just... | [
"It's not necessary to do so, but if you want you can have your method raise a TypeError if you know that the object is of a type that you cannot handle. One reason to do this is to help people to understand why the method call is failing and to give them some help fixing it, rather than giving them obscure error f... | [
5,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004179831_python.txt |
Q:
Multiple frames in Tkinter while using Python
Hi I have been trying to get a simple GUI working which accepts a string using an entry form, included in the Tkinter module, and, depending on which container it is in, either runs "killall + string" or "open + string" through terminal. Below is my code that I am usin... | Multiple frames in Tkinter while using Python | Hi I have been trying to get a simple GUI working which accepts a string using an entry form, included in the Tkinter module, and, depending on which container it is in, either runs "killall + string" or "open + string" through terminal. Below is my code that I am using. The problem is in line 8 and the comments above... | [
"This is probably not the answer you are looking for, but I can make it do the right thing by getting rid of the class. Here is what I have:\nfrom tkinter import *\nimport os\nroot = Tk()\n\ndef buttonPressed():\n # this is the problem in the program.\n # it keeps returning [''] in the print statement and do... | [
0
] | [] | [] | [
"python",
"python_3.x",
"terminal",
"tkinter",
"user_interface"
] | stackoverflow_0004179044_python_python_3.x_terminal_tkinter_user_interface.txt |
Q:
Can I use Django's mail API in Google App Engine?
I'm using Django-nonrel for Google App Engine and I was wondering if it's possible to use Django's built-in mail API instead of GAE's mail API for sending mail. If it is, how do I do it?
Sorry if this seems like a noob question. I just started learning Django and G... | Can I use Django's mail API in Google App Engine? | I'm using Django-nonrel for Google App Engine and I was wondering if it's possible to use Django's built-in mail API instead of GAE's mail API for sending mail. If it is, how do I do it?
Sorry if this seems like a noob question. I just started learning Django and GAE recently and I can't work out this problem that I ha... | [
"Yes, djangoappengine has a mail backend for GAE and it's enabled by default in your settings.py via \"from djangoappengine.settings_base import *\". You can take a look at the settings_base module to see all backends and default settings.\n"
] | [
3
] | [] | [] | [
"django",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0004177907_django_django_nonrel_google_app_engine_python.txt |
Q:
Python script load testing web page
I want to do a test load for a web page. I want to do it in python with multiple threads.
First POST request would login user (set cookies).
Then I need to know how many users doing the same POST request simultaneously can server take.
So I'm thinking about spawning threads in w... | Python script load testing web page | I want to do a test load for a web page. I want to do it in python with multiple threads.
First POST request would login user (set cookies).
Then I need to know how many users doing the same POST request simultaneously can server take.
So I'm thinking about spawning threads in which requests would be made in loop.
I ha... | [
"cPython does not take advantage from multiple cores when running multiple threads. It means, that basically, You will only have one core doing the testing job.\nThere are dedicated tools to do what You want to do. Let me suggest two:\nFunkLoad is a functional and load web tester, written in Python, whose main use ... | [
6,
1
] | [] | [] | [
"load_testing",
"multithreading",
"python"
] | stackoverflow_0004179879_load_testing_multithreading_python.txt |
Q:
Django reverse lookup by ForeignKey
I have a django project which has two apps, one is AppA and AppB. Now AppA has a model
ModelA which is referenced by the model ModelB in AppB, using modelA = models.ForeignKey(ModelA, related_name='tricky')
Now in my view for AppA, when it shows ModelA, I do a get_object_or_404(... | Django reverse lookup by ForeignKey | I have a django project which has two apps, one is AppA and AppB. Now AppA has a model
ModelA which is referenced by the model ModelB in AppB, using modelA = models.ForeignKey(ModelA, related_name='tricky')
Now in my view for AppA, when it shows ModelA, I do a get_object_or_404(ModelA, pk=prim_id). Then I want to get a... | [
"If the ForeignKey is, as you describe in ModelB and you do mb = ModelB.objects.get(pk=prim_id) then the look up for the modela attribute is not a reverse lookup. you simply access the related object via mb.modela!\n"
] | [
5
] | [] | [] | [
"django",
"django_queryset",
"model",
"python"
] | stackoverflow_0004180120_django_django_queryset_model_python.txt |
Q:
Dynamic global variables assignment
I'm new in python and I'm having many troubles in using global instruction.
Here is a code example:
mouse = "a"
background = "b"
list_ab = [mouse, background]
def func ():
for item in list_ab:
global item # I want to modify the GLOBAL item, which is mouse
... | Dynamic global variables assignment | I'm new in python and I'm having many troubles in using global instruction.
Here is a code example:
mouse = "a"
background = "b"
list_ab = [mouse, background]
def func ():
for item in list_ab:
global item # I want to modify the GLOBAL item, which is mouse
# and background.
it... | [
"Your problem is that Python works not the way you think.\nSo I will try to explain what's going on in your code, line by line.\nmouse = \"a\"\n\nAssigns the string \"a\" to the name mouse.\nbackground = \"b\"\n\nAssigns the string \"b\" to the name background.\nlist_ab = [mouse, background]\n\nAssigns two objects,... | [
7,
5,
2,
2,
1,
0
] | [] | [] | [
"dynamic",
"global_variables",
"python",
"variable_assignment"
] | stackoverflow_0004180095_dynamic_global_variables_python_variable_assignment.txt |
Q:
Python classes - instances being overwritten?
When calling on a new instance of an object for a class I've created, my one instance of the class is just being overwritten. Why could this be? Example is below.
My class is defined as follows:
class my_class:
attribute = ""
examples = []
children = []
... | Python classes - instances being overwritten? | When calling on a new instance of an object for a class I've created, my one instance of the class is just being overwritten. Why could this be? Example is below.
My class is defined as follows:
class my_class:
attribute = ""
examples = []
children = []
d = {}
def __init__(self, attribute, e):
... | [
"I don't think you are doing with the initializations of attribute, examples, children and d what you think you are doing. Those are now attributes of the class, not of each instance. If you want each instance of the class to have its own attributes for attribute, examples, children and d, you should instead writ... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0004180505_python.txt |
Q:
Make a Python log file only when there are errors (using logging module)
I'd like to use the "logging" module in Python to write errors to a log file. However, I want the file to only be created when there are errors. I use the following code:
import logging
f = 'test.conf'
logger = logging.getLogger("test_logg... | Make a Python log file only when there are errors (using logging module) | I'd like to use the "logging" module in Python to write errors to a log file. However, I want the file to only be created when there are errors. I use the following code:
import logging
f = 'test.conf'
logger = logging.getLogger("test_logger")
logger.setLevel(logging.INFO)
ch_file = logging.FileHandler("test_logger... | [
"You're in luck. The FileHandler has a delay parameter designed for this purpose:\nch_file = logging.FileHandler(\"test_logger.conf\",delay=True)\n\n"
] | [
8
] | [] | [] | [
"error_logging",
"logging",
"python"
] | stackoverflow_0004180518_error_logging_logging_python.txt |
Q:
Do I use integer or float?
This is the model in Google App Engine:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mW... | Do I use integer or float? | This is the model in Google App Engine:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mWEIGHT = db.FloatProperty()
So, ... | [
"It looks like you are occasionally not setting mWEIGHT. How about changing\nfor result in RESULTS:\n self.response.out.write(\"mUNIQUE: <b>%s</b> | \"\n \"mWEIGHT: %f | \" \n \"mCOUNT: %s | <br />\" \n % (result.mUN... | [
1
] | [] | [] | [
"floating_point",
"google_app_engine",
"google_cloud_datastore",
"integer",
"python"
] | stackoverflow_0004180566_floating_point_google_app_engine_google_cloud_datastore_integer_python.txt |
Q:
Change Firefox Proxy settings from Python
Is there are way to change the Firefox Proxy settings from a Python script?
A:
Yes, you can edit the settings saved in the prefs.js file in the Firefox profile directory. Firefox has to be restarted for the settings to take effect, though.
This article details where the ... | Change Firefox Proxy settings from Python | Is there are way to change the Firefox Proxy settings from a Python script?
| [
"Yes, you can edit the settings saved in the prefs.js file in the Firefox profile directory. Firefox has to be restarted for the settings to take effect, though.\nThis article details where the profile is stored, depending on the operating system:\nhttp://support.mozilla.com/en-US/kb/profiles\n"
] | [
2
] | [] | [] | [
"configure",
"firefox",
"proxy",
"python",
"settings"
] | stackoverflow_0004180550_configure_firefox_proxy_python_settings.txt |
Q:
Python urllib2 sending POST data
I am attempting to send POST data using urllib, but the problem is normally you urlencode your dictionary of fields and then you send that along with your request. But some of my fields that I have to send to the server are named the exact same name, so using a dictionary I end up ... | Python urllib2 sending POST data | I am attempting to send POST data using urllib, but the problem is normally you urlencode your dictionary of fields and then you send that along with your request. But some of my fields that I have to send to the server are named the exact same name, so using a dictionary I end up deleting a lot of my data out of the d... | [
"urllib.urlencode() can take a list of tuples, allowing you to specify multiple values for a parameter:\n>>> urlencode([(\"var\", \"value\"), (\"var\", \"value2\")])\n'var=value&var=value2'\n\nOr use a map with lists as values:\n>>> p = {\"var\": [\"value\", \"value2\"], \"var2\": [\"yetanothervalue\"]}\n>>> urlenc... | [
6
] | [] | [] | [
"http",
"python"
] | stackoverflow_0004180584_http_python.txt |
Q:
How to enable/disable toolbar items?
How do you make a gtk.ToolButton disabled so that it is 'greyed out'? Like this:
How do you make it enabled again?
A:
Use the set_sensitive method. If all you need is to disable/enable the button, you should call the method on the button; the argument should be True for enab... | How to enable/disable toolbar items? | How do you make a gtk.ToolButton disabled so that it is 'greyed out'? Like this:
How do you make it enabled again?
| [
"Use the set_sensitive method. If all you need is to disable/enable the button, you should call the method on the button; the argument should be True for enabling and False for disabling:\nbutton.set_sensitive(True) # enables the button\nbutton.set_sensitive(False) # disables the button\nIf you are dealing wit... | [
13
] | [] | [] | [
"gtk",
"pygtk",
"python",
"toolbar"
] | stackoverflow_0004179910_gtk_pygtk_python_toolbar.txt |
Q:
Trying to update a 3D graphs coordinates with matplotlib
I have a function that will graph a 3D sphere with matplotlib in tkinter. However, every successive time I call the function the performance when orbiting the sphere drops. Also the graph only updates after I try to orbit the sphere.
self.A is a variable th... | Trying to update a 3D graphs coordinates with matplotlib | I have a function that will graph a 3D sphere with matplotlib in tkinter. However, every successive time I call the function the performance when orbiting the sphere drops. Also the graph only updates after I try to orbit the sphere.
self.A is a variable that adjusts the size of the sphere.
My function:
def draw_fig(... | [
"You should not regenerate each time all the data, but just modify your existing one.\nEdit: Just move out of the calling draw_fig the axes building code\ndef __init__...\n u = numpy.linspace(0, 2 * numpy.pi, 100)\n v = numpy.linspace(0, numpy.pi, 100)\n self.x = A * numpy.outer(numpy.cos(u), numpy.sin(... | [
4
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0004181097_matplotlib_python_tkinter.txt |
Q:
How can I parse html using lxml , python
I have some html file:
<html>
<body>
<span class="text">One</span>some text1</br>
<span class="cyrillic">Мир</span>some text2</br>
</body>
</html>
How can i get "some text1" and "some text2" using lxml with python?
A:
import lxml.html
doc = lxml.html.document_fr... | How can I parse html using lxml , python | I have some html file:
<html>
<body>
<span class="text">One</span>some text1</br>
<span class="cyrillic">Мир</span>some text2</br>
</body>
</html>
How can i get "some text1" and "some text2" using lxml with python?
| [
"import lxml.html\n\ndoc = lxml.html.document_fromstring(\"\"\"<html>\n <body>\n <span class=\"text\">One</span>some text1</br>\n <span class=\"cyrillic\">Мир</span>some text2</br>\n </body>\n</html>\n\"\"\")\n\ntxt1 = doc.xpath('/html/body/span[@class=\"text\"]/following-sibling::text()[1]')\ntxt2 = doc.xpath(... | [
6,
3
] | [] | [] | [
"lxml",
"parsing",
"python"
] | stackoverflow_0004180887_lxml_parsing_python.txt |
Q:
Best way to store a python time.struct_time in a mysql database
I am using python's feedparser module, to parse an RSS feed. Once parsed, feedparser returns dates in a python 9 tuple time format (time.struct_time).
I am want to store these values in my mysql database so I can later check the Last-Modified heade... | Best way to store a python time.struct_time in a mysql database | I am using python's feedparser module, to parse an RSS feed. Once parsed, feedparser returns dates in a python 9 tuple time format (time.struct_time).
I am want to store these values in my mysql database so I can later check the Last-Modified headers of the feed. It's import that if the times tuples are converted, ... | [
"Store the datetime as UTC in the database, along with the timezone. Convert back to a local time when pulling from the database if needed.\n",
"I believe the reason why your method is not preserving the time tuple is because the is_dst value was changed. time.mktime respected the is_dst in struct, but dt.timetup... | [
1,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004180280_mysql_python.txt |
Q:
Python: Organization of user-defined exceptions in a complete project
I have some questions about user-defined exceptions in Python and how they should be organized in a complete project.
I have a fairly complex python project with some sub-packages that has the following structure (__init__.py omitted):
/docs (Do... | Python: Organization of user-defined exceptions in a complete project | I have some questions about user-defined exceptions in Python and how they should be organized in a complete project.
I have a fairly complex python project with some sub-packages that has the following structure (__init__.py omitted):
/docs (Documentation)
/apidocs (generated API documentation)
/askindex (my applicati... | [
"In general I've found with my own work that when I want a custom type of exception, it's specific to a particular module or package. If it's relevant to a module, I put it just in that module. I haven't yet found a case where it would be neater to have a module or package dedicated to exceptions.\nExamples: if I h... | [
8
] | [] | [] | [
"exception",
"exception_handling",
"python"
] | stackoverflow_0004181708_exception_exception_handling_python.txt |
Q:
What will be the upgrade path to Python 3.x for Google App Engine Applications?
What is required to make the transition to Python 3.x for Google App Engine?
I know Google App Engine requires the use of at least Python 2.5.
Is it possible to use Python 3.0 already on Google App Engine?
A:
It is impossible to curr... | What will be the upgrade path to Python 3.x for Google App Engine Applications? | What is required to make the transition to Python 3.x for Google App Engine?
I know Google App Engine requires the use of at least Python 2.5.
Is it possible to use Python 3.0 already on Google App Engine?
| [
"It is impossible to currently use Python 3.x applications on Google App Engine. It's simply not supported, and I'd expect to see support for Java (or Perl, or PHP) before Python 3.x.\nThat said, the upgrade path is likely to be very simple from Python 2.5 to Python 3.x on App Engine. If/when the capability is ad... | [
5,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000625042_google_app_engine_python.txt |
Q:
Making Matplotlib run faster
Snippet:
ax = Axes3D(self.fig)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = self.prop * np.outer(np.cos(u), np.sin(v))
y = self.prop * np.outer(np.sin(u), np.sin(v))
z = self.prop * np.outer(np.ones(np.size(u)), np.cos(v))
t = ax.plot_surface(x, y, z, rstrid... | Making Matplotlib run faster | Snippet:
ax = Axes3D(self.fig)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = self.prop * np.outer(np.cos(u), np.sin(v))
y = self.prop * np.outer(np.sin(u), np.sin(v))
z = self.prop * np.outer(np.ones(np.size(u)), np.cos(v))
t = ax.plot_surface(x, y, z, rstride=6, cstride=6,color='lightgreen',... | [
"Really, the problem is more within plot_surface. There are a lot of things that can be done to improve it. For instance, the shading takes a lot of time and just by changing one line:\ncolors = [color * (0.5 + norm(v) * 0.5) for v in shade]\n\nto\ncolors = np.outer(0.5+norm(shade)*0.5,color)\n\nwithin one of the f... | [
13,
1,
0
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0004181294_matplotlib_python_tkinter.txt |
Q:
Making maps and pathfinding AI
I want to retrace maps from google earth these maps would then be used for calculating fastest route from A to B as well as location probability defined by some factors. How would i go about doing these? My first thought is pygame and using some already made ones or using them as a t... | Making maps and pathfinding AI | I want to retrace maps from google earth these maps would then be used for calculating fastest route from A to B as well as location probability defined by some factors. How would i go about doing these? My first thought is pygame and using some already made ones or using them as a template.
| [
"I've worked on a routing application for a while. The most common algorithm for this is to start on both ends (start and finish) and move towards each other, traversing all possible methods of travel. The branches that meet in the middle will be your ideal path.\nYou can weight things appropriately, like speed l... | [
4,
0
] | [] | [] | [
"path_finding",
"python"
] | stackoverflow_0004175287_path_finding_python.txt |
Q:
A trouble with python 'self' argument in functions
This is the code for a simple test:
class ECollector:
#error msg collector
#this class should be used as 'global'
msgs = []
def addmsg(self,msg):
self.msgs.append(msg)
def clear(self):
self.msgs = []
class test(ECollector):
... | A trouble with python 'self' argument in functions | This is the code for a simple test:
class ECollector:
#error msg collector
#this class should be used as 'global'
msgs = []
def addmsg(self,msg):
self.msgs.append(msg)
def clear(self):
self.msgs = []
class test(ECollector):
dcodes = []
ECollector
def new(self):
E... | [
"You have defined addmsg to be an instance method. You probably meant self.addmsg(\"test!\") instead of ECollector.addmsg(\"test!\").\n",
"There's lots of things that might be wrong with this. lets start at the top. It looks like you are really just using ECollector as a namespace to group some functions. That... | [
3,
2,
1
] | [] | [] | [
"arguments",
"function",
"python",
"python_3.x"
] | stackoverflow_0004182200_arguments_function_python_python_3.x.txt |
Q:
Python regular expression
str1 = abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>
We need the contents inside the h1 tag and h2 tag.
What is the best way to do that? Thanks
Thanks for the help!
A:
The best way if it needs to scale at all would be with something like BeautifulSoup.
>>> from... | Python regular expression | str1 = abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>
We need the contents inside the h1 tag and h2 tag.
What is the best way to do that? Thanks
Thanks for the help!
| [
"The best way if it needs to scale at all would be with something like BeautifulSoup.\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('abdk3<h1>The content we need</h1>aaaaabbb<h2>The content we need2</h2>')\n>>> soup.h1\n<h1>The content we need</h1>\n>>> soup.h1.text\nu'The content we need'\... | [
6,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004182331_python_regex.txt |
Q:
ld can't link with a main executable
On OSX 10.6.4 with i686-apple-darwin10-g++-4.2.1 compiling using TextMate and a Makefile which in the first place has been made für a Linux and I am trying to translate for OSX.
When compiling a c++ project I get the "can't link with a main executable" error:
g++ -Wall -g -I ~... | ld can't link with a main executable | On OSX 10.6.4 with i686-apple-darwin10-g++-4.2.1 compiling using TextMate and a Makefile which in the first place has been made für a Linux and I am trying to translate for OSX.
When compiling a c++ project I get the "can't link with a main executable" error:
g++ -Wall -g -I ~/svnX-Repository/axp-Projekte/xrlfupa/trun... | [
"The error message is telling you the problem—it is that /usr/local/lib/libxrlTUB.so is not a shared library; it's an executable. You can't link against an executable. Probably whatever build process you used for libxrlTUB.so didn't understand how to build shared libraries on the Mac (it's more suspect because .d... | [
3
] | [] | [] | [
"c++",
"linker",
"macos",
"python",
"swig"
] | stackoverflow_0004179804_c++_linker_macos_python_swig.txt |
Q:
Formatting data quantity/capacity as string
A common task in many programs is converting a byte count (such as from a drive capacity or file size), into a more human readable form. Consider 150000000000 bytes as being more readable as "150 GB", or "139.7 GiB".
Are there any libraries that contain functionality to ... | Formatting data quantity/capacity as string | A common task in many programs is converting a byte count (such as from a drive capacity or file size), into a more human readable form. Consider 150000000000 bytes as being more readable as "150 GB", or "139.7 GiB".
Are there any libraries that contain functionality to perform these conversions? In Python? In C? In ps... | [
"Here's a method that uses logarithms to determine the file size unit exponent:\nfrom math import log\n\nbyteunits = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')\n\ndef filesizeformat(value):\n exponent = int(log(value, 1024))\n return \"%.1f %s\" % (float(value) / pow(1024, exponent), byteun... | [
7,
1,
0
] | [] | [] | [
"c",
"python",
"readability",
"stringification"
] | stackoverflow_0004180980_c_python_readability_stringification.txt |
Q:
Python API to know the location
Is there an Python API from which if we input the ipadress, will we be able to know the location and place of the access
A:
Take a look at the MaxMind python API
A:
GeoDjango looks like it will suit your needs. I'm not sure exactly how you would want to direct users, but using... | Python API to know the location | Is there an Python API from which if we input the ipadress, will we be able to know the location and place of the access
| [
"Take a look at the MaxMind python API\n",
"GeoDjango looks like it will suit your needs. I'm not sure exactly how you would want to direct users, but using the GeoIP API, you can do something like:\nfrom django.contrib.gis.utils import GeoIP\n\ng = GeoIP()\n\nip = request.META.get('REMOTE_ADDR', None)\n\nif ip:\... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004181828_python.txt |
Q:
Using HTMLParser in Python efficiently
In response to Python regular expression I tried to implement an HTML parser using HTMLParser:
import HTMLParser
class ExtractHeadings(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.text = None
self.headings = []
def i... | Using HTMLParser in Python efficiently | In response to Python regular expression I tried to implement an HTML parser using HTMLParser:
import HTMLParser
class ExtractHeadings(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.text = None
self.headings = []
def is_relevant(self, tagname):
return tagnam... | [
"Well, I tend to agree that it's a horrible oversight for the HTMLParser not to include code to convert HTML entity references into normal ASCII and/or other characters. I gather that this is remedied by completely different work in Python3.\nHowever, it seems we can write a fairly simple entity handler something ... | [
1,
0
] | [] | [] | [
"api",
"html_parsing",
"python"
] | stackoverflow_0004182521_api_html_parsing_python.txt |
Q:
Regular expression for checking
I am facing a problem with regular expression in Python.
The problem is that "Have to check a list and have to find out space containing strings."
The code is:
def testFunction(self, func):
a = re.findall(r'\w+[\ ]*\(.*?\)', func)
j = len(a)
print j
... | Regular expression for checking | I am facing a problem with regular expression in Python.
The problem is that "Have to check a list and have to find out space containing strings."
The code is:
def testFunction(self, func):
a = re.findall(r'\w+[\ ]*\(.*?\)', func)
j = len(a)
print j
if j<=1:
return True
... | [
"if all you care about is whether there are any spaces, why not just do something like\nreturn \" \" in func\n\n",
"how about this r'.*\\s+.*'\n",
"[\\ ]* matches zero or more occurrences of space. Try [\\ ]+ instead\n",
"re.findall(r\"function\\ *\\(\\)\", func)\n\n",
"HI,\nI have done this by\n def testFu... | [
2,
2,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004182528_python_regex.txt |
Q:
python: Why this happen?
Below is the full log, the problem is in
23 dd.append(str(msg.get_json()))
I have some utf-8 returned from msg.get_json()...
Will str() try to encode the parameter using ASCII?
<type 'exceptions.UnicodeEncodeError'> Python 2.6.5: /usr/bin/python
Mon Nov 15 18:53:39 2010
... | python: Why this happen? | Below is the full log, the problem is in
23 dd.append(str(msg.get_json()))
I have some utf-8 returned from msg.get_json()...
Will str() try to encode the parameter using ASCII?
<type 'exceptions.UnicodeEncodeError'> Python 2.6.5: /usr/bin/python
Mon Nov 15 18:53:39 2010
A problem occurred in a Python... | [
"The problem is most likely ocurring in str(msg.get_json()) or one of the other places where you use str. The object contains unicode data and str is not built to handle unicode. You should be able to use json.dumps(msg.get_json()) instead. Alternatively use str(msg.get_json().decode('utf-8')).\n",
"Try the unico... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004183631_python.txt |
Q:
str to time in python
time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"
How to convert the above from string to time stamp?
I need to subtract the above timestamps time2-time1.
A:
For Python 2.5+
from datetime import datetime
format = '%Y-%m-%d %H:%M:%S'
print datetime.strptime(time2, format) -
... | str to time in python | time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"
How to convert the above from string to time stamp?
I need to subtract the above timestamps time2-time1.
| [
"For Python 2.5+\nfrom datetime import datetime\nformat = '%Y-%m-%d %H:%M:%S'\nprint datetime.strptime(time2, format) - \n datetime.strptime(time1, format)\n# 1 day, 0:00:00\n\nEdit: for Python 2.4\nimport time\nformat = '%Y-%m-%d %H:%M:%S'\nprint time.mktime(time.strptime(time2, format)) - \n time.mk... | [
24,
3,
3
] | [
"import time\n\ntime1 = \"2010-04-20 10:07:30\"\n\ntime_tuple = time.strptime(time1, \"%Y-%m-%d %H:%M:%S\")\n\ntimestamp = time.mktime(time_tuple)\n\n"
] | [
-1
] | [
"datetime",
"python",
"strptime"
] | stackoverflow_0004183793_datetime_python_strptime.txt |
Q:
Data insertion error: invalid literal for int() with base 10
I'm using Django-nonrel on Google App Engine. I'm trying to add a row to the database but I get this error when trying to use save():
invalid literal for int() with base 10
Here's my code:
views.py
from django import forms
from django.contrib.auth.deco... | Data insertion error: invalid literal for int() with base 10 | I'm using Django-nonrel on Google App Engine. I'm trying to add a row to the database but I get this error when trying to use save():
invalid literal for int() with base 10
Here's my code:
views.py
from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import... | [
"The problem is here:\nsaying = Saying(content, category, added_date, added_user)\n\nYou've forgotten that Django adds an automatic id field to the model definition. If you did this in the shell, then printed saying.__dict__, you would see that the content has been assigned to id, the category to content, and so on... | [
5,
3
] | [] | [] | [
"django",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0004183702_django_django_nonrel_google_app_engine_python.txt |
Q:
Python Traits UI (Enthought)
I am working with some code that uses Traits UI to show a dialog from which the user is able to select two files:
class Files(HasTraits):
filename_1 = File(exists=True)
filename_2 = File(exists=True)
traits_ui = View(
'filename_1', 'filename_2',
title = '... | Python Traits UI (Enthought) | I am working with some code that uses Traits UI to show a dialog from which the user is able to select two files:
class Files(HasTraits):
filename_1 = File(exists=True)
filename_2 = File(exists=True)
traits_ui = View(
'filename_1', 'filename_2',
title = 'Select Geometry Files',
bu... | [
"At some point after Traits 3.2, a new trait was added to the FileEditor ToolkitEditorFactory that enables you set whether editing the trait is an 'open' or 'save' dialog. Try this:\nfrom enthought.traits.ui.api import FileEditor \n\nsave_file_editor = FileEditor(dialog_style='save')\n\nclass Files(HasTraits):\n... | [
3
] | [] | [] | [
"enthought",
"python",
"traits",
"user_interface"
] | stackoverflow_0001867194_enthought_python_traits_user_interface.txt |
Q:
jquery: how to decode the stringized utf-8 character?
My python server uses json.dumps() to dump the json object into the string, but it also converts the binary utf-8 code which is not ascii, into the stringized thing, like "\u4e2d". So what my client see is this string, is there any api to convert "\u4e2d" back ... | jquery: how to decode the stringized utf-8 character? | My python server uses json.dumps() to dump the json object into the string, but it also converts the binary utf-8 code which is not ascii, into the stringized thing, like "\u4e2d". So what my client see is this string, is there any api to convert "\u4e2d" back to utf-8 character?
| [
"In jQuery you can use $.parseJSON to decode a JSON-formatted object. That includes decoding encoded characters. Using dataType: 'json' with $.ajax (or $.post) or using $.getJSON will do that for you if you are trying to make AJAX requests.\n"
] | [
1
] | [] | [] | [
"javascript",
"jquery",
"python"
] | stackoverflow_0004184208_javascript_jquery_python.txt |
Q:
Unable to install and build PyAudio
I've build and installed PortAudio using this tarball: 'pa_stable_v19_20071207.tar.gz'
After this step, when I'm trying to install PyAudio via the tarball from this URL:
http://people.csail.mit.edu/hubert/pyaudio/packages/pyaudio-0.2.4.tar.gz
I'm getting the following error. Wha... | Unable to install and build PyAudio | I've build and installed PortAudio using this tarball: 'pa_stable_v19_20071207.tar.gz'
After this step, when I'm trying to install PyAudio via the tarball from this URL:
http://people.csail.mit.edu/hubert/pyaudio/packages/pyaudio-0.2.4.tar.gz
I'm getting the following error. What might be going wrong in this case?
ente... | [
"\nsrc/_portaudiomodule.c:30:20: error: Python.h: No such file or directory\n\nYou forgot to install the Python development files.\n"
] | [
3
] | [] | [] | [
"portaudio",
"pyaudio",
"python"
] | stackoverflow_0004184262_portaudio_pyaudio_python.txt |
Q:
Python module visiable only in iPython
I have used set PYTHONPATH=%PYTHONPATH%;dictionary_containing_modules to make some modules globaly visiable.
I have a script importing the modules with import my_module.
When i run the script from the iPython shell (run my_script.py), i get no errors and the script runs as i... | Python module visiable only in iPython | I have used set PYTHONPATH=%PYTHONPATH%;dictionary_containing_modules to make some modules globaly visiable.
I have a script importing the modules with import my_module.
When i run the script from the iPython shell (run my_script.py), i get no errors and the script runs as intended, but when I run the script from the ... | [
"Remember that you can dynamically change your system path from within your script, using sys.path or the site module. So maybe you want to add them to your script...\nOr maybe you want to write a BAT or Python launcher script that sets the PYTHONPATH...\nOr you want to edit the Windows environment variables (somew... | [
1
] | [] | [] | [
"ipython",
"python",
"scope"
] | stackoverflow_0004184180_ipython_python_scope.txt |
Q:
real time gui for python using only traits
Is it possible to create a ui using traits from python to make an interface for a cellular automata simulation?
A:
Of course, you can do anything with Traits that can with Python!
Seriously though, I presume your question is really about generating a GUI in which to dis... | real time gui for python using only traits | Is it possible to create a ui using traits from python to make an interface for a cellular automata simulation?
| [
"Of course, you can do anything with Traits that can with Python!\nSeriously though, I presume your question is really about generating a GUI in which to display the CA. In that case I can recommend Mayavi which is based on Traits. It has a surf function which plots an array of regularly-spaced data as a 3D surface... | [
1
] | [] | [] | [
"ca",
"python",
"simulation",
"traits",
"user_interface"
] | stackoverflow_0003893576_ca_python_simulation_traits_user_interface.txt |
Q:
Difference between android sha224 and python sha224
For an application prototype I'm creating a simple user login. The Password of the user will then be hashed using sha224 and transferred to the back-end. The Problem I am facing right now is the following. The password that was stored in the DB (also hashed using... | Difference between android sha224 and python sha224 | For an application prototype I'm creating a simple user login. The Password of the user will then be hashed using sha224 and transferred to the back-end. The Problem I am facing right now is the following. The password that was stored in the DB (also hashed using sha224) seems to look a little different then the hash I... | [
"You're not formatting the hex values on the Android properly; leading 0s are being dropped.\nbuffer.append(String.format(\"%02x\", 0xFF & digest[i]));\n\n",
"final MessageDigest mDigest = MessageDigest.getInstance(\"SHA-224\");\nbyte[] messageDigest = mDigest.digest(toEncrypt.getBytes());\nfinal BigInteger numbe... | [
4,
0,
0
] | [] | [] | [
"android",
"hash",
"python",
"sha2"
] | stackoverflow_0004184792_android_hash_python_sha2.txt |
Q:
Coloring an edge detected image by user input co-ordinates..??What's wrong with this code?
I need to color the white part surrounded by black edges!
from PIL import Image
import sys
image=Image.open("G:/ghgh.bmp")
data=image.load()
image_width,image_height=image.size
sys.setrecursionlimit(10115)
def f(x,y):
... | Coloring an edge detected image by user input co-ordinates..??What's wrong with this code? | I need to color the white part surrounded by black edges!
from PIL import Image
import sys
image=Image.open("G:/ghgh.bmp")
data=image.load()
image_width,image_height=image.size
sys.setrecursionlimit(10115)
def f(x,y):
if(x<image_width and y<image_height and x>0 and y>0):
if (data[x,y]==255):
... | [
"What's up with the while loop? It never changes the coordinates, so it seems it would loop forever, doing recursive calls. From a quick reading it sounds like it should be a plain if.\nAlso: drop the parens with while and if; they're not needed in Python.\n",
"\"unwind\" above is right. Just replace your \"while... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004184841_python.txt |
Q:
Problems raising a ValidationError on a Django Form
I'm trying to validate that a submitted URL doesn't already exist in the database.
The relevant parts of the Form class look like this:
from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(... | Problems raising a ValidationError on a Django Form | I'm trying to validate that a submitted URL doesn't already exist in the database.
The relevant parts of the Form class look like this:
from django.contrib.sites.models import Site
class SignUpForm(forms.Form):
# ... Other fields ...
url = forms.URLField(label='URL for new site, eg: example.com')
def clean... | [
"django channel in IRC saved me here. The problem was that the URLField.clean() does two things I wasn't expecting:\n\nIf no URL scheme is present (eg, http://) the method prepends 'http://' to the url\nthe method also appends a trailing slash.\n\nThe results are returned and stored in the form's cleaned_data. So... | [
4,
1,
0,
0
] | [] | [] | [
"cleaned_data",
"django",
"django_forms",
"python"
] | stackoverflow_0000339387_cleaned_data_django_django_forms_python.txt |
Q:
Creating an empty list to have data assigned afterwards
Lets say that I want to create a list of names
listOfNames = []
Then I have a while loop such as
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
Python says that the list index is out of range, but t... | Creating an empty list to have data assigned afterwards | Lets say that I want to create a list of names
listOfNames = []
Then I have a while loop such as
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
Python says that the list index is out of range, but the list index should be at 0, correct?
How do add to the list... | [
"An empty list doesn't have any index yet, it's an empty list! If you want to fill it, you have to do something like this :\nwhile count < 10:\n nameList.append(raw_input(\"Enter a name: \"))\n count += 1\n\nThis way, your condition will be evaluated and with the append method, you will be able to add new ite... | [
11,
5,
1,
0
] | [] | [] | [
"indexing",
"list",
"python",
"range"
] | stackoverflow_0004185462_indexing_list_python_range.txt |
Q:
How to copy a message from one imap server to another imap server using Python imaplib?
I want to copy a message from one IMAP server to another IMAP server. I don't want to alter any of the message data. I'm using python imaplib.
This is the code I tried:
typ, data = connection1.uid('FETCH', uid, 'RFC822')
connec... | How to copy a message from one imap server to another imap server using Python imaplib? | I want to copy a message from one IMAP server to another IMAP server. I don't want to alter any of the message data. I'm using python imaplib.
This is the code I tried:
typ, data = connection1.uid('FETCH', uid, 'RFC822')
connection2.uid('APPEND', None, data[0][1])
But this raises an exception:
imaplib.error: UID comm... | [
"You can try the follwing code:\ntyp, data = connection1.uid('FETCH', uid, 'RFC822')\nimport email\nmsg_str = email.message_from_string(data[0][1])\nmsg_create = connection2.append(str(dest_fold_code) , flags, '', str(msg_str))\n\nwhere flags would be '(\\Seen)' in case of seen email or '' in case of unseen email... | [
2,
1,
1
] | [] | [] | [
"imap",
"imaplib",
"python",
"rfc822"
] | stackoverflow_0004179150_imap_imaplib_python_rfc822.txt |
Q:
Rewrite this loop function with range
Is it possible to rewrite this loop:
for k,n in [[aa,1],[ab,2], [ac,3], [ad,4], [ba,5], [bb,6], [bc,7], [bd,8],
[ca,9],[cb,10],[cc,12],[cd,13],[da,14],[db,15],[dc,16],[dd,17],...zd,220]]:
with two range functions or "list multiplication"? I have tried all sorts o... | Rewrite this loop function with range | Is it possible to rewrite this loop:
for k,n in [[aa,1],[ab,2], [ac,3], [ad,4], [ba,5], [bb,6], [bc,7], [bd,8],
[ca,9],[cb,10],[cc,12],[cd,13],[da,14],[db,15],[dc,16],[dd,17],...zd,220]]:
with two range functions or "list multiplication"? I have tried all sorts of approaches, but none worked so far.
Thank... | [
"If you have the objects in a list its actually quite simple:\nobject_list = [aa, ab, ... ]\nfor n, k in enumerate( object_list, start=1):\n ...\n\nSo you should look for a way to put them in a list instead.\n",
"If all those objects are in the modules global namespace you could do something like this:\nfrom ... | [
4,
0,
0,
0,
0,
0
] | [] | [] | [
"for_loop",
"loops",
"python",
"range"
] | stackoverflow_0004185976_for_loop_loops_python_range.txt |
Q:
How to find out how many clients are on a certain address range?
I tried googling for this but i didnt find anything... I am building a port scanner and i would like to make it so, that i can scan a network range e.g 192.168.2.* and find out how many computers are on that range that are online. Alot like Nmap. I a... | How to find out how many clients are on a certain address range? | I tried googling for this but i didnt find anything... I am building a port scanner and i would like to make it so, that i can scan a network range e.g 192.168.2.* and find out how many computers are on that range that are online. Alot like Nmap. I am programming in python. Is this possible in Python?
| [
"Use python-nmap. Basic usage:\nimport nmap\nnm = nmap.PortScanner()\nnm.scan(hosts='192.168.2.0/24', arguments='-n -sP -PE -PA21,23,80,3389')\nhosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]\nfor host, status in hosts_list:\n print('{0}:{1}'.format(host, status))\n\nFor further reference se... | [
2,
1,
0,
0
] | [] | [] | [
"networking",
"nmap",
"port_scanning",
"python"
] | stackoverflow_0004186374_networking_nmap_port_scanning_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.