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:
Any easy way to alter the data that comes from a mysql database?
so I'm using mysql to grab data from a database and feeding it into a python function. I import mysqldb, connect to the database and run a query like this:
conn.query('SELECT info FROM bag')
x = conn.store_result()
for row in x.fetch_row(100):
... | Any easy way to alter the data that comes from a mysql database? | so I'm using mysql to grab data from a database and feeding it into a python function. I import mysqldb, connect to the database and run a query like this:
conn.query('SELECT info FROM bag')
x = conn.store_result()
for row in x.fetch_row(100):
print row
but my problem is that my data comes out like this (1.23423... | [
"Rows are returned as tuples, even if there is only one column in the query. You can access the first and only item as row[0]\nThe first time around in the for loop, row does indeed refer to the first row. The second time around, it refers to the second row, and so on.\nBy the way, you say that you are using mySQLd... | [
2,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004709560_mysql_python.txt |
Q:
remove the spaces
#!/usr/bin/python
import random
lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W'... | remove the spaces | #!/usr/bin/python
import random
lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ... | [
"Putting it all together with the string module.\nimport random\nimport string\n\nchars = string.ascii_uppercase + string.ascii_lowercase + string.digits\n\nfor row in range(10):\n print ''.join(random.choice(chars) for col in range(7))\n\n",
"instead of:\n for i in range(7):\n a = random.choice(all)\n print... | [
6,
1,
0,
0
] | [] | [] | [
"choice",
"python",
"random",
"space",
"string"
] | stackoverflow_0004709118_choice_python_random_space_string.txt |
Q:
Convert a string to a dictionary in Python?
I am pulling data from twitter, which is in the structure of a python dictionary, but the data is held in a string variable.
How can I convert this string variable to a dictionary in Python?
Thanks for the help!
EDIT: Here is an example of the data.
A:
You are probably... | Convert a string to a dictionary in Python? | I am pulling data from twitter, which is in the structure of a python dictionary, but the data is held in a string variable.
How can I convert this string variable to a dictionary in Python?
Thanks for the help!
EDIT: Here is an example of the data.
| [
"You are probably looking for the json module.\nFor example,\nIn [165]: json.loads('{\"a\": 0, \"c\": 0, \"b\": 0}')\nOut[165]: {u'a': 0, u'b': 0, u'c': 0}\n\n",
"As unutbu says, you should use the json module.\nUsing your example data, I can do this:\nimport json\nimport codecs\ntweet = codecs.open('example.txt'... | [
9,
3
] | [] | [] | [
"json",
"python",
"twitter"
] | stackoverflow_0004709737_json_python_twitter.txt |
Q:
Remove all articles, connector words, etc., from a string in Python
I have a list that contains many sentences. I want to iterate through the list, removing from all sentences words like "and", "the", "a", "are", etc.
I tried this:
def removearticles(text):
articles = {'a': '', 'an':'', 'and':'', 'the':''}
for... | Remove all articles, connector words, etc., from a string in Python | I have a list that contains many sentences. I want to iterate through the list, removing from all sentences words like "and", "the", "a", "are", etc.
I tried this:
def removearticles(text):
articles = {'a': '', 'an':'', 'and':'', 'the':''}
for i, j in articles.iteritems():
text = text.replace(i, j)
return text... | [
"I would go for regex, something like:\ndef removearticles(text):\n re.sub('(\\s+)(a|an|and|the)(\\s+)', '\\1\\3', text)\n\nor if you want to remove the leading whitespace as well:\ndef removearticles(text):\n re.sub('\\s+(a|an|and|the)(\\s+)', '\\2', text)\n\n",
"This looks more like an NLP job than something ... | [
8,
4,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004709665_python_string.txt |
Q:
Browser control for wxPython that can run java applets
I need to incorporate a small web browser in my wxPython project.
I have tried out the control that ships with wxPython (wx.html module), but it sucks for me. It can't run java applets, CSS, javascript, nothing but html.
Anyone knows of a webbrowser control fo... | Browser control for wxPython that can run java applets | I need to incorporate a small web browser in my wxPython project.
I have tried out the control that ships with wxPython (wx.html module), but it sucks for me. It can't run java applets, CSS, javascript, nothing but html.
Anyone knows of a webbrowser control for wxPython that can at least:
Parse HTML
Run java applets
R... | [
"You can use wxWebkit - there are bindings available for wxPython. Not too sure on its running of Java apps, though.\n"
] | [
0
] | [] | [] | [
"browser",
"html",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0004708932_browser_html_python_user_interface_wxpython.txt |
Q:
How can I limit the number of curl calls to the write function?
I'm trying to limit the number of times this WRITEFUNCTION is called. Is there any way I can do that?
defining the writefunction:
conn.setopt(pycurl.WRITEFUNCTION, on_receive)
Thanks for the help!
A:
Here's a dirty simple version that should work. ... | How can I limit the number of curl calls to the write function? | I'm trying to limit the number of times this WRITEFUNCTION is called. Is there any way I can do that?
defining the writefunction:
conn.setopt(pycurl.WRITEFUNCTION, on_receive)
Thanks for the help!
| [
"Here's a dirty simple version that should work. Building PycURL to test and find a better way.\nimport pycurl, json\n\nSTREAM_URL = \"http://chirpstream.twitter.com/2b/user.json\"\n\nUSER = \"segphault\"\nPASS = \"XXXXXXXXX\"\n\nclass LimitError(Exception): pass\n\ncounter = 0\nlimit = 10\ndef on_receive(data):\n ... | [
1
] | [] | [] | [
"curl",
"pycurl",
"python"
] | stackoverflow_0004710094_curl_pycurl_python.txt |
Q:
Find the most recent file in a directory without reading all the contents of it
I'm trying to find out the latest file in a huge filesystem. One way to do this is to go through all directories - one at a time, read its contents, select the latest file etc.
The obvious drawback is I have to get all the files in a s... | Find the most recent file in a directory without reading all the contents of it | I'm trying to find out the latest file in a huge filesystem. One way to do this is to go through all directories - one at a time, read its contents, select the latest file etc.
The obvious drawback is I have to get all the files in a specific directory. I was wondering whether there was a 'magic' call in Python [1] whi... | [
"Have you considered using pyinotify which can watch a directory and subdirectories?\nThis might require your code to be threaded, say, a watcher thread that records the latest changes for the main thread to poll.\nAlternatively, you could use popen and get the result of 'ls -t | head -1' \n",
"I do not believe t... | [
7,
5,
3
] | [
"You don't have to use Python for this task, wrap python over the Unix utilities which understand filesystem better and can give you this information.\nFor e.g.\nDo ls -ltr |tail -1 on that directory and the result would be string, split that and get the last item which would be file you are looking for.\nimport su... | [
-3
] | [
"c",
"python",
"unix"
] | stackoverflow_0004709968_c_python_unix.txt |
Q:
Remove final slash and number in a string in Python
I have strings like these:
text-23
the-text-9
2011-is-going-to-be-cool-455
I need to remove the final -number from the string in Python (and I'm terrible with regular expressions).
Thanks for your help!
A:
assuming all the text you have ends with -number
>>> s=... | Remove final slash and number in a string in Python | I have strings like these:
text-23
the-text-9
2011-is-going-to-be-cool-455
I need to remove the final -number from the string in Python (and I'm terrible with regular expressions).
Thanks for your help!
| [
"assuming all the text you have ends with -number\n>>> s=\"2011-is-going-to-be-cool-455\"\n>>> s.rsplit(\"-\",1)[0]\n'2011-is-going-to-be-cool'\n\nor \n>>> iwant=s.rsplit(\"-\",1)\n>>> if iwant[-1].isdigit():\n... print iwant[0]\n...\n2011-is-going-to-be-cool\n\n",
"'2011-is-going-to-be-cool-455'.rstrip('012345... | [
5,
4,
3,
2,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0004710109_python_regex_string.txt |
Q:
Screen scraping in LXML with python-- extract specific data
I've been trying to write a program for the last several hours that does what I thought would be an incredibly simple task:
Program asks for user input (let's say the type 'happiness')
Program queries the website thinkexist using this format ("http://thi... | Screen scraping in LXML with python-- extract specific data | I've been trying to write a program for the last several hours that does what I thought would be an incredibly simple task:
Program asks for user input (let's say the type 'happiness')
Program queries the website thinkexist using this format ("http://thinkexist.com/search/searchQuotation.asp?search=USERINPUT")
Program... | [
"import lxml.html\nimport urllib\n\nsite = 'http://thinkexist.com/search/searchquotation.asp'\n\nuserInput = raw_input('Search for: ').strip()\nurl = site + '?' + urllib.urlencode({'search':userInput})\n\nroot = lxml.html.parse(url).getroot()\nquotes = root.xpath('//a[@class=\"sqq\"]')\n\nprint quotes[0].text_conte... | [
6,
1,
1
] | [] | [] | [
"lxml",
"python",
"screen",
"screen_scraping",
"web_scraping"
] | stackoverflow_0004710307_lxml_python_screen_screen_scraping_web_scraping.txt |
Q:
Python:When to use Threads vs. Multiprocessing
What are some good guidelines to follow when deciding to use threads or multiprocessing when speaking in terms of efficiency and code clarity?
A:
Many of the differences between threading and multiprocessing are not really Python-specific, and some differences are s... | Python:When to use Threads vs. Multiprocessing | What are some good guidelines to follow when deciding to use threads or multiprocessing when speaking in terms of efficiency and code clarity?
| [
"Many of the differences between threading and multiprocessing are not really Python-specific, and some differences are specific to a certain Python implementation.\nFor CPython, I would use the multiprocessing module in either fo the following cases:\n\nI need to make use of multiple cores simultaneously for perfo... | [
16,
6
] | [] | [] | [
"python"
] | stackoverflow_0004710433_python.txt |
Q:
Modify system configuration files and use system commands through web interface
I received a project recently and I am wondering how to do something in a correct and secure manner.
The situation is the following:
There are classes to manage linux users, mysql users and databases and apache virtual hosts. They're u... | Modify system configuration files and use system commands through web interface | I received a project recently and I am wondering how to do something in a correct and secure manner.
The situation is the following:
There are classes to manage linux users, mysql users and databases and apache virtual hosts. They're used to automate the addition of users in a small shared-hosting environnement. These ... | [
"You can use sudo to give the apache user root permission for only the commands/scripts you need for your web app.\n",
"Hello\nYou can easily create web applications in Python using WSGI-compliant web frameworks such as CherryPy2 and templating engines such as Genshi. You can use the 'subprocess' module to manadg... | [
0,
0
] | [] | [] | [
"apache",
"privileges",
"python",
"root",
"security"
] | stackoverflow_0004680693_apache_privileges_python_root_security.txt |
Q:
Packaging an application that uses perl and python on debian
I have an application that has various sections some of which are written in perl and some in python. What would be the best tool to use for packaging such an application.
I am looking at deb-helper at the moment and still learning how to use it though I... | Packaging an application that uses perl and python on debian | I have an application that has various sections some of which are written in perl and some in python. What would be the best tool to use for packaging such an application.
I am looking at deb-helper at the moment and still learning how to use it though I cant find a HOW TO for something like this. Ideas?
Update
My sour... | [
"Using debhelper is the right approach - you should certainly create a .deb package. I recommend to start with this tutorial.\nEdit: If the scripts you are trying to install are actually \"executables\" (in the sense that they are meant to be invoked as programs, rather than acting as libraries in their respective ... | [
4
] | [] | [] | [
"debhelper",
"debian",
"packaging",
"perl",
"python"
] | stackoverflow_0004710798_debhelper_debian_packaging_perl_python.txt |
Q:
[Word Game]Quiddler Solver Algorithm
Quiddler Solver
I have a card game called Quiddler that I'm trying to write an algorithm to solve, but when I try and solve it linearly its very slow and inefficient.
The Game (Step by step):
Each player is dealt a number of cards between 3 and 10, each card has either one or ... | [Word Game]Quiddler Solver Algorithm | Quiddler Solver
I have a card game called Quiddler that I'm trying to write an algorithm to solve, but when I try and solve it linearly its very slow and inefficient.
The Game (Step by step):
Each player is dealt a number of cards between 3 and 10, each card has either one or two letters on it.
The player then tries t... | [
"You can try storing the word list as a directed acyclic word graph (DAWG) or a trie for fast lookups.\nPlace the first letter and use the DAWG/trie to find out all the possibilities for the second letter, and so on. Use backtracking when no more letters can be placed, or when a solution has been found and you want... | [
4,
1
] | [] | [] | [
"algorithm",
"c",
"c++",
"python"
] | stackoverflow_0004710824_algorithm_c_c++_python.txt |
Q:
How to connect PyQt slot from background thread to gui thread
I wish to connect up a signal in the background thread to a slot in the GUI thread in a pythonic way.
I have the following code snippet.
from PyQt4.QtCore import *
class CompanyPresenter(QObject):
fieldChangeSignal = pyqtSignal(str, str)
def... | How to connect PyQt slot from background thread to gui thread | I wish to connect up a signal in the background thread to a slot in the GUI thread in a pythonic way.
I have the following code snippet.
from PyQt4.QtCore import *
class CompanyPresenter(QObject):
fieldChangeSignal = pyqtSignal(str, str)
def __init__(self,model,view):
self.model = model # a Co... | [
"you forgot this:\ndef __init__(self,model,view):\n super(CompanyPresenter, self).__init__() # this!!!!!!!!!\n\nadd this will work.(tested)\n"
] | [
23
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0004708436_pyqt_python.txt |
Q:
Python Web Server
I want a simple python web server for the following use case:
I want to write a simple server that will accept HTTP requests from my application running on Google App Engine.
The server will accept HTTP requests, and then send iphone notifications. (Basically, I need this extra server to account ... | Python Web Server | I want a simple python web server for the following use case:
I want to write a simple server that will accept HTTP requests from my application running on Google App Engine.
The server will accept HTTP requests, and then send iphone notifications. (Basically, I need this extra server to account for the lack of socket ... | [
"One option would be the (appropriately named) SimpleHTTPServer, which is part of the Python standard library. Another, more flexible but more complicated option would be to write your server in Twisted.\n",
"I've been writing simple http servers using gevent and bottle -- an example:\n#!/usr/bin/env python\n\nim... | [
4,
3
] | [] | [] | [
"apple_push_notifications",
"google_app_engine",
"python"
] | stackoverflow_0004709303_apple_push_notifications_google_app_engine_python.txt |
Q:
How do I check if a list is sorted?
Possible Duplicate:
Pythonic way to check if a list is sorted or not
In python, how do I test whether a list of numbers is already sorted or not?
A:
This is only possible by iterating over the list (implicitly or explicitly):
all(b >= a for a, b in zip(the_list, the_list[1:]... | How do I check if a list is sorted? |
Possible Duplicate:
Pythonic way to check if a list is sorted or not
In python, how do I test whether a list of numbers is already sorted or not?
| [
"This is only possible by iterating over the list (implicitly or explicitly):\nall(b >= a for a, b in zip(the_list, the_list[1:])\n\nBut why not just sort it if you need it to be sorted? Python's sorting algorithm will be really cheap on an already sorted list -- possibly cheaper than the test above.\nEDIT: Becaus... | [
26,
12,
5,
5
] | [
"if L == (lambda pp=[]: reduce(lambda p, i: pp.append(reduce(lambda t, i:\n (lambda t, i, j: (lambda l=[]: map(lambda x: (lambda xx=l.append(1):\n t[sum(l) - 1] if sum(l) not in map(1..__radd__, (i, j)) else (t[i] if\n sum(l) == j + 1 else t[j]))(), t))())(t, i, i + 1) if t[i] >= t[i + 1]\n ... | [
-3
] | [
"python",
"sorting"
] | stackoverflow_0004710763_python_sorting.txt |
Q:
How to remove the unselected item in a select and radio input in Django
If a model's field is a choice or foreign key, the widget on the page is a select input or radios if you specify that. Django places "---------" in the first item as an unselected value. How can I override it or even remove it? I remember read... | How to remove the unselected item in a select and radio input in Django | If a model's field is a choice or foreign key, the widget on the page is a select input or radios if you specify that. Django places "---------" in the first item as an unselected value. How can I override it or even remove it? I remember reading the way to do it but can't find it any more.
| [
"From the Django forms doc:\n\nBy default the <select> widget used by ModelChoiceField will have a an empty choice at the top of the list. You can change the text of this label (which is \"---------\" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label=None... | [
8,
6,
3
] | [] | [] | [
"choice",
"django",
"forms",
"model",
"python"
] | stackoverflow_0003935602_choice_django_forms_model_python.txt |
Q:
Django: Encapsulate the whole template in the spaceless tag?
It would eliminate whitespace. But, other than poor readability, any potential risks I should be aware of?
Here is the Django doc for the tag.
A:
The filter will parse the whole output, which might slow down rendering a bit.
Given the reduced readabili... | Django: Encapsulate the whole template in the spaceless tag? | It would eliminate whitespace. But, other than poor readability, any potential risks I should be aware of?
Here is the Django doc for the tag.
| [
"The filter will parse the whole output, which might slow down rendering a bit.\nGiven the reduced readability and potential performance woes, I would refrain from filtering whitespaces.\nThe question is what you want to achieve by filtering white spaces. If you are concerned about traffic or transfer speed, check ... | [
8,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004694573_django_django_templates_python.txt |
Q:
Multiple request when FB edge.create Event catched
I wanted to use facebook's like button for voting on my page. Unfortunately when 'Like' is clicked I get 3-5 requests to my function instead of only one. Is there a way to prevent this ?Sample code:
FB.Event.subscribe('edge.create', function(href, widget) {
co... | Multiple request when FB edge.create Event catched | I wanted to use facebook's like button for voting on my page. Unfortunately when 'Like' is clicked I get 3-5 requests to my function instead of only one. Is there a way to prevent this ?Sample code:
FB.Event.subscribe('edge.create', function(href, widget) {
console.log(href, widget);
});
My code:
FB.Event.subs... | [
"I do facing slightly same issue, have been creating like buttons on the fly using AJAX, specific to the content but 'edge.create' some how storing the event and incrementing the edge.create events and firing multiple times when I click on another FB like widget.\nHave bee hitting my head so badly, no luck till yet... | [
1,
0
] | [] | [] | [
"django",
"facebook",
"python",
"xfbml",
"xmlhttprequest"
] | stackoverflow_0004359840_django_facebook_python_xfbml_xmlhttprequest.txt |
Q:
Is boolean logic possible in django templates?
I want to do something like:
{% if ("view_video" in video_perms) OR purchase_override %}
Is that possible?
A:
Django docs on boolean operators
Gives you:
{% if user in users %}
If users is a QuerySet, this will appear if user is an
instance that belongs to the ... | Is boolean logic possible in django templates? | I want to do something like:
{% if ("view_video" in video_perms) OR purchase_override %}
Is that possible?
| [
"Django docs on boolean operators\nGives you:\n{% if user in users %}\n If users is a QuerySet, this will appear if user is an\n instance that belongs to the QuerySet.\n{% endif %}\n\nand\n{% if a == b or c == d and e %}\n\nBe aware that and has a higher order of precedence than or, and that parentheses are not p... | [
40
] | [] | [] | [
"boolean",
"django",
"python",
"templates"
] | stackoverflow_0004711627_boolean_django_python_templates.txt |
Q:
Python raw_input causing EOFError after creating app with py2app
I have written a small script that helps me solve scrabble and word-warp problems. It works fine when I run it from Mac OS X terminal. I would like to share the script with my friends as a standalone Mac app. Hence I used py2app for this, but the App... | Python raw_input causing EOFError after creating app with py2app | I have written a small script that helps me solve scrabble and word-warp problems. It works fine when I run it from Mac OS X terminal. I would like to share the script with my friends as a standalone Mac app. Hence I used py2app for this, but the App crashed when I double-click on it. The console shows the following er... | [
"Python programs wrapped as apps by py2app do not have a terminal window from which to enter input. You would need to supply some fancier way of enter input and suppling output, for example by using Python's Tkinter module. If your script runs from the terminal and you want to make a clickable application, it wou... | [
2
] | [] | [] | [
"eoferror",
"py2app",
"python",
"raw_input"
] | stackoverflow_0004711589_eoferror_py2app_python_raw_input.txt |
Q:
Python - test that succeeds when exception is not raised
I know about unittest Python module.
I know about assertRaises() method of TestCase class.
I would like to write a test that succeeds when an exception is not raised.
Any hints please?
A:
def runTest(self):
try:
doStuff()
except:
se... | Python - test that succeeds when exception is not raised | I know about unittest Python module.
I know about assertRaises() method of TestCase class.
I would like to write a test that succeeds when an exception is not raised.
Any hints please?
| [
"def runTest(self):\n try:\n doStuff()\n except:\n self.fail(\"Encountered an unexpected exception.\")\n\nUPDATE: As liw.fi mentions, the default result is a success, so the example above is something of an antipattern. You should probably only use it if you want to do something special before f... | [
25,
15,
6
] | [] | [] | [
"exception",
"exception_handling",
"python",
"unit_testing"
] | stackoverflow_0000647900_exception_exception_handling_python_unit_testing.txt |
Q:
Django - Passing arguments to models through ForeignKey attributes
I've got a class like this:
class Image (models.Model):
...
sizes = ((90,90), (300,250))
def resize_image(self):
for size in sizes:
...
and another class like this:
class SomeClassWithAnImage (models.Model):
..... | Django - Passing arguments to models through ForeignKey attributes | I've got a class like this:
class Image (models.Model):
...
sizes = ((90,90), (300,250))
def resize_image(self):
for size in sizes:
...
and another class like this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image)
what i'd like to do with that... | [
"All the attributes of an object in Django are stored in the database, so you are going to have to make your sizes a Field in your model. You can't just set random properties and expect them to persist.\nAs there isn't a field for a list of tuples you are going to either have to kludge it by using a text field or w... | [
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004688500_django_django_models_python.txt |
Q:
Auto expanding blocks of comments in emacs
I like any comment to appear on its own line. I don't like to put comments on the same line that code is on. In some languages you can write a comment block such as:
/**
* I am a comment block. This comment block will be automatically expanded by the
* IDE such that it ... | Auto expanding blocks of comments in emacs | I like any comment to appear on its own line. I don't like to put comments on the same line that code is on. In some languages you can write a comment block such as:
/**
* I am a comment block. This comment block will be automatically expanded by the
* IDE such that it can contain all of the text in this block.
**/
... | [
"auto-fill-mode seems to do what you want. When the length of the line exceeds the value of fill-column it breaks the line and insert new comment line. \nIt's not fully automatic though, if the text is inserted in between , you will have to press M-q to refill. \n[Edit: here is a way to smartify the \"space\" comma... | [
4,
2
] | [] | [] | [
"comments",
"emacs",
"python"
] | stackoverflow_0004711179_comments_emacs_python.txt |
Q:
Python multithreaded memoization
Python multithreaded memoization, is it possible? If so, how?
A:
Sure it's possible. In fact, I think that the straightforward single-threaded implementation should work just fine, assuming that it is acceptable that some redundant calculations may be performed in the case when t... | Python multithreaded memoization | Python multithreaded memoization, is it possible? If so, how?
| [
"Sure it's possible. In fact, I think that the straightforward single-threaded implementation should work just fine, assuming that it is acceptable that some redundant calculations may be performed in the case when the same function is called with the same parameters in parallel.\nFor an illustration of the scenari... | [
3
] | [] | [] | [
"memoization",
"python"
] | stackoverflow_0004710266_memoization_python.txt |
Q:
VIM + Python - "gd" command not working properly
I'm getting started with using VIM to program Python. I've run into some issues, hopefully someone can help me with this one.
The "gd" command is supposed to take you to the first place a variable is defined/used in the current function. From what I understand, it's... | VIM + Python - "gd" command not working properly | I'm getting started with using VIM to program Python. I've run into some issues, hopefully someone can help me with this one.
The "gd" command is supposed to take you to the first place a variable is defined/used in the current function. From what I understand, it's the same as doing "[[" to go to the top of the functi... | [
"I think the problem is due to the way that Vim treats a function. From the documentation for [[:\n *[[*\n[[ [count] sections backward or to the previous '{' in\n the first column. |exclusive|\n Note that |exclusive-linewise| often applies.\n\nUnless a sec... | [
3,
2
] | [] | [] | [
"editor",
"ide",
"python",
"vim"
] | stackoverflow_0004711488_editor_ide_python_vim.txt |
Q:
ImportError: No module named modelsinspector
I get the following error when I do syncdb
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.ex... | ImportError: No module named modelsinspector | I get the following error when I do syncdb
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/lib/python2.7/site-packages/d... | [
"Why have you installed South 0.5? The current version of South is 0.7.3 - 0.5 is more than two years old and dates from before the reorganisation that added the modelsinspector module. Delete that version and install the latest one.\n",
"You are missing module modelsinspector. Install it.\n"
] | [
1,
0
] | [] | [] | [
"django",
"django_models",
"django_south",
"python"
] | stackoverflow_0004711916_django_django_models_django_south_python.txt |
Q:
Add functions dynamically to existing celery worker processes?
I'm getting started with celery and I want to know if it is possible to add modules to celeryd processes that have already been started. In other words, instead of adding modules via celeryconfig.py as in
CELERY_IMPORTS = ("tasks", "additional_module"... | Add functions dynamically to existing celery worker processes? | I'm getting started with celery and I want to know if it is possible to add modules to celeryd processes that have already been started. In other words, instead of adding modules via celeryconfig.py as in
CELERY_IMPORTS = ("tasks", "additional_module" )
before starting the workers, I want to make additional_module av... | [
"You can achieve your goal by starting a new celeryd with an expanded import list and eventually gracefully shutting down your old worker (after it's finished its current jobs).\nBecause of the asynchronous nature of getting jobs pushed to you and only marking them done after celery has finished its work, you won't... | [
2
] | [] | [] | [
"celery",
"celery_task",
"distributed_computing",
"python"
] | stackoverflow_0004675356_celery_celery_task_distributed_computing_python.txt |
Q:
How can I configure different worker pools using celery?
I need to deploy a queued execution service with (generally) the following three classes of worker:
A periodic, low-priority job class that takes a long time and can be processed serially; these jobs should only use 0..2 workers in the system at most.
A per... | How can I configure different worker pools using celery? | I need to deploy a queued execution service with (generally) the following three classes of worker:
A periodic, low-priority job class that takes a long time and can be processed serially; these jobs should only use 0..2 workers in the system at most.
A periodic, deadline-sensitive job class that take a short to mediu... | [
"You can use Celery Routing to achieve your goal. What you do is setup three different routing keys and have multiple celery workers (with custom configs) listing only on the specific routing keys you set up.\n"
] | [
3
] | [] | [] | [
"celery",
"python",
"queue",
"scheduled_tasks",
"task"
] | stackoverflow_0004665441_celery_python_queue_scheduled_tasks_task.txt |
Q:
Multiple independent embedded Python Interpreters on multiple operating system threads invoked from C/C++ program
Embedding Python interpreter in a C/C++ application is well documented. What is the best approach to run multiple python interpreter on multiple operating system threads (i.e. one interpreter on one op... | Multiple independent embedded Python Interpreters on multiple operating system threads invoked from C/C++ program | Embedding Python interpreter in a C/C++ application is well documented. What is the best approach to run multiple python interpreter on multiple operating system threads (i.e. one interpreter on one operating system thread within the same process) which are invoked from the C/C++ application? Such applications may also... | [
"It's not exactly an answer to your question, but you could use separate processes instead of threads, then the problems should vanish.\nPros:\n\nNo need hacking python (and making sure the result works in all of the intended cases)\nProbably less development effort overall\nEasy upgrading to new python versions\nC... | [
5
] | [] | [] | [
"python",
"python_embedding",
"thread_local"
] | stackoverflow_0002968317_python_python_embedding_thread_local.txt |
Q:
PyQt4 - Maximize window along with inside widgets
I have a main window and I want that when I maximize it the widgets inside it should automatically be resized ....
Is there any way I can do that ????
A:
Yes. Use layout objects (such as QHBoxLayout or QGridLayout) to organize your widgets inside, and set the wid... | PyQt4 - Maximize window along with inside widgets | I have a main window and I want that when I maximize it the widgets inside it should automatically be resized ....
Is there any way I can do that ????
| [
"Yes. Use layout objects (such as QHBoxLayout or QGridLayout) to organize your widgets inside, and set the widgets' resize modes accordingly. Note that standard Qt-supplied widgets support resizing by default.\n",
"If you want to save you a lot of work, don't hand-code the ui. Use Qt Creator to create a ui file a... | [
2,
1
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0004712705_pyqt4_python.txt |
Q:
PLPGSQL using single quotes in function call (python)
I am having problems when using single quotes in a insert value for a plpgsql function
It looks like this:
"AND (u.firstname LIKE 'koen') OR
(u.firstname LIKE 'dirk')"
This is done with python
I have tried \' and '' and ''' and '''' and ''''' and even '''''... | PLPGSQL using single quotes in function call (python) | I am having problems when using single quotes in a insert value for a plpgsql function
It looks like this:
"AND (u.firstname LIKE 'koen') OR
(u.firstname LIKE 'dirk')"
This is done with python
I have tried \' and '' and ''' and '''' and ''''' and even '''''''
none of them seem to be working and return the following... | [
"I don't know Python well, but it probably supports data binding where you first prepare a statement (and you don't need quotes around the question marks there):\nprepare(\"..... AND (u.firstname LIKE ?) OR (u.firstname LIKE ?)\")\n\nand then you call execute('koen', 'dirk') or whatever that function is called in P... | [
0
] | [] | [] | [
"plpgsql",
"python",
"quotes"
] | stackoverflow_0004434404_plpgsql_python_quotes.txt |
Q:
OverflowError: normalized days too large to fit in a C int
I am using the following Python code to compute the User+Sys time.
t = os.times()
usersystime = t[0] + t[1]
usersystime = datetime.timedelta(seconds=usersystime)
However, on an Amazon EC2 m.4xlarge instance, I get the following error occasionally:
Overflo... | OverflowError: normalized days too large to fit in a C int | I am using the following Python code to compute the User+Sys time.
t = os.times()
usersystime = t[0] + t[1]
usersystime = datetime.timedelta(seconds=usersystime)
However, on an Amazon EC2 m.4xlarge instance, I get the following error occasionally:
OverflowError: normalized days too large to fit in a C int
I have used... | [
"I've found out that some of Python's built-in functions, such as range or xrange, do not support larger integers, probably because they're implemented in C as an optimization. Take a look at this question for an example.\nThis could be the case for your code. Does t[0] + t[1] fit in an integer? If not, you'll have... | [
1
] | [] | [] | [
"amazon_ec2",
"python",
"time"
] | stackoverflow_0004663817_amazon_ec2_python_time.txt |
Q:
Calling a Python function in C++ with Swig
Here is my c++ code:
void callMethod(void (*someMethod)()) {
(*someMethod)();
}
My Swig .i file is:
%module test
%{
#define SWIG_FILE_WITH_INIT
extern void callMethod(void (*someMethod)());
%}
%typemap (in) void*
%{
$1 = PyCObject_AsVoidPtr($input);
%}
extern ... | Calling a Python function in C++ with Swig | Here is my c++ code:
void callMethod(void (*someMethod)()) {
(*someMethod)();
}
My Swig .i file is:
%module test
%{
#define SWIG_FILE_WITH_INIT
extern void callMethod(void (*someMethod)());
%}
%typemap (in) void*
%{
$1 = PyCObject_AsVoidPtr($input);
%}
extern void callMethod(void (*someMethod)());
Here is... | [
"Pointers to functions and callbacks\n"
] | [
1
] | [] | [] | [
"python",
"swig"
] | stackoverflow_0003302146_python_swig.txt |
Q:
Cumulative count of unique values in a dictionary
I have a huge dictionary dd{} where I have people and sets of fruits they prefer:
A set(['Apple', 'Orange', 'Strawberries'])
B set(['Banana', 'Strawberries', 'Orange', 'Kiwi', 'Dates'])
C set(['Apple', 'Kiwi', 'Grapes'])
A set(['Banana', 'Orange', 'Apple', 'Lemon']... | Cumulative count of unique values in a dictionary | I have a huge dictionary dd{} where I have people and sets of fruits they prefer:
A set(['Apple', 'Orange', 'Strawberries'])
B set(['Banana', 'Strawberries', 'Orange', 'Kiwi', 'Dates'])
C set(['Apple', 'Kiwi', 'Grapes'])
A set(['Banana', 'Orange', 'Apple', 'Lemon'])
I want a cumulative count for the fruits, meaning fo... | [
"Something like this?\nallFruits = set()\nfor i,(k,v) in enumerate(sorted(dd.iteritems()), 1):\n allFruits.update(v)\n print i, len(allFruits)\n\nThis works for Python 2.6 and newer. For older versions try this:\nallFruits = set()\nfor i,(k,v) in enumerate(sorted(dd.iteritems())):\n allFruits.update(v)\n ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004714096_python.txt |
Q:
Are **kwargs a good choice for non-configuration data in __init__?
I'm thinking of using **kwargs in an unusual way: as data provider and not as overloading substituting tool. In this way all keyword arguments should be of one type, for example specifically formed tuple, and no way else. In example:
class SomeClas... | Are **kwargs a good choice for non-configuration data in __init__? | I'm thinking of using **kwargs in an unusual way: as data provider and not as overloading substituting tool. In this way all keyword arguments should be of one type, for example specifically formed tuple, and no way else. In example:
class SomeClass(object):
'''All **kwargs should be in ("string", 1, True) form'''
... | [
"See what the dict constructor does in Python:\n>>> dict(one=1, two=2, three=3)\n{'three': 3, 'two': 2, 'one': 1}\n\nAlso a \"creative\" use of keyword arguments. If this works for a standard type, and makes sense in your application, go for it.\n"
] | [
3
] | [] | [] | [
"constructor",
"keyword_argument",
"python"
] | stackoverflow_0004714115_constructor_keyword_argument_python.txt |
Q:
Which of these is pythonic? and Pythonic vs. Speed
I'm new to python and just wrote this module level function:
def _interval(patt):
""" Converts a string pattern of the form '1y 42d 14h56m'
to a timedelta object.
y - years (365 days), M - months (30 days), w - weeks, d - days,
h - hours, m - minut... | Which of these is pythonic? and Pythonic vs. Speed | I'm new to python and just wrote this module level function:
def _interval(patt):
""" Converts a string pattern of the form '1y 42d 14h56m'
to a timedelta object.
y - years (365 days), M - months (30 days), w - weeks, d - days,
h - hours, m - minutes, s - seconds"""
m = _re.findall(r'([+-]?\d*(?:\.... | [
"You seem to create a lot of lambdas every time you parse. You really don't need a lambda, just a multiplier. Try this:\ndef _factor_for(what):\n if what == 'y': return 365\n elif what == 'M': return 30\n elif what in ('w', 'd', 'h', 's', 'm'): return 1\n else raise ValueError(\"Invalid specifier %r\" %... | [
4,
3
] | [
"Yes, there is. Use time.strptime instead:\n\nParse a string representing a time\n according to a format. The return\n value is a struct_time as returned\n by gmtime() or localtime().\n\n"
] | [
-1
] | [
"datetime",
"python",
"timedelta"
] | stackoverflow_0004714222_datetime_python_timedelta.txt |
Q:
Get function's 'namespace path'
I have some namespaces, one included in the other:
class A:
class B:
class C:
def method(): pass
get_ns_path(A.B.C.method) # >>> 'A.B.C.method'
Is it possible to implement such get_ns_path(func) that receives a method/function and returns the 'namespace pa... | Get function's 'namespace path' | I have some namespaces, one included in the other:
class A:
class B:
class C:
def method(): pass
get_ns_path(A.B.C.method) # >>> 'A.B.C.method'
Is it possible to implement such get_ns_path(func) that receives a method/function and returns the 'namespace path' as a string?
A.B.C.method.im_clas... | [
"I don't think that is possible:\n>>> dir(A.B.C)\n['__doc__', '__module__', 'method']\n\nMore convincingly, there's no reason A.B.C should know about A.B, because you can do Z.C = A.B.C and they would be the same object. So what would get_ns_path(Z.C.method) return?\n"
] | [
2
] | [
"Youn can get the mro using the inspect module.\ninspect.getmro(cls)¶\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0004707288_python.txt |
Q:
Why 'NoneType' is returned in Python?
I have a code that basically solves one of the problem in Project Euler and aims to find out LCM of first 20 natural numbers.
def GCD(a, b): #Euclid's algorithim
if (b == 0):
return a
else:
GCD(b, a % b)
def LCM(a, b): #LCM(a,b... | Why 'NoneType' is returned in Python? | I have a code that basically solves one of the problem in Project Euler and aims to find out LCM of first 20 natural numbers.
def GCD(a, b): #Euclid's algorithim
if (b == 0):
return a
else:
GCD(b, a % b)
def LCM(a, b): #LCM(a,b) = a*b/GCD(a,b)
x = GCD(a, b)
retu... | [
"Try\ndef GCD(a, b): #Euclid's algorithim\n if (b == 0):\n return a\n else:\n return GCD(b, a % b)\n\nYou have to return the value returned by the recursive call. RFIND has a similar problem.\n",
"You've implemented your recursion incorrectly.\ndef GCD(a, b): #Euclid... | [
14,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004714764_python.txt |
Q:
"IOError [Errno 13] Permisson denied" when copy a file on Windows
I wrote a program that will copy a file called a.exe to C:/Windows/, then I pack it to exe with PyInstaller, and rename the exe file to a.exe. When I run the exe file, it output IOError [Errno 13] Permisson denied: 'C:/Windows/a.exe', but the file a... | "IOError [Errno 13] Permisson denied" when copy a file on Windows | I wrote a program that will copy a file called a.exe to C:/Windows/, then I pack it to exe with PyInstaller, and rename the exe file to a.exe. When I run the exe file, it output IOError [Errno 13] Permisson denied: 'C:/Windows/a.exe', but the file a.exe was copied to the directory C:/Windows. Then I ran it as the Admin... | [
"Check if a.exe has read-only attribute. shutil.copy raises \"Permission denied\" error when it is called to overwrite existing file with read-only attribute set\n",
"Apparently you're trying to execute a file that moves itself to a different place ... I guess that cannot work.\n",
"Can you copy files that are ... | [
4,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0004713589_python_windows.txt |
Q:
Django - USStateField vs USZipCodeField
Why is one of these a model and the other is a form? For example, in order to get it to behave correctly this is my model:
class UserProfile(models.Model):
state = USStateField()
zip = models.CharField(max_length=30)
and this is my form:
class UserProfileForm(forms... | Django - USStateField vs USZipCodeField | Why is one of these a model and the other is a form? For example, in order to get it to behave correctly this is my model:
class UserProfile(models.Model):
state = USStateField()
zip = models.CharField(max_length=30)
and this is my form:
class UserProfileForm(forms.ModelForm):
zip = USZipCodeField()
I wo... | [
"I think you probably just want to use USStateField directly:\nfrom django.contrib.localflavor.us.forms import USStateField\n\nclass UserProfileForm(forms.ModelForm):\n state = USStateField()\n zip = USZipCodeField()\n class Meta:\n model = UserProfile\n\nIs there a reason you were using USZipCodeFi... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004715666_django_django_forms_django_models_python.txt |
Q:
What version of python can I use with Twisted/Zope?
I noticed that Twisted has a dependency on Zope. I found that when I tried to install Zope, after running, ./configure it tells me I need to use python2.4 (not python 2.5+ which I would like to be using).
However, I have seen some tutorials and guides that sugges... | What version of python can I use with Twisted/Zope? | I noticed that Twisted has a dependency on Zope. I found that when I tried to install Zope, after running, ./configure it tells me I need to use python2.4 (not python 2.5+ which I would like to be using).
However, I have seen some tutorials and guides that suggested using python 2.5 for Twisted. So I'm just generally c... | [
"Twisted doesn't have a dependency on full zope. It's just zope.interface, which is a small pure-python module packaged separately from all zope.\nYou can download the .tar.gz version and run the usual python setup.py install, that should work. Or if your operational system includes a package management system, you... | [
7,
0
] | [] | [] | [
"python",
"twisted",
"zope"
] | stackoverflow_0004715357_python_twisted_zope.txt |
Q:
python system tray using tkinter
I want to create a system tray for my application using python tkinter.
can anyone let me know how can I do the same using python tkinter?
A:
No, I don't think python Tkinter can do it alone. You'll probably need to install some tk extension, which will be platform-dependant and ... | python system tray using tkinter | I want to create a system tray for my application using python tkinter.
can anyone let me know how can I do the same using python tkinter?
| [
"No, I don't think python Tkinter can do it alone. You'll probably need to install some tk extension, which will be platform-dependant and hard to use from python's bindings.\nFor completeness, on gtk you'd use gtk.StatusIcon \n"
] | [
1
] | [] | [] | [
"python",
"system",
"system_tray",
"tkinter"
] | stackoverflow_0004711004_python_system_system_tray_tkinter.txt |
Q:
What's the best way to add a GUI to a Pygame application?
Are there any good GUIs that support Pygame surfaces as a widget within the application?
If this isn't possible or practical, what GUI toolkit has the best graphics component? I'm looking to keep the speedy rendering made possible by a SDL wrapper.
A:
Don... | What's the best way to add a GUI to a Pygame application? | Are there any good GUIs that support Pygame surfaces as a widget within the application?
If this isn't possible or practical, what GUI toolkit has the best graphics component? I'm looking to keep the speedy rendering made possible by a SDL wrapper.
| [
"Dont use wxPython, its very hard to get to work well with Pygame, as described over at the GUI section of the Pygame wiki.\n\nFirst of all, pygame relies on the\n SDL, which means that it can only have\n one window at a time. Thus, trying to\n implement multiple Gtk, Qt, ...\n application instances that use py... | [
11,
6,
4,
1
] | [] | [] | [
"graphics",
"pygame",
"python",
"user_interface"
] | stackoverflow_0002142912_graphics_pygame_python_user_interface.txt |
Q:
Django-South introspection rule doesn't work
I'm using Django 1.2.3 and South 0.7.3.
I am trying to convert my app (named core) to use Django-South. I have a custom model/field that I'm using, named ImageWithThumbsField. It's basically just the ol' django.db.models.ImageField with some attributes such as height, w... | Django-South introspection rule doesn't work | I'm using Django 1.2.3 and South 0.7.3.
I am trying to convert my app (named core) to use Django-South. I have a custom model/field that I'm using, named ImageWithThumbsField. It's basically just the ol' django.db.models.ImageField with some attributes such as height, weight, etc.
While trying to ./manage.py convert_to... | [
"I got it! :)\nI changed this: [\"^core/.fields/.ImageWithThumbsField\",]\nTo this: [\"^lib\\.thumbs\\.ImageWithThumbsField\",]\nThis whole line is a regular-expression of python paths of Django field types (read this again, long sentence).\nSouth stumbled upon a field name ImageWithThumbsField that was declared in... | [
17
] | [] | [] | [
"django",
"django_south",
"migration",
"python"
] | stackoverflow_0004715964_django_django_south_migration_python.txt |
Q:
Problem with Python 3.1(syntax error). Im a beginner please help!
im new to pragraming :)
I got a problem with sytax error while making a guessing game. the problem is in (if Gender = boy or Boy), the equal(=) letter is a syntax error. Please help!
Answer = 23
Guess = ()
Gender = input("Are you a boy, a girl or ... | Problem with Python 3.1(syntax error). Im a beginner please help! | im new to pragraming :)
I got a problem with sytax error while making a guessing game. the problem is in (if Gender = boy or Boy), the equal(=) letter is a syntax error. Please help!
Answer = 23
Guess = ()
Gender = input("Are you a boy, a girl or an alien? ")
if Gender = boy or Boy:
print("Nice!", Gender)
if G... | [
"Write them like this:\nif Gender in ('boy', 'Boy'):\n\nif Gender in ('girl', 'Girl'):\n\nAnd = is assignment operator, not equality and that is why the error is there. Either ways, use the in method of comparing. \nif Gender in options\n\nwhere options is a tuple.\nOr if you want to stick to your method:\nif Gende... | [
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004716096_python.txt |
Q:
How to use simplejson to serialize and maintain properties?
For a dictionary containing these two key-value pairs:
str = StringProperty
time = DateTimeProperty
I want to serialize it to JSON, store it in the Datastore, and then fetch it, and deserialize it into the original properties.
A:
Try to do it this way:... | How to use simplejson to serialize and maintain properties? | For a dictionary containing these two key-value pairs:
str = StringProperty
time = DateTimeProperty
I want to serialize it to JSON, store it in the Datastore, and then fetch it, and deserialize it into the original properties.
| [
"Try to do it this way:\nd = {\n 'str' : StringProperty,\n 'time' : unicode(DateTimeProperty)\n}\ns = simplejson.dumps(d)\nprint s\n\n",
"This is simple if your values are strings:\n>>> import simplejson\n>>> print simplejson.dumps({'str': 'StringProperty', 'time': 'DateTimeProperty'})\n{\"str\": \"StringPrope... | [
2,
0
] | [] | [] | [
"google_app_engine",
"json",
"python",
"serialization",
"simplejson"
] | stackoverflow_0004715974_google_app_engine_json_python_serialization_simplejson.txt |
Q:
Python Module for rich gui interfaces
Was just wondering what all python modules are available for rich(and easy to build :) ) gui interfaces. I am aware of Tkinter and Pwm extension but any other reference would be highly appreciated.
A:
The following list comes from Mark Lutz's Programming Python 4th edition:
... | Python Module for rich gui interfaces | Was just wondering what all python modules are available for rich(and easy to build :) ) gui interfaces. I am aware of Tkinter and Pwm extension but any other reference would be highly appreciated.
| [
"The following list comes from Mark Lutz's Programming Python 4th edition:\n\ntkinter and extensions: Pmw, Tix, and ttk\nwxPython: \"A Python interface for the open source wxWidgets.\" This is what we use at our company for any Python desktop GUIs.\nPyQt\nPyGTK\nJython\nIronPython\nPythonCard\nDabo: Dabo looks pret... | [
6,
3,
1,
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004714567_python_tkinter_user_interface.txt |
Q:
Safe way to connect to RPC server
This question is related to How do we handle Python xmlrpclib Connection Refused?
When I try to use the following code, with my RPC server down, _get_rpc() returns False and I'm good to go. However if the server is running, it fails with unknown method. Is it trying to execute .c... | Safe way to connect to RPC server | This question is related to How do we handle Python xmlrpclib Connection Refused?
When I try to use the following code, with my RPC server down, _get_rpc() returns False and I'm good to go. However if the server is running, it fails with unknown method. Is it trying to execute .connect() on the remote server? How can ... | [
"Well i was just looking in to it ; my old method suck because xmlrpclib.ServerProxy try to connect to the XmlRPC server when you call a method, not before !!!\nTry this instead :\nimport xmlrpclib\nimport socket\n\ndef _get_rpc():\n a = xmlrpclib.ServerProxy('http://dd:LNXFhcZnYshy5mKyOFfy@127.0.0.1:9001')\n\n ... | [
5
] | [] | [] | [
"python",
"xmlrpclib"
] | stackoverflow_0004716598_python_xmlrpclib.txt |
Q:
How to use Python distutils?
I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.
my main goal is to cr... | How to use Python distutils? | I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.
my main goal is to create a .deb package for debian/ubu... | [
"See the distutils simple example. That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping ... | [
14,
6,
2,
2,
1
] | [] | [] | [
"debian",
"distutils",
"installation",
"linux",
"python"
] | stackoverflow_0000029562_debian_distutils_installation_linux_python.txt |
Q:
How to use sparse matrix in python hcluster?
I'm trying to use hcluster library in python. I have no enough python knowledges to use sparse matrix in hcluster. Please help me anybody. So, that what I'm doing:
import os.path
import numpy
import scipy
import scipy.io
from hcluster import squareform, pdist, linkage... | How to use sparse matrix in python hcluster? | I'm trying to use hcluster library in python. I have no enough python knowledges to use sparse matrix in hcluster. Please help me anybody. So, that what I'm doing:
import os.path
import numpy
import scipy
import scipy.io
from hcluster import squareform, pdist, linkage, complete
from hcluster.hierarchy import linkage... | [
"Represent the inputs each as a dictionary, from feature name to value. Zeros are not present in the dictionary.\nCompute the Y matrix yourself, not using the hcluster.pdist. The following code does sparse squared-error. Squared-error is equivalent to cosine distance IF you l2-normalize all feature vectors.\ndef sq... | [
2
] | [] | [] | [
"hcluster",
"linkage",
"python",
"sparse_matrix"
] | stackoverflow_0004360806_hcluster_linkage_python_sparse_matrix.txt |
Q:
Indexing one-dimensional numpy.array as matrix
I am trying to index a numpy.array with varying dimensions during runtime. To retrieve e.g. the first row of a n*m array a, you can simply do
a[0,:]
However, in case a happens to be a 1xn vector, this code above returns an index error:
IndexError: too many indices ... | Indexing one-dimensional numpy.array as matrix | I am trying to index a numpy.array with varying dimensions during runtime. To retrieve e.g. the first row of a n*m array a, you can simply do
a[0,:]
However, in case a happens to be a 1xn vector, this code above returns an index error:
IndexError: too many indices
As the code needs to be executed as efficiently as... | [
"Just use a[0] instead of a[0,:]. It will return the first line for a matrix and the first entry for a vector. Is this what you are looking for?\nIf you want to get the whole vector in the one-dimensional case instead, you can use numpy.atleast_2d(a)[0]. It won't copy your vector -- it will just access it as a t... | [
9,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004716647_numpy_python.txt |
Q:
Python 3 order of testing undetermined
string='a'
p=0
while (p <len(string)) & (string[p]!='c') :
p +=1
print ('the end but the process already died ')
while (p <1) & (string[p]!='c') :
IndexError: string index out of range
I want to test a condition up to the end of a string (examp... | Python 3 order of testing undetermined | string='a'
p=0
while (p <len(string)) & (string[p]!='c') :
p +=1
print ('the end but the process already died ')
while (p <1) & (string[p]!='c') :
IndexError: string index out of range
I want to test a condition up to the end of a string (example string length=1)
why are both parts of ... | [
"You're not using proper boolean and. Use it and you won't see this problem. What you're using (&) is a bitwise comparison, which evaluates both sides.\n",
"Bitwise AND, \"a & b\", should be thought of as\nfunction _bitwise_and(A,B):\n # A and B are Python expressions\n # which result in lists of 1's and ... | [
9,
1,
0
] | [] | [] | [
"boolean",
"comparison",
"python",
"python_3.x"
] | stackoverflow_0004713941_boolean_comparison_python_python_3.x.txt |
Q:
Splitting strings using a delimiter in python
OK so I have a string that has this:
Dan|warrior|54
I'm trying to make so I can use python and split it using | as the delimiter. Here's what I have so far:
#!/usr/bin/env python
dan = 'dan|warrior|54'
print dan.split('|')
and that results into this:
['dan', 'warrior... | Splitting strings using a delimiter in python | OK so I have a string that has this:
Dan|warrior|54
I'm trying to make so I can use python and split it using | as the delimiter. Here's what I have so far:
#!/usr/bin/env python
dan = 'dan|warrior|54'
print dan.split('|')
and that results into this:
['dan', 'warrior', '54']
I know it's incomplete but what do I have... | [
"So, your input is 'dan|warrior|54' and you want \"warrior\". You do this like so:\n>>> dan = 'dan|warrior|54'\n>>> dan.split('|')[1]\n\"warrior\"\n\n"
] | [
68
] | [] | [] | [
"python"
] | stackoverflow_0004717074_python.txt |
Q:
Can you register multiple ModelAdmins for a Model? Alternatives?
Say I have the Django model class:
class Foo(models.Model):
bar = models.CharField()
baz = models.CharField()
and the ModelAdmins:
class Foo_Admin_1(admin.ModelAdmin):
list_display = ['id','bar']
class Foo_Admin_2(admin.ModelAdmin):
list_displa... | Can you register multiple ModelAdmins for a Model? Alternatives? | Say I have the Django model class:
class Foo(models.Model):
bar = models.CharField()
baz = models.CharField()
and the ModelAdmins:
class Foo_Admin_1(admin.ModelAdmin):
list_display = ['id','bar']
class Foo_Admin_2(admin.ModelAdmin):
list_display = ['id','baz']
is there any way to register both ModelAdmins so tha... | [
"Create an empty proxy subclass and register it instead:\nclass Foo(models.Model):\n bar = models.CharField()\n baz = models.CharField()\n\n# admin.py\nclass FooProxy(Foo):\n class Meta:\n proxy=True\n\nadmin.site.register(Foo, FooAdmin1)\nadmin.site.register(FooProxy, FooAdmin2) \n\n"
] | [
11
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004716880_django_django_admin_django_models_python.txt |
Q:
Commit a variable to the next function
I just simple want to pass the emailadress from def send_username to the second def username_is_send. How do I do it? How can I pass the variable to the next def?
@csrf_protect
def send_username(request, template_name='auth/user/registration/send_username_form.html',
em... | Commit a variable to the next function | I just simple want to pass the emailadress from def send_username to the second def username_is_send. How do I do it? How can I pass the variable to the next def?
@csrf_protect
def send_username(request, template_name='auth/user/registration/send_username_form.html',
email_template_name='auth/user/registration/se... | [
"You need to store the state somehow in order to pass parameters through a redirect. Multiple possibilities:\n\nStore the mail address in the session, then read in the session variable again in the username_is_send view.\nUse a GET parameter to pass the mail address. \n\nAnd it's \"pass\", not \"path\". And the \"d... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004717367_django_python.txt |
Q:
How can I programmatically generate relevant tags for a database of URLs?
I'm writing an RSS reader in python as a learning exercise, and I would really like to be able to tag individual entries with keywords for searching. Unfortunately, most real-world feeds don't include keyword metadata. I currently have abo... | How can I programmatically generate relevant tags for a database of URLs? | I'm writing an RSS reader in python as a learning exercise, and I would really like to be able to tag individual entries with keywords for searching. Unfortunately, most real-world feeds don't include keyword metadata. I currently have about 60,000 entries in my test database from about 600 feeds, so manually tagging... | [
"There are a number of free and commercial text annotation tools/services you might consider, depending on your specific needs, listed under:\nIs there a better tool than OpenCalais?. \nA number of these provide entities, some provide a measure of keyword relevance, and others provide topic tags.\n",
"You can us... | [
2,
1
] | [] | [] | [
"google_ads_api",
"keyword",
"nlp",
"python"
] | stackoverflow_0004710261_google_ads_api_keyword_nlp_python.txt |
Q:
Dot product of every element with every other element of an array
Is there an easy way to take the dot product of one element of an array with every other?
So given:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
I would like to get the result:
array([ 32., 50., 122.])
I.e. a[0] dot a[1], a[0] dot a[... | Dot product of every element with every other element of an array | Is there an easy way to take the dot product of one element of an array with every other?
So given:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
I would like to get the result:
array([ 32., 50., 122.])
I.e. a[0] dot a[1], a[0] dot a[2], a[1] dot a[2].
The array I am working with will NOT be square; that... | [
">>> X = scipy.matrix('1 2 3; 4 5 6; 7 8 9')\n>>> X*X.T\nmatrix([[ 14, 32, 50],\n [ 32, 77, 122],\n [ 50, 122, 194]])\n\nIt gives you more than what you wanted, but it's undeniably easy.\nOr\n>>> X = scipy.array([[1,2,3], [4,5,6], [7,8,9]])\n>>> scipy.dot(X, X.T)\narray([[ 14, 32, 50],\n [ ... | [
4,
1,
0
] | [] | [] | [
"dot_product",
"numpy",
"python"
] | stackoverflow_0004717311_dot_product_numpy_python.txt |
Q:
Is there a python module that is good with graphics?
I'm looking all over and I can't find a decent graphics tool for like making games. NOT PYGAME! It would be best simpler than pyopengl but easier to understand than pygame.
A:
An option is pyglet.
The pyglet.gl module exposes an interface that uses OpenGL at l... | Is there a python module that is good with graphics? | I'm looking all over and I can't find a decent graphics tool for like making games. NOT PYGAME! It would be best simpler than pyopengl but easier to understand than pygame.
| [
"An option is pyglet.\nThe pyglet.gl module exposes an interface that uses OpenGL at lowest level to draw in windows.\n",
"I would say that Cocos2D fits your criteria.\n",
"...also do check out PyOgre.\n"
] | [
1,
0,
0
] | [] | [] | [
"graphics",
"module",
"python"
] | stackoverflow_0004717217_graphics_module_python.txt |
Q:
How do I convert a django form input to python data?
I have a widget that allows user to enter data for a model field. The data in the form can't be directly converted to Python - it requires some coercion. Where do I put this code? Is the widget responsible for translating its post data to a python value? The fie... | How do I convert a django form input to python data? | I have a widget that allows user to enter data for a model field. The data in the form can't be directly converted to Python - it requires some coercion. Where do I put this code? Is the widget responsible for translating its post data to a python value? The field itself?
I thought that maybe value_from_datadict() woul... | [
"The clean and clean_<field> methods in Form subclass are responsible for this. Here are the docs about validation (and cleaning): http://docs.djangoproject.com/en/1.2/ref/forms/validation/\n",
"Quoting the django source for value_from_datadict():\n\nGiven a dictionary of data and this widget's name, returns the ... | [
1,
1
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0004717761_django_forms_python.txt |
Q:
Method returns variable into its original parameter variable
I am encountering a problem with my program, where a method is saving everything that it does to the parameter variable used in it.
Here's an example: method that moves a list's element to the left by given spaces.
def moveLeft (perm, pos, spaces):
... | Method returns variable into its original parameter variable | I am encountering a problem with my program, where a method is saving everything that it does to the parameter variable used in it.
Here's an example: method that moves a list's element to the left by given spaces.
def moveLeft (perm, pos, spaces):
permTemp = perm
for n in range(spaces):
charMoved = permT... | [
"Use\npermTemp = perm[:]\n\nto actually copy the list, instead of just assigning a new name to the same object.\nPython assignment does not create new objects, it just names existing ones. That's why you are modifying the original list.\n",
"Use Sven's list copy, but note also that you don't need a temporal vari... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004718075_python.txt |
Q:
In python writing from XML to CSV, encoding error
I am trying to convert an XML file to CSV, but the encoding of the XML ("ISO-8859-1") apparently contains characters that are not in the ascii codec which Python uses to write rows.
I get the error:
Traceback (most recent call last):
File "convert_folder_to_csv_P... | In python writing from XML to CSV, encoding error | I am trying to convert an XML file to CSV, but the encoding of the XML ("ISO-8859-1") apparently contains characters that are not in the ascii codec which Python uses to write rows.
I get the error:
Traceback (most recent call last):
File "convert_folder_to_csv_PLAYER.py", line 139, in <module>
xml2csv_PLAYER(fil... | [
"The xml parser returns unicode objects. That's a good thing. Thing is, csv module can't deal with them.\nYou could encode each unicode string returned by the xml parser before handing to the csv writer, but a better idea is to use this csv UnicodeWriter recipe from the official docs of the csv module:\nimport csv,... | [
1
] | [] | [] | [
"character_encoding",
"minidom",
"python",
"xml"
] | stackoverflow_0004718161_character_encoding_minidom_python_xml.txt |
Q:
Programatically posting a comment in Reddit using Python
I'm using the httplib2 library located here
So far my code is this:
http = httplib2.Http()
url= 'http://www.reddit.com/api/login'
body= {'user' : 'DUMMYUSERNAME', 'passwd': 'DUMMYPASSWORD'}
headers = {'Content-type': 'application/x-www-form-u... | Programatically posting a comment in Reddit using Python | I'm using the httplib2 library located here
So far my code is this:
http = httplib2.Http()
url= 'http://www.reddit.com/api/login'
body= {'user' : 'DUMMYUSERNAME', 'passwd': 'DUMMYPASSWORD'}
headers = {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}
response, content= http.request... | [
"I'd suggest taking at look at the Reddit API:\nhttp://code.reddit.com/wiki/API\n"
] | [
1
] | [] | [] | [
"automation",
"forms",
"networking",
"python"
] | stackoverflow_0004718397_automation_forms_networking_python.txt |
Q:
Center origin in matplotlib
I need help customizing my plots. I want the canvas to look approximately like the default 2D-graph template from MacOS's Grapher (see screenshot).
To clarify - I need
a centered axis
a grid (preferably with an additional darker grid every 1 unit)
axislines with arrows
only one zero... | Center origin in matplotlib | I need help customizing my plots. I want the canvas to look approximately like the default 2D-graph template from MacOS's Grapher (see screenshot).
To clarify - I need
a centered axis
a grid (preferably with an additional darker grid every 1 unit)
axislines with arrows
only one zero at the origo (when I tried my be... | [
"This definitely falls under the category of more trouble than it's worth with matplotlib, but here you go. Also, for the basic case, have a look at the centering spines demo in the documentation.\nYou can do this in a few different ways, but for the best visual effect, consider something along the lines of the fol... | [
40,
3
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0004694478_matplotlib_plot_python.txt |
Q:
Unserialize 'nested' arrays in Python
I've been trying to unserialize an array coming into my python script. I have found some extensions to Python (like Scott Hurring's version: http://hurring.com/scott/code/python/serialize/) that unserialize simple data structures like:
a:2:{s:7:"version";s:3:"457";s:12:"versio... | Unserialize 'nested' arrays in Python | I've been trying to unserialize an array coming into my python script. I have found some extensions to Python (like Scott Hurring's version: http://hurring.com/scott/code/python/serialize/) that unserialize simple data structures like:
a:2:{s:7:"version";s:3:"457";s:12:"version_beta";s:3:"461";};
My data looks like th... | [
"There is a module for serialization in the stdlib, called pickle.\n\nThe pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the ... | [
2,
0
] | [] | [] | [
"python",
"serialization"
] | stackoverflow_0004706398_python_serialization.txt |
Q:
python indentation
I am trying to make this script work but it's... giving me indentation errors
#!/usr/bin/env python
import io
myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('|')[0]
try:
myfile.write('blah')
finally:
myfile.close()
except IOError:
... | python indentation | I am trying to make this script work but it's... giving me indentation errors
#!/usr/bin/env python
import io
myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('|')[0]
try:
myfile.write('blah')
finally:
myfile.close()
except IOError:
Help?
| [
"Try-except-finally statement has the following syntax:\ntry:\n statement 1\nexcept:\n statement 2\nfinally:\n statement 3\n\nYou're doing it a little bit wrong :) Try to fix)\nAlso, as Herohtar said, swap your finally and except statements. Finally really should go after except.\n",
"Your Finally is ind... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004718768_python.txt |
Q:
OAuth Gdata Python Client throws stacktrace on RSA_KEY
Moving on from AuthSub to OAuth, I think I'm slowly beginning to understand the process.
This one threw me an error though:
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.we... | OAuth Gdata Python Client throws stacktrace on RSA_KEY | Moving on from AuthSub to OAuth, I think I'm slowly beginning to understand the process.
This one threw me an error though:
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from gdata.calendar import service
impo... | [
"tlslite has two keyformats: PEM and XML. It first tries PEM (see parsePrivateKey), and then falls back to XML. Apparently, there is an error in your PEM file, so PEM parsing fails (but should have succeeded). Parsing XML then clearly must fail.\nMy guess is that you messed up line endings somehow, but perhaps ther... | [
2
] | [] | [] | [
"gdata",
"gdata_api",
"google_app_engine",
"python"
] | stackoverflow_0004718261_gdata_gdata_api_google_app_engine_python.txt |
Q:
I/O reading from a file (python)
Ok, I have an IRC bot and I have a file full of nicknames (which are the admins for the bot), for example if someone types "!op" in the channel how would I go about making the bot read the file to see if the user who typed "!op" is in the list of admins and if he is then proceed wi... | I/O reading from a file (python) | Ok, I have an IRC bot and I have a file full of nicknames (which are the admins for the bot), for example if someone types "!op" in the channel how would I go about making the bot read the file to see if the user who typed "!op" is in the list of admins and if he is then proceed with the action.. I'm just confused on h... | [
"You should probably just run through the whole Python tutorial. There is a whole section about reading and writing files.\n",
"I assume your names are line seperated.\ndef isadmin(name, file):\n for admin in file:\n if name == admin.rstrip():\n return True\n return False\n\nBut they coul... | [
4,
1,
0
] | [] | [] | [
"input",
"io",
"irc",
"python"
] | stackoverflow_0004718064_input_io_irc_python.txt |
Q:
Class variable and instance variable question in Python
When I have this class, the variable 'value' is class variable.
class Hello:
value = 10
def __init__(self):
print 'init'
I have an object 'h' and I could get the same value of '10' both for Hello.value and h.value.
h = Hello()
pri... | Class variable and instance variable question in Python | When I have this class, the variable 'value' is class variable.
class Hello:
value = 10
def __init__(self):
print 'init'
I have an object 'h' and I could get the same value of '10' both for Hello.value and h.value.
h = Hello()
print Hello.value
print h.value
When I run this command,
h.val... | [
"That's how attribute lookup works in Python: \n\nIf an attribute can't be found in the dictionary of an instance, it is looked up in the dictionary of its class, and if it can't be found there, also in the dictionaries of the base classes.\nIf you assign to an instance attribute, this will always only affect the i... | [
4,
4
] | [] | [] | [
"class_variables",
"instance_variables",
"python"
] | stackoverflow_0004718801_class_variables_instance_variables_python.txt |
Q:
Is there an API of Google App Engine provided to better configure the Bigtable besides Datastore?
According to the Bigtable original article, a column key of a Bigtable is named using "family:qualifier" syntax where column family names must be printable but qualifiers may be arbitrary strings. In the application I... | Is there an API of Google App Engine provided to better configure the Bigtable besides Datastore? | According to the Bigtable original article, a column key of a Bigtable is named using "family:qualifier" syntax where column family names must be printable but qualifiers may be arbitrary strings. In the application I am working on, I would like to specify the qualifiers using Chinese words (or phrase). Is it possible ... | [
"The Datastore is the only interface to the underlying storage on App Engine. You should be able to use any valid UTF-8 string as a kind name, key name, or property name, however.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004712143_google_app_engine_python.txt |
Q:
PHP part in Python based website
I need to write a small addition to a Python+Django based website, hosted on Google Apps. Trouble is that I don't have any experience with Python.
The addition is pretty straight forward, it requires little database access
So thought of 2 possible solution's:
Quickly dive into Py... | PHP part in Python based website | I need to write a small addition to a Python+Django based website, hosted on Google Apps. Trouble is that I don't have any experience with Python.
The addition is pretty straight forward, it requires little database access
So thought of 2 possible solution's:
Quickly dive into Python and get it done with Python.
Run ... | [
"I am not sure about how you will run php on GAE since it only support Java and Python.\nI'd go with solution 1. Python isn't hard to apprehend, you should find ready-to-go code snippets in GAE documentation, and its Datastore doesn't seem too hard to use :D\nthere's a nice tutorial in GAE documentation: here\n",
... | [
2,
1
] | [] | [] | [
"google_app_engine",
"php",
"python"
] | stackoverflow_0004711544_google_app_engine_php_python.txt |
Q:
Python: inject new functions into an instance of class?
I tried to manipulate the __mro__ but it it read-only
The use case is as follow:
The Connection object created from pyodbc (a DBAPI) used to provide a property called 'autocommit'. Lately I have wrapped a SQLAlchemy db connection pool around the pyodbc for be... | Python: inject new functions into an instance of class? | I tried to manipulate the __mro__ but it it read-only
The use case is as follow:
The Connection object created from pyodbc (a DBAPI) used to provide a property called 'autocommit'. Lately I have wrapped a SQLAlchemy db connection pool around the pyodbc for better resource management. The new db pool will return a _Conn... | [
"You can \"extend\" almost any class using following syntax:\ndef new_func(self, param):\n print param\n\nclass a:\n pass\n\na.my_func = new_func\nb = a()\nb.my_func(10)\n\nUPDATE\nIf you want to create some kind of wrappers for some methods you can use getattr and setattr to save original method and replace ... | [
11
] | [] | [] | [
"python"
] | stackoverflow_0004719083_python.txt |
Q:
Python and sqlite3 - importing and exporting databases
I'm trying to write a script to import a database file. I wrote the script to export the file like so:
import sqlite3
con = sqlite3.connect('../sqlite.db')
with open('../dump.sql', 'w') as f:
for line in con.iterdump():
f.write('%s\n' % line)
No... | Python and sqlite3 - importing and exporting databases | I'm trying to write a script to import a database file. I wrote the script to export the file like so:
import sqlite3
con = sqlite3.connect('../sqlite.db')
with open('../dump.sql', 'w') as f:
for line in con.iterdump():
f.write('%s\n' % line)
Now I want to be able to import that database. I have tried :
... | [
"sql = f.read() # watch out for built-in `str`\ncur.executescript(sql)\n\nDocumentation.\n",
"Try using\ncon.executescript(str)\n\nDocumentation\nConnection.executescript(sql_script)\n This is a nonstandard shortcut that creates an intermediate cursor object\n by calling the cursor method, then calls the cu... | [
23,
4
] | [] | [] | [
"django",
"python",
"sql",
"sqlite"
] | stackoverflow_0004719159_django_python_sql_sqlite.txt |
Q:
How to add commas / delimiters for all list items except last?
Say I have a for loop, which lists a bunch of Users. There might be 0-n Users in the loop. I want to put commas after each User name except the last one.
So for:
<p>
{% for u in users %}
{{u.name}},
{% endfor }
</p>
I get:
Sam, Neil, Bob,
I want:
S... | How to add commas / delimiters for all list items except last? | Say I have a for loop, which lists a bunch of Users. There might be 0-n Users in the loop. I want to put commas after each User name except the last one.
So for:
<p>
{% for u in users %}
{{u.name}},
{% endfor }
</p>
I get:
Sam, Neil, Bob,
I want:
Sam, Neil, Bob
| [
"I agree join is a good approach. If you want to do it with for, try\n{% for u in users %}\n{{u.name}}{% if not forloop.last %},{% endif %}\n{% endfor }\n\n",
"The for loop in Django 1.2 includes a few automatically generated variables. Among those are:\nforloop.first\nforloop.last\n\nSo you could place the delim... | [
7,
2
] | [
"If you don't need to loop, and you just have a list, then 'join' is probably your best solution.\nBut first we need to get a list of all names, map should help us with that, then join all the results:\n{% with names = map(lambda u: u.name, users) %}\n{{ names|join:\", \" }}\n{% endwith %}\n\n"
] | [
-1
] | [
"css",
"django",
"html",
"python"
] | stackoverflow_0004719103_css_django_html_python.txt |
Q:
string manipulation in python
I have a python file like this
import urllib2
try:
data = urllib2.urlopen('http:....').read()
except urllib2.HTTPError, e:
print "HTTP error: %d" % e.code
except urllib2.URLError, e:
print "Network error: %s" % e.reason.args[1]
print data1
the output looks like this
>>>... | string manipulation in python | I have a python file like this
import urllib2
try:
data = urllib2.urlopen('http:....').read()
except urllib2.HTTPError, e:
print "HTTP error: %d" % e.code
except urllib2.URLError, e:
print "Network error: %s" % e.reason.args[1]
print data1
the output looks like this
>>>
15.95
>>>
I need to perform some... | [
"Perhaps you just need to strip whitespace from your variable? Use data1.strip(). Read up on str.strip() for more information.\nBy the way, to see the whitespace explicitly, use print repr(data1).\n",
"Use strip.\n",
"data1.strip()\n\nhttp://docs.python.org/library/stdtypes.html#str.strip\n\n\"Return a copy of... | [
7,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004719244_python.txt |
Q:
Python: Calling method A from class A within class B?
There are a number of questions that are similar to this, but none of the answers hits the spot - so please bear with me.
I am trying my hardest to learn OOP using Python, but i keep running into errors (like this one) which just make me think this is all point... | Python: Calling method A from class A within class B? | There are a number of questions that are similar to this, but none of the answers hits the spot - so please bear with me.
I am trying my hardest to learn OOP using Python, but i keep running into errors (like this one) which just make me think this is all pointless and it would be easier to just use methods.
Here is my... | [
"You seem to have several misconceptions.\n\nYou are using methods here. (Did you mean \"functions\", as in not belonging to a class?)\nClasses are not some kind of container or namespace for functionality. They define a data type. The point of having the class WebParser is that you can have more than one WebParser... | [
6,
2,
0
] | [] | [] | [
"class",
"oop",
"python",
"wxpython"
] | stackoverflow_0004719185_class_oop_python_wxpython.txt |
Q:
HTML-escaping replacement fields when using str.format() in Python
I am using the string .format() function to format my strings with keyword arguments. I pass in some basic objects to the strings and use attributes of these objects in the strings. For example:
"Hello, {user.first_name}!".format(user=my_user)
T... | HTML-escaping replacement fields when using str.format() in Python | I am using the string .format() function to format my strings with keyword arguments. I pass in some basic objects to the strings and use attributes of these objects in the strings. For example:
"Hello, {user.first_name}!".format(user=my_user)
These strings may be used in HTML e-mails, so the replacement fields shou... | [
"Well, the question is why you are using format to begin with. Aren't you going to push this to a template? I mean, if you escape something in your template (using a template tag) you're pretty much just passing a string through this escape function.\nMaybe this isn't what you're looking for but would't you just ... | [
1,
0
] | [] | [] | [
"python",
"string",
"string_formatting"
] | stackoverflow_0004632150_python_string_string_formatting.txt |
Q:
python script for downloading all Ctrl+Alt+Del webcomics?
Does anyone have one? Ive tried Comicdownloader but that only lets me download the newest comic and I dont understand Python well enough to figure out how to change it to download all the comics
A:
Well, it's not python and the method is not very elegant ... | python script for downloading all Ctrl+Alt+Del webcomics? | Does anyone have one? Ive tried Comicdownloader but that only lets me download the newest comic and I dont understand Python well enough to figure out how to change it to download all the comics
| [
"Well, it's not python and the method is not very elegant either but it'll work.\nAfter a brief inspection of the ctrl+alt+del archive site I found that all the comics are stored in /comics/ as jpg files.\nWith that assumption, running the following command in a shell on a *nix machine will download all comics. The... | [
4,
2,
0
] | [] | [] | [
"download",
"python",
"web_scraping"
] | stackoverflow_0001183111_download_python_web_scraping.txt |
Q:
django, datetime and timezones
I am using: datetime.now() to get the current time in an Event app that lets you create an event that has an end date, then all of the events are displayed in a calendar and if an event is passed due it is displayed in red.
My issue is that I have some users in different timezones ... | django, datetime and timezones | I am using: datetime.now() to get the current time in an Event app that lets you create an event that has an end date, then all of the events are displayed in a calendar and if an event is passed due it is displayed in red.
My issue is that I have some users in different timezones than me saying that the events are e... | [
"You will need your users to specify their timezone in their user profile. This can then be used to calculate local times correctly.\nCheck out Relativity of time – shortcomings in Python datetime, and workaround for some good information (and concrete examples).\nUPDATE: From Django 1.4 it comes up with timezone s... | [
4,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001793386_django_python.txt |
Q:
Unsupported operand type for NoneType and str
I get a message that states:
Traceback (most recent call last):
File "/var/www/fosa/error_supressor.py", line 46, in <module>
sys.stderr.write(latest + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
I have been trying to solve this proble... | Unsupported operand type for NoneType and str | I get a message that states:
Traceback (most recent call last):
File "/var/www/fosa/error_supressor.py", line 46, in <module>
sys.stderr.write(latest + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
I have been trying to solve this problem for days now but honestly I'm a rocky programmer.... | [
"\nSomething is binding None to latest. Figure out what it is and fix your logic error.\nSomething is binding None to course. Figure etc.\n\n",
"Obviously from the traceback, one has:\n- latest is None\n- course is None\nA common pattern in python is to have variable names always be bound to a unique type, except... | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0004718624_python.txt |
Q:
How can you get the system default language/locale, in a py2app packaged Python app on Mac OS X?
I wrote a simple wxPython app which I package with py2app, turning it into a self-contained double-clickable .app bundle which I can give to other people to run.
My app uses some locale-specific settings -- specificall... | How can you get the system default language/locale, in a py2app packaged Python app on Mac OS X? | I wrote a simple wxPython app which I package with py2app, turning it into a self-contained double-clickable .app bundle which I can give to other people to run.
My app uses some locale-specific settings -- specifically, it wants to parse dates in text form -- so it lets the user specify what locale to use, and it call... | [
"The values for environment variables for applications launched (by double-clicking, say) are not the same as when run under a terminal window shell. There is a way to specify those by creating ~/.MacOSX/environment.plist: see here for more details. But that's probably not what you want to do. If you need to cre... | [
1
] | [] | [] | [
"localization",
"macos",
"python"
] | stackoverflow_0004719789_localization_macos_python.txt |
Q:
Python 2.6 send connection object over Queue / Pipe / etc
Given this bug (Python Issue 4892) that gives rise to the following error:
>>> import multiprocessing
>>> multiprocessing.allow_connection_pickling()
>>> q = multiprocessing.Queue()
>>> p = multiprocessing.Pipe()
>>> q.put(p)
>>> q.get()
Traceback (most rec... | Python 2.6 send connection object over Queue / Pipe / etc | Given this bug (Python Issue 4892) that gives rise to the following error:
>>> import multiprocessing
>>> multiprocessing.allow_connection_pickling()
>>> q = multiprocessing.Queue()
>>> p = multiprocessing.Pipe()
>>> q.put(p)
>>> q.get()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ... | [
"Here's roughly what I did:\n# Producer\nfrom multiprocessing.reduction import reduce_connection\nfrom multiprocessing import Pipe\n\n # Producer and Consumer share the Queue we call queue\ndef handle(queue):\n reader, writer = Pipe()\n pickled_writer = pickle.dumps(reduce_connection(writer))\n queue.put(pi... | [
8,
8
] | [] | [] | [
"multiprocessing",
"pickle",
"pipe",
"python",
"queue"
] | stackoverflow_0001446004_multiprocessing_pickle_pipe_python_queue.txt |
Q:
Markaby/Erector for Python
I like using Python, but hate writing HTML. Is there a Markaby/Erector - like module for Python?
A:
Seems like you can kind of do this with lxml:
http://lxml.de/lxmlhtml.html#creating-html-with-the-e-factory
from lxml.html import builder as E
from lxml.html import usedoctest
html = E.H... | Markaby/Erector for Python | I like using Python, but hate writing HTML. Is there a Markaby/Erector - like module for Python?
| [
"Seems like you can kind of do this with lxml:\nhttp://lxml.de/lxmlhtml.html#creating-html-with-the-e-factory\nfrom lxml.html import builder as E\nfrom lxml.html import usedoctest\nhtml = E.HTML(\n E.HEAD(\n E.LINK(rel=\"stylesheet\", href=\"great.css\", type=\"text/css\"),\n E.TITLE(\"Best Page Ever\")\n )... | [
1
] | [] | [] | [
"markaby",
"python",
"ruby"
] | stackoverflow_0004719180_markaby_python_ruby.txt |
Q:
Returning all "positions" of a list
I Have a list with "a" and "b" and the "b"'s are somewhat of a path and "a"'s are walls. Im writing a program to make a graph of all the possible moves. I got the code running to check the first "b" for possible moves, but i have NO Idea how im going to find all "b"'s , even les... | Returning all "positions" of a list | I Have a list with "a" and "b" and the "b"'s are somewhat of a path and "a"'s are walls. Im writing a program to make a graph of all the possible moves. I got the code running to check the first "b" for possible moves, but i have NO Idea how im going to find all "b"'s , even less check them all without repeating.
Major... | [
"grid = [['b','a','b'],['b','b','b'],['a','a','a']\nresults = []\nfor row in range(len(grid)):\n for col in range(len(grid[row])):\n if grid[row][col] == 'b':\n results.append((row, col))\n\nprint results\n\nThere's probably some better way of doing it using maps but its been awhile since I've used Python.... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"graph",
"list",
"logic",
"python"
] | stackoverflow_0004719922_dictionary_graph_list_logic_python.txt |
Q:
Adding the tuple values into another tuple...but added 1
I'm using 1 tuple and i want to create 4 tuple variations of the tuple I'm using. Example:
a=(x,y)
and i want to make
b=(x+1,y)
c=(x,y+1)
etc
etc
Since I cant change a tuple, any ideas on how to do this?
A:
While you cannot modify an existing tuple, you ... | Adding the tuple values into another tuple...but added 1 | I'm using 1 tuple and i want to create 4 tuple variations of the tuple I'm using. Example:
a=(x,y)
and i want to make
b=(x+1,y)
c=(x,y+1)
etc
etc
Since I cant change a tuple, any ideas on how to do this?
| [
"While you cannot modify an existing tuple, you can create a new tuple based on an existing tuple's values. I think something like this might be what you want:\n>>> a = (1, 2)\n>>> [(a[0]+dx, a[1]+dy) for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]]\n[(0, 2), (2, 2), (1, 3), (1, 1)]\n\nThis creates the four tuples... | [
3,
0,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0004719780_python_tuples.txt |
Q:
python -> time a while loop has been running
i have a loop that runs for up to a few hours at a time. how could I have it tell me how long it has been at a set interval?
just a generic...question
EDIT: it's a while loop that runs permutations, so can i have it print the time running every 10 seconds?
A:
Instead ... | python -> time a while loop has been running | i have a loop that runs for up to a few hours at a time. how could I have it tell me how long it has been at a set interval?
just a generic...question
EDIT: it's a while loop that runs permutations, so can i have it print the time running every 10 seconds?
| [
"Instead of checking the time on every loop, you can use a Timer object\nimport time\nfrom threading import Timer\n\ndef timeout_handler(timeout=10):\n print time.time()\n timer = Timer(timeout, timeout_handler)\n timer.start()\n\ntimeout_handler()\nwhile True:\n print \"loop\"\n time.sleep(1)\n\n",
... | [
9,
2,
1
] | [] | [] | [
"loops",
"permutation",
"python",
"time",
"while_loop"
] | stackoverflow_0004720073_loops_permutation_python_time_while_loop.txt |
Q:
Combinations of numbers and letters
#!/usr/bin/python
import random
lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', ... | Combinations of numbers and letters | #!/usr/bin/python
import random
lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ... | [
"It's best not to recreate functionality that is already in the standard library.\nTake a look at the standard library module itertools. Particularly the combinations(), permutations(), and product() functions.\nimport itertools\n\nlower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'... | [
8,
1,
0,
0
] | [] | [] | [
"combinations",
"python"
] | stackoverflow_0004719850_combinations_python.txt |
Q:
How to overload effectively and systematically Python class methods
Assume that you have a Python (>=2.6) class with plenty (hundreds!) of methods. Now someone wants to subclass that but realized that most of the base class methods needs only some simple 'tuning'. Also there are only handful of different ways to t... | How to overload effectively and systematically Python class methods | Assume that you have a Python (>=2.6) class with plenty (hundreds!) of methods. Now someone wants to subclass that but realized that most of the base class methods needs only some simple 'tuning'. Also there are only handful of different ways to tune those methods. Some involving input transformations, some output tran... | [
"I suggest to use some form of Aspected-Oriented Programming. With the Logilab library, it is easy to put wrappers around all methods of a class.\n",
"I hope this helps:\n\n # the base class\nclass B(object):\n def f1(self, val):\n pass\n def f2(self, val):\n pass\ndef decorator(cls, f):\n ... | [
2,
2,
0,
0
] | [] | [] | [
"boilerplate",
"inheritance",
"methods",
"overloading",
"python"
] | stackoverflow_0004718520_boilerplate_inheritance_methods_overloading_python.txt |
Q:
python -> password safety program
i decided to write a brute force function to show people how vulnerable a password is. right now, i can show them the list it goes through to find the password, but how do i tell them how long it took?
here's the code:
#!/usr/bin/python
import itertools
lower_a = ['a', 'b', 'c',... | python -> password safety program | i decided to write a brute force function to show people how vulnerable a password is. right now, i can show them the list it goes through to find the password, but how do i tell them how long it took?
here's the code:
#!/usr/bin/python
import itertools
lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k... | [
"First of all passwords are quite safe and it will take many many days to find one using brute force attack.\nBut if you'd like you could use following:\nimport time\n\nstart_time = time.time()\n\n# Your code here\n\nstop_time = time.time()\nprint \"Running time in sec:\", stop_time - start_time\n\n",
"What you n... | [
4,
1,
0
] | [] | [] | [
"brute_force",
"combinations",
"python",
"time"
] | stackoverflow_0004720363_brute_force_combinations_python_time.txt |
Q:
py2exe bundle_files=1 or 2 fails
My application uses QGraphicsPixmapItem, and to make it able to load jpeg files I've placed qjpeg4.dll under 'imageformats' subdirectory in the 'dist' directory.
It works, but only as long as 'bundle_files' option is set to 3.
If I set it to 1 or 2, qt4 (pyqt4) is no longer able to... | py2exe bundle_files=1 or 2 fails | My application uses QGraphicsPixmapItem, and to make it able to load jpeg files I've placed qjpeg4.dll under 'imageformats' subdirectory in the 'dist' directory.
It works, but only as long as 'bundle_files' option is set to 3.
If I set it to 1 or 2, qt4 (pyqt4) is no longer able to find needed dlls, and so QGraphicsPix... | [
"You should be able to convince py2exe to include the dll by using:\nsetup(\n # other options,\n data_files=[('imageformats', 'qjpeg4.dll'),\n #other options\n )\n\nFor future reference, data_files should look like this (afaik):\ndata_files = [ (dir1, [file1, file2, ...]), (dir2, [file3, file4, .... | [
0
] | [] | [] | [
"py2exe",
"pyqt4",
"python"
] | stackoverflow_0004720547_py2exe_pyqt4_python.txt |
Q:
Cannot get Pylons to work with mongokit
I've tried following the guide for intergrating mongokit into pylons thats here: http://namlook.github.com/mongokit/pylons.html
When I go to serve with paster it throws the error:
File "/home/ciferkey/Projects/runnr-site/runnrsite/config/environment.py", line 29, in load_env... | Cannot get Pylons to work with mongokit | I've tried following the guide for intergrating mongokit into pylons thats here: http://namlook.github.com/mongokit/pylons.html
When I go to serve with paster it throws the error:
File "/home/ciferkey/Projects/runnr-site/runnrsite/config/environment.py", line 29, in load_environment
config['pylons.app_globals'] = app_g... | [
"Have you tried Mongoengine? I'm currently using it for my own Pylons project and found it very easy to setup and use. http://www.cleverkoala.com/2010/09/how-to-integrate-mongoengine-into-pylons/\n"
] | [
0
] | [] | [] | [
"mongodb",
"mongokit",
"pylons",
"python"
] | stackoverflow_0004710081_mongodb_mongokit_pylons_python.txt |
Q:
PHP framework similar to Python Pylons
What is most similar PHP framework to Pylons?
I mean mostly ideology of programming.
A:
Being primarily a Python developer, and having used Pylons, TurboGears, and Django, I would whole heartedly, 100% recommend Kohana 3.x. To be completely honest I am not a huge fan of PH... | PHP framework similar to Python Pylons | What is most similar PHP framework to Pylons?
I mean mostly ideology of programming.
| [
"Being primarily a Python developer, and having used Pylons, TurboGears, and Django, I would whole heartedly, 100% recommend Kohana 3.x. To be completely honest I am not a huge fan of PHP, even though it is the language of choice at my current employer. Given the choice I would use Python and Pylons. But, using ... | [
2,
1,
1
] | [] | [] | [
"comparison",
"php",
"pylons",
"python",
"web_frameworks"
] | stackoverflow_0004716689_comparison_php_pylons_python_web_frameworks.txt |
Q:
Python dictionary manipulation
I got a list of object
lst = [1,2,3]
I want them in a dictionary with a default key 'number', and then put them in a list.
The result should look like
lst = [{'number':1},{'number':2},{'number':3}
Use less code, please.
A:
Use a list comprehension
lst = [{'number': x} for x in ls... | Python dictionary manipulation | I got a list of object
lst = [1,2,3]
I want them in a dictionary with a default key 'number', and then put them in a list.
The result should look like
lst = [{'number':1},{'number':2},{'number':3}
Use less code, please.
| [
"Use a list comprehension\nlst = [{'number': x} for x in lst]\n\n",
"This matches your code samples:\n>>> lst = [1,2,3]\n>>> newlst = [dict(number=n) for n in lst]\n>>> newlst\n[{'number': 1}, {'number': 2}, {'number': 3}]\n>>> \n\nWhat you say, however, is a bit different - you want them all in the same dictiona... | [
7,
2
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004721045_dictionary_list_python.txt |
Q:
Fastest way to download 3 million objects from a S3 bucket
I've tried using Python + boto + multiprocessing, S3cmd and J3tset but struggling with all of them.
Any suggestions, perhaps a ready-made script you've been using or another way I don't know of?
EDIT:
eventlet+boto is a worthwhile solution as mentioned bel... | Fastest way to download 3 million objects from a S3 bucket | I've tried using Python + boto + multiprocessing, S3cmd and J3tset but struggling with all of them.
Any suggestions, perhaps a ready-made script you've been using or another way I don't know of?
EDIT:
eventlet+boto is a worthwhile solution as mentioned below. Found a good eventlet reference article here http://web.arch... | [
"Okay, I figured out a solution based on @Matt Billenstien's hint. It uses eventlet library. The first step is most important here (monkey patching of standard IO libraries).\nRun this script in the background with nohup and you're all set.\nfrom eventlet import *\npatcher.monkey_patch(all=True)\n\nimport os, sys, ... | [
35,
5
] | [] | [] | [
"amazon_s3",
"boto",
"eventlet",
"linux",
"python"
] | stackoverflow_0004720735_amazon_s3_boto_eventlet_linux_python.txt |
Q:
Python: Processing Javascript with urllib2?
I am coding a HTML scraper which gets values from a table on a website. I also need to grab the URL of an image, but the problem is this image is dynamically generated via javascript - and when i get contents of the website via urllib, the Javascript does not run or show... | Python: Processing Javascript with urllib2? | I am coding a HTML scraper which gets values from a table on a website. I also need to grab the URL of an image, but the problem is this image is dynamically generated via javascript - and when i get contents of the website via urllib, the Javascript does not run or show in the resulting HTML.
Is there any way to enabl... | [
"No, you'd need some sort of JS interpreter for that. There might be Python-Browser integrations to help parsing this kind of page.\n"
] | [
2
] | [] | [] | [
"javascript",
"python",
"urllib2"
] | stackoverflow_0004720342_javascript_python_urllib2.txt |
Q:
Undefined variable in django
I am a python newbie. i was trying out a django tutorial and got this error. I have two classes :
class Package(models.Model):
name = models.CharField(max_length =300)
version = models.CharField(max_length=300,blank=True)
home_page = models.URLField(blank=True)
summary ... | Undefined variable in django | I am a python newbie. i was trying out a django tutorial and got this error. I have two classes :
class Package(models.Model):
name = models.CharField(max_length =300)
version = models.CharField(max_length=300,blank=True)
home_page = models.URLField(blank=True)
summary = models.TextField()
descripti... | [
"It's because Category is not defined before Package is parsed.\nPython parses the file from top to bottom. Therefore the Category class will not be defined when the Packages's categories ManyToManyField relation is defined.\nYou can move Category class above the Package class, or enclose the relation in quotes so ... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004721307_django_python.txt |
Q:
Does python show problem with really large integers?
I have a code to calculate highest prime factor of 600851475143.
def PRIME(a): #Check if no is prime
f = 0
i = 2
while(i < a/2): #No factor of a no can be greater than a/2
if (a % i == 0):
f = 1
... | Does python show problem with really large integers? | I have a code to calculate highest prime factor of 600851475143.
def PRIME(a): #Check if no is prime
f = 0
i = 2
while(i < a/2): #No factor of a no can be greater than a/2
if (a % i == 0):
f = 1
break
i = i + 1
if(f == 1):
return 0... | [
"Python's support for large integers is fine. I think your problem is that you're doing very slow algorithms for both brute-force finding the factor and testing whether your factor is prime. If you just invert the order of those two tests (ie, test whether it's a factor, then test whether it's prime), it'll go a lo... | [
8,
3,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004720411_python.txt |
Q:
Iterating multiple (parent,child) nodes using Python ElementTree
The standard implementation of ElementTree for Python (2.6) does not provide pointers to parents from child nodes. Therefore, if parents are needed, it is suggested to loop over parents rather than children.
Consider my xml is of the form:
<Content>
... | Iterating multiple (parent,child) nodes using Python ElementTree | The standard implementation of ElementTree for Python (2.6) does not provide pointers to parents from child nodes. Therefore, if parents are needed, it is suggested to loop over parents rather than children.
Consider my xml is of the form:
<Content>
<Para>first</Para>
<Table><Para>second</Para></Table>
<Para>thir... | [
"Consider this:\n>>> xml = \"\"\"<Content>\n... <Para>first</Para>\n... <Table><Para>second</Para></Table>\n... <Para>third</Para>\n... </Content>\"\"\"\n>>> import xml.etree.cElementTree as et\n>>> page = et.fromstring(xml)\n>>> for p in page.getiterator():\n... print \"ppp\", p.tag, repr(p.text)\n... ... | [
5
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0004720476_elementtree_python_xml.txt |
Q:
Exception while converting string to datetime in python on GAE with timezone?
I am getting this exception
time data did not match format: data=19:51:06 Jan 17, 2011 PST fmt=%H:%M:%S %b %d, %Y %Z
for following code
datetime.strptime(parameters['19:51:06 Jan 17, 2011 PST'], "%H:%M:%S %b %d, %Y %Z")
in python co... | Exception while converting string to datetime in python on GAE with timezone? | I am getting this exception
time data did not match format: data=19:51:06 Jan 17, 2011 PST fmt=%H:%M:%S %b %d, %Y %Z
for following code
datetime.strptime(parameters['19:51:06 Jan 17, 2011 PST'], "%H:%M:%S %b %d, %Y %Z")
in python code running on Google app engine.
How to modify the formatter so that it works?
| [
"Look for the python docs for datetime.strptime [1]. They say it uses time.strptime internally, so let's check there [2].\n\nSupport for the %Z directive is based\n on the values contained in tzname and\n whether daylight is true. Because of\n this, it is platform-specific except\n for recognizing UTC and GMT w... | [
0
] | [] | [] | [
"datetime",
"google_app_engine",
"python"
] | stackoverflow_0004721164_datetime_google_app_engine_python.txt |
Q:
What's the difference of numpy.ndarray.T and numpy.ndarray.transpose() when self.ndim < 2
The document numpy.ndarray.T says
ndarray.T — Same as self.transpose(), except that self is returned if self.ndim < 2.
Also, ndarray.transpose(*axes) says
For a 1-D array, this has no effect.
Doesn't this mean the same th... | What's the difference of numpy.ndarray.T and numpy.ndarray.transpose() when self.ndim < 2 | The document numpy.ndarray.T says
ndarray.T — Same as self.transpose(), except that self is returned if self.ndim < 2.
Also, ndarray.transpose(*axes) says
For a 1-D array, this has no effect.
Doesn't this mean the same thing?
Here's a little demo snippet:
>>> import numpy as np
>>> print np.__version__
1.5.1rc1
... | [
"Regardless of rank, the .T attribute and the .transpose() method are the same—they both return the transpose of the array.\nIn the case of a rank 1 array, the .T and .transpose() don't do anything—they both return the array.\n",
"It looks like .T is just a convenient notation, and that .transpose(*axes) is the m... | [
26,
10
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004068177_numpy_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.