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:
What's a good embedded browser for a pygtk application?
I'm planning on using an embedded browser in my pygtk application and I'm debating between gtkmozembed and pywebkitgtk. Is there any compelling difference between the two? Are there any third options that I don't know about?
It should be noted that I won't ... | What's a good embedded browser for a pygtk application? | I'm planning on using an embedded browser in my pygtk application and I'm debating between gtkmozembed and pywebkitgtk. Is there any compelling difference between the two? Are there any third options that I don't know about?
It should be noted that I won't be using this to access content on the web. I'm mainly using... | [
"gtkmozembed is not available on Windows, although you can use the gecko embedding interface directly. This would require you to write some C++ code.\nAs far as I know, the gtk webkit port is not available on Windows yet, and still appears to be undergoing a lot of change.\nFor an example of a cross-platform gecko ... | [
6,
2
] | [] | [] | [
"gtk",
"mozilla",
"python",
"user_interface",
"webkit"
] | stackoverflow_0000569547_gtk_mozilla_python_user_interface_webkit.txt |
Q:
What's different between Python and Javascript regular expressions?
Are Python and JavaScript regular expression syntax identical?
If not, then:
What are the important differences between them
Is there a python library that "implements" JavaScript regexps?
A:
There is a comparison table here:
Regex Flavor Com... | What's different between Python and Javascript regular expressions? | Are Python and JavaScript regular expression syntax identical?
If not, then:
What are the important differences between them
Is there a python library that "implements" JavaScript regexps?
| [
"There is a comparison table here:\nRegex Flavor Comparison\n",
"Part 1\nThey are different; One difference is Python supports Unicode and Javascript doesn't. \nPart 2\nRead Mastering Regular Expressions. It gives information on how to identify the back-end engines (DFA vs NFA vs Hybrid) that a regex flavour us... | [
32,
7,
1
] | [] | [] | [
"javascript",
"python",
"regex"
] | stackoverflow_0000636485_javascript_python_regex.txt |
Q:
Privilege Escalation in Web Environment for File Access
I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device.
The specific case is where I have a web interface for configuring a modem that comes up on /dev/ttyUSB[0-9].
Zero or more mode... | Privilege Escalation in Web Environment for File Access | I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device.
The specific case is where I have a web interface for configuring a modem that comes up on /dev/ttyUSB[0-9].
Zero or more modems will be plugged in by an end user. I am writing some softw... | [
"In this case, I would write a daemon run by a system user that accepted socket connections and relayed them to the appropriate device, then use sockets within the web application to talk to the daemon. This also helps keep the web app from blocking when opening a device that isn't quite ready to deal with users, s... | [
2,
2,
1,
1
] | [
"The sudo idea could be possible. IIRC, you can set specific commands to be sudo-able, but without requiring a password.\nThe other option is to put nobody in a group that has access to the device you want, or to start Apache as the group that does have access.\nIf you're using fastcgi (or equiv), I think you can ... | [
-1
] | [
"cgi",
"linux",
"permissions",
"python",
"serial_port"
] | stackoverflow_0000628956_cgi_linux_permissions_python_serial_port.txt |
Q:
How do you add event to Trac event time line
I am writing a plug-in for Trac. I would like to add an event to the time line each time the plug-in receives some data from a Git post-receive hook.
Looking at the timeline API, it seems you can only add new source of events. So you are responsible for retrieving and d... | How do you add event to Trac event time line | I am writing a plug-in for Trac. I would like to add an event to the time line each time the plug-in receives some data from a Git post-receive hook.
Looking at the timeline API, it seems you can only add new source of events. So you are responsible for retrieving and displaying the data. I would prefer saving my event... | [
"The timeline API is a level higher than what you need to do. There is a general VCS implementation of it in ChangesetModule, which delegates the changeset (event) retrieval itself to a VCS-specific Repository. So you should implement the versioncontrol API instead.\nThe API is designed for a “pull model”, in which... | [
2
] | [] | [] | [
"plugins",
"python",
"trac"
] | stackoverflow_0000623822_plugins_python_trac.txt |
Q:
Django workflow when modifying models frequently?
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to ... | Django workflow when modifying models frequently? | as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome..
Modify the m... | [
"Steps 2 & 3 can be done in one step:\nmanage.py reset appname\n\nStep 4 is most easily managed, from my understanding, by using fixtures\n",
"This is a job for Django's fixtures. They are convenient because they are database independent and the test harness (and manage.py) have built-in support for them.\nTo use... | [
22,
15,
12,
11,
4,
1
] | [] | [] | [
"django",
"django_models",
"django_syncdb",
"python",
"workflow"
] | stackoverflow_0000497654_django_django_models_django_syncdb_python_workflow.txt |
Q:
Unable to make each sentence to start at a new line in LaTex by AWK/Python
I have a long document in LaTex, which contains paragraphs. The paragraphs contain sentences such that no subsequent sentence start at a new line.
How can you make each subsequent sentence to start at a new line in my .tex file?
My attempt ... | Unable to make each sentence to start at a new line in LaTex by AWK/Python | I have a long document in LaTex, which contains paragraphs. The paragraphs contain sentences such that no subsequent sentence start at a new line.
How can you make each subsequent sentence to start at a new line in my .tex file?
My attempt to the problem
We need to put \n to the end of Sentence B where Sentence B has S... | [
"So you want every sentence in your .tex file to start on a new line, but without introducing extra paragraphs? Is that correct?\nPossibly you could go through your file and, every time you see a '.' followed by whitespace and a capital letter, insert a newline.\ne.g. in python:\nimport re\nsentence_end = r'\\.\\s... | [
3,
2,
2
] | [] | [] | [
"awk",
"latex",
"python"
] | stackoverflow_0000636887_awk_latex_python.txt |
Q:
Best way to remove duplicate characters (words) in a string?
What would be the best way of removing any duplicate characters and sets of characters separated by spaces in string?
I think this example explains it better:
foo = 'h k k h2 h'
should become:
foo = 'h k h2' # order not important
Other example:
foo = ... | Best way to remove duplicate characters (words) in a string? | What would be the best way of removing any duplicate characters and sets of characters separated by spaces in string?
I think this example explains it better:
foo = 'h k k h2 h'
should become:
foo = 'h k h2' # order not important
Other example:
foo = 's s k'
becomes:
foo = 's k'
| [
"' '.join(set(foo.split()))\n\nNote that split() by default will split on all whitespace characters. (e.g. tabs, newlines, spaces)\nSo if you want to split ONLY on a space then you have to use:\n' '.join(set(foo.split(' ')))\n\n",
"Do you mean?\n' '.join( set( someString.split() ) )\n\nThat's the unique space-de... | [
13,
10,
6
] | [] | [] | [
"duplicates",
"python",
"string"
] | stackoverflow_0000636977_duplicates_python_string.txt |
Q:
What should I be aware of when moving from asp.net to python for web development?
I'm thinking about converting an app from Asp.net to python. I would like to know: what are the key comparisons to be aware of when moving a asp.net app to python(insert framework)?
Does python have user controls? Master pages?
A:
... | What should I be aware of when moving from asp.net to python for web development? | I'm thinking about converting an app from Asp.net to python. I would like to know: what are the key comparisons to be aware of when moving a asp.net app to python(insert framework)?
Does python have user controls? Master pages?
| [
"First, Python is a language, while ASP.NET is a web framework. In fact, you can code ASP.NET applications using IronPython.\nIf you want to leave ASP.NET behind and go with the Python \"stack,\" then you can choose from several different web application frameworks, including Django and Zope.\nZope, for example, of... | [
8,
4,
0
] | [] | [] | [
"asp.net",
"python"
] | stackoverflow_0000624062_asp.net_python.txt |
Q:
What are some strategies to write python code that works in CPython, Jython and IronPython
Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this s... | What are some strategies to write python code that works in CPython, Jython and IronPython | Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?
| [
"If you do find you need to write unique code for an environment, use pythons \nimport mymodule_jython as mymodule\n\nimport mymodule_cpython as mymodule\n\nhave this stuff in a simple module (''module_importer''?) and write your code like this:\nfrom module_importer import mymodule\n\nThis way, all you need to do ... | [
15,
10,
2,
1,
0,
0
] | [] | [] | [
"cpython",
"ironpython",
"jython",
"python"
] | stackoverflow_0000053543_cpython_ironpython_jython_python.txt |
Q:
Python Profiling in Eclipse
This questions is semi-based of this one here:
How can you profile a python script?
I thought that this would be a great idea to run on some of my programs. Although profiling from a batch file as explained in the aforementioned answer is possible, I think it would be even better to hav... | Python Profiling in Eclipse | This questions is semi-based of this one here:
How can you profile a python script?
I thought that this would be a great idea to run on some of my programs. Although profiling from a batch file as explained in the aforementioned answer is possible, I think it would be even better to have this option in Eclipse. At the ... | [
"if you follow the common python idiom to make all your code, even the \"existing programs\", importable as modules, you could do exactly what you describe, without any additional hassle.\nhere is the specific idiom I am talking about, which turns your program's flow \"upside-down\" since the __name__ == '__main__'... | [
4,
0
] | [] | [] | [
"eclipse",
"profiling",
"python"
] | stackoverflow_0000636695_eclipse_profiling_python.txt |
Q:
Django with Passenger
I'm trying to get a trivial Django project working with Passenger on Dreamhost, following the instructions here
I've set up the directories exactly as in that tutorial, and ensured that django is on my PYTHONPATH (I can run python and type 'import django' without any errors). However, when... | Django with Passenger | I'm trying to get a trivial Django project working with Passenger on Dreamhost, following the instructions here
I've set up the directories exactly as in that tutorial, and ensured that django is on my PYTHONPATH (I can run python and type 'import django' without any errors). However, when I try to access the url in... | [
"Are those fancy quotation marks also in your code?\nos.environ['DJANGO_SETTINGS_MODULE'] = ‘myproject.settings’\n ^ ^\n\nIf so, start by fixing them, as they cause a syntax error.\n"
] | [
24
] | [] | [] | [
"django",
"dreamhost",
"passenger",
"python"
] | stackoverflow_0000637565_django_dreamhost_passenger_python.txt |
Q:
Paging depending on grouping of items in Django
For a website implemented in Django/Python we have the following requirement:
On a view page there are 15 messages per web paging shown. When there are more two or more messages from the same source, that follow each other on the view, they should be grouped together... | Paging depending on grouping of items in Django | For a website implemented in Django/Python we have the following requirement:
On a view page there are 15 messages per web paging shown. When there are more two or more messages from the same source, that follow each other on the view, they should be grouped together.
Maybe not clear, but with the following exemple it... | [
"I don't see any great way to do what you're trying to do directly. If you're willing to accept a little de-normalization, I would recommend a pre-save signal to mark messages as being at the head.\n#In your model\nhead = models.BooleanField(default=True)\n\n#As a signal plugin:\ndef check_head(sender, **kwargs):\... | [
3,
1
] | [] | [] | [
"django",
"django_models",
"mysql",
"python",
"sql"
] | stackoverflow_0000638647_django_django_models_mysql_python_sql.txt |
Q:
Default encoding for python for stderr?
I've got a noisy python script that I want to silence by directing its stderr output to /dev/null (using bash BTW).
Like so:
python -u parse.py 1> /tmp/output3.txt 2> /dev/null
but it quickly exits prematurely. Hmm. I can't see the traceback because of course that goes out... | Default encoding for python for stderr? | I've got a noisy python script that I want to silence by directing its stderr output to /dev/null (using bash BTW).
Like so:
python -u parse.py 1> /tmp/output3.txt 2> /dev/null
but it quickly exits prematurely. Hmm. I can't see the traceback because of course that goes out with stderr. It runs noisily and normally if... | [
"You can silence stderr by binding it to a custom writer:\n#!/usr/bin/env python\nimport codecs, sys\n\nclass NullWriter:\n def write(self, *args, **kwargs):\n pass\n\nif len(sys.argv) == 2:\n if sys.argv[1] == '1':\n sys.stderr = NullWriter()\n elif sys.argv[1] == '2':\n #NOTE: sys.stderr.e... | [
5,
4,
2
] | [] | [] | [
"bash",
"python",
"shell",
"unicode"
] | stackoverflow_0000637396_bash_python_shell_unicode.txt |
Q:
Django Admin relations between tables: save database updates in several tables
I am using Django admin for managing my data.
I have a Users, Groups and Domains tables.
Users table has many to many relationship with Groups and Domains tables.
Domains table has one to many relationship with Groups table.
and when I ... | Django Admin relations between tables: save database updates in several tables | I am using Django admin for managing my data.
I have a Users, Groups and Domains tables.
Users table has many to many relationship with Groups and Domains tables.
Domains table has one to many relationship with Groups table.
and when I save the User data through admin I also need some addtional database updates in the... | [
"I think you are looking for InlineModels. They allow you to edit related models in the same page as the parent model. If you are looking for greater control than this, you can override the ModelAdmin save methods.\nAlso, always check out the Manual when you need something. It really is quite good.\n",
"The best ... | [
2,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0000635048_django_django_admin_python.txt |
Q:
Python time to age, part 2: timezones
Following on from my previous question, Python time to age, I have now come across a problem regarding the timezone, and it turns out that it's not always going to be "+0200". So when strptime tries to parse it as such, it throws up an exception.
I thought about just chopping ... | Python time to age, part 2: timezones | Following on from my previous question, Python time to age, I have now come across a problem regarding the timezone, and it turns out that it's not always going to be "+0200". So when strptime tries to parse it as such, it throws up an exception.
I thought about just chopping off the +0200 with [:-6] or whatever, but i... | [
"\nis there a real way to do this with strptime?\n\nNo, but since your format appears to be an RFC822-family date, you can read it much more easily using the email library instead:\n>>> import email.utils\n>>> email.utils.parsedate_tz('Tue, 22 Jul 2008 08:17:41 +0200')\n(2008, 7, 22, 8, 17, 41, 0, 1, 0, 7200)\n\n(7... | [
40,
28,
18,
1,
0
] | [] | [] | [
"datetime",
"python",
"timezone"
] | stackoverflow_0000526406_datetime_python_timezone.txt |
Q:
Problem Inserting data into MS Access database using ADO via Python
[Edit 2: More information and debugging in answer below...]
I'm writing a python script to export MS Access databases into a series of text files to allow for more meaningful version control (I know - why Access? Why aren't I using existing soluti... | Problem Inserting data into MS Access database using ADO via Python | [Edit 2: More information and debugging in answer below...]
I'm writing a python script to export MS Access databases into a series of text files to allow for more meaningful version control (I know - why Access? Why aren't I using existing solutions? Let's just say the restrictions aren't of a technical nature).
I've ... | [
"And found an answer.\n rs = client.CreateObject(\"ADODB.Recordset\")\n\nNeeds to be:\n rs = client.CreateObject(\"ADODB.Recordset\", dynamic=True)\n\nNow I just need to look into why. Just hope this question saves someone else a few hours...\n",
"Is data[i] being treated as a string? What happens if you sp... | [
4,
0,
0
] | [] | [] | [
"ado",
"comtypes",
"ms_access",
"python"
] | stackoverflow_0000638095_ado_comtypes_ms_access_python.txt |
Q:
Unable search names which contain three 7s in random order by AWK/Python/Bash
I need to find names which contain three number 7 in the random order.
My attempt
We need to find first names which do not contain seven
ls | grep [^7]
Then, we could remove these matches from the whole space
ls [remove] ls | grep [^7]
... | Unable search names which contain three 7s in random order by AWK/Python/Bash | I need to find names which contain three number 7 in the random order.
My attempt
We need to find first names which do not contain seven
ls | grep [^7]
Then, we could remove these matches from the whole space
ls [remove] ls | grep [^7]
The problem in my pseudo-code starts to repeat itself quickly.
How can you find th... | [
"I don't understand the part about \"random order\". How do you differentiate between the \"order\" when it's the same token that repeats? Is \"a7b7\" different from \"c7d7\" in the order of the 7s?\nAnyway, this ought to work:\n ls *7*7*7*\n\nIt just let's the shell solve the problem, but maybe I didn't understand... | [
7,
5,
2,
2,
1
] | [] | [] | [
"awk",
"bash",
"python",
"regex"
] | stackoverflow_0000639078_awk_bash_python_regex.txt |
Q:
In stackless Python, can you send a channel over a channel?
I do not have stackless currently running, so I can not try this myself.
import stackless
ch1 = stackless.channel()
ch2 = stackless.channel()
ch1.send(ch2)
ch3 = ch1.receive()
Are ch2 and ch3 then the same channel? Say:
text = "Hallo"
ch2.send(text)
ass... | In stackless Python, can you send a channel over a channel? | I do not have stackless currently running, so I can not try this myself.
import stackless
ch1 = stackless.channel()
ch2 = stackless.channel()
ch1.send(ch2)
ch3 = ch1.receive()
Are ch2 and ch3 then the same channel? Say:
text = "Hallo"
ch2.send(text)
assert text == ch3.receive()
This feature reminded me of a talk abo... | [
"Yes. Just tested.\n>>> import stackless\n>>> ch1 = stackless.channel()\n>>> def a():\n... ch2 = stackless.channel()\n... ch1.send(ch2)\n... ch2.send(\"Hello\")\n...\n>>> def b():\n... ch3 = ch1.receive()\n... print ch3.receive()\n...\n>>> stackless.tasklet(a)()\n<stackless.tasklet object at 0x01C6FCB0>\n>>> s... | [
4,
3
] | [] | [] | [
"python",
"python_stackless",
"stackless"
] | stackoverflow_0000638464_python_python_stackless_stackless.txt |
Q:
Ruby on Rails versus Python
I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic.
But when I start ... | Ruby on Rails versus Python | I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic.
But when I start googling for web development I st... | [
"Ruby and Python are languages.\nRails is a framework.\nSo it is not really sensible to compare Ruby on Rails vs Python.\nThere are Python Frameworks out there you should take a look at for a more direct comparison - http://wiki.python.org/moin/WebFrameworks (e.g. I know Django gets a lot of love, but there are oth... | [
25,
16,
9,
3
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0000638150_python_ruby.txt |
Q:
Are there any pitfalls with using whitespace in Python?
At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language?
A:
... | Are there any pitfalls with using whitespace in Python? | At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language?
| [
"It can be confusing in some editors where one line is indented with spaces and the next is indented with a tab. This is confusing as the indentation looks the same but causes an error.\nAlso when your copying code, if your editor doesn't have a function to indent entire blocks, it could be annoying fixing all the ... | [
11,
10,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"whitespace"
] | stackoverflow_0000637295_python_whitespace.txt |
Q:
PHP vs. long-running process (Python, Java, etc.)?
I'd like to have your opinion about writing web apps in PHP vs. a long-running process using tools such as Django or Turbogears for Python.
As far as I know:
- In PHP, pages are fetched from the hard-disk every time (although I assume the OS keeps files in RAM for... | PHP vs. long-running process (Python, Java, etc.)? | I'd like to have your opinion about writing web apps in PHP vs. a long-running process using tools such as Django or Turbogears for Python.
As far as I know:
- In PHP, pages are fetched from the hard-disk every time (although I assume the OS keeps files in RAM for a while after they've been accessed)
- Pages are recomp... | [
"After you apply memcache, opcode caching, and connection pooling, the only real difference between PHP and other options is that PHP is short-lived, processed based, while other options are, typically, long-lived multithreaded based.\nThe advantage PHP has is that its dirt simple to write scripts. You don't have ... | [
3,
2,
1,
0
] | [
"PHP is a language like Java etc. \nOnly your executable is the php binary and not the JVM! You can set another MAX-Runtime for PHP-Scripts without any problems (if your shared hosting provider let you do so).\nWhere your apps are running shouldn't depend on the kind of the server. It should depend on the ressource... | [
-1
] | [
"php",
"python"
] | stackoverflow_0000639409_php_python.txt |
Q:
Validating Oracle dates in Python
Our Python CMS stores some date values in a generic "attribute" table's varchar column. Some of these dates are later moved into a table with an actual date column. If the CMS user entered an invalid date, it doesn't get caught until the migration, when the query fails with an "... | Validating Oracle dates in Python | Our Python CMS stores some date values in a generic "attribute" table's varchar column. Some of these dates are later moved into a table with an actual date column. If the CMS user entered an invalid date, it doesn't get caught until the migration, when the query fails with an "Invalid string date" error.
How can I u... | [
"\nHow can I use Python to make sure that all dates put into our CMS are valid Oracle string date representations?\n\nI'd change the approach a bit. Have Python parse the original date input as forgivingly as possible, then output the date in a known-good representation.\ndateutil's liberal parser may be a good pla... | [
5,
1
] | [
"Validate as early as possible. Why don't you store dates as dates in your Python CMS? \nIt is difficult to know what date a string like '03-04-2008' is. Is it 3 april 2008 or 4 march 2008? An American will say 4 march 2008 but a Dutch person will say 3 april 2008. \n"
] | [
-1
] | [
"oracle",
"python",
"validation"
] | stackoverflow_0000639949_oracle_python_validation.txt |
Q:
Is there any linux distribution that comes with python 2.6 yet?
I've heard ubuntu 9.4 will but it's still in alpha. Are there any stable distros that come with python 2.6 or at least don't depend on it so much so reinstalling python won't break anything?
A:
Arch Linux - http://www.archlinux.org/
A:
You can ins... | Is there any linux distribution that comes with python 2.6 yet? | I've heard ubuntu 9.4 will but it's still in alpha. Are there any stable distros that come with python 2.6 or at least don't depend on it so much so reinstalling python won't break anything?
| [
"Arch Linux - http://www.archlinux.org/\n",
"You can install python 2.6 in Ubuntu 8.10 just fine.\n./configure --prefix=/usr/local\nmake\nsudo make altinstall --prefix=/usr/local\n\nThen just run python with:\npython2.6\n\nIf you want to use it in a shebang line, just use:\n#!/usr/bin/env python2.6\n\nYour script... | [
9,
6,
4,
3,
1,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0000640191_linux_python.txt |
Q:
Running unit tests with Nose inside a Python environment such as Autodesk Maya?
I'd like to start creating unit tests for my Maya scripts. These scripts must be run inside the Maya environment and rely on the maya.cmds module namespace.
How can I run Nose tests from inside a running environment such as Maya?
A:
... | Running unit tests with Nose inside a Python environment such as Autodesk Maya? | I'd like to start creating unit tests for my Maya scripts. These scripts must be run inside the Maya environment and rely on the maya.cmds module namespace.
How can I run Nose tests from inside a running environment such as Maya?
| [
"Use the mayapy executable included in your maya install instead of the standard python executable.\nIn order for this work you'll need to run nose programmatically. Create a python file called runtests.py and put it next to your test files. In it, include the following code:\nimport os\nos.environ['PYTHONPATH'] ... | [
15
] | [] | [] | [
"environment",
"maya",
"nose",
"python",
"unit_testing"
] | stackoverflow_0000639744_environment_maya_nose_python_unit_testing.txt |
Q:
Scalable polling of an AppEngine application from numerous "active" clients?
I'm working on an application that will run on Google AppEngine.
I plan to have the web interface of that application wait, among many other things, for notifications coming from the AppEngine server.
Ideally I would have liked to use an ... | Scalable polling of an AppEngine application from numerous "active" clients? | I'm working on an application that will run on Google AppEngine.
I plan to have the web interface of that application wait, among many other things, for notifications coming from the AppEngine server.
Ideally I would have liked to use an XMLHttpRequest() to make a request to the server that would be waiting until the n... | [
"OR...\nYou might be interested in some pubsub implementation. Like the venerable pubsubhubbub, made by guys from Google and Jaiku.\n"
] | [
1
] | [] | [] | [
"ajax",
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0000633999_ajax_google_app_engine_javascript_python.txt |
Q:
tell whether python is in -i mode
How can you tell whether python has been started with the -i flag?
According to the docs, you can check the PYTHONINSPECT variable in os.environ, which is the equivalent of -i. But apparently it doesn't work the same way.
Works:
$ PYTHONINSPECT=1 python -c 'import os; print os.env... | tell whether python is in -i mode | How can you tell whether python has been started with the -i flag?
According to the docs, you can check the PYTHONINSPECT variable in os.environ, which is the equivalent of -i. But apparently it doesn't work the same way.
Works:
$ PYTHONINSPECT=1 python -c 'import os; print os.environ["PYTHONINSPECT"]'
Doesn't work:
$... | [
"How to set inspect mode programmatically\nThe answer from the link @Jweede provided is imprecise. It should be:\nimport os\nos.environ['PYTHONINSPECT'] = '1'\n\nHow to retrieve whether interactive/inspect flags are set\nJust another variant of @Brian's answer:\nimport os\nfrom ctypes import POINTER, c_int, cast, p... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0000640389_python.txt |
Q:
Is it pythonic for a function to return multiple values?
In python, you can have a function return multiple values. Here's a contrived example:
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
This seems very useful, but it looks like it can also... | Is it pythonic for a function to return multiple values? | In python, you can have a function return multiple values. Here's a contrived example:
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as... | [
"Absolutely (for the example you provided).\nTuples are first class citizens in Python\nThere is a builtin function divmod() that does exactly that.\nq, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x\n\nThere are other examples: zip, enumerate, dict.items. \nfor i, e in enumerate([1, 3, 3]):\n ... | [
112,
27,
13,
4,
1,
1,
1,
0,
0
] | [] | [] | [
"function",
"multiple_return_values",
"python",
"return_value"
] | stackoverflow_0000061605_function_multiple_return_values_python_return_value.txt |
Q:
How do I upload a file with mod_python?
I want to create a simple file upload form and I must be completely incapable. I've read docs and tutorials,but for some reason, I'm not getting the submitted form data. I wrote the smallest amount of code I could to test and it still isn't working. Any ideas what's wrong?
d... | How do I upload a file with mod_python? | I want to create a simple file upload form and I must be completely incapable. I've read docs and tutorials,but for some reason, I'm not getting the submitted form data. I wrote the smallest amount of code I could to test and it still isn't working. Any ideas what's wrong?
def index():
html = '''
<html>
<... | [
"try putting enctype=\"multipart/form-data\" in your form tag. Your mistake is not really mod_python related.\n"
] | [
1
] | [] | [] | [
"mod_python",
"python",
"upload"
] | stackoverflow_0000640310_mod_python_python_upload.txt |
Q:
Python - How to calculate equal parts of two dictionaries?
I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists:
d1 = {0:['11','18','25','38'],
1:['11','18','25','38'],
2:['11','18','25','38'],
3:['11','18','25','38']... | Python - How to calculate equal parts of two dictionaries? | I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists:
d1 = {0:['11','18','25','38'],
1:['11','18','25','38'],
2:['11','18','25','38'],
3:['11','18','25','38']}
d2 = {0:['05','08','11','13','16','25','34','38','40', '43'],... | [
"Assuming this is Python, you want:\ndict((x, set(y) & set(d1.get(x, ()))) for (x, y) in d2.iteritems())\n\nto generate the resulting dictionary \"d3\".\nPython 3.0+ version\n>>> d3 = {k: list(set(d1.get(k,[])).intersection(v)) for k, v in d2.items()}\n{0: ['11', '25', '38'], 1: ['38'], 2: ['11', '18'], 3: ['11', '... | [
7,
4,
1,
1
] | [
"in pseudocode:\nDictionary d3 = new Dictionary()\nfor (i = 0 to min(d1.size(), d2.size()))\n{\n element shared = getSharedElements(d1[i], d2[i]);\n d3.store(i, shared);\n}\n\nfunction getsharedElements(array e1, array e2)\n{\n element e3 = new element();\n for (int i = 0 to e1.length)\n {\n if (e2.contains... | [
-1
] | [
"dictionary",
"list",
"merge",
"python"
] | stackoverflow_0000638360_dictionary_list_merge_python.txt |
Q:
Django, Python Loop Logic Problem
This works, partially. More information may be needed, however, I thought I would post to get advice on anything obvious that might be wrong here.
The problem is that if activity.get_cost() returns a False value, the function seems to exit entirely, returning None.
What I'd like ... | Django, Python Loop Logic Problem | This works, partially. More information may be needed, however, I thought I would post to get advice on anything obvious that might be wrong here.
The problem is that if activity.get_cost() returns a False value, the function seems to exit entirely, returning None.
What I'd like it to do, of course, is accumulate cost... | [
"I notice you're returning False if all the costs were None; I don't know if there's a specific reason for that, but it does make it a little bit harder to write. If that's not a requirement, you could write it like this:\ndef get_jobrecord_cost(self):\n costs = [activity.get_cost() or 0 for activity in self.ac... | [
3,
2,
1
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0000641145_django_models_python.txt |
Q:
Writing to the serial port in Vista from Python
How do I write to the serial port in Vista from Python? The termios package only seem to support posix.
A:
pyserial does the trick, you'll need python extensions for windows for it to work in windows.
A:
Seems like it wasn't any harder than this using pyserial:
... | Writing to the serial port in Vista from Python | How do I write to the serial port in Vista from Python? The termios package only seem to support posix.
| [
"pyserial does the trick, you'll need python extensions for windows for it to work in windows.\n",
"Seems like it wasn't any harder than this using pyserial: \nimport serial\n\nser = serial.Serial(0) # open first serial port with 9600,8,N,1\nprint ser.portstr # check which port was really used\nser.write('... | [
9,
7
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0000640802_python_windows.txt |
Q:
Python for mathematics students?
I need to deliver one and half hour seminar on programming for students at the department of mathematics.
I have chosen python as language.
What should be content of my presentation ?
What are good resources available ?
What is necessity of programming for maths students?
How wi... | Python for mathematics students? | I need to deliver one and half hour seminar on programming for students at the department of mathematics.
I have chosen python as language.
What should be content of my presentation ?
What are good resources available ?
What is necessity of programming for maths students?
How will knowledge of programming will help ... | [
"Do the getting started guide to scipy?\nhttp://www.scipy.org/Getting_Started\n",
"Sage: http://www.sagemath.org/\n",
"Assuming that these students are new to programming (which is quite likely for math students), you'll want to give them a basic introduction to programming (what a function is, what a variable ... | [
9,
7,
4,
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0000593685_math_python.txt |
Q:
Formatted text in GAE
Google app engine question: What is a good way to take formatted text (does not have to be rich text) from the user and then store it in a text or blog property in the datastore? Mainly what I'm looking for is it to store newlines and strings of spaces, so that the text comes back looking the... | Formatted text in GAE | Google app engine question: What is a good way to take formatted text (does not have to be rich text) from the user and then store it in a text or blog property in the datastore? Mainly what I'm looking for is it to store newlines and strings of spaces, so that the text comes back looking the same as when it was submit... | [
"The text will always \"come back\" the same as how you put it in. You will lose some formatting rendering to HTML (as you noticed line endings and spaces). One solution might be to render the text into a <pre> element (which implies preformatted text).\n<pre>\nThis text will\n\nbe formatted correctly\n</pre>\n... | [
2,
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0000640733_google_app_engine_google_cloud_datastore_python.txt |
Q:
Function Parser with RegEx in Python
I have a source code in Fortran (almost irrelevant) and I want to parse the function names and arguments.
eg using
(\w+)\([^\(\)]+\)
with
a(b(1 + 2 * 2), c(3,4))
I get the following: (as expected)
b, 1 + 2 * 2
c, 3,4
where I would need
a, b(1 + 2 * 2), c(3,4)
b, 1 + 2 * 2
c... | Function Parser with RegEx in Python | I have a source code in Fortran (almost irrelevant) and I want to parse the function names and arguments.
eg using
(\w+)\([^\(\)]+\)
with
a(b(1 + 2 * 2), c(3,4))
I get the following: (as expected)
b, 1 + 2 * 2
c, 3,4
where I would need
a, b(1 + 2 * 2), c(3,4)
b, 1 + 2 * 2
c, 3,4
Any suggestions?
Thanks for your ti... | [
"I don't think this is a job for regular expressions... they can't really handle nested patterns.\nThis is because regexes are compiled into FSMs (Finite State Machines). In order to parse arbitrarily nested expressions, you can't use a FSM, because you need infinitely many states to keep track of the arbitrary nes... | [
2,
2,
2,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000637773_python_regex.txt |
Q:
Scrape a dynamic website
What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.
--Edit--
For more detail: I'm trying to scrape the C... | Scrape a dynamic website | What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.
--Edit--
For more detail: I'm trying to scrape the CNN primary database. There is... | [
"This is a difficult problem because you either have to reverse engineer the javascript on a per-site basis, or implement a javascript engine and run the scripts (which has its own difficulties and pitfalls).\nIt's a heavy weight solution, but I've seen people doing this with greasemonkey scripts - allow Firefox to... | [
7,
7,
4,
3,
2,
1,
1,
0
] | [] | [] | [
"ajax",
"beautifulsoup",
"python",
"screen_scraping"
] | stackoverflow_0000206855_ajax_beautifulsoup_python_screen_scraping.txt |
Q:
Python script at Visual C++ 2005 build step not spawning other processes
I have the following post-build step in a VC++ 2005 project that calls a Python 2.5.1 script:
postbuild.py
postbuild.py does:
import os
os.system('cd') # cd is just a test, could be anything
The process never starts, and it's the same with ... | Python script at Visual C++ 2005 build step not spawning other processes | I have the following post-build step in a VC++ 2005 project that calls a Python 2.5.1 script:
postbuild.py
postbuild.py does:
import os
os.system('cd') # cd is just a test, could be anything
The process never starts, and it's the same with any other process I try, even using subprocess.call or Popen instead of os.sys... | [
"Solved. For some reason, using \"postbuild.py\" as postbuild step inhibits the python script from spawning other processes, where \"python.exe postbuild.py\" has no problems, and neither \"pythonw.exe postbuild.py\". I'm not sure why this happens, as all three methods are valid when used from cmd.exe.\nBut I would... | [
2,
0
] | [] | [] | [
"post_build_event",
"python",
"spawn",
"spawning",
"visual_c++"
] | stackoverflow_0000642877_post_build_event_python_spawn_spawning_visual_c++.txt |
Q:
Can I override the html_name for a tabularinline field in the admin interface?
Is it possible to override the html naming of fields in TabularInline admin forms so they won't contain dashes?
I'm trying to apply the knowledge obtained here to create a TabularInline admin form that has the auto-complete feature.
It ... | Can I override the html_name for a tabularinline field in the admin interface? | Is it possible to override the html naming of fields in TabularInline admin forms so they won't contain dashes?
I'm trying to apply the knowledge obtained here to create a TabularInline admin form that has the auto-complete feature.
It all works except that Django insists in naming the fields in a tabularinline queryse... | [
"Paolo and Guðmundur are right. I modified my usage in the javascript according to Guðmundur's suggestion and things now work as expected - no django intervention needed.\nSorry for the mental lapse...\nThanks!\n"
] | [
0
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0000640218_django_django_admin_django_forms_python.txt |
Q:
regular expression help with converting exp1^exp2 to pow(exp1, exp2)
I am converting some matlab code to C, currently I have some lines that have powers using the ^, which is rather easy to do with something along the lines \(?(\w*)\)?\^\(?(\w*)\)?
works fine for converting (glambda)^(galpha),using the sub routine... | regular expression help with converting exp1^exp2 to pow(exp1, exp2) | I am converting some matlab code to C, currently I have some lines that have powers using the ^, which is rather easy to do with something along the lines \(?(\w*)\)?\^\(?(\w*)\)?
works fine for converting (glambda)^(galpha),using the sub routine in python pattern.sub(pow(\g<1>,\g<2>),'(glambda)^(galpha)')
My problem c... | [
"Unfortunately, regular expressions aren't the right tool for handling nested structures. There are some regular expressions engines (such as .NET) which have some support for recursion, but most — including the Python engine — do not, and can only handle as many levels of nesting as you build into the expression ... | [
2,
1,
0,
0,
0
] | [] | [] | [
"c",
"python",
"regex"
] | stackoverflow_0000643173_c_python_regex.txt |
Q:
Django: Uploaded file locked. Can't rename
I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.
I have it working when a file is first uploaded, when a new file is uploaded, and when there are no chang... | Django: Uploaded file locked. Can't rename | I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.
I have it working when a file is first uploaded, when a new file is uploaded, and when there are no changes to the file or file title.
However, when the ... | [
"I think you should look more closely at the upload_to field. This would probably be simpler than messing around with renaming during save.\nhttp://docs.djangoproject.com/en/dev/ref/models/fields/#filefield\n\nThis may also be a callable, such as a\n function, which will be called to\n obtain the upload path, in... | [
5,
3,
0
] | [] | [] | [
"django",
"file_io",
"python"
] | stackoverflow_0000637160_django_file_io_python.txt |
Q:
How do I rewrite $x = $hash{blah} || 'default' in Python?
How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:
$x = $hash{blah} || 'default'
What's the equivalent Python?
A:
Use the get(key, default) method:
>>> dict().get("blah", "default")
'default'
A:
If you'... | How do I rewrite $x = $hash{blah} || 'default' in Python? | How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:
$x = $hash{blah} || 'default'
What's the equivalent Python?
| [
"Use the get(key, default) method:\n>>> dict().get(\"blah\", \"default\")\n'default'\n\n",
"If you're going to be doing this a lot, it's better to use collections.defaultdict:\nimport collections\n\n# Define a little \"factory\" function that just builds the default value when called.\ndef get_default_value():\n ... | [
9,
7,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000643950_python.txt |
Q:
How should I conditionally assign based on the existence of a dictionary key?
I've got some Perl code like this:
my $match = $matches{$key}
? "$matches{$key} was a match!"
: "There was no match."
How is this best rewritten in Python? I'm trying to avoid getting a KeyError.
A:
This.
messa... | How should I conditionally assign based on the existence of a dictionary key? | I've got some Perl code like this:
my $match = $matches{$key}
? "$matches{$key} was a match!"
: "There was no match."
How is this best rewritten in Python? I'm trying to avoid getting a KeyError.
| [
"This.\nmessage = \"%s was a match\"%(matches[key],) if key in matches else \"There was no match.\"\n\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0000644062_python.txt |
Q:
help with complex join in Django ORM
class Domains(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
user = models.ManyToManyField("Users", blank=True, null=True)
def __unicode__(self):
return self.name
class Groups(models.Model):
doma... | help with complex join in Django ORM | class Domains(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
user = models.ManyToManyField("Users", blank=True, null=True)
def __unicode__(self):
return self.name
class Groups(models.Model):
domain = models.ForeignKey(Domains)
name =... | [
"I second elo80ka's comment about using singular names for your models. To filter the groups by domain and user, try:\nGroups.objects.filter(domain__user=u)\n\nThis will perform the appropriate join across the many-to-many. As written, the query will return group objects. If you want the name property only, then ap... | [
4,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000644081_django_django_models_python.txt |
Q:
Concurrency implications of EAFP/LBYL
When writing concurrent/multithreaded code in Python, is it especially important to follow the "Easier to Ask for Forgiveness than Permission" (EAFP) idiom, rather than "Look Before You Leap" (LBYL)? Python's exceptionally dynamic nature means that almost anything (e.g., attr... | Concurrency implications of EAFP/LBYL | When writing concurrent/multithreaded code in Python, is it especially important to follow the "Easier to Ask for Forgiveness than Permission" (EAFP) idiom, rather than "Look Before You Leap" (LBYL)? Python's exceptionally dynamic nature means that almost anything (e.g., attribute removal) can happen between looking a... | [
"Your thoughts are correct. Some additional points:\nIf the attribute exists most of the time, try:except: might be much faster than\nthe LBYL idiom.\nIf you don't like the try: except: syntax, you can also write:\nitem = getattr(foo, 'bar', None)\nif item is None:\n ....\nelse:\n ....\n\n"
] | [
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0000644052_multithreading_python.txt |
Q:
Parallel/Async Download of S3 data into EC2 in Python?
I have large data files stored in S3 that I need to analyze. Each batch consists of ~50 files, each of which can be analyzed independently.
I'd like to setup parallel downloads of the S3 data into the EC2 instance, and setup triggers that start the analysis p... | Parallel/Async Download of S3 data into EC2 in Python? | I have large data files stored in S3 that I need to analyze. Each batch consists of ~50 files, each of which can be analyzed independently.
I'd like to setup parallel downloads of the S3 data into the EC2 instance, and setup triggers that start the analysis process on each file that downloads.
Are there any libraries ... | [
"Answering my own question, I ended up writing a simple modification to the Amazon S3 python library that lets you download the file in chunks or read it line by line. Available here.\n",
"It sounds like you're looking for twisted:\n\"Twisted is an event-driven networking engine written in Python and licensed und... | [
3,
0,
0
] | [] | [] | [
"amazon_ec2",
"amazon_s3",
"python"
] | stackoverflow_0000538875_amazon_ec2_amazon_s3_python.txt |
Q:
How does Python sort a list of tuples?
Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?
A:
It automatically sorts a list of tuples by... | How does Python sort a list of tuples? | Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?
| [
"It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0.\n",
"Yes, this i... | [
81,
8,
8,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000644170_python.txt |
Q:
How to handle a glade project with many windows
I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I cal... | How to handle a glade project with many windows | I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I call it like...
self.wTree = gtk.glade.XML("interface.gl... | [
"In my projects, I always have one window per glade file. I'd recommend the same for your project.\nThe following are the two main reasons:\n\nIt will be faster and use less memory, since each call to gtk.glade.XML() parses the whole thing. Sure you can pass in the root argument to avoid creating the widget tree fo... | [
9,
2,
0,
0
] | [] | [] | [
"glade",
"gtk",
"pygtk",
"python"
] | stackoverflow_0000336013_glade_gtk_pygtk_python.txt |
Q:
Python: Incrementally marshal / pickle an object?
I have a large object I'd like to serialize to disk. I'm finding marshal works quite well and is nice and fast.
Right now I'm creating my large object then calling marshal.dump . I'd like to avoid holding the large object in memory if possible - I'd like to dump i... | Python: Incrementally marshal / pickle an object? | I have a large object I'd like to serialize to disk. I'm finding marshal works quite well and is nice and fast.
Right now I'm creating my large object then calling marshal.dump . I'd like to avoid holding the large object in memory if possible - I'd like to dump it incrementally as I build it. Is that possible?
The ob... | [
"The bsddb module's 'hashopen' and 'btopen' functions provide a persistent dictionary-like interface. Perhaps you could use one of these, instead of a regular dictionary, to incrementally serialize the arrays to disk?\nimport bsddb\nimport marshal\n\ndb = bsddb.hashopen('file.db')\ndb['array1'] = marshal.dumps(arra... | [
4,
4,
0,
0
] | [] | [] | [
"data_structures",
"memory_management",
"python",
"serialization"
] | stackoverflow_0000639821_data_structures_memory_management_python_serialization.txt |
Q:
Discussion of multiple inheritance vs Composition for a project (+other things)
I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a num... | Discussion of multiple inheritance vs Composition for a project (+other things) | I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors.
The example below briefly demonstrates the concept.
#prewri... | [
"The sensor architecture can be solved by using composition if you want to stick to your original map-of-data design. You seem to be new to Python so I'll try to keep idioms to a minimum.\nclass IRSensor:\n def read(self): return {'ir_amplitude': 12}\n\nclass UltrasonicSensor:\n def read(self): return {'ultra... | [
12,
1,
1
] | [] | [] | [
"constructor",
"multiple_inheritance",
"oop",
"python"
] | stackoverflow_0000645493_constructor_multiple_inheritance_oop_python.txt |
Q:
Is there a way to build a C-like DLL from a Python module?
I have a Python module with nothing but regular global functions. I need to call it from another business-domain scripting environment that can only call out to C DLLs. Is there anyway to build my Python modules so that to other code it can be called like ... | Is there a way to build a C-like DLL from a Python module? | I have a Python module with nothing but regular global functions. I need to call it from another business-domain scripting environment that can only call out to C DLLs. Is there anyway to build my Python modules so that to other code it can be called like a standard C function that's exported from a DLL? This is for a ... | [
"Take a look at this Codeproject article. One way would be wrap your python functions in a C dll and expose this to the callee.\nCOM is a binary protocol to solve this issue. But you will have to wrap this python dll in a COM wrapper. And add some code on the calling side as well.\n",
"The standard solution is to... | [
6,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0000645892_python.txt |
Q:
How do you make a case for Django [or Ruby on Rails] to non-technical clients
Businessmen typically want a web application developed. They are aware of .net or J2EE by names, without much knowledge about either.
Altho' Rails and Django offer for a much better and faster development stack, it is a big task to convi... | How do you make a case for Django [or Ruby on Rails] to non-technical clients | Businessmen typically want a web application developed. They are aware of .net or J2EE by names, without much knowledge about either.
Altho' Rails and Django offer for a much better and faster development stack, it is a big task to convince businessmen to use these platforms.
The task begins with introducing Django (or... | [
"It's easier to ask forgiveness than permission.\nFirst, build the initial release in Django. Quickly. Build the model well (really well!). But use as much default admin functionality as you can.\nSpend time only only reporting and display pages where the HTML might actually matter to the presentation.\nShow thi... | [
21,
16,
5,
2,
2,
1,
1
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0000644237_django_python_ruby_ruby_on_rails.txt |
Q:
Workflow for configuring apache on a webfaction account via ssh and ftp. (django/python)
I'm new at this, however, when it comes to configuring mod_python/apache or wsgi/apache I suffer.
I've been able to use the python debugger tool.. pdb.set_trace() to success, especially when using the django development server... | Workflow for configuring apache on a webfaction account via ssh and ftp. (django/python) | I'm new at this, however, when it comes to configuring mod_python/apache or wsgi/apache I suffer.
I've been able to use the python debugger tool.. pdb.set_trace() to success, especially when using the django development server, i.e. it out puts to the terminal all of the server activity, including the pdb interface.
So... | [
"How to use pdb with mod_wsgi is documented on the mod_wsgi site. See:\nhttp://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Python_Interactive_Debugger\nOther debugging techniques are shown on the same page.\n"
] | [
1
] | [] | [] | [
"apache",
"django",
"mod_python",
"python"
] | stackoverflow_0000647005_apache_django_mod_python_python.txt |
Q:
Python: How to detect debug interpreter
How can I detect in my python script if its being run by the debug interpreter (ie python_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension.
eg Id like to do something like this at the start of my python script:
#get paths to ... | Python: How to detect debug interpreter | How can I detect in my python script if its being run by the debug interpreter (ie python_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension.
eg Id like to do something like this at the start of my python script:
#get paths to graphics dlls
if debug_build:
d3d9Path ... | [
"Distutils use sys.gettotalrefcount to detect a debug python build:\n# ...\nif hasattr(sys, 'gettotalrefcount'):\n plat_specifier += '-pydebug'\n\n\nthis method doesn't rely on an executable name '*_d.exe'. It works for any name.\nthis method is cross-platform. It doesn't depend on '_d.pyd' suffix.\n\nSee Debuggi... | [
15,
3,
2
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0000646518_debugging_python.txt |
Q:
How do I forward a complete email without downloading attachments?
Hello (and thanks in advance!)
I'm working in Python and I got IMAP and SMTP to work with my Gmail account.
I now need to forward select messages to another account (after reading their body).
How do I do this without downloading the attachments an... | How do I forward a complete email without downloading attachments? | Hello (and thanks in advance!)
I'm working in Python and I got IMAP and SMTP to work with my Gmail account.
I now need to forward select messages to another account (after reading their body).
How do I do this without downloading the attachments and recreating the entire message?
Thanks!
Tal.
| [
"Look at the IMAP and SMTP Lemonade extensions. There is support for forwarding messages without downloading. It's a very new extension, so not many IMAP servers support it yet; I'm not sure if Gmail is one of them.\nSection 2 of RFC 4550 contains the technical details on how this works.\n"
] | [
1
] | [] | [] | [
"forward",
"gmail",
"imap",
"python",
"smtp"
] | stackoverflow_0000647500_forward_gmail_imap_python_smtp.txt |
Q:
Why can I not paste the output of Pythons REPL without manual-editing?
A huge amount of example Python code shows the output of the Python REPL, for example:
>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
..... | Why can I not paste the output of Pythons REPL without manual-editing? | A huge amount of example Python code shows the output of the Python REPL, for example:
>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
Now, the obvious th... | [
"How to run/adopt \"the output of Pythons REPL\"\n\nUse IPython shell\nIn [99]: %cpaste\nPasting code; enter '--' alone on the line to stop.\n:>>> class eg(object):\n:... def __init__(self, name):\n:... self.name = name\n:... def hi(self):\n:... print \"Hi %s\" % (self.name)\n:...\n:... | [
9,
2,
1,
0
] | [] | [] | [
"python",
"read_eval_print_loop",
"user_interface"
] | stackoverflow_0000647142_python_read_eval_print_loop_user_interface.txt |
Q:
socket trouble in python
I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some_file" when it wants to send a file, followed by the file's contents, and the string "end some_file". Here is my client code :
file = sys.argv[1]
host = sys.argv[2]
... | socket trouble in python | I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some_file" when it wants to send a file, followed by the file's contents, and the string "end some_file". Here is my client code :
file = sys.argv[1]
host = sys.argv[2]
port = int(sys.argv[3])
sock =... | [
"With socket programming, even if you do 2 independent sends, it doesn't mean that the other side will receive them as 2 independent recvs.\nOne simple solution that works for both strings and binary data is to: First send the number of bytes in the message, then send the message.\nHere is what you should do for ea... | [
9,
1,
0
] | [
"TCP/IP data is buffered, more-or-less randomly.\nIt's just a \"stream\" of bytes. If you want, you can read it as though it's delimited by '\\n' characters. However, it is not broken into meaningful chunks; nor can it be. It must be a continuous stream of bytes.\nHow are you reading it in C? Are you reading up... | [
-3
] | [
"python",
"sockets"
] | stackoverflow_0000647813_python_sockets.txt |
Q:
File handling in Django when posting image from service call
I am using PyAMF to transfer a dynamically generated large image from Flex to Django.
On the Django side i receive the encodedb64 data as a parameter:
My Item model as an imagefield.
What i have trouble to do is saving the data as the File Django Field.
... | File handling in Django when posting image from service call | I am using PyAMF to transfer a dynamically generated large image from Flex to Django.
On the Django side i receive the encodedb64 data as a parameter:
My Item model as an imagefield.
What i have trouble to do is saving the data as the File Django Field.
def save_item(request, uname, data):
""" Save a new item """ ... | [
"In django.core.files.base you can find the class ContentFile. That class extends the basic Django File class, so you do not need StringIO (which ContentFile though uses internally). The modified save method looks like this:\nfrom django.core.files.base import ContentFile\ndef save_item(request, uname, data):\n ... | [
9
] | [] | [] | [
"apache_flex",
"django",
"pyamf",
"python"
] | stackoverflow_0000647888_apache_flex_django_pyamf_python.txt |
Q:
How to make a list comprehension with the group() method in python?
I'm trying to write a little script to clean my directories. In fact I have:
pattern = re.compile(format[i])
...
current_f.append(pattern.search(str(ls)))
and I want to use a list comprehension but when I try:
In [25]: [i for i in current_f.group... | How to make a list comprehension with the group() method in python? | I'm trying to write a little script to clean my directories. In fact I have:
pattern = re.compile(format[i])
...
current_f.append(pattern.search(str(ls)))
and I want to use a list comprehension but when I try:
In [25]: [i for i in current_f.group(0)]
I get:
AttributeError: 'list' object has no attribute 'group'
So h... | [
"Are you trying to do this?:\n[f.group(0) for f in current_f]\n\n"
] | [
7
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0000648276_list_list_comprehension_python.txt |
Q:
Why don't Django admin "Today" and "Now" buttons show up in Safari?
I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:
alt text http://www.cs.wm.edu/~mpd/images/bugs/djan... | Why don't Django admin "Today" and "Now" buttons show up in Safari? | I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:
alt text http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png
This is as expected. However, when I deploy to my webse... | [
"I think you have to look at what is different between your firefox configuration and safary config\nOff the top of my head:\n\nOne could be configured to use a proxy (messing with the trafic) the other not. Make sure the configuration is the same in both.\nSafari could have cached the error clear the cache before ... | [
3,
2,
1,
0,
0
] | [] | [] | [
"django",
"javascript",
"python",
"safari",
"webkit"
] | stackoverflow_0000443920_django_javascript_python_safari_webkit.txt |
Q:
Print out list of function parameters in Python
Is there a way to print out a function's parameter list?
For example:
def func(a, b, c):
pass
print_func_parametes(func)
Which will produce something like:
["a", "b", "c"]
A:
Use the inspect module.
>>> import inspect
>>> inspect.getargspec(func)
(['a', 'b', 'c... | Print out list of function parameters in Python | Is there a way to print out a function's parameter list?
For example:
def func(a, b, c):
pass
print_func_parametes(func)
Which will produce something like:
["a", "b", "c"]
| [
"Use the inspect module.\n>>> import inspect\n>>> inspect.getargspec(func)\n(['a', 'b', 'c'], None, None, None)\n\nThe first part of returned tuple is what you're looking for.\n",
"Read the source. Seriously. Python programs and libraries are provided as source. You can read the source.\n",
"You might also t... | [
17,
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0000648679_python.txt |
Q:
Why are Python objects of different types ordered by type names?
From Python docs: http://docs.python.org/library/stdtypes.html#comparisons
Implementation note: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by ... | Why are Python objects of different types ordered by type names? | From Python docs: http://docs.python.org/library/stdtypes.html#comparisons
Implementation note: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
Is there any reason for choosing to do this over raisi... | [
"About four lines up from that line you quoted:\n\nObjects of different types, except\n different numeric types and different\n string types, never compare equal;\n such objects are ordered consistently\n but arbitrarily (so that sorting a\n heterogeneous array yields a\n consistent result).\n\nYou don't want... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0000649191_python.txt |
Q:
In Python, is it possible to access the class which contains a method, given only a method object?
I'm pretty new to Python, and haven't been able to find an answer to this question from searching online.
Here is an example decorator that does nothing (yet)
def my_decorator(text):
def wrap(f):
# grab magic f... | In Python, is it possible to access the class which contains a method, given only a method object? | I'm pretty new to Python, and haven't been able to find an answer to this question from searching online.
Here is an example decorator that does nothing (yet)
def my_decorator(text):
def wrap(f):
# grab magic f.parent_class_object.my_var and append text
def wrap_f(*args, **kwargs):
f(*args, **kwargs)
... | [
"It is not possible to read it from a function inside a class decorator, since the \"methods\" are still normal function while the class is being compiled. Also, the class name has not been defined while it is being compiled.\nWhat you could do is supply the my_var list to the decorator.\nclass MyClass:\n my_var... | [
3
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0000649329_decorator_python.txt |
Q:
wxPython auinotebook.GetSelection() return index to the first page
Why do 'GetSelection()' return the index to the first page and not the last created in 'init' and 'new_panel'? It do return correct index in the 'click' method.
The output should be 0 0 1 1 2 2, but mine is 0 0 0 0 0 0.
Running latest version of py... | wxPython auinotebook.GetSelection() return index to the first page | Why do 'GetSelection()' return the index to the first page and not the last created in 'init' and 'new_panel'? It do return correct index in the 'click' method.
The output should be 0 0 1 1 2 2, but mine is 0 0 0 0 0 0.
Running latest version of python and wxpython in ArchLinux.
Ørjan Pettersen
#!/usr/bin/python
#12_a... | [
"The solution was pretty simple. The problem seemed to be that creating the new page didn't generate a page change event.\nThe solution is:\nself.nb.AddPage(pnl, nm, select=True)\n\nAdding 'select=True' will trigger a page change event. So problem solved.\nAnother solution is to add this line:\nself.nb.SetSelection... | [
1,
0
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0000647906_python_wxpython_wxwidgets.txt |
Q:
Directory checksum with python?
So I'm in the middle of web-based filesystem abstraction layer development.
Just like file browser, except it has some extra features like freaky permissions etc.
I would like users to be notified somehow about directory changes.
So, i.e. when someone uploads a new file via FTP, ... | Directory checksum with python? | So I'm in the middle of web-based filesystem abstraction layer development.
Just like file browser, except it has some extra features like freaky permissions etc.
I would like users to be notified somehow about directory changes.
So, i.e. when someone uploads a new file via FTP, certain users should get a proper mes... | [
"If your server is Linux you can do this with something like inotify\nIf the only updates are coming from FTP, then another solution I've used in the past is to write an add-on module to ProFTPD that performs the \"notification\" once upload is complete.\n",
"See this question: How to quickly find added / removed... | [
2,
1,
0
] | [] | [] | [
"checksum",
"file",
"filesystems",
"python"
] | stackoverflow_0000649623_checksum_file_filesystems_python.txt |
Q:
Do Python lists have an equivalent to dict.get?
I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?
if 13 in intList:
i = intList.index(13)
In the case of dictionaries, there's a get function which will asc... | Do Python lists have an equivalent to dict.get? | I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?
if 13 in intList:
i = intList.index(13)
In the case of dictionaries, there's a get function which will ascertain membership and perform look-up with the same s... | [
"You answered it yourself, with the index() method. That will throw an exception if the index is not found, so just catch that:\ndef getIndexOrMinusOne(a, x):\n try:\n return a.index(x)\n except ValueError:\n return -1\n\n",
"It looks like you'll just have to catch the exception...\ntry:\n i = intList.... | [
14,
8,
4,
2
] | [
"Just put what you got in a function and use it:) \nYou can either use if i in list: return list.index(i) or the try/except, depending on your preferences.\n"
] | [
-1
] | [
"list",
"python"
] | stackoverflow_0000650340_list_python.txt |
Q:
How do you substitue a Python capture followed by a number character?
When using re.sub, how to you handle a situation where you need a capture followed by a number in the replacement string? For example, you cannot use "\10" for capture 1 followed by a '0' character because it will be interpreted as capture 10.
... | How do you substitue a Python capture followed by a number character? | When using re.sub, how to you handle a situation where you need a capture followed by a number in the replacement string? For example, you cannot use "\10" for capture 1 followed by a '0' character because it will be interpreted as capture 10.
| [
"\\g<1>0\n\nhttp://docs.python.org/library/re.html#re.sub\n\n\\g<number> uses the corresponding\n group number; \\g<2> is therefore\n equivalent to \\2, but isn’t ambiguous\n in a replacement such as \\g<2>0. \\20\n would be interpreted as a reference to\n group 20, not a reference to group 2\n followed by th... | [
6
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0000650926_python_regex_string.txt |
Q:
Is it possible, with the Python Standard Library (say version 2.5) to perform MS-SQL queries which are parameterized?
While the particular data I'm working with right now will not be user-generated, and will be sanitized within an inch of its life during my usual validation routines, I would like to learn how to d... | Is it possible, with the Python Standard Library (say version 2.5) to perform MS-SQL queries which are parameterized? | While the particular data I'm working with right now will not be user-generated, and will be sanitized within an inch of its life during my usual validation routines, I would like to learn how to do your basic INSERT, SELECT, etc. SQL queries while protecting myself against SQL injection attacks, just for future refere... | [
"PEP 249 (DB API 2.0) defines 5 paramstyles, PyMSSQL uses paramstyle == pyformat. But although it looks like string interpolation, it is actually binding.\nNote difference between binding:\ncur.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')\n\nand interpolating (this is how it should NOT be done):\n... | [
5,
2
] | [] | [] | [
"binding",
"parameters",
"python",
"sql",
"sql_injection"
] | stackoverflow_0000650979_binding_parameters_python_sql_sql_injection.txt |
Q:
Bimodal distribution in C or Python
What's the easiest way to generate random values according to a bimodal distribution in C or Python?
I could implement something like the Ziggurat algorithm or a Box-Muller transform, but if there's a ready-to-use library, or a simpler algorithm I don't know about, that'd be bet... | Bimodal distribution in C or Python | What's the easiest way to generate random values according to a bimodal distribution in C or Python?
I could implement something like the Ziggurat algorithm or a Box-Muller transform, but if there's a ready-to-use library, or a simpler algorithm I don't know about, that'd be better.
| [
"Aren't you just picking values either of two modal distributions?\nhttp://docs.python.org/library/random.html#random.triangular\nSounds like you just toggle back and forth between two sets of parameters for your call to triangular.\ndef bimodal( low1, high1, mode1, low2, high2, mode2 ):\n toss = random.choice( ... | [
5,
2
] | [] | [] | [
"c",
"python",
"random"
] | stackoverflow_0000651421_c_python_random.txt |
Q:
What's the best way to replace the ternary operator in Python?
Possible Duplicate:
Ternary conditional operator in Python
If I have some code like:
x = foo ? 1 : 2
How should I translate it to Python? Can I do this?
if foo:
x = 1
else:
x = 2
Will x still be in scope outside the if / then blocks? Or do I ha... | What's the best way to replace the ternary operator in Python? |
Possible Duplicate:
Ternary conditional operator in Python
If I have some code like:
x = foo ? 1 : 2
How should I translate it to Python? Can I do this?
if foo:
x = 1
else:
x = 2
Will x still be in scope outside the if / then blocks? Or do I have to do something like this?
x = None
if foo:
x = 1
else:
x = ... | [
"Use the ternary operator(formally conditional expression) in Python 2.5+.\nx = 1 if foo else 2\n\n",
"A nice python trick is using this:\nfoo = [\"ifFalse\",\"ifTrue\"][booleanCondition]\n\nIt creates a 2 membered list, and the boolean becomes either 0 (false) or 1 (true), which picks the correct member.\nNot ve... | [
32,
10,
5,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0000643983_python.txt |
Q:
What's the best way to initialize a dict of dicts in Python?
A lot of times in Perl, I'll do something like this:
$myhash{foo}{bar}{baz} = 1
How would I translate this to Python? So far I have:
if not 'foo' in myhash:
myhash['foo'] = {}
if not 'bar' in myhash['foo']:
myhash['foo']['bar'] = {}
myhash['foo'... | What's the best way to initialize a dict of dicts in Python? | A lot of times in Perl, I'll do something like this:
$myhash{foo}{bar}{baz} = 1
How would I translate this to Python? So far I have:
if not 'foo' in myhash:
myhash['foo'] = {}
if not 'bar' in myhash['foo']:
myhash['foo']['bar'] = {}
myhash['foo']['bar']['baz'] = 1
Is there a better way?
| [
"If the amount of nesting you need is fixed, collections.defaultdict is wonderful.\ne.g. nesting two deep:\nmyhash = collections.defaultdict(dict)\nmyhash[1][2] = 3\nmyhash[1][3] = 13\nmyhash[2][4] = 9\n\nIf you want to go another level of nesting, you'll need to do something like:\nmyhash = collections.defaultdict... | [
127,
110,
15,
2
] | [] | [] | [
"autovivification",
"python"
] | stackoverflow_0000651794_autovivification_python.txt |
Q:
Simultaneously inserting and extending a list?
Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):
>>> a = ['1', '2', '3', '4']
>>> b = a[:a.index('2')+1] + ['2.4', '2.6'] ... | Simultaneously inserting and extending a list? | Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):
>>> a = ['1', '2', '3', '4']
>>> b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'):]
>>> b
<<< ['1', '2', '2.4', '2.6'... | [
">>> a = ['1', '2', '3', '4']\n>>> a\n['1', '2', '3', '4']\n>>> i = a.index('2') + 1 # after the item '2'\n>>> a[i:i] = ['2.4', '2.6']\n>>> a\n['1', '2', '2.4', '2.6', '3', '4']\n>>>\n\n",
"You can easily insert a single element using list.insert(i, x), which Python defines as s[i:i] = [x].\na = ['1', '2', '3', ... | [
15,
5,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0000652184_python.txt |
Q:
Check if value exists in nested lists
in my list:
animals = [ ['dog', ['bite'] ],
['cat', ['bite', 'scratch'] ],
['bird', ['peck', 'bite'] ], ]
add('bird', 'peck')
add('bird', 'screech')
add('turtle', 'hide')
The add function should check that the animal and action haven't been added b... | Check if value exists in nested lists | in my list:
animals = [ ['dog', ['bite'] ],
['cat', ['bite', 'scratch'] ],
['bird', ['peck', 'bite'] ], ]
add('bird', 'peck')
add('bird', 'screech')
add('turtle', 'hide')
The add function should check that the animal and action haven't been added before adding them to the list. Is there a ... | [
"You're using the wrong data type. Use a dict of sets instead:\ndef add(key, value, userdict):\n userdict.setdefault(key, set())\n userdict[key].add(value)\n\nUsage:\nanimaldict = {}\nadd('bird', 'peck', animaldict)\nadd('bird', 'screech', animaldict)\nadd('turtle', 'hide', animaldict)\n\n",
"While it is p... | [
6,
4,
4,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000652423_python.txt |
Q:
Writing a binary buffer to a file in python
I have some python code that:
Takes a BLOB from a database which is compressed.
Calls an uncompression routine in C that uncompresses the data.
Writes the uncompressed data to a file.
It uses ctypes to call the C routine, which is in a shared library.
This mostly works... | Writing a binary buffer to a file in python | I have some python code that:
Takes a BLOB from a database which is compressed.
Calls an uncompression routine in C that uncompresses the data.
Writes the uncompressed data to a file.
It uses ctypes to call the C routine, which is in a shared library.
This mostly works, except for the actual writing to the file. To u... | [
"Slicing works for c_char_Arrays too:\nmyfile.write(c_uncompData_p[:c_uncompSize])\n\n",
"buffer() might help to avoid unnecessary copying (caused by slicing as in @elo80ka's answer):\nmyfile.write(buffer(c_uncompData_p.raw, 0, c_uncompSize))\n\nIn your example it doesn't matter (due to c_uncompData_p is written ... | [
6,
6
] | [] | [] | [
"binary",
"io",
"python"
] | stackoverflow_0000652535_binary_io_python.txt |
Q:
Effective way to iteratively append to a string in Python?
I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a bett... | Effective way to iteratively append to a string in Python? | I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a better way to do this?
def getwords(text, splitchars=' \t|!?.;:"'):
... | [
"http://www.skymind.com/~ocrow/python_string/ talks about several ways of concatenating strings in Python and assesses their performance as well. \n",
"You don't want to use re.split?\nimport re\nre.split(\"[,; ]+\", \"coucou1 , coucou2;coucou3\")\n\n",
"You can use re.split\nre.split('[\\s|!\\?\\.;:\"]', tex... | [
5,
4,
3,
1
] | [] | [] | [
"append",
"generator",
"python",
"split",
"string"
] | stackoverflow_0000653259_append_generator_python_split_string.txt |
Q:
For Python programmers, is there anything equivalent to Perl's CPAN?
I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Py... | For Python programmers, is there anything equivalent to Perl's CPAN? | I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modu... | [
"sammy, have a look at pip, which will let you do \"pip install foo\", and will download and install its dependencies (as long as they're on PyPI). There's also EasyInstall, but pip is intended to replace that.\n",
"It might be useful to note that pip and easy_install both use the Python Package Index (PyPI), som... | [
33,
11,
2
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0000410163_perl_python.txt |
Q:
A simple freeze behavior decorator
I'm trying to write a freeze decorator for Python.
The idea is as follows :
(In response to the two comments)
I might be wrong but I think there is two main use of
test case.
One is the test-driven development :
Ideally , developers are writing case before writing the code.
It... | A simple freeze behavior decorator | I'm trying to write a freeze decorator for Python.
The idea is as follows :
(In response to the two comments)
I might be wrong but I think there is two main use of
test case.
One is the test-driven development :
Ideally , developers are writing case before writing the code.
It usually helps defining the architecture... | [
"\"In general, would you use such a feature, knowing its limitation...?\"\nFrankly speaking -- never.\nThere are no circumstances under which I would \"freeze\" results of a function in this way.\nThe use case appears to be based on two wrong ideas: (1) that unit testing is either hard or complex or expensive; and... | [
3,
0
] | [] | [] | [
"decorator",
"freeze",
"python",
"testing"
] | stackoverflow_0000653783_decorator_freeze_python_testing.txt |
Q:
sorting a list of dictionary values by date in python
I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.
ex:
data = "data from database"
list = []
for x in data:
dict = {'title':title, 'date': x.created_on}
list.append(... | sorting a list of dictionary values by date in python | I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.
ex:
data = "data from database"
list = []
for x in data:
dict = {'title':title, 'date': x.created_on}
list.append(dict)
I want to sort the list in reverse order by value of... | [
"You can do it this way:\nlist.sort(key=lambda item:item['date'], reverse=True)\n\n",
"from operator import itemgetter\n\nyour_list.sort(key=itemgetter('date'), reverse=True)\n\nRelated notes\n\ndon't use list, dict as variable names, they are builtin names in Python. It makes your code hard to read.\nyou might n... | [
81,
24,
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0000652291_python.txt |
Q:
How do I create a unique value for each key using dict.fromkeys?
First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use dict.fromkeys (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and ... | How do I create a unique value for each key using dict.fromkeys? | First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use dict.fromkeys (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the list to contain ... | [
"The problem is that in \nresults = dict.fromkeys(inputs, [])\n\n[] is evaluated only once, right there. \nI'd rewrite this code like that:\nruns = 10\ninputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)\nresults = {}\n\nfor run in range(runs):\n for i in inputs:\n results.setdefault(i,[]).append(benchmark(i))\n\nO... | [
13,
12,
2
] | [] | [] | [
"dictionary",
"fromkeys",
"python"
] | stackoverflow_0000654646_dictionary_fromkeys_python.txt |
Q:
Python Hash Functions
What is a good way of hashing a hierarchy (similar to a file structure) in python?
I could convert the whole hierarchy into a dotted string and then hash that, but is there a better (or more efficient) way of doing this without going back and forth all the time?
An example of a structure I mi... | Python Hash Functions | What is a good way of hashing a hierarchy (similar to a file structure) in python?
I could convert the whole hierarchy into a dotted string and then hash that, but is there a better (or more efficient) way of doing this without going back and forth all the time?
An example of a structure I might want to hash is:
a -> b... | [
"If you have access to your hierarchy components as a tuple, just hash it - tuples are hashable. You may not gain a lot over conversion to and from a delimited string, but it's a start.\nIf this doesn't help, perhaps you could provide more information about how you store the hierarchy/path information.\n",
"How ... | [
8,
4,
1
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0000654128_hash_python.txt |
Q:
Sending Rich Text Format email using Outlook 2003
I am trying to send a Rich Text Format email message using Outlook 2003.
The following code results the RTF HTML source code to be dumped into the mail message body.
What should I do in order to fix that, and make Outlook display the formatted data and not the sour... | Sending Rich Text Format email using Outlook 2003 | I am trying to send a Rich Text Format email message using Outlook 2003.
The following code results the RTF HTML source code to be dumped into the mail message body.
What should I do in order to fix that, and make Outlook display the formatted data and not the source HTML ?
import win32com.client
RTFTEMPLATE = """<!DO... | [
"If you must use RTF, you will need to convert your HTML to RTF format. Check out the zopyx package.\nTo use HTML, change the line:\nmainMsg.Body = RTFTEMPLATE % (subject,body)\n\nto:\nmainMsg.HTMLBody = RTFTEMPLATE % (subject,body)\n\n"
] | [
0
] | [] | [] | [
"email",
"outlook",
"python"
] | stackoverflow_0000655180_email_outlook_python.txt |
Q:
splitting a ManyToManyField over multiple form fields in a ModelForm
So I have a model with a ManyToManyField called tournaments. I have a ModelForm with two tournament fields:
pay_tourns = forms.ModelMultipleChoiceField(
queryset=Tourn.objects.all().active().pay_tourns(),
... | splitting a ManyToManyField over multiple form fields in a ModelForm | So I have a model with a ManyToManyField called tournaments. I have a ModelForm with two tournament fields:
pay_tourns = forms.ModelMultipleChoiceField(
queryset=Tourn.objects.all().active().pay_tourns(),
widget=forms.CheckboxSelectMultiple())
rep_tourns = forms.ModelMult... | [
"You could do something like this to the ModelForm: \ndef __init__(self, *args, **kwargs):\n super(MyForm, self).__init__(*args, **kwargs)\n\n instance = kwargs.get('instance')\n if instance:\n self.fields['pay_tourns'].queryset.filter(post=instance)\n self.fields['rep_tourns'].queryset.filte... | [
2,
1
] | [] | [] | [
"django",
"django_forms",
"modelform",
"python"
] | stackoverflow_0000654576_django_django_forms_modelform_python.txt |
Q:
python regular expression for retweets
i'm working on a regex that will extract retweet keywords and user names from tweets. here's an example, with a rather terrible regex to do the job:
tweet='foobar RT@one, @two: @three barfoo'
m=re.search(r'(RT|retweet|from|via)\b\W*@(\w+)\b\W*@(\w+)\b\W*@(\w+)\b\W*',tweet)
m.... | python regular expression for retweets | i'm working on a regex that will extract retweet keywords and user names from tweets. here's an example, with a rather terrible regex to do the job:
tweet='foobar RT@one, @two: @three barfoo'
m=re.search(r'(RT|retweet|from|via)\b\W*@(\w+)\b\W*@(\w+)\b\W*@(\w+)\b\W*',tweet)
m.groups()
('RT', 'one', 'two', 'three')
what... | [
"Try\n(RT|retweet|from|via)(?:\\b\\W*@(\\w+))+'\n\nEnclosing the \\b\\W*@(\\w+) in '(?:...)` allows you to group the terms for repetition without capturing the aggregate.\nI'm not sure I'm following the second part of your question, but I think you may be looking for something involving a construct like:\n(?:(?!RT|... | [
3
] | [] | [] | [
"python",
"regex",
"twitter"
] | stackoverflow_0000655903_python_regex_twitter.txt |
Q:
Rotation based on end points
I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling.
It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rota... | Rotation based on end points | I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling.
It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing i... | [
"Here is the complete code to do it. Note that when using pygame, the y co-ordinate is measured from the top, and so we take the negative when using math functions.\nimport pygame\nimport math\nimport random\npygame.init()\n\nscreen=pygame.display.set_mode((300,300))\nscreen.fill((255,255,255))\n\npos1=random.randr... | [
9,
2,
1,
1
] | [] | [] | [
"geometry",
"pygame",
"python"
] | stackoverflow_0000650646_geometry_pygame_python.txt |
Q:
Implementation: How to retrieve and send emails for different Gmail accounts?
I need advice and how to got about setting up a simple service for my users. I would like to add a new feature where users can send and receive emails from their gmail account. I have seen this done several times and I know its possible.... | Implementation: How to retrieve and send emails for different Gmail accounts? | I need advice and how to got about setting up a simple service for my users. I would like to add a new feature where users can send and receive emails from their gmail account. I have seen this done several times and I know its possible.
There use to be a project for "Libgmailer" at sourceforge but I think it was aband... | [
"any library/source that works with imap or pop will work.\n",
"Well if Google didn't come up with anything personally I'd see if I could reverse engineer the Python API by implementing it and watching it with a packet sniffer. My guess is it's just accessing some web service which should be pretty easy to mimic ... | [
6,
0,
0
] | [] | [] | [
"email",
"gmail",
"php",
"python"
] | stackoverflow_0000656180_email_gmail_php_python.txt |
Q:
How to implement Google Suggest in your own web application (e.g. using Python)
In my website, users have the possibility to store links.
During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.
Example:
User is... | How to implement Google Suggest in your own web application (e.g. using Python) | In my website, users have the possibility to store links.
During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.
Example:
User is typing as URL:
http://www.sta
Suggestions which would be displayed:
http://www.stap... | [
"You could try with\nhttp://google.com/complete/search?output=toolbar&q=keyword\nand then parse the xml result.\n",
"I did this once before in a Django server. There's two parts - client-side and server-side.\nClient side you will have to send out XmlHttpRequests to the server as the user is typing, and then when... | [
8,
2,
1,
0,
0
] | [] | [] | [
"autocomplete",
"autosuggest",
"python"
] | stackoverflow_0000255700_autocomplete_autosuggest_python.txt |
Q:
Why did Python 2.6 add a global next() function?
I noticed that Python2.6 added a next() to it's list of global functions.
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method.
If default is given, it is returned if
the iterator is exhausted, otherwise
StopIteration... | Why did Python 2.6 add a global next() function? | I noticed that Python2.6 added a next() to it's list of global functions.
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method.
If default is given, it is returned if
the iterator is exhausted, otherwise
StopIteration is raised.
What was the motivation for adding this?
... | [
"It's just for consistency with functions like len(). I believe next(i) calls i.__next__() internally.\nSee http://www.python.org/dev/peps/pep-3114/\n",
"Note that in Python 3.0+ the next method has been renamed to __next__. This is because of consistency. next is a special method and special methods are named by... | [
18,
10,
0
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0000656155_python_python_2.6.txt |
Q:
Django form fails validation on a unique field
I have a simple model that is defined as:
class Article(models.Model):
slug = models.SlugField(max_length=50, unique=True)
title = models.CharField(max_length=100, unique=False)
and the form:
class ArticleForm(ModelForm):
class Meta:
model = Arti... | Django form fails validation on a unique field | I have a simple model that is defined as:
class Article(models.Model):
slug = models.SlugField(max_length=50, unique=True)
title = models.CharField(max_length=100, unique=False)
and the form:
class ArticleForm(ModelForm):
class Meta:
model = Article
The validation here fails when I try to update ... | [
"I don't think you are actually updating an existing article, but instead creating a new one, presumably with more or less the same content, especially the slug, and thus you will get an error. It is a bit strange that you don't get better error reporting, but also I do not know what the rest of your view looks lik... | [
28,
5,
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000526457_django_python.txt |
Q:
Accessing Microsoft Automation Objects from Python
I have a set of macros that I have turned into an add-in in excel. The macros allow me to interact with another program that has what are called Microsoft Automation Objects that provide some control over what the other program does. For example, I have a filter... | Accessing Microsoft Automation Objects from Python | I have a set of macros that I have turned into an add-in in excel. The macros allow me to interact with another program that has what are called Microsoft Automation Objects that provide some control over what the other program does. For example, I have a filter tool in the add-in that filters the list provided by th... | [
"You will probably need the win32com package.\nThis is a sample exemple I found at : http://www.markcarter.me.uk/computing/python/excel.html which shows how to use com with Excel. This might be a good start.\n# this example starts Excel, creates a new workbook, \n# puts some text in the first and second cell\n# clo... | [
15,
5,
0,
0
] | [] | [] | [
"automation",
"object",
"python"
] | stackoverflow_0000659018_automation_object_python.txt |
Q:
pinging mysql using mysql alchemy and python
how do i ping mysql using mysql alchemy and python?
A:
Use mysqlshow to see if MySQL is running as expected.
http://dev.mysql.com/doc/refman/5.1/en/mysqlshow.html
Assure that SQLAlchemy has supprt for MySQL.
http://www.sqlalchemy.org/docs/05/dbengine.html#supported-db... | pinging mysql using mysql alchemy and python | how do i ping mysql using mysql alchemy and python?
| [
"Use mysqlshow to see if MySQL is running as expected.\nhttp://dev.mysql.com/doc/refman/5.1/en/mysqlshow.html\nAssure that SQLAlchemy has supprt for MySQL.\nhttp://www.sqlalchemy.org/docs/05/dbengine.html#supported-dbapis\nUse a simple query through SQLAlchemy.\nhttp://www.sqlalchemy.org/docs/05/ormtutorial.html\n"... | [
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0000658888_mysql_python.txt |
Q:
Python sequence naming convention
Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. O... | Python sequence naming convention | Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous PEP... | [
"In general, avoid this kind of behaviour. Notice from PEP8\n\nA Foolish Consistency is the Hobgoblin\n of Little Minds\n\nwhich is exactly what calling a variable weightss would be doing. So in general have your variables describing what they are, not according to some naming convention:\nweights = [44, 66, 88]\n... | [
20,
10,
0,
0
] | [] | [] | [
"naming_conventions",
"python",
"sequence"
] | stackoverflow_0000659415_naming_conventions_python_sequence.txt |
Q:
How to get distinct Django apps on same subdomain to share session cookie?
We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID fr... | How to get distinct Django apps on same subdomain to share session cookie? | We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID from Django.
I don't use the Django session table much except in one complex wor... | [
"I would instead advise you to set SESSION_COOKIE_NAME to different values for the two apps. Your users will still have to log in twice initially, but their sessions won't conflict - if they log in to app A, then app B, and return to A, they'll still have their A session.\nSharing sessions between Django instances ... | [
19,
9
] | [] | [] | [
"cookies",
"deployment",
"django",
"python",
"session"
] | stackoverflow_0000556907_cookies_deployment_django_python_session.txt |
Q:
How do I find the modules that are available for import from within a package?
Is there a way of knowing which modules are available to import from inside a package?
A:
Many packages will include a list called __all__, which lists the member modules. This is used when python does from x import *. You can read ... | How do I find the modules that are available for import from within a package? | Is there a way of knowing which modules are available to import from inside a package?
| [
"Many packages will include a list called __all__, which lists the member modules. This is used when python does from x import *. You can read more about that here.\nIf the package does not define __all__, you'll have to do something like the answer to a question I asked earlier, here.\n"
] | [
3
] | [
"You have the source.\nLook at the files inside the package directory. Those modules are available for you to import.\n",
"dir([object]);\nWithout arguments, dir() return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.\nSo, in the case... | [
-1,
-1,
-2
] | [
"import",
"python"
] | stackoverflow_0000657868_import_python.txt |
Q:
How to manage a CPU intensive process on a server
I need to run a CPU- and memory-heavy Python script (analyzing and altering a lengthy WAV file) as a background process on my web server (a VPS), between HTTP requests.
The script takes up to 20 seconds to run and I am concerned about the performance on my server. ... | How to manage a CPU intensive process on a server | I need to run a CPU- and memory-heavy Python script (analyzing and altering a lengthy WAV file) as a background process on my web server (a VPS), between HTTP requests.
The script takes up to 20 seconds to run and I am concerned about the performance on my server. Is there a good approach to either lower the priority o... | [
"Assuming it's a UNIX server, you could use the nice command to lower its priority. That should do the trick.\n",
"You can use cpulimit on a linux based server. It will allow you to limit the CPU usage (specify the limit as a percentage) even of scripts that have already started running, and its usage is pretty ... | [
7,
5
] | [] | [] | [
"performance",
"python",
"signal_processing"
] | stackoverflow_0000660059_performance_python_signal_processing.txt |
Q:
.NET Framework equivalent for Python's imghdr
Python's imghdr module determines the type of image contained in a file or byte stream.
Is there an equivalent for python's imghdr module in the .Net Framework?
A:
Just recently I needed to determine mime type used in file. I don't know the exact logic behind this w... | .NET Framework equivalent for Python's imghdr | Python's imghdr module determines the type of image contained in a file or byte stream.
Is there an equivalent for python's imghdr module in the .Net Framework?
| [
"Just recently I needed to determine mime type used in file. I don't know the exact logic behind this windows API calls, but I suspect it goes inside the file to get idea of it's mime type. Hope this will help\nusing System;\nusing System.IO;\nusing System.Runtime.InteropServices;\n\nnamespace SomeNamespace\n{\n ... | [
0,
0
] | [] | [] | [
".net",
"c#",
"python"
] | stackoverflow_0000660057_.net_c#_python.txt |
Q:
Linking to Python import library in Visual Studio 2005
I have a C++ application that has embedded Python. I'm building with Visual Studio 2005. When I try to link to python26.lib, I get a number of unresolved symbols, all of which begin with "__imp":
error LNK2019: unresolved external symbol __imp__Py_Initialize r... | Linking to Python import library in Visual Studio 2005 | I have a C++ application that has embedded Python. I'm building with Visual Studio 2005. When I try to link to python26.lib, I get a number of unresolved symbols, all of which begin with "__imp":
error LNK2019: unresolved external symbol __imp__Py_Initialize referenced in function _main
python26.lib is an import librar... | [
"Looks like I was trying to link a 64-bit Python library to a 32-bit application. I wish the linker would tell me something other than \"unresolved symbol.\" Linking to the 32-bit library fixes the problem. \n",
"Try to include C:\\WINDOWS\\system32\\python26.dll in your references. python26.lib contains the symb... | [
13,
2
] | [] | [] | [
"import",
"linker",
"python",
"visual_studio"
] | stackoverflow_0000658879_import_linker_python_visual_studio.txt |
Q:
Checking file attributes in python
I'd like to check the archive bit for each file in a directory using python. So far i've got the following but i can't get it to work properly. The idea of the script is to be able to see all the files that have the archive bit on.
Thanks
# -*- coding: latin-1 -*-
import os , win... | Checking file attributes in python | I'd like to check the archive bit for each file in a directory using python. So far i've got the following but i can't get it to work properly. The idea of the script is to be able to see all the files that have the archive bit on.
Thanks
# -*- coding: latin-1 -*-
import os , win32file, win32con
from time import *
star... | [
"The file list returned from os.walk are not fully qualified paths, so when you call\nwin32file.GetFileAttributes(i)\n\nit can't find the file and returns an error code; which happens to be -1. So the operation\nfattrs & win32con.FILE_ATTRIBUTE_ARCHIVE \n\nis always true.\nYou need to join the root to the filename ... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0000659847_python.txt |
Q:
Python lib to Read a Flash swf Format File
I'm interested in using Python to hack on the data in Flash swf files. There is good documentation available on the format of swf files, and I am considering writing my own Python lib to parse that data out using the standard Python struct lib.
Does anybody know of a Pyt... | Python lib to Read a Flash swf Format File | I'm interested in using Python to hack on the data in Flash swf files. There is good documentation available on the format of swf files, and I am considering writing my own Python lib to parse that data out using the standard Python struct lib.
Does anybody know of a Python project that already does this? I would als... | [
"Well, unless you're doing it for fun (in which case, go for it!), why not use Ming? It supposedly has python wrappers...\n",
"I found another option in SWF Tools. They provide a Python wrapper that supports generating SWF files in Python.\nI'm not sure if either SWF Tools or Ming actually supports parsing in an... | [
3,
1
] | [] | [] | [
"flash",
"python"
] | stackoverflow_0000656704_flash_python.txt |
Q:
Python: decorator specific argument (unrelated to wrapped function)?
I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:
@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'
T... | Python: decorator specific argument (unrelated to wrapped function)? | I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:
@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'
The argument to the decorator is completely separate from the argument to t... | [
"The idea is that your decorator is a function returning a decorator.\nFIRST Write your decorator as if you knew your argument was a global variable. Let's say something like:\n-\ndef decorator(f):\n def decorated(*args,**kwargs):\n cache = Cache(cachepath)\n if cache.iscached(*args,**kwargs):\n ... | [
9,
5,
3
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0000660727_decorator_python.txt |
Q:
Python Django loop logic: Error says 'int' is not iterable - check my syntax?
return sum(jobrecord.get_cost() or 0
for jobrecord in self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date) or 0)
A:
After a small rewrite
query = self.project.jobrecord_set.filter(
... | Python Django loop logic: Error says 'int' is not iterable - check my syntax? | return sum(jobrecord.get_cost() or 0
for jobrecord in self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date) or 0)
| [
"After a small rewrite\nquery = self.project.jobrecord_set.filter(\n date__lte=date,\n date__gte=self.start_date)\nvalues= ( jobrecord.get_cost() or 0 for jobrecord in query or 0 )\nreturn sum( values )\n\nLook closely at the values= ( jobrecord.get_cost() or 0 for jobrecord in query or 0 )\nWhat happ... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000660773_django_python.txt |
Q:
Progress bar not updating during operation
in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload comple... | Progress bar not updating during operation | in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...... | [
"I'm going to quote the PyGTK FAQ:\n\nYou have created a progress bar inside a window, then you start running a loop that does some work:\n\nwhile work_left:\n ...do something...\n progressbar.set_fraction(...)\n\n\nYou will notice that the window doesn't even show up, or if it does the progress bar stays fro... | [
13,
1,
0,
0,
0
] | [] | [] | [
"gtk",
"progress_bar",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0000496814_gtk_progress_bar_pygtk_python_user_interface.txt |
Q:
Can I make pdb start debugging right away?
I want to debug a python project
The problem is, I don't know where to set a break point,
what I want to do, is be able to call a method
SomeClass( some_ctor_arguments ).some_method()`
and have the debugger be fired right away
How do I do that?
I tried pdb.run( string_... | Can I make pdb start debugging right away? | I want to debug a python project
The problem is, I don't know where to set a break point,
what I want to do, is be able to call a method
SomeClass( some_ctor_arguments ).some_method()`
and have the debugger be fired right away
How do I do that?
I tried pdb.run( string_command ) but it doesn't seem to work right
>>> ... | [
"Found it ..\npdb.runcall( object.method )\n\n",
"pdb.set_trace()\n\nwill start the debugger at this point.\nPlace it at the beginning of the method you want to debug.\n"
] | [
5,
4
] | [] | [] | [
"debugging",
"pdb",
"python"
] | stackoverflow_0000661034_debugging_pdb_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.