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:
Error with getattr
I was going to Calling a function of a module from a string with the function's name in Python but whenever i call my class in my program it gives me this error:TypeError: unbound method bar() must be called with foo instance as first argument (got nothing instead)
Can someone help me
A:
Here ... | Error with getattr | I was going to Calling a function of a module from a string with the function's name in Python but whenever i call my class in my program it gives me this error:TypeError: unbound method bar() must be called with foo instance as first argument (got nothing instead)
Can someone help me
| [
"Here is a typical situation which produces the problem you describe. \nclass Foo(object):\n def bar(self,x):\n print(x)\n\nfoo=Foo()\n\nCalling gettatrr(Foo,'bar') returns the unbound method, Foo.bar.\ngetattr(Foo,'bar')(1)\n\nresults in \n\nTypeError: unbound method bar() must be called with Foo instanc... | [
9,
1
] | [] | [] | [
"python"
] | stackoverflow_0007191852_python.txt |
Q:
how to crawl html pages to create a total subjective site score
Thanks in advance for your help.
I have been exhaustively trying to find/write a utility that does the following:
Crawls through a specified site (sitename) looking for various strings (a, b, c, d, e) in all html pages on the site AND a specific name... | how to crawl html pages to create a total subjective site score | Thanks in advance for your help.
I have been exhaustively trying to find/write a utility that does the following:
Crawls through a specified site (sitename) looking for various strings (a, b, c, d, e) in all html pages on the site AND a specific named javascript file (javascriptfile.js)
If the javascript file is not f... | [
"I suggest python's urllib.\n\nFetching Web Pages\nFetching standard Web pages over HTTP is very easy with Python:\nimport urllib\nf = urllib.urlopen(\"http://www.python.org\") \ns = f.read() \nf.close() \n\n--this is from here\nThen use python's html parser\n",
"Crawls through a specified site (sitename) looking... | [
1,
1,
1,
0,
0
] | [] | [] | [
"php",
"python",
"shell",
"web_crawler"
] | stackoverflow_0007191853_php_python_shell_web_crawler.txt |
Q:
how to format a shell command line from a list of arguments in python
I have a list of arguments, e.g. ["hello", "bobbity bob", "bye"]. How would I format these so they would be passed appropriately to a shell?
Wrong:
>>> " ".join(args)
hello bobbity bob bye
Correct:
>>> magic(args)
hello "bobbity bob" bye
A:
Y... | how to format a shell command line from a list of arguments in python | I have a list of arguments, e.g. ["hello", "bobbity bob", "bye"]. How would I format these so they would be passed appropriately to a shell?
Wrong:
>>> " ".join(args)
hello bobbity bob bye
Correct:
>>> magic(args)
hello "bobbity bob" bye
| [
"You could use the undocumented but long-stable (at least since Oct 2004) subprocess.list2cmdline:\nIn [26]: import subprocess\nIn [34]: args=[\"hello\", \"bobbity bob\", \"bye\"]\n\nIn [36]: subprocess.list2cmdline(args)\nOut[36]: 'hello \"bobbity bob\" bye'\n\n",
"The easier way to solve your problem is to add ... | [
16,
1,
1,
0
] | [] | [] | [
"command_line",
"command_line_arguments",
"formatting",
"python",
"shell"
] | stackoverflow_0007192104_command_line_command_line_arguments_formatting_python_shell.txt |
Q:
Django-Python-Use python modules that aren't installed on the host server
I want to use a python module on my django website (matplotlib) that isn't installed on the host server. Is this possible? I found some information about virtualenv, but I don't know if this does what I want. Can someone help me find informa... | Django-Python-Use python modules that aren't installed on the host server | I want to use a python module on my django website (matplotlib) that isn't installed on the host server. Is this possible? I found some information about virtualenv, but I don't know if this does what I want. Can someone help me find information about this?
Thanks in advance
| [
"Virtualenv may or may not be an option on your host, depending on how it invokes your application. In either case, building matplotlib and placing the resulting package in the same place your application lives is probably adequate. You can add that path to sys.path before importing it the first time if the pytho... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007192099_django_python.txt |
Q:
Concatenation of tuples
Normal text:
I'm having some problems with coding on python 3.2.1. Actually I'm taking online lectures that are on python 2.5.
Here is the code:
x = 100
divisors = ()
for i in range(1,x):
if x%i == 0:
divisors = divisors + (i)
on running the program, following error appears: ... | Concatenation of tuples |
Normal text:
I'm having some problems with coding on python 3.2.1. Actually I'm taking online lectures that are on python 2.5.
Here is the code:
x = 100
divisors = ()
for i in range(1,x):
if x%i == 0:
divisors = divisors + (i)
on running the program, following error appears:
divisors = divisors + (i) ... | [
"(1) is not a tuple, its just a parenthesized expression. To make it a tuple, add a trailing comma, (1,)\n"
] | [
28
] | [
"Try to use this instead:\ndivisors.append(i)\n\nEdit: \ndivisors = []\n\nsince you can't append on tuples.\n"
] | [
-1
] | [
"python",
"python_3.x",
"tuples"
] | stackoverflow_0007192391_python_python_3.x_tuples.txt |
Q:
How to change the value of a reference contained inside a list?
In python how can i change the value of references contained inside a list ?
For example in the following code
x = 'stack'
y = 'exchange'
l = [x,y]
l[1] = 'overflow'
The last line would actually replace y with 'overflow' but what I want to do is ch... | How to change the value of a reference contained inside a list? | In python how can i change the value of references contained inside a list ?
For example in the following code
x = 'stack'
y = 'exchange'
l = [x,y]
l[1] = 'overflow'
The last line would actually replace y with 'overflow' but what I want to do is change the reference contained at l[1] to 'overflow' how can I achieve ... | [
"You do rebind reference at l[1] to 'overflow' with l[1] = 'overflow'. If you want to actually modify the string object, you can't. Strings are immutable.\n",
"\"change the value of references\" is awkward phrasing and there are two separate things that I can imagine that you mean:\n1) cause the element of the li... | [
5,
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007189111_python.txt |
Q:
Removing a PYGTK treeview row programmatically
I'm trying to find out how you remove a row in a pygtk treeview without selecting it. I can remove rows by selecting the row first but the application I'm working on needs to be able to remove rows automatically (without the user selecting the row). As simple a featur... | Removing a PYGTK treeview row programmatically | I'm trying to find out how you remove a row in a pygtk treeview without selecting it. I can remove rows by selecting the row first but the application I'm working on needs to be able to remove rows automatically (without the user selecting the row). As simple a feature as this seems to be I can't for the life of me fig... | [
"You can change the model underlying, and access any line by one of its three reference methods. Say iter is the row number :\n model = gtk.TreeView.get_model()\n model.remove(iter) \n\nshould do the trick.\nBut you will be better to work immediately on the listStore without passing by the treeview, it will be easi... | [
3
] | [] | [] | [
"glade",
"gtk",
"pygtk",
"python"
] | stackoverflow_0007192662_glade_gtk_pygtk_python.txt |
Q:
Segfault with pymssql when cannot connect to server on multiple threads
We've come across this when our MS SQL server became unreachable. This caused a bug in our code that brought our program to a screeching halt and of course pitchforks and torches of users to our door. We've been able to boil down our problem t... | Segfault with pymssql when cannot connect to server on multiple threads | We've come across this when our MS SQL server became unreachable. This caused a bug in our code that brought our program to a screeching halt and of course pitchforks and torches of users to our door. We've been able to boil down our problem to this: If a user, Bob, attempts to connect to the downed database he will of... | [
"We went and asked the question over at pymssql's user group as well to cover all our bases. According to one of the developers pymssql is not thread safe in the current stable release. It sounds like it might be in the development 1.9 release or in the next major 2.0 release. We will probably switch to a different... | [
2
] | [] | [] | [
"pymssql",
"python"
] | stackoverflow_0007182425_pymssql_python.txt |
Q:
Python: How does "IN" (for lists) works?
I have this code
list = ['a','b','c']
if 'b' in list:
return "found it"
return "not found"
Now, how does this work? Does it traverse the whole list comparing the element? Does it use some kind of hash function?
Also, is it the same for this code?
list.index('b')
A:
i... | Python: How does "IN" (for lists) works? | I have this code
list = ['a','b','c']
if 'b' in list:
return "found it"
return "not found"
Now, how does this work? Does it traverse the whole list comparing the element? Does it use some kind of hash function?
Also, is it the same for this code?
list.index('b')
| [
"in uses the method __contains__. Each container type implements it differently. For a list, it uses linear search. For a dict, it uses a hash lookup.\n",
"Python Wiki states that val in list has O(n) average time complexity. This implies linear search. I expect list.index(val) to be the same.\nAfter all, list is... | [
16,
7,
2,
1
] | [
"Here is the disassembly:\n>>> from dis import dis\n>>> def foo():\n... a = ['a', 'b', 'c']\n... if 'b' in a:\n... print \"Found it!\"\n... \n>>> dis(foo)\n 2 0 LOAD_CONST 1 ('a')\n 3 LOAD_CONST 2 ('b')\n 6 LOAD_CONST ... | [
-1
] | [
"data_structures",
"list",
"python"
] | stackoverflow_0007192900_data_structures_list_python.txt |
Q:
using CSV module with readline()
Yesterday I posted the below link:
Python CSV Module read and write simultaneously
Several people suggested that I "If file b is not extremely large I would suggest using readlines() to get a list of all lines and then iterate over the list and change lines as needed."
I want to st... | using CSV module with readline() | Yesterday I posted the below link:
Python CSV Module read and write simultaneously
Several people suggested that I "If file b is not extremely large I would suggest using readlines() to get a list of all lines and then iterate over the list and change lines as needed."
I want to still be able to use the functionality o... | [
"Here is a sample that reads a CSV file using a DictReader and uses a DictWriter to write to stdout. The file has a column named PERCENT_CORRECT_FLAG, and this modifies the CSV file to set this field to 0.\n#!/usr/bin/env python\nfrom __future__ import with_statement\nfrom __future__ import print_function\n\nfrom c... | [
0
] | [] | [] | [
"csv",
"python",
"readline"
] | stackoverflow_0007192826_csv_python_readline.txt |
Q:
TypeError in Django
Have this error while creating tutorial:
http://img718.imageshack.us/img718/2194/unled2bh.jpg
Have no freakin idea what's wrong. It's displays when i added this modifications:
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_proces... | TypeError in Django | Have this error while creating tutorial:
http://img718.imageshack.us/img718/2194/unled2bh.jpg
Have no freakin idea what's wrong. It's displays when i added this modifications:
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.c... | [
"You need to use the full path to your views in urls.py:\nurl(r'^koszyk/$', 'app_name.views.koszyk', name=\"sklep_koszyk\"),\nurl(r'^koszyk/dodaj/(\\d+)/$', 'app_name.views.koszyk_dodaj', name=\"sklep_koszyk_dodaj\"),\n\n"
] | [
3
] | [] | [] | [
"django",
"python",
"typeerror"
] | stackoverflow_0007193607_django_python_typeerror.txt |
Q:
Get text outside one tag and inside another
I am parsing a web page with BeautifulSoup, and it has some elements like the following:
<td><font size="2" color="#00009c"><b>Consultant Registration Number :</b></font> 16043646</td>
The structure always seems to be a <td> with the first part surrounded by <font><b>... | Get text outside one tag and inside another | I am parsing a web page with BeautifulSoup, and it has some elements like the following:
<td><font size="2" color="#00009c"><b>Consultant Registration Number :</b></font> 16043646</td>
The structure always seems to be a <td> with the first part surrounded by <font><b>, and the text after the </font> tag can be empty... | [
">>> from BeautifulSoup import BeautifulSoup\n>>> text1 = '<td><font size=\"2\" color=\"#00009c\"><b>Consultant Registration Number :</b></font> 16043646</td>'\n>>> text2 = '<td><font size=\"2\" color=\"#00009c\"><b>Consultant Registration Number :</b></font></td>'\n>>> BeautifulSoup(text1).td.font.nextSibling\n... | [
5
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0007193664_beautifulsoup_html_parsing_python.txt |
Q:
Transcode videos with queue
I want to transcode videos that are uploaded to a directory in a server with a queue.
How can I order the server to encode a video using FFmpeg with Python? And how a queue system can be added above that?
A:
Did you look at Celery distributed task queueing system? I use it in the quit... | Transcode videos with queue | I want to transcode videos that are uploaded to a directory in a server with a queue.
How can I order the server to encode a video using FFmpeg with Python? And how a queue system can be added above that?
| [
"Did you look at Celery distributed task queueing system? I use it in the quitd same project as yours.\nSultan\n"
] | [
0
] | [] | [] | [
"ffmpeg",
"python"
] | stackoverflow_0006850080_ffmpeg_python.txt |
Q:
Dynamically creating classes in python and __repr__
This is a fairly straightforward question hopefully you all can enlighten me. In the example below how do I define __repr__ to be dynamically set to self.name?
Thanks all!
import re
inputlist = 'Project="Sparcy" Desc=""\nProject="Libs" Desc=""\nProject="Darwin"... | Dynamically creating classes in python and __repr__ | This is a fairly straightforward question hopefully you all can enlighten me. In the example below how do I define __repr__ to be dynamically set to self.name?
Thanks all!
import re
inputlist = 'Project="Sparcy" Desc=""\nProject="Libs" Desc=""\nProject="Darwin" Desc=""\nProject="Aaple" Desc="The big project"'
regex ... | [
"I'm guessing that you want \nprint results\n\nto return\n[\"Sparcy\", \"Libs\", \"Darwin\", \"Aaple\"]\n\n\nPrinting a list shows the repr of its elements.\nrepr(elt) is determined by type(elt).__repr__.\nSince in this case the elements are classes, you need to set the\n__repr__ for the type of the class.\n\n\nimp... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0007193858_python.txt |
Q:
Python dir() not displaying all modules in a package
I'm using python 2.6 and I'm seeing somewhat weird behavior with the dir() function. I'm trying to import all the modules from a directory/package for a unittest but when I do a dir() on on the folder, I don't get all the modules in that directory.
Sample direc... | Python dir() not displaying all modules in a package | I'm using python 2.6 and I'm seeing somewhat weird behavior with the dir() function. I'm trying to import all the modules from a directory/package for a unittest but when I do a dir() on on the folder, I don't get all the modules in that directory.
Sample directory structure:
|-mod_dir\
|---__init__.py
|---modA.py
|--... | [
"I believe it does matter that the __init__.py file is empty.\nTry this in the __init__.py:\nimport modA\nimport modB\nimport modC\n\nFrom the python docs, dir should not be used for this (see the Note at the bottom of the dir section). It's not rigorous enough, and mainly used in the interactive prompt.\n"
] | [
3
] | [] | [] | [
"dir",
"module",
"python",
"unit_testing"
] | stackoverflow_0007193850_dir_module_python_unit_testing.txt |
Q:
python xinetd client not receiving data
I'm trying to use xinetd to remotely run a command (traccejob). When I connect through telnet, everything works fine. Unfortuantely, the client that I've written doesn't seem to receive the data from the server. The code looks like:
server:
import sys
import commands
def... | python xinetd client not receiving data | I'm trying to use xinetd to remotely run a command (traccejob). When I connect through telnet, everything works fine. Unfortuantely, the client that I've written doesn't seem to receive the data from the server. The code looks like:
server:
import sys
import commands
def main():
tjinput = sys.stdin.readline... | [
"You have a deadlock situation: The client sends an incomplete line and waits for the server to send something, the server waits for line completion or EOF before it sends a reply.\nSo you have now 2 ways to proceed now:\n\nAppend a \\n to the string being sent.\n\"Half-close\" the socket on client side with sock.s... | [
1
] | [] | [] | [
"python",
"xinetd"
] | stackoverflow_0007193738_python_xinetd.txt |
Q:
Django: CSRF verification failed
Don't know how to resolve this problem :/.
views.py:
# coding: utf-8
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic.simple import direct_to_template
from django.core.mail import send_mail
from django.template impo... | Django: CSRF verification failed | Don't know how to resolve this problem :/.
views.py:
# coding: utf-8
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic.simple import direct_to_template
from django.core.mail import send_mail
from django.template import Context, loader
from django.conf im... | [
"The problem is probably in your template sklep/koszyk.html. Inside of the form on the html page you need to include {% csrf_token %}. The documentation has more information about this feature.\n",
"Also, to add to what murgatroid99 said, you need to include the csrf(request) when you are calling that page. I usu... | [
1,
0,
0
] | [] | [] | [
"csrf",
"django",
"python"
] | stackoverflow_0007194072_csrf_django_python.txt |
Q:
legend inside a loop in a subplot in Matplotlib: what is wrong with my code?
I have a plot with 6 different subplots. I iterate through a loop to make each of the subplots and I want to add the legend for each subplot at this time too. So here is an easy example:
matrixSol = scipy.random.random((6,6,4))
print matr... | legend inside a loop in a subplot in Matplotlib: what is wrong with my code? | I have a plot with 6 different subplots. I iterate through a loop to make each of the subplots and I want to add the legend for each subplot at this time too. So here is an easy example:
matrixSol = scipy.random.random((6,6,4))
print matrixSol
mylegend = ['10 Million','15 Million','1 Million','20 Million','25 Million',... | [
"Use:\nplt.plot(ys, zs,'o', c=color[k], label=mylegend[k], markersize=10)\nplt.legend(loc=2)\n\n\nalternatively, the solution already indicated by Chris Redford also works: \nplt.legend((mylegend[k],), loc=2)\n\n",
"I'm pretty sure it's treating the code (mylegend[k]) in the line:\nplt.legend((mylegend[k]),loc=2)... | [
5,
2
] | [] | [] | [
"legend",
"matplotlib",
"python"
] | stackoverflow_0007194423_legend_matplotlib_python.txt |
Q:
How can I create a pyserial web service?
I have written a web application that interacts with a serial device on /dev/ttyS02.
The problem is my current messaging and queuing solution. Please read below.
Heres the communication bridge between the application and pyserial:
My web application inserts a request reco... | How can I create a pyserial web service? | I have written a web application that interacts with a serial device on /dev/ttyS02.
The problem is my current messaging and queuing solution. Please read below.
Heres the communication bridge between the application and pyserial:
My web application inserts a request record via PHP into a d_requests table in MySQL.
... | [
"\nIs there a better way to improve my current messaging and queuing solution?\n\nYou bet! They're called message queues, and they are awesome.\nMy favorite is Gearman, written by the the same team that brought us memcached. It has PHP and Python bindings. It's not actually a message queue so much as an RPC serv... | [
1,
0
] | [] | [] | [
"linux",
"php",
"pyserial",
"python",
"ubuntu"
] | stackoverflow_0005266347_linux_php_pyserial_python_ubuntu.txt |
Q:
Descriptor for lazy loading
I wanted to implement lazy loading of variables, but I seem to misunderstand descriptors a bit. I'd like to have object variables, which on first access will call the obj.load() function which will initialize the variables with their real value. I wrote
class ToLoad(object):
def __i... | Descriptor for lazy loading | I wanted to implement lazy loading of variables, but I seem to misunderstand descriptors a bit. I'd like to have object variables, which on first access will call the obj.load() function which will initialize the variables with their real value. I wrote
class ToLoad(object):
def __init__(self, loader_name="load")
... | [
"Well, there are two problems here:\n\nYou return None from __get__, whereas it should be the value you want x to represent.\nYou do x = y, but your descriptor doesn't implement __set__.\n\nSo, instead of setting a \"is loaded\" flag, you should rather create an attribute with the actual value, and check for that. ... | [
1,
0
] | [] | [] | [
"descriptor",
"lazy_loading",
"python"
] | stackoverflow_0007194426_descriptor_lazy_loading_python.txt |
Q:
Python - Unicode to something split-able
I need to break a date value down to it's elements ( 8/23/2011 ) which should be a piece of cake with
variable.split("/")
but it tells me that
'unicode' object has no attribute 'Split'
I tried encoding it as a different format:
date.encode("utf-8")
then it tells me... | Python - Unicode to something split-able | I need to break a date value down to it's elements ( 8/23/2011 ) which should be a piece of cake with
variable.split("/")
but it tells me that
'unicode' object has no attribute 'Split'
I tried encoding it as a different format:
date.encode("utf-8")
then it tells me that
'str' object has no attribute 'Split'
... | [
"Python is case-sensitive; you want split, not Split.\n>>> x = u\"8/23/2011\"\n>>> x.Split('/')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'unicode' object has no attribute 'Split'\n>>> x.split('/')\n[u'8', u'23', u'2011']\n\n",
"Python is case-sensitive. The met... | [
7,
1,
0
] | [] | [] | [
"python",
"split",
"unicode"
] | stackoverflow_0007194906_python_split_unicode.txt |
Q:
Debugging IndexError: Trivial sum generation problem
I can't wrap my head around what's causing the index error here, not exactly looking for a quick fix. Let me know however if my code repulses you/is incredibly ineffectual. The goal is to generate palindromes produced by the product of two four digit numbers.
Co... | Debugging IndexError: Trivial sum generation problem | I can't wrap my head around what's causing the index error here, not exactly looking for a quick fix. Let me know however if my code repulses you/is incredibly ineffectual. The goal is to generate palindromes produced by the product of two four digit numbers.
Code:
for x in range(10000):
for y in range(10000):
... | [
"You iterate over values 0...lengthprod , but the legal subscripts for product are 0...lengthprod-1.\nThe last index is out of bounds. It references an element that is one byte beyond the end of the string.\n",
"Converting a number to a string is generally a slow operation, since there are many possibilities in ... | [
3,
3,
2,
1
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0007184796_debugging_python.txt |
Q:
Read in file - change contents - write out to same file
I have to read in a file, change a sections of the text here and there, and then write out to the same file.
Currently I do:
f = open(file)
file_str = f.read() # read it in as a string, Not line by line
f.close()
#
# do_actions_on_file_str
#
f = open(file, 'w... | Read in file - change contents - write out to same file | I have to read in a file, change a sections of the text here and there, and then write out to the same file.
Currently I do:
f = open(file)
file_str = f.read() # read it in as a string, Not line by line
f.close()
#
# do_actions_on_file_str
#
f = open(file, 'w') # to clear the file
f.write(file_str)
f.close()
But I wou... | [
"That looks straightforward, and clear already. Any suggestion depends on how big the files are. If not really huge that looks fine. If really large, you could process in chunks. \nBut you could use a context manager, to avoid the explicit closes.\nwith open(filename) as f:\n file_str = f.read()\n\n# do stuff wi... | [
28,
5
] | [] | [] | [
"python"
] | stackoverflow_0007194665_python.txt |
Q:
Finding sub-directories on a web server
We can easily find subdirectories on our local disc using os.walk() but what if those directories are not local and are on a web server?
For example, I have a website called http://www.geoglobaldomination.org. There are a couple subdirectories that are NOT referenced on the... | Finding sub-directories on a web server | We can easily find subdirectories on our local disc using os.walk() but what if those directories are not local and are on a web server?
For example, I have a website called http://www.geoglobaldomination.org. There are a couple subdirectories that are NOT referenced on the home page. eg.http://www.geoglobaldomination... | [
"Well, in the most general sense you can't. \nThere are some websites that may give you an index of subdirectories when you end your uri with a '/', or a \"index.html\", but they don't have to. A website author can basically return anything they want when you visit their site (with a browser or a program). They c... | [
2,
2
] | [] | [] | [
"python",
"web_crawler"
] | stackoverflow_0007194958_python_web_crawler.txt |
Q:
Django Custom Manager
I'm looking at some code and I'm curious whether this is good practice.
class ToDoManager(models.Manager):
def scheduled(self):
"""
Returns QuerySet of all things to be done.
"""
return self.filter(...)
class ImpStuff(models.Mode... | Django Custom Manager | I'm looking at some code and I'm curious whether this is good practice.
class ToDoManager(models.Manager):
def scheduled(self):
"""
Returns QuerySet of all things to be done.
"""
return self.filter(...)
class ImpStuff(models.Model):
....model de... | [
"Using model managers for wrapping complex ORM queries is something very DRY and recommended. You can add parameters to those methods and save yourself a lot of code:\nclass ToDoManager(models.Manager):\n def scheduled(self, start_date, end_date):\n \"\"\"\n Returns tasks to be done within two dates.... | [
3,
1
] | [] | [] | [
"django",
"django_custom_manager",
"models",
"python"
] | stackoverflow_0007193478_django_django_custom_manager_models_python.txt |
Q:
python: forcing relative imports to search from script file
This is my directory structure:
scripts/
bpydata/
bpymodules/
myCustomScripts/
lib/
__init__.py
customLib.py
plugin/
__init__.py
myParser.py
__init__.py
runner.py
...
my_import_script.py
...... | python: forcing relative imports to search from script file | This is my directory structure:
scripts/
bpydata/
bpymodules/
myCustomScripts/
lib/
__init__.py
customLib.py
plugin/
__init__.py
myParser.py
__init__.py
runner.py
...
my_import_script.py
...
I start with my_import_script, which will import the myCustomSc... | [
"To import from a parent package use ... If I'm not misunderstanding you, this should work:\nfrom ..lib import customLib\n\nSee http://docs.python.org/tutorial/modules.html.\n"
] | [
2
] | [] | [] | [
"import",
"python"
] | stackoverflow_0007194701_import_python.txt |
Q:
URL pattern matching in django
I am getting a Page Not Found when I try to access http://127.0.0.7:8000/edit-paragraph/6/edit/, with the following error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
^login/$
^login/home/
^logout/$
^edit-section/(?P<s_id>\d+)/edi... | URL pattern matching in django | I am getting a Page Not Found when I try to access http://127.0.0.7:8000/edit-paragraph/6/edit/, with the following error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
^login/$
^login/home/
^logout/$
^edit-section/(?P<s_id>\d+)/edit/
^edit-section/(?P<s_id>\d+)
^edit... | [
"A couple of things: \n\nIf you're being redirected, make sure you're actually being redirected and it's not simply that your browser is being too helpful with it's URL autocomplete function. Your web developer tools (firebug, web inspector, etc.) will log the redirect if it's happening.\nMany browsers have odd be... | [
0
] | [] | [] | [
"django",
"python",
"urlconf"
] | stackoverflow_0007195340_django_python_urlconf.txt |
Q:
Adding column in SQLite3, then filling it
I'm using SQLite 3.6, and connecting to it using Python 2.7 on Fedora 14.
I am attempting to add a column to a table using ALTER TABLE, then immediately afterwards UPDATE the table with data for the newly created column. Through python, I get nothing but NULLs in the data... | Adding column in SQLite3, then filling it | I'm using SQLite 3.6, and connecting to it using Python 2.7 on Fedora 14.
I am attempting to add a column to a table using ALTER TABLE, then immediately afterwards UPDATE the table with data for the newly created column. Through python, I get nothing but NULLs in the database's new column. If I run the queries throug... | [
"The issue was in the main function, which exited before the connection's commit() call could be made due to an error in the main function.\n"
] | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0007163441_python_sqlite.txt |
Q:
pyodbc returns SQL Server DATE fields as strings
I'm using pyodbc to query a SQL Server 2008 database table with columns of DATE type.
The resulting rows of data contain date strings rather than python datetime.date or datetime.datetime instances.
This only appears to be an issue for columns of type DATE; columns... | pyodbc returns SQL Server DATE fields as strings | I'm using pyodbc to query a SQL Server 2008 database table with columns of DATE type.
The resulting rows of data contain date strings rather than python datetime.date or datetime.datetime instances.
This only appears to be an issue for columns of type DATE; columns of type DATETIME are handled correctly and return a d... | [
"Use the SQL Server native client. e.g. Put Driver={SQL Server Native Client 10.0} in your connection string,instead of \nDRIVER={SQL Server}.\nReproduced your scenario with date being returned as string using SQL Server ODBC driver. When using a 2008+ compatible version of the SQL Server native client, the date ty... | [
8
] | [] | [] | [
"database",
"pyodbc",
"python",
"sql_server"
] | stackoverflow_0007172540_database_pyodbc_python_sql_server.txt |
Q:
Loop in Django tempates
I have two variables, name = ["Fedora", "Ubuntu"] and state = {"Fedora": "up", "Ubuntu": "down"}.
How do I display this data in a loop?
{% for s in state %}
{% for n in state %}
{{ n }} {{ s }}
{% endfor %}
{% endfor %}
Variable "n" is displayed four times instead of two times.... | Loop in Django tempates | I have two variables, name = ["Fedora", "Ubuntu"] and state = {"Fedora": "up", "Ubuntu": "down"}.
How do I display this data in a loop?
{% for s in state %}
{% for n in state %}
{{ n }} {{ s }}
{% endfor %}
{% endfor %}
Variable "n" is displayed four times instead of two times.
| [
"Try this:\n{% for n,s in state.items %}\n{{ n }}: {{ s }}<br>\n{% endfor %}\n\n"
] | [
4
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0007196427_django_django_templates_python.txt |
Q:
referring to self from within self in python
I am not even sure whether the title of my question is correct, but I will fire away anyway. But I would like to apologise, if it turns out that the title is not entirely correct. Also, I have to admit that I am not a guru, as far as python is concerned, so if my questi... | referring to self from within self in python | I am not even sure whether the title of my question is correct, but I will fire away anyway. But I would like to apologise, if it turns out that the title is not entirely correct. Also, I have to admit that I am not a guru, as far as python is concerned, so if my question is stupid, just have a good laugh!
I have defin... | [
"Change this part:\ndef self.do_something( self ):\n print 'I have done something'\n\nto just:\ndef do_something( self ):\n print 'I have done something'\n\nWhen you call a method, you use self.some_method(). When you define it, you just define it with the parameter self, which will be implicitly passed in.\... | [
3,
2,
0
] | [] | [] | [
"interactive",
"interpreter",
"parsing",
"python",
"self"
] | stackoverflow_0007196495_interactive_interpreter_parsing_python_self.txt |
Q:
Creating an instance of a C++ class and calling methods on it in Python
I am trying to use a C++ library in my python app. I can load the dll in python but could not find any solution on how to create an instance of a class that is inside that c++ dll and invoke methods on that onject.
Following is what I did and ... | Creating an instance of a C++ class and calling methods on it in Python | I am trying to use a C++ library in my python app. I can load the dll in python but could not find any solution on how to create an instance of a class that is inside that c++ dll and invoke methods on that onject.
Following is what I did and want
C++ code inside My.dll
class MyClass
{
public:
MyMethod(int param)... | [
"While it might be possible with ctypes, it certainly won't be as straightforward as that. It'll be much easier to use e.g. Boost.Python or Cython to create a proper CPython extension that exposes that class as a Python type.\n",
"Loading a C++ dll with Ctypes is dangerous and has some strong limitations. The exp... | [
4,
2
] | [] | [] | [
"c++",
"dll",
"instantiation",
"python"
] | stackoverflow_0007196118_c++_dll_instantiation_python.txt |
Q:
Erase previously drawn content from a pyplot drawing
Using pyplot, I've created a figure and plotted a number of randomly scattered (x,y) points. I then want to connect some subset of these points with line segments. After the user presses a key, my program needs to then erase the previously drawn set of line segm... | Erase previously drawn content from a pyplot drawing | Using pyplot, I've created a figure and plotted a number of randomly scattered (x,y) points. I then want to connect some subset of these points with line segments. After the user presses a key, my program needs to then erase the previously drawn set of line segments (leaving the original points in place) and then draw ... | [
"Scipy has a tutorial for deleting a line from an axes. I use this in the following example, which I think emulates what you are trying to do:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(10)\nnp.random.seed(101)\ny = np.random.rand(10)\n\nsmall = [i for i in range(len(x)) if y[i] < .5 ]\nb... | [
3,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007196461_matplotlib_python.txt |
Q:
Matplotlib with dual scale mouse over
I try to plot some curves with matplotlib using the default gui component and have some trouble to select which of the two y-axes that the mouse over functionality should select. The default case seems to be that ax2 gets selected but I would like to use ax1 instead. Is this p... | Matplotlib with dual scale mouse over | I try to plot some curves with matplotlib using the default gui component and have some trouble to select which of the two y-axes that the mouse over functionality should select. The default case seems to be that ax2 gets selected but I would like to use ax1 instead. Is this possible to fix in some easy way?
This is t... | [
"Add the following after calling twinx\nax3 = ax1.figure.add_axes(ax1.get_position(True), sharex=ax1, sharey=ax1,\n frameon=False)\nax3.xaxis.set_visible(False)\nax3.yaxis.set_visible(False)\n\nYou will also need to change plt.grid(True) to ax1.grid(True)\n"
] | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0002127183_matplotlib_python.txt |
Q:
Django RSS feed 500 error
I'm working on setting up an RSS feed for my Django-based blog. I'm getting 500 errors when I try and access the URL:
$ curl -I http://172.16.91.140:8000/blogg/feeds/latest/
HTTP/1.0 500 INTERNAL SERVER ERROR
WSGIServer is reporting nothing more than
[25/Aug/2011 20:21:41] "HEAD /blogg/... | Django RSS feed 500 error | I'm working on setting up an RSS feed for my Django-based blog. I'm getting 500 errors when I try and access the URL:
$ curl -I http://172.16.91.140:8000/blogg/feeds/latest/
HTTP/1.0 500 INTERNAL SERVER ERROR
WSGIServer is reporting nothing more than
[25/Aug/2011 20:21:41] "HEAD /blogg/feeds/latest/ HTTP/1.1" 500 0
... | [
"I found the issue. Calling\nreturn item.subject\n\nMeant there was an invalid property, I changed it to\nreturn item.blog_subject\n\nSchool boy error. Sorry I hadn't included my model as well. Sometimes writing out a problem will cause me to notice something I've overlooked. Happy coding everyone!\n"
] | [
0
] | [] | [] | [
"django",
"django_rss",
"python",
"rss"
] | stackoverflow_0007196059_django_django_rss_python_rss.txt |
Q:
Regex to replace hyphen in middle of a word
How can I replace a hyphens in the middle of a word using python3 and re.sub()?
"-ice-cream- - hang-out" -> "-ice cream- - hang out"
Thanks,
Barry
EDIT: I tried self.lines = re.sub(r'\w(-)\w', " ", self.lines) but wasn't sure how to proceed. I like the /b way of doing it... | Regex to replace hyphen in middle of a word | How can I replace a hyphens in the middle of a word using python3 and re.sub()?
"-ice-cream- - hang-out" -> "-ice cream- - hang out"
Thanks,
Barry
EDIT: I tried self.lines = re.sub(r'\w(-)\w', " ", self.lines) but wasn't sure how to proceed. I like the /b way of doing it.
| [
"re.sub(pattern, repl, string[, count, flags]) see docs.python.org\nYour pattern would be r'\\b-\\b'\nSee the pattern here on Regexr\nAnd replace this with a space (' ')\nThe r before the regex string deifnes a raw string, that means you don't need double escaping.\n\\b is a word boundary, that means it will match... | [
5,
1
] | [] | [] | [
"python",
"python_3.x",
"regex"
] | stackoverflow_0007197029_python_python_3.x_regex.txt |
Q:
python imaplib gpg file contents into message
Lo,
Having some issues with imaplib. I'm trying to get the contents of a gpg file into the body of an email.
The encrypted file looks something like this:
ÕþëÂüÿΩfXаÕ庼H»[ßÖq«Ì5ßö
my code looks something like this:
gpgFH = open(gpgFile, 'rb')
gpgStr = gpgFH.read()... | python imaplib gpg file contents into message | Lo,
Having some issues with imaplib. I'm trying to get the contents of a gpg file into the body of an email.
The encrypted file looks something like this:
ÕþëÂüÿΩfXаÕ庼H»[ßÖq«Ì5ßö
my code looks something like this:
gpgFH = open(gpgFile, 'rb')
gpgStr = gpgFH.read()
newEmail = email.message.Message()
newEmail['Subje... | [
"Try base64-encoding the file's data. The above code is putting binary data into the email, which isn't going to work. \nimport base64\n\ngpgFH = open(gpgFile, 'rb')\ngpgStr = gpgFH.read()\ngpgEncoded = base64.b64encode(gpgStr)\n...\n\nAlternatively, you might want to add the GPG data as an attachment instead of th... | [
2
] | [] | [] | [
"encryption",
"imap",
"python"
] | stackoverflow_0007197199_encryption_imap_python.txt |
Q:
How to implement division with round-towards-infinity in Python
I want 3/2 to equal 2 not 1.5
I know there's a mathematical term for that operation(not called rounding up), but I can't recall it right now.
Anyway, how do i do that without having to do two functions?
ex of what I do NOT want:
answer = 3/2 then mat... | How to implement division with round-towards-infinity in Python | I want 3/2 to equal 2 not 1.5
I know there's a mathematical term for that operation(not called rounding up), but I can't recall it right now.
Anyway, how do i do that without having to do two functions?
ex of what I do NOT want:
answer = 3/2 then math.ceil(answer)=2 (why does math.ceil(3/2)=1?)
ex of what I DO want... | [
"To give a short answer...\nPython only offers native operators for two types of division: \"true\" division, and \"round down\" division. So what you want isn't available as a single function. However, it is possible to easily implement a number of different types of division-with-rounding using some short express... | [
16,
4,
4,
2,
1,
1,
1,
0
] | [] | [] | [
"division",
"floating_point",
"math",
"python",
"rounding"
] | stackoverflow_0007181757_division_floating_point_math_python_rounding.txt |
Q:
how to filter model with a list containing the field and the value?
see what I have:
> bar = [(u'code__regex', u'^[^J]'), (u'active__exact', u'0'), (u'type__id__exact', u'E01')]
There are the fields/values that I want to use to filter the model Foo.
> #want to have this equivalent:
> Foo.objects.filter(bar)
Than... | how to filter model with a list containing the field and the value? | see what I have:
> bar = [(u'code__regex', u'^[^J]'), (u'active__exact', u'0'), (u'type__id__exact', u'E01')]
There are the fields/values that I want to use to filter the model Foo.
> #want to have this equivalent:
> Foo.objects.filter(bar)
Thanks!
| [
"Foo.objects.filter(**dict(bar))\n\nThis isn't a django issue, this is a python issue. You want to pass the keyword pairs as keyword arguments (kwargs) to the filter. Your bar is perfect as a kwarg set, so the dict(bar) converts it to the dictionary, and the ** prefix informs the python parser that the dictionary... | [
8,
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007197929_django_python.txt |
Q:
Python decorators compared to CLOS "around" method
I'm reaching back to my CLOS (Common Lisp Object System) days for this abstract question.
I'm augmenting the question to clarify:
It appears to me that a Python decorator is sort of like an "around" method in CLOS.
From what I remember, an "around" method in CL... | Python decorators compared to CLOS "around" method | I'm reaching back to my CLOS (Common Lisp Object System) days for this abstract question.
I'm augmenting the question to clarify:
It appears to me that a Python decorator is sort of like an "around" method in CLOS.
From what I remember, an "around" method in CLOS is a method/function that wraps around the primary me... | [
"Here's a quick and dirty implementation slightly better implementation (now with the around method called hopefully in the right places), using decorators\ndef hints(before=None, after=None, around=None):\n \"\"\"A decorator that implements function hints to be run before, after or\n around another function,... | [
3,
2,
2,
0
] | [] | [] | [
"decorator",
"lisp",
"oop",
"python"
] | stackoverflow_0003672243_decorator_lisp_oop_python.txt |
Q:
How to solve Python Sockets/SocketServer Connection [Errno 10048] & [Errno 10049]?
I'm trying to make an online FPS game and so far it works on my local network. What I'm trying to do is make it work globally
I've tried making other Python projects work globally in the past but so far I haven't been able to get it... | How to solve Python Sockets/SocketServer Connection [Errno 10048] & [Errno 10049]? | I'm trying to make an online FPS game and so far it works on my local network. What I'm trying to do is make it work globally
I've tried making other Python projects work globally in the past but so far I haven't been able to get it to work. I get my IP from ipchicken or whatever and put it as the HOST for the server, ... | [
"First off, port 80 is typically http traffic. Anything under port 5000 is priviledged which means you really don't want to assign your server to this port unless you absolutely know what you are doing... Following is a simple way to set up a server socket to accept listen...\nimport socket\nhost = None #will det... | [
2
] | [] | [] | [
"connect",
"ip",
"ip_address",
"python",
"sockets"
] | stackoverflow_0007162869_connect_ip_ip_address_python_sockets.txt |
Q:
How do I put string at the end of every line?
I am wondering how could I add " Hello " to the end of every line?
Example:
Super
Cool
Fun
Output:
Super Hello
Cool Hello
Fun Hello
A:
lines = "Foo\nBar\nBaz"
for line in lines.splitlines():
print "%s Hello" % line
A:
You could just use the string function r... | How do I put string at the end of every line? | I am wondering how could I add " Hello " to the end of every line?
Example:
Super
Cool
Fun
Output:
Super Hello
Cool Hello
Fun Hello
| [
"lines = \"Foo\\nBar\\nBaz\"\n\nfor line in lines.splitlines():\n print \"%s Hello\" % line\n\n",
"You could just use the string function replace. It would look like:\nIn [3]: a = 'Super\\n Cool\\n Fun\\n' \n\nIn [4]: a.replace('\\n', ' Hello \\n')\nOut[4]: 'Super Hello \\n Cool Hello \\n Fun Hello \\n'\n\n",... | [
2,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007198125_python_string.txt |
Q:
Embed python code in C++ (Windows + minGW + Python 2.7.2 + Eclipse)
I'm trying to embed python code in C++ (Windows 7 + minGW + Python 2.7.2 + Eclipse Indigo with CDT and PyDev).
So, this is the simple code:
#include <Python.h> //Python.h
#include <iostream> //iostream
using namespace std;
int main(int argc, char ... | Embed python code in C++ (Windows + minGW + Python 2.7.2 + Eclipse) | I'm trying to embed python code in C++ (Windows 7 + minGW + Python 2.7.2 + Eclipse Indigo with CDT and PyDev).
So, this is the simple code:
#include <Python.h> //Python.h
#include <iostream> //iostream
using namespace std;
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import ... | [
"That is a linker error, not a compiler error. You need to link to the python. As you can see, with the \"CrossGCC\" toolchain you are almost there:\n-lC:/Python27/libs/libpython27.a\n\nYou need to change this to\n-LC:/Python27/libs -lpython\n\n"
] | [
2
] | [] | [] | [
"c++",
"eclipse",
"embed",
"mingw",
"python"
] | stackoverflow_0007198537_c++_eclipse_embed_mingw_python.txt |
Q:
set_data and autoscale_view matplotlib
I have multiple lines to be drawn on the same axes, and each of them are dynamically updated (I use set_data), The issue being that i am not aware of the x and y limits of each of the lines. And axes.autoscale_view(True,True,True) / axes.set_autoscale_on(True) are not doing w... | set_data and autoscale_view matplotlib | I have multiple lines to be drawn on the same axes, and each of them are dynamically updated (I use set_data), The issue being that i am not aware of the x and y limits of each of the lines. And axes.autoscale_view(True,True,True) / axes.set_autoscale_on(True) are not doing what they are supposed to. How do i auto scal... | [
"From the matplotlib docs for autoscale_view:\n\nThe data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. In that case, use matplotlib.axes.Axes.relim() prior to calling autoscale_view.\n\nSo, you'll need to add two lines before your plt.draw() ... | [
51
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007187504_matplotlib_python.txt |
Q:
Including and referencing 3rd party libraries in a GAE project
For my gae python project, I'd like to import an external library named 'vobject'. What's the correct way to import it in my .py files?
The project's readme says that in order to install it, you need to run
python setup.py install
Additionally, vo... | Including and referencing 3rd party libraries in a GAE project | For my gae python project, I'd like to import an external library named 'vobject'. What's the correct way to import it in my .py files?
The project's readme says that in order to install it, you need to run
python setup.py install
Additionally, vobject requires the 'dateutil' package.
Since this is going to run o... | [
"Don't modify the library. If you want to put all your libraries in external, you need to add external to your python path before you attempt to import libraries from there:\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), 'external'))\nimport some_external_library\n\n",
"You can't ... | [
3,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007169554_google_app_engine_python.txt |
Q:
making many to many relationships database in google app engine by python
Im trying to make 3 database; person, event and hobby. Each person selects hobbies from the list that is provided, which are in the hobby database. when a person creates a event, that person choose which hobby will be tagged to that event.... | making many to many relationships database in google app engine by python | Im trying to make 3 database; person, event and hobby. Each person selects hobbies from the list that is provided, which are in the hobby database. when a person creates a event, that person choose which hobby will be tagged to that event. From there event invitation will be send out to person who selected that hobb... | [
"Your problem with creating a Person entity is that above (at p1) you're trying to assign a Hobby entity to Person.hobby which should be a list of Hobby keys (and probably be named hobbies)\nh = Hobby(name='basketball')\nh_key = h.put() # or after h.put(), h.key()\np = Person(name='tom', hobbies=[h_key])\np.put()\n... | [
0
] | [] | [] | [
"database",
"google_app_engine",
"python"
] | stackoverflow_0007174821_database_google_app_engine_python.txt |
Q:
How do I set the PYTHONPATH on Cygwin?
In the Biopython installation instructions, it says that if Biopython doesn't work I'm supposed to do this:
export PYTHONPATH = $PYTHONPATH':/directory/where/you/put/Biopython'
I tried doing that in Cygwin from the ~ directory using the name of the Biopython directory (or eve... | How do I set the PYTHONPATH on Cygwin? | In the Biopython installation instructions, it says that if Biopython doesn't work I'm supposed to do this:
export PYTHONPATH = $PYTHONPATH':/directory/where/you/put/Biopython'
I tried doing that in Cygwin from the ~ directory using the name of the Biopython directory (or everything of it past the ~ directory), but whe... | [
"You can add the directory to your sys.path list\nimport sys\nbiopythondir = '/where/you/put/biopython'\nif biopythondir not in sys.path:\n sys.path.append(biopythondir)\n\n# import seq\n\nOr, for a more elegant solution than mucking around with environment variables and sys.path, see how to use .pth files to exte... | [
2,
2
] | [] | [] | [
"biopython",
"cygwin",
"python"
] | stackoverflow_0007199082_biopython_cygwin_python.txt |
Q:
Outputed py2exe exe won't run only when signed: ImportError
So, I've got a program I made in python 2.6, it ran fine as normal python, and ran fine when made into an exe via py2exe v0.6.9. I used signtool to sign it, having changed nothing else, and it stops working.
When I run the signed exe, I receive an "Import... | Outputed py2exe exe won't run only when signed: ImportError | So, I've got a program I made in python 2.6, it ran fine as normal python, and ran fine when made into an exe via py2exe v0.6.9. I used signtool to sign it, having changed nothing else, and it stops working.
When I run the signed exe, I receive an "ImportError: No module named os" from line 1 of my script. I did some d... | [
"If it's a py2exe issue, maybe give the newer PyInstaller a shot to build your executable. It's in active development, unlike py2exe which apparently hasn't been updated since 2008-11-16. \n"
] | [
2
] | [] | [] | [
"code_signing",
"py2exe",
"python",
"signtool"
] | stackoverflow_0007198431_code_signing_py2exe_python_signtool.txt |
Q:
How to Break Import Loop in python
I have a situation where there two related large python classes and hence i have put them in separate files. Let say classes are Cobra and Rat.
Now need to call methods of Rat from methods of Cobra and vice versa.
For this i need to import Cobra in Rat.py and Rat in Cobra.py
Thi... | How to Break Import Loop in python | I have a situation where there two related large python classes and hence i have put them in separate files. Let say classes are Cobra and Rat.
Now need to call methods of Rat from methods of Cobra and vice versa.
For this i need to import Cobra in Rat.py and Rat in Cobra.py
This creates an import loop and gives an er... | [
"If you don't use Cobra in the class definition of Rat or vice versa (i.e. only used inside methods), then you can actually move the import statement to the bottom of the file, by which time the class definition would already exist.\n# Cobra.py\nclass Cobra:\n # ...\n def check_prey(self, rat):\n # som... | [
42
] | [] | [] | [
"python"
] | stackoverflow_0007199466_python.txt |
Q:
Where are functions saved in Python and will they still remain after I close the cmd
I'm new with Python and I created a method that clears the screen. Is it already saved somewhere in my computer so that everytime I call it in Python cmd I can use it?
Something to add:
Should I learn Python 2 or 3 is fine enough?... | Where are functions saved in Python and will they still remain after I close the cmd | I'm new with Python and I created a method that clears the screen. Is it already saved somewhere in my computer so that everytime I call it in Python cmd I can use it?
Something to add:
Should I learn Python 2 or 3 is fine enough?
| [
"No. Each interactive session is separate. However, see this question for ways to save sessions if you want to.\n",
"No, it will be gone when you start a new session. If you want to add your shortcut so that it's there every time you start python, you have a few options:\n\nAdd it in your sitecustomize.py file, ... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007199647_python.txt |
Q:
How to copy file based on partial filename in python
I'm trying to copy certain .JPG files from my photocard to another directory. The files are named IMG_7853.JPG, IMG_7854.JPG, and so on (they range from IMG_0001.JPG to IMG_9999.JPG). If I want to copy all files greater than IMG_7853 what's the best approach i... | How to copy file based on partial filename in python | I'm trying to copy certain .JPG files from my photocard to another directory. The files are named IMG_7853.JPG, IMG_7854.JPG, and so on (they range from IMG_0001.JPG to IMG_9999.JPG). If I want to copy all files greater than IMG_7853 what's the best approach in python. The code below works fine for listing all files... | [
"fnmatch does glob-style matching.\n",
"...\n if name.endswith(\".JPG\") and int( name.split(\"_\")[-1].split(\".\")[0] ) > 7853 :\n...\n\n",
"I don't know python but you should be able to just compare them. As long as the files are strings and all start with IMG_ with no leading zeros, you should just be abl... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007199941_python.txt |
Q:
Python - A TypeError occurs calling a overwritten method
I'm running into a problem with method overwriting.
Look at the src code below,
class Foo(object):
@staticmethod
def bar():
pass
Foo.bar() # works fine
print Foo.bar # <function bar at 0x028A5B30>
print dir(Foo.bar)
"""
['__call__', '__class__', ... | Python - A TypeError occurs calling a overwritten method | I'm running into a problem with method overwriting.
Look at the src code below,
class Foo(object):
@staticmethod
def bar():
pass
Foo.bar() # works fine
print Foo.bar # <function bar at 0x028A5B30>
print dir(Foo.bar)
"""
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__',
'__d... | [
"If you want it to continue to be a static method then you must tell Python so when assigning. Otherwise it will become a normal method.\nFoo.bar = staticmethod(backup)\n\n",
"If you put a function as an attribute to an object, things get confusing: due to their __get__() methods, they behave differently than the... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0007200057_python.txt |
Q:
Alternative to Pythons SQLite3 module - maybe MySQL
We have a website that uses SQL (currently SQLite3) to store entrants into a competition & the server side language is python & uses the module sqlite3. It turns out that the webhost runs python 2.4 & the module sqlite3 is only available in python 2.6/2,7 & up.
S... | Alternative to Pythons SQLite3 module - maybe MySQL | We have a website that uses SQL (currently SQLite3) to store entrants into a competition & the server side language is python & uses the module sqlite3. It turns out that the webhost runs python 2.4 & the module sqlite3 is only available in python 2.6/2,7 & up.
So I need to be able to write competition entrants to my S... | [
"Obviously you cannot use pysqlite when your webhost has not installed it. There are, of course, other libraries to access different databases, such as MySQL. If you can you those depends, again, on your webhost: He will have to install the respective database module.\nMoreover, most SQL databases are standalone ... | [
2
] | [] | [] | [
"cgi",
"mysql",
"python",
"sqlite"
] | stackoverflow_0007200384_cgi_mysql_python_sqlite.txt |
Q:
How does urllib.urlopen() work?
Let's consider a big file (~100MB). Let's consider that the file is line-based (a text file, with relatively short line ~80 chars).
If I use built-in open()/file() the file will be loaded in lazy manner.
I.E. if a I do aFile.readline() only a chunk of a file will reside in memory. ... | How does urllib.urlopen() work? | Let's consider a big file (~100MB). Let's consider that the file is line-based (a text file, with relatively short line ~80 chars).
If I use built-in open()/file() the file will be loaded in lazy manner.
I.E. if a I do aFile.readline() only a chunk of a file will reside in memory. Does the urllib.urlopen() do somethin... | [
"open (or file) and urllib.urlopen look like they're more or less doing the same thing there. urllib.urlopen is (basically) creating a socket._socketobject and then invoking the makefile method (contents of that method included below)\ndef makefile(self, mode='r', bufsize=-1):\n \"\"\"makefile([mode[, bufsize]])... | [
2,
1
] | [] | [] | [
"file",
"performance",
"python",
"urllib",
"urlopen"
] | stackoverflow_0007200252_file_performance_python_urllib_urlopen.txt |
Q:
Making import statements explicit
I was running an app on django's local server, and I was able to use import statements without using the project's directory:
from userprofile.views import Profile
However, now that I've transferred it to an apache server, it is throwing an error if I use the above import, and wi... | Making import statements explicit | I was running an app on django's local server, and I was able to use import statements without using the project's directory:
from userprofile.views import Profile
However, now that I've transferred it to an apache server, it is throwing an error if I use the above import, and will only work if I include the full path... | [
"import looks in every directory in sys.path for the specified module (userprofile/__init__.py in your case).\nIf you compare the values of sys.path on the two systems, you'll see it is missing the myproject directory. You can simply add it to the sys.path list.\n"
] | [
2
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0007200465_django_import_python.txt |
Q:
good automation testing tool based on python's unittest
I'm looking for a good open sourced automation testing tool using python's unittest, which can
be followed as a "formal pattern" of writing a similar tool.
A:
Although I haven't integrated it into my own personal workflow, I know of quite a number of develo... | good automation testing tool based on python's unittest | I'm looking for a good open sourced automation testing tool using python's unittest, which can
be followed as a "formal pattern" of writing a similar tool.
| [
"Although I haven't integrated it into my own personal workflow, I know of quite a number of developers who swear by Jenkins. Source is available on Github.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007200549_python.txt |
Q:
Why is bash language often slower than python or ruby?
I assume it is because of the interpreter's implementation.
Can anyone give me a more in-depth answer please? Thanks.
Also, I wonder if bash has a garbage collector?
A:
bash loads a large number of commands from disk. Most other scripting languages have m... | Why is bash language often slower than python or ruby? | I assume it is because of the interpreter's implementation.
Can anyone give me a more in-depth answer please? Thanks.
Also, I wonder if bash has a garbage collector?
| [
"bash loads a large number of commands from disk. Most other scripting languages have many more instructions that they run internally.\nFor example, to do a simple computation in bash, you'd use a=`expr 1 + 2` and bash will first load /usr/bin/expr, run that command which writes the result in the output, bash colle... | [
4
] | [] | [] | [
"bash",
"interpreter",
"python",
"ruby"
] | stackoverflow_0007200700_bash_interpreter_python_ruby.txt |
Q:
Importing a specific module thats not part of my current Python 2.X version
My webhost where our website is runs Python 2.4 & the website uses the SQLite3 python module (which is only part of Python 2.5 & up). This means that I cant use the module SQLite3 because its not part of Python 2.4.
Is there a way for me t... | Importing a specific module thats not part of my current Python 2.X version | My webhost where our website is runs Python 2.4 & the website uses the SQLite3 python module (which is only part of Python 2.5 & up). This means that I cant use the module SQLite3 because its not part of Python 2.4.
Is there a way for me to upload the python SQLite3 module myself & just import/refernce that in my scrip... | [
"This very much depends about how much control your webhost gives you about the Python environment. For normal shared hosting, the runtime Python environment is fixed.\n"
] | [
0
] | [] | [] | [
"mysql",
"python",
"sqlite",
"web_hosting"
] | stackoverflow_0007200745_mysql_python_sqlite_web_hosting.txt |
Q:
printing to excel file, python
import csv
from math import sqrt
import os
class MaxiAverageCalculator(object):
def __init__(self):
self.ncols = 3
self.nrows = 0
self.s = [0.0, 0.0, 0.0]
self.s2 = [0.0, 0.0, 0.0]
def run(self, fullpath):
with open(fullpath, "rb") as... | printing to excel file, python | import csv
from math import sqrt
import os
class MaxiAverageCalculator(object):
def __init__(self):
self.ncols = 3
self.nrows = 0
self.s = [0.0, 0.0, 0.0]
self.s2 = [0.0, 0.0, 0.0]
def run(self, fullpath):
with open(fullpath, "rb") as infile:
reader = csv.re... | [
"You still work with flopy disks? Wow :-)\nNevertheless, in one path you write \"A:\\\\...\", in the other \"A\\\\...\". Maybe that's it.\nBesides, you should explicitly pass f to run(). It is better style.\n",
"When you do this:\nfor name, a, s in zip(self.colnames, self.avg, self.std):\n f.write(str(a))\... | [
1,
0
] | [] | [] | [
"excel",
"python",
"python_3.x"
] | stackoverflow_0007200472_excel_python_python_3.x.txt |
Q:
How Can I Automatically Add Google Alerts Using Python Mechanize
I'm aware of a Python API for sale here (http://oktaykilic.com/my-projects/google-alerts-api-python/), but I'd like to understand why the way I'm doing it now isn't working.
Here is what I have so far:
class GAlerts():
def __init__(self, uName = 'US... | How Can I Automatically Add Google Alerts Using Python Mechanize | I'm aware of a Python API for sale here (http://oktaykilic.com/my-projects/google-alerts-api-python/), but I'd like to understand why the way I'm doing it now isn't working.
Here is what I have so far:
class GAlerts():
def __init__(self, uName = 'USERNAME', passWord = 'PASSWORD'):
self.uName = uName
self.pass... | [
"The custom drop-down menus are done using JavaScript, so the proper solution would be to figure out the URL parameters and then try to reproduce them (this might be the reason it doesn't works as expected right now - you are omitting required URL parameters that are normally set by JavaScript when you visit the si... | [
2,
2
] | [] | [] | [
"alerts",
"mechanize",
"python"
] | stackoverflow_0007198589_alerts_mechanize_python.txt |
Q:
calculating mean of several numpy masked arrays (masked_all)
first of all I'm new to python and programming but you guys already helped me a lot, so thanks a lot! But I've come to a problem I haven't found an answer so far:
I have the data of several plates where the data represents the pressure on each plate at a... | calculating mean of several numpy masked arrays (masked_all) | first of all I'm new to python and programming but you guys already helped me a lot, so thanks a lot! But I've come to a problem I haven't found an answer so far:
I have the data of several plates where the data represents the pressure on each plate at a large number of different spots. The thing is, these plates aren'... | [
"EDIT: Sorry, I misinterpreted the question. Try this:\nallplates = ma.masked_all((160, 65, numplates))\n# fill in allplates\nmeanplate = allplates.mean(axis=2)\n\nThis will compute the mean over the last dimension of the array, i.e., average the plates together. Missing values are ignored.\n\nEarlier answer: You c... | [
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007186958_numpy_python.txt |
Q:
how to get expired domain names by python
I am writing a function by python to get a list of expired domains just like this one, but I can not find any library can do this, any ideas about this?
A:
See https://github.com/richardpenman/whois (first Google search result when searching for python whois). This allo... | how to get expired domain names by python | I am writing a function by python to get a list of expired domains just like this one, but I can not find any library can do this, any ideas about this?
| [
"See https://github.com/richardpenman/whois (first Google search result when searching for python whois). This allows you to determine the expiration date of a domain. But you will need to get a list of domains to check from somewhere (domaintools apparently gets them from domain auctions).\n"
] | [
5
] | [
"Why should there be a library for this kind of work? You probably have to build up your own database of WHOIS information and your own logic.\n"
] | [
-1
] | [
"dns",
"python",
"whois"
] | stackoverflow_0007201190_dns_python_whois.txt |
Q:
What are the SCons alternatives?
I have projects in C++, Java and Python. Projects in C++ export SWIG interfaces so they can be used by Java and Python projects.
My question is: what building mechanism can I use to manage dependencies and build these projects?
I have used SCons and GYP. They are fairly easy to use... | What are the SCons alternatives? | I have projects in C++, Java and Python. Projects in C++ export SWIG interfaces so they can be used by Java and Python projects.
My question is: what building mechanism can I use to manage dependencies and build these projects?
I have used SCons and GYP. They are fairly easy to use and allow plugins (code-generators, c... | [
"CMake\nI use and prefer it for my projects.\nThere's also Rake (comes with Ruby, but can be used for anything), which I regard rather highly.\n",
"One promising alternative is waf:\n\nhttps://waf.io/\n\nOthers:\n\nhttp://code.google.com/p/fabricate/\n\nNot exactly but very relevant:\n\nhttp://www.buildout.org/do... | [
9,
7,
4,
1,
1
] | [] | [] | [
"c++",
"gyp",
"java",
"python",
"scons"
] | stackoverflow_0004141511_c++_gyp_java_python_scons.txt |
Q:
Searching large data set for multiple strings
I am working with two sets of data:
Set 1 has 500 members in a single column (all strings)
Set 2 has 30,000 members in two columns (tab delimited) where column 1 is a numerical ID number and column 2 is a , delimited list of strings (10,000 possibilities).
I need to se... | Searching large data set for multiple strings | I am working with two sets of data:
Set 1 has 500 members in a single column (all strings)
Set 2 has 30,000 members in two columns (tab delimited) where column 1 is a numerical ID number and column 2 is a , delimited list of strings (10,000 possibilities).
I need to search column 2 of Set 2 for the strings in set 1 and... | [
"Not sure about how you hold your sets, but somehow you have to transform/import them in some python data structures. It seems that a very simple way to do this is to hold set1 in a python set (or list) and set2 in a dict, with ids as keys and strings as values. Then a simple iteration through keys and appropriate... | [
0,
0
] | [] | [] | [
"excel",
"large_data_volumes",
"python",
"search"
] | stackoverflow_0007197266_excel_large_data_volumes_python_search.txt |
Q:
Python Bitshift 32 Bit Constraint
Possible Duplicate:
Problem in calculating checksum : casting int to signed int32
This should be a relatively easy answer, I just don't really know how to search for it...I got a few semi-relevant things, but nothing that fits what I'm trying to do.
>>> 1171855803 << 7
149997542... | Python Bitshift 32 Bit Constraint |
Possible Duplicate:
Problem in calculating checksum : casting int to signed int32
This should be a relatively easy answer, I just don't really know how to search for it...I got a few semi-relevant things, but nothing that fits what I'm trying to do.
>>> 1171855803 << 7
149997542784L # I want -326312576
In other wor... | [
"May not be the best answer, but this works...\nimport numpy as np\nnp.int32(1171855803) << 7\n\n",
"You could try\nimport ctypes\na=ctypes.c_int32(1171855803)\na.value<<=7\nprint a\n\nwhich gives: c_int(-326312576)\nIt seems to allow platform specific bit-manipulations. I am not sure about efficiency.\n"
] | [
1,
1
] | [] | [] | [
"bit_manipulation",
"bit_shift",
"integer",
"python"
] | stackoverflow_0007201207_bit_manipulation_bit_shift_integer_python.txt |
Q:
Python ( robot module): conversion hom. transformation (rotation) matrix and Euler or RPY angles
I'm using in the robotics toolbox (c.q. robot module) in Python http://code.google.com/p/robotics-toolbox-python/) and I'm utterly confused how to interpret the following conversion results (I've done things like this ... | Python ( robot module): conversion hom. transformation (rotation) matrix and Euler or RPY angles | I'm using in the robotics toolbox (c.q. robot module) in Python http://code.google.com/p/robotics-toolbox-python/) and I'm utterly confused how to interpret the following conversion results (I've done things like this in the past could always work them out...).
A simple phi=PI/10 rotation about the x-axes produces the ... | [
"Solved:\nWith successive angles, a[0],a[1],a[2], \n1) For Euler angles these are successive rotations around Z-Y-Z axes; \n2) For RPY angles these are successive Y(aw)-P(itch)-R(roll) rotations (i.e around Z-Y-X axes).\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007192390_python.txt |
Q:
Python encoding problems
So, I've read a lot about Python encoding and stuff - maybe not enough but I've been working on this for 2 days and still nothing - but I'm still getting troubles. I'll try to be as clear as I can. The main thing is that I'm trying to remove all accents and characters such as #, !, %, &...... | Python encoding problems | So, I've read a lot about Python encoding and stuff - maybe not enough but I've been working on this for 2 days and still nothing - but I'm still getting troubles. I'll try to be as clear as I can. The main thing is that I'm trying to remove all accents and characters such as #, !, %, &...
The thing is, I do a query se... | [
"See this page.\nThe decode() method is to be applied to a str object, not a unicode object. Given a unicode string as input, it first tries to encode it to a str using the ascii codec, then decode as utf-8, which fails.\nTry return normalize('NFKD', unicode(txt) ). \n",
"This is what I used in my code to discard... | [
9,
5,
1
] | [] | [] | [
"django",
"encoding",
"python",
"twitter",
"utf_8"
] | stackoverflow_0007199179_django_encoding_python_twitter_utf_8.txt |
Q:
M2CRYPTO generating RSA key pair with automotically passphrase
I am using this "key = RSA.gen_key(2048, 65537,genPass)" for RSA key generation,
It is asking to enter a passphrase.
How can i generate it without passphrase from user?and put some known passphrase automaticlly? Thanks.
A:
Key generation does not req... | M2CRYPTO generating RSA key pair with automotically passphrase | I am using this "key = RSA.gen_key(2048, 65537,genPass)" for RSA key generation,
It is asking to enter a passphrase.
How can i generate it without passphrase from user?and put some known passphrase automaticlly? Thanks.
| [
"Key generation does not require a password. It is required only when you save to file. If you want to do so automatically, you can provide a password generator as the callback to the save_key method.\n>>> import M2Crypto\n>>> rsaKey = M2Crypto.RSA.gen_key(2048, 65537)\n.........................+++\n................ | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003254981_python.txt |
Q:
How to change a function's return using a decorator?
I want create a decorator to change a function's return value like that, How to do that like below?:
def dec(func):
def wrapper():
#some code...
#change return value append 'c':3
return wrapper
@dec
def foo():
return {'a':1, 'b':2}
... | How to change a function's return using a decorator? | I want create a decorator to change a function's return value like that, How to do that like below?:
def dec(func):
def wrapper():
#some code...
#change return value append 'c':3
return wrapper
@dec
def foo():
return {'a':1, 'b':2}
result = foo()
print result
{'a':1, 'b':2, 'c':3}
| [
"Well.... you call the decorated function and change the return value:\ndef dec(func):\n def wrapper(*args, **kwargs):\n result = func(*args, **kwargs)\n result['c'] = 3\n return result\n return wrapper\n\n",
"I'll try to be fairly general here since this is probably a toy example, and ... | [
60,
15
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0007201715_decorator_python.txt |
Q:
Dynamically generate pygtk menu's based on dictionaries and lists
I have a list of options that I read from an xml file. In the list there is information like codenames, item relations, child codenames ...
I use the following functions to generate pygtk boxes with the proper buttons in it. My problem is that I hav... | Dynamically generate pygtk menu's based on dictionaries and lists | I have a list of options that I read from an xml file. In the list there is information like codenames, item relations, child codenames ...
I use the following functions to generate pygtk boxes with the proper buttons in it. My problem is that I have to be able to hide/show those boxes at some points (one example would... | [
"That's a lot of code to go through, so I'm not entirely sure that I know exactly what you want to do. I can think of a couple of ways that you can later access these dynamically created widgets, though. \nOne would be to use widget.set_name() to give each widget a name. You could then later get all the child widge... | [
0
] | [] | [] | [
"dynamic",
"generator",
"menu",
"pygtk",
"python"
] | stackoverflow_0007199988_dynamic_generator_menu_pygtk_python.txt |
Q:
Persistent HTTPS Connections in Python
I want to make an HTTPS request to a real-time stream and keep the connection open so that I can keep reading content from it and processing it.
I want to write the script in python. I am unsure how to keep the connection open in my script. I have tested the endpoint with cur... | Persistent HTTPS Connections in Python | I want to make an HTTPS request to a real-time stream and keep the connection open so that I can keep reading content from it and processing it.
I want to write the script in python. I am unsure how to keep the connection open in my script. I have tested the endpoint with curl which keeps the connection open successful... | [
"It looks like your real-time stream is delivered as one endless HTTP GET response, yes? If so, you could just use python's built-in urllib2.urlopen(). It returns a file-like object, from which you can read as much as you want until the server hangs up on you.\nf=urllib2.urlopen('https://encrypted.google.com/')\n... | [
3,
1,
0
] | [] | [] | [
"http",
"persistent",
"python",
"real_time"
] | stackoverflow_0007198552_http_persistent_python_real_time.txt |
Q:
Is there any way to see the codes of functions you've typed in your Python CMD
Just found out that when I pressed up in my cmd one of my function codes is no longer accessible meaning I couldn't see the code I made it with. Is there any way I can see it again? And is there any way I could see all the functions I c... | Is there any way to see the codes of functions you've typed in your Python CMD | Just found out that when I pressed up in my cmd one of my function codes is no longer accessible meaning I couldn't see the code I made it with. Is there any way I can see it again? And is there any way I could see all the functions I created for this session in Python cmd?
| [
"dir() should give you everything.\nEDIT\n>>> def blah():\n... return 1\n...\n>>> dir()\n['__builtins__', '__doc__', '__name__', 'blah']\n>>>\n>>> dir(blah.func_code)\n['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__\n', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007201333_python.txt |
Q:
Multithread with workerpool modul
import os
import urllib
import workerpool
from datetime import datetime
class DownloadJob(workerpool.Job):
def __init__(self, fa):
self.fa = fa
def run(self):
f = open(self.fa + '.txt','w')
f.write('Example Note.......')
f.close... | Multithread with workerpool modul | import os
import urllib
import workerpool
from datetime import datetime
class DownloadJob(workerpool.Job):
def __init__(self, fa):
self.fa = fa
def run(self):
f = open(self.fa + '.txt','w')
f.write('Example Note.......')
f.close()
pool = workerpool.WorkerPool(siz... | [
"I think you should only shutdown the pool if you are finished with it, i.e. after the for a loop, maybe even in a try...finally clause.\nIt would look that way:\ntry:\n for a in range(ranges + 1):\n os.chdir(path + '\\\\' + str(workname))\n os.system('mkdir ' + str(range1 + a))\n os.chdir(p... | [
3
] | [] | [] | [
"multithreading",
"pool",
"python",
"threadpool"
] | stackoverflow_0007202351_multithreading_pool_python_threadpool.txt |
Q:
Working with Django's post_save() signal
I have two tables:
class Advertisement(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
author_email = models.EmailField()
class Verification(models.Model):
advertisement = models.ForeignKeyField(Advertisement)
key = models.CharField(max_... | Working with Django's post_save() signal | I have two tables:
class Advertisement(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
author_email = models.EmailField()
class Verification(models.Model):
advertisement = models.ForeignKeyField(Advertisement)
key = models.CharField(max_length=32)
And I need to auto populate Verifi... | [
"instead of connecting to a specific sender, just connect to post_save in general and check the class of the saved instance in your handler eg\ndef gen_key(sender, **kwargs):\n if issubclass(sender, Advertisement):\n code goes here\npost_save.connect(gen_key, dispatch_uid=\"my_unique_identifier\")\n\n"
] | [
5
] | [] | [] | [
"django_signals",
"python"
] | stackoverflow_0005472818_django_signals_python.txt |
Q:
Python Manipulate and save XML without third-party libraries
I have a xml in which I have to search for a tag and replace the value of tag with a new values. For example,
<tag-Name>oldName</tag-Name>
and replace oldName to newName like
<tag-Name>newName</tag-Name>
and save the xml. How can I do that... | Python Manipulate and save XML without third-party libraries | I have a xml in which I have to search for a tag and replace the value of tag with a new values. For example,
<tag-Name>oldName</tag-Name>
and replace oldName to newName like
<tag-Name>newName</tag-Name>
and save the xml. How can I do that without using thirdparty lib like BeautifulSoup
Thank you
| [
"The best option from the standard lib is (I think) the xml.etree package.\nAssuming that your example tag occurs only once somewhere in the document:\nimport xml.etree.ElementTree as etree\n# or for a faster C implementation\n# import xml.etree.cElementTree as etree\n\ntree = etree.parse('input.xml')\nelem = tree.... | [
6,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0007197947_python_xml.txt |
Q:
how to use Python-meep?
I am new with Python. I am using XP, I downloaded Python 2.7.2 and Python_meep 1.4.2 and I am trying to use it. (I put both of them in the same direction)
If I try to use some samples of Python-meep for example use_averaging i got an error:
Traceback (most recent call last):
File "D:\... | how to use Python-meep? | I am new with Python. I am using XP, I downloaded Python 2.7.2 and Python_meep 1.4.2 and I am trying to use it. (I put both of them in the same direction)
If I try to use some samples of Python-meep for example use_averaging i got an error:
Traceback (most recent call last):
File "D:\Python\samples\use_averaging.... | [
"It looks like this python library is a wrapper around libmeep. This is not available directly on Windows. The authors of the library say that it should be possible to build and install it on Windows using something like cygwin - http://ab-initio.mit.edu/wiki/index.php/Meep_Installation\nMinGW might work as well.\... | [
0
] | [] | [] | [
"meep",
"python"
] | stackoverflow_0007202721_meep_python.txt |
Q:
How do I make a Gnome Panel applet (written in python) store seperate settings for each instance?
Someone asked this question about a year ago but I was unable to turn either of the answers into usable code. The accepted answer seemed to reference a C function (I could find no python equivalent) and the other one ... | How do I make a Gnome Panel applet (written in python) store seperate settings for each instance? | Someone asked this question about a year ago but I was unable to turn either of the answers into usable code. The accepted answer seemed to reference a C function (I could find no python equivalent) and the other one referenced a python function that did not work for me (applet.get_preferences_key() returns None). wat ... | [
"I can't access the pages linked in the accepted answer from the other question for some reason. However, you can access the GConf C libraries through PyGObject introspection:\nfrom gi.repository import GConf. So, the function that they recommend (if only I could load the web page to see), is presumably available i... | [
0
] | [] | [] | [
"gnome",
"python"
] | stackoverflow_0007182671_gnome_python.txt |
Q:
Accessing bitfields while reading/writing binary data structures
I'm writing a parser for a binary format. This binary format involves different tables which are again in binary format containing varying field sizes usually (somewhere between 50 - 100 of them).
Most of these structures will have bitfields and will... | Accessing bitfields while reading/writing binary data structures | I'm writing a parser for a binary format. This binary format involves different tables which are again in binary format containing varying field sizes usually (somewhere between 50 - 100 of them).
Most of these structures will have bitfields and will look something like these when represented in C:
struct myHeader
{
... | [
"Using bitstring (which you mention you're looking at) it should be easy enough to implement. First to create some data to decode:\n>>> myheader = \"3, 2, 3, 14, 4\"\n>>> a = bitstring.pack(myheader, 1, 0, 5, 1000, 2)\n>>> a.bin\n'00100101000011111010000010'\n>>> a.tobytes()\n'%\\x0f\\xa0\\x80'\n\nAnd then decoding... | [
7,
6
] | [] | [] | [
"binary_data",
"bit_fields",
"ctypes",
"python",
"struct"
] | stackoverflow_0007198388_binary_data_bit_fields_ctypes_python_struct.txt |
Q:
Using a module variable within a class instance
I have a class which is instantiated many times. It requires a certain parameter from a configuration file. I thought of reading the config file once in the module level so that each instance can refer to the loaded parameter.
I'm probably missing something as I'm re... | Using a module variable within a class instance | I have a class which is instantiated many times. It requires a certain parameter from a configuration file. I thought of reading the config file once in the module level so that each instance can refer to the loaded parameter.
I'm probably missing something as I'm receiving: UnboundLocalError: local variable 'the_param... | [
"Works for me\n>>> class MyClass( object ):\n... def aFunc( self ):\n... print( some_global )\n... \n>>> some_global= 3\n>>> x= MyClass()\n>>> x.aFunc()\n3\n\nThe code that's posted has probably had too many details removed to show the real error.\n",
"Don't try to use global variables in your classes... | [
4,
3,
1,
1,
0
] | [] | [] | [
"global_variables",
"module",
"python",
"scope"
] | stackoverflow_0006663866_global_variables_module_python_scope.txt |
Q:
python condition and calculate the sum?
Write a function that compares two DNA sequences based on the following scoring scheme: +1 for a match, +3 for each consecutive match and -1 for each mismatch.
MY CODE:
def pairwiseScore(seqA, seqB):
'''1+1+3-1-1+1+3+1-1-1+1-1-1-1'''
print
signed = ''
score = 0
... | python condition and calculate the sum? | Write a function that compares two DNA sequences based on the following scoring scheme: +1 for a match, +3 for each consecutive match and -1 for each mismatch.
MY CODE:
def pairwiseScore(seqA, seqB):
'''1+1+3-1-1+1+3+1-1-1+1-1-1-1'''
print
signed = ''
score = 0
for i in range(len(seqA)):
if(seqA[i] == ... | [
"if signed=='||':\n\nThis code only matches if signed is exactly equal to '||'.\nYou want to look at the last two chars, so try:\nif signed[-2:] == '||':\n\nI think you also have a calculation error in the score calculation.\nHere's a fixed and cleaned up version for your function:\ndef pairwiseScore(seqA, seqB): \... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007203264_python.txt |
Q:
Run External Python Programs with Eclipse PyDev
I want to use the refactoring enabled by PyDev but think it is a little ridiculous to create a project folder in my Eclipse workspace for every single little python script I create.
I'm able to get refactoring by editing the file in Eclipse using File > Open File....... | Run External Python Programs with Eclipse PyDev | I want to use the refactoring enabled by PyDev but think it is a little ridiculous to create a project folder in my Eclipse workspace for every single little python script I create.
I'm able to get refactoring by editing the file in Eclipse using File > Open File.... However, I still have to go to the Terminal to run t... | [
"The latest PyDev already has improved things a bit... the workflow for the use-case of dealing with external files is the following (checking on PyDev 2.2.2 and Eclipse 3.7):\n\nDrag file from filesystem to Eclipse (should open the file to edit it).\nPress F9 with the editor open to run the file... It'll still ask... | [
9
] | [] | [] | [
"aptana",
"eclipse",
"pydev",
"python"
] | stackoverflow_0007194424_aptana_eclipse_pydev_python.txt |
Q:
String.find is not returning any value
I am trying to substring the following value to get the link(image value) out of it:
<p>This is a recipe developed by my wife, Irene. It’s been tweaked to perfection. I've never ordered congee in Manila since then.</p>
<p style="text-align: center;">
(img src="http://im... | String.find is not returning any value | I am trying to substring the following value to get the link(image value) out of it:
<p>This is a recipe developed by my wife, Irene. It’s been tweaked to perfection. I've never ordered congee in Manila since then.</p>
<p style="text-align: center;">
(img src="http://img35.imageshack.us/img35/6047/69934653.jpg" a... | [
"str.find() returns int, so Log('Position HTTP'+pos) will raise TypeError.\nChange to Log('Position HTTP %s' % pos)\n",
"Perhaps you should consider using the Regex module instead:\nhttp://docs.python.org/library/re.html\nimport re\nmatch = re.search('http://\\S+.(?:jpeg|jpg|png)', a_string)\nprint match.group(0)... | [
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007203415_python_string.txt |
Q:
OOP: What would be the best way to design this object?
I have a settings object that contains some generic settings. These settings will change for each user. I'm wondering what would be the best way to code this. My current method is this:
class Settings(object):
def __init__(self, user=None):
if us... | OOP: What would be the best way to design this object? | I have a settings object that contains some generic settings. These settings will change for each user. I'm wondering what would be the best way to code this. My current method is this:
class Settings(object):
def __init__(self, user=None):
if user and not isinstance(user, users.User):
raise T... | [
"Overriding methods is not only not bad OOP design, it's the basis for subtype polymorphism, which is core to OOP, and a common way to get rid of the need for such conditional checks.\nThere are certainly times when you should prefer composition to inheritance, but it's not clear from your description that there's ... | [
3
] | [] | [] | [
"design_patterns",
"oop",
"python"
] | stackoverflow_0007203529_design_patterns_oop_python.txt |
Q:
Python Object from a SQL row (with a large number of columns)
Given the following SQL query,
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("select field1, field2, field3, fieldA, fieldB, fieldB from users")
row = cur... | Python Object from a SQL row (with a large number of columns) | Given the following SQL query,
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("select field1, field2, field3, fieldA, fieldB, fieldB from users")
row = cursor.fetchone()
I would like to pass the row object as an argument ... | [
"If your fields are known as a list of string you should use setattr builtin function to set the field from its name.\nfields = [\"field1\", \"field2\", \"field3\", \"fieldA\", \"fieldB\"]\ncnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')\ncursor = cnxn.cursor()\ncursor.... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007203258_python.txt |
Q:
Google appengine, Cannot fetch data from child model
My bulkloader.yaml looks like this:
- import: models
transformers:
- model: models.Company
connector: csv
connector_options:
encoding: utf_8
columns: from_header
property_map:
- property: __key__
external_name: companyid
import_tra... | Google appengine, Cannot fetch data from child model | My bulkloader.yaml looks like this:
- import: models
transformers:
- model: models.Company
connector: csv
connector_options:
encoding: utf_8
columns: from_header
property_map:
- property: __key__
external_name: companyid
import_transform: int
export_transform: transform.key_id_or_na... | [
"Alright I found what i was doing wrong. \nIn my bulkloader.yaml, i was referencing entities as models instead of kind.\nOnce i used \n- kind: Home\n\ninstead of \n- model: models.Home\n\nAlso i used key_is_id=True at both the foreign key references to solve the problem of finding parent and child data.\nNow this i... | [
0
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0007081644_bulkloader_google_app_engine_python.txt |
Q:
How to model many blobs for an object?
I want to enable something like a one-to-many relation between a text object and blobs so that a text object (an "article" or likewise) has many images and/or videos. There are two ways I see how to do this where the first is using a list of blobs as instance variable. Will i... | How to model many blobs for an object? | I want to enable something like a one-to-many relation between a text object and blobs so that a text object (an "article" or likewise) has many images and/or videos. There are two ways I see how to do this where the first is using a list of blobs as instance variable. Will it work?
class A(search.SearchableModel):
b... | [
"App Engine actually has an article on this in their documentation: http://code.google.com/appengine/articles/modeling.html\n"
] | [
4
] | [] | [] | [
"blobstore",
"data_modeling",
"google_app_engine",
"python"
] | stackoverflow_0007204365_blobstore_data_modeling_google_app_engine_python.txt |
Q:
Infinite socket connect attempt in python
Is it possible for socket to keep attempting to connect to specified socket until the connection is established?
If it's possible do you mind showing me on example how it's done? I searched around google and on stack overflow but didn't find anything useful.
Thanks in adva... | Infinite socket connect attempt in python | Is it possible for socket to keep attempting to connect to specified socket until the connection is established?
If it's possible do you mind showing me on example how it's done? I searched around google and on stack overflow but didn't find anything useful.
Thanks in advance.
| [
"How about this:\nwhile True:\n if do_connection_attempt():\n break\n\nwhere do_connection_attempt is a placeholder for the connection attempting phase, returning True if connection was established?\n"
] | [
2
] | [
"Have you meant something like this?\ndef run(self):\n while True:\n try:\n self.csock.connect(self.ADDR)\n except socket.error:\n self.run()\n\nIf so, this produces error after few attempts.\n"
] | [
-2
] | [
"python",
"sockets"
] | stackoverflow_0007204680_python_sockets.txt |
Q:
Generating patches for open source, source code in virtualenv site-packages
I have an open source python library sitting in my virtualenv site-packages. And I noticed a bug in that library and would like to contribute my patches back to the open source project.
The problem is, my virtualenv site-packages is not ve... | Generating patches for open source, source code in virtualenv site-packages | I have an open source python library sitting in my virtualenv site-packages. And I noticed a bug in that library and would like to contribute my patches back to the open source project.
The problem is, my virtualenv site-packages is not version controlled by git (obviously, since it was installed via pip) and it's a pa... | [
"Fork the project on github, clone it to a directory separate from your virtualenv, make the pull request, and install your own fork into the virtualenv by pointing pip at your fork in github.\n"
] | [
2
] | [] | [] | [
"open_source",
"python",
"virtualenv"
] | stackoverflow_0007204880_open_source_python_virtualenv.txt |
Q:
How to solve an integral equation in python?
I'm trying to solve this integral equation using Python:
where z ranges from 0 to 1.
The scipy.quad function only provides the numerical solution for a certain interval, but it doesn't provide the solution over the interval.
def f(z,Om,Ol): return 1./p.sqrt((1+z)**2 * ... | How to solve an integral equation in python? | I'm trying to solve this integral equation using Python:
where z ranges from 0 to 1.
The scipy.quad function only provides the numerical solution for a certain interval, but it doesn't provide the solution over the interval.
def f(z,Om,Ol): return 1./p.sqrt((1+z)**2 * (1+Om*z) - z*(2+z)*Ol)
quad(lambda r:f(r,Om,Ol),0,... | [
"I understand that you want to solve a differential equation dF/dz1 = f(z1, Om, Ol) and want F(z1) at different locations. If this is the case, then the Ordinary Differential Equation (ODE) routines of SciPy are the way to go. You might want to check odeint(), in particular, as it can give you the values of your ... | [
4,
1,
0,
0
] | [] | [] | [
"equation",
"integration",
"python",
"scipy"
] | stackoverflow_0007160926_equation_integration_python_scipy.txt |
Q:
Python: Assign multiple values at once: pass all argv arguments to a function
I want to pass all argv arguments to a function. I have created this code, but it gives me an error. How knows how to make this work? Many thanks for your help.
if __name__ == "__main__":
import sys
createP(sys.argv[1:])
def cre... | Python: Assign multiple values at once: pass all argv arguments to a function | I want to pass all argv arguments to a function. I have created this code, but it gives me an error. How knows how to make this work? Many thanks for your help.
if __name__ == "__main__":
import sys
createP(sys.argv[1:])
def createP( a, b, c):
print a + b + c
I am running this app using the commandline:
... | [
"You're calling createP before you define it. You're also passing the wrong number of arguments to it; you need to expand the array:\ndef createP( a, b, c):\n print a + b + c\n\nif __name__ == \"__main__\":\n import sys\n createP(*sys.argv[1:])\n\n",
"Try switching the order between the definition and t... | [
4,
1,
1
] | [] | [] | [
"arguments",
"argv",
"python",
"tuples"
] | stackoverflow_0007204973_arguments_argv_python_tuples.txt |
Q:
Displaying real-time text in Tkinter after Button command calls function?
I am trying to display real-time text in Tkinter after a Button command calls a function. The function should display a "timestamp" when PycURL receives "HTTP/1.1 200 OK". The function POSTs energy data to a server every 2 minutes.
Pseudoc... | Displaying real-time text in Tkinter after Button command calls function? | I am trying to display real-time text in Tkinter after a Button command calls a function. The function should display a "timestamp" when PycURL receives "HTTP/1.1 200 OK". The function POSTs energy data to a server every 2 minutes.
Pseudocode, a basic example, and/or general discussion should get me headed in the rig... | [
"Found the answer in the book \"Programming Python\" by Mark Lutz. The following code is adapted from the book using info from Threads and Queues!\n import thread, Queue, time, random, poster\n from Tkinter import *\n\n dataQueue = Queue.Queue()\n\n def status(t):\n try:\n data = data... | [
1,
0
] | [] | [] | [
"python",
"real_time",
"text",
"tkinter"
] | stackoverflow_0007182084_python_real_time_text_tkinter.txt |
Q:
Numpy - Getting index positions by testing adjacent indexes
I am using numpy is Python. I have an image loaded up into numpy 2-dimensional array as:
[
[...], # row0
[...], # row1
[...], # row2
...
]
I need to get all the index positions of all pixels where either (only one of the following) north, south, ... | Numpy - Getting index positions by testing adjacent indexes | I am using numpy is Python. I have an image loaded up into numpy 2-dimensional array as:
[
[...], # row0
[...], # row1
[...], # row2
...
]
I need to get all the index positions of all pixels where either (only one of the following) north, south, east, or west adjacent pixels are of certain value. In my case if... | [
"If a is your original array, define a bunch of slices:\nfrom scipy import *\n\na = ones((12,22))\na[5,10] = a[5,12] = 0\n\na_ = a[1:-1, 1:-1]\naE = a[1:-1, 0:-2]\naW = a[1:-1, 2:]\naN = a[0:-2, 1:-1]\naS = a[ 2:, 1:-1]\n\na4 = dstack([aE,aW,aN,aS])\nnum_adjacent_zeros = sum(a4 == 0, axis=2)\nprint num_adjacent_... | [
5,
3
] | [] | [] | [
"image_processing",
"numpy",
"python"
] | stackoverflow_0007204946_image_processing_numpy_python.txt |
Q:
Issue with monkeypatching methods and references
I was wondering if anyone could explain and offer a solution to this issue:
$ cat object-override-methods.py
class A:
def foo(self):
return 1
class B:
def foo(self):
return 1
for klass in A, B:
orig_foo = klass.foo
def foo(self):
... | Issue with monkeypatching methods and references | I was wondering if anyone could explain and offer a solution to this issue:
$ cat object-override-methods.py
class A:
def foo(self):
return 1
class B:
def foo(self):
return 1
for klass in A, B:
orig_foo = klass.foo
def foo(self):
return orig_foo(self) * 2
klass.foo = foo
... | [
"Because orig_foo is defined at global scope, you're trampling on its value each time round the loop. That trampled value is then shared by each of your new foo methods.\nA simple fix is to move the code into a function, like this:\ndef rebind_foo(klass):\n orig_foo = klass.foo\n def foo(self):\n retu... | [
2,
2
] | [] | [] | [
"monkeypatching",
"python"
] | stackoverflow_0007205180_monkeypatching_python.txt |
Q:
Multiple Context menus in PyQt based on mouse location
I have a window with multiple tables using QTableWidget (PyQt). I created a popup menu using the right click mouse and it works fine.
However, I need to create different popup menu based on which table the mouse is hovering over at the time the right mouse i... | Multiple Context menus in PyQt based on mouse location | I have a window with multiple tables using QTableWidget (PyQt). I created a popup menu using the right click mouse and it works fine.
However, I need to create different popup menu based on which table the mouse is hovering over at the time the right mouse is clicked. How can I get the mouse to tell me which table it... | [
"One way is to subclass QTableWidget and then implement your own contextMenuEvent method. Then you can set different handling of the context menu event for each of your instances. Here's a small example.\nfrom PyQt4 import QtGui, QtCore\nimport sys\n\nclass MyTableWidget(QtGui.QTableWidget):\n\n def __init__(s... | [
7
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0007196919_pyqt_python_qt.txt |
Q:
Python can't list my directory
I have this code in my Bottle app to list a directory full of files:
[Post(name[:-3]) for name in os.listdir("posts")]
On my local computer, it's fine. But on my server I am consistently getting this error:
OSError: [Errno 2] No such file or directory: 'posts'
os.listdir('.') and $... | Python can't list my directory | I have this code in my Bottle app to list a directory full of files:
[Post(name[:-3]) for name in os.listdir("posts")]
On my local computer, it's fine. But on my server I am consistently getting this error:
OSError: [Errno 2] No such file or directory: 'posts'
os.listdir('.') and $ ls reports that the directory is th... | [
"The first thing that comes to mind is permissions -- make sure that your permissions are set so that the app has at least read access. listdir will still say that something exists, even if it can't read it.\nNext thought is that looks like a relative path -- are you sure that the relative path is correct? I know t... | [
0
] | [] | [] | [
"bottle",
"directory",
"file",
"operating_system",
"python"
] | stackoverflow_0007205308_bottle_directory_file_operating_system_python.txt |
Q:
(python) matplotlib pyplot show() .. blocking or not?
I have run into this trouble with show() over and over again, and I'm sure I'm doing something wrong but not sure of the 'correct' way to do what I want.
And [I think] what I want is some way to block in the main thread until an event happens in the GUI threa... | (python) matplotlib pyplot show() .. blocking or not? | I have run into this trouble with show() over and over again, and I'm sure I'm doing something wrong but not sure of the 'correct' way to do what I want.
And [I think] what I want is some way to block in the main thread until an event happens in the GUI thread, something like this works the first time:
from matplotli... | [
"Couple ideas of varying quality:\nIf you don't like s being a global variable, you could make onclick() a callable object attach it to that.\nYour callback could acquire/release a lock to control program flow (little dirty).\nYou could actively poll s to control program flow (very dirty).\nYou can manually control... | [
2,
1,
0
] | [] | [] | [
"blocking",
"events",
"matplotlib",
"python"
] | stackoverflow_0006187603_blocking_events_matplotlib_python.txt |
Q:
Accessing table data created through manytomanyfield in django
I have this model file in which a user can own any number of farms and admin can create a charge and put it on one or many farms.The problem is that i want to access the table created through ManyToManyField in Charges model.I want to select only those... | Accessing table data created through manytomanyfield in django | I have this model file in which a user can own any number of farms and admin can create a charge and put it on one or many farms.The problem is that i want to access the table created through ManyToManyField in Charges model.I want to select only those rows of manytomanyfield that are related to a single user.
suppose... | [
"Considering that the charge Id is 3383 and that the user is mike you can get those 2 related rows by using this \nmikes_farm_list = FarmOwner.Objects.filter(owner=\"Mike\").values_list('farms', flat=True)\nCharges.Objects.filter(chargeId=3383, farms__in=mikes_farm_list)\n\n",
"mike = Farm.objects.get(farmNo=\"Mi... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007202953_django_django_models_django_templates_django_views_python.txt |
Q:
Python import problem
I have some problem, that look like some spaces in my understanding how python does import modules. For example i have module which called somemodule with two submodules a.py and b.py.
content of a.py:
from somemodule.b import b
def a():
b()
print "I'am A"
content b.py
from somemod... | Python import problem | I have some problem, that look like some spaces in my understanding how python does import modules. For example i have module which called somemodule with two submodules a.py and b.py.
content of a.py:
from somemodule.b import b
def a():
b()
print "I'am A"
content b.py
from somemodule.a import a
def b():
... | [
"You've got a circular reference. You import module a which then imports module b. But module b imports function a from module a. But at the time it tries to do so, a has not been defined. Remember that Python import effectively executes the module.\nThe solution would appear to be to move the function definitions ... | [
6,
3
] | [] | [] | [
"import",
"python"
] | stackoverflow_0007205507_import_python.txt |
Q:
matplotlib: change axes
I have an array of measurements m, taken every minute. I plot these measurements against time by simply saying
import pylab as pl
pl.plot(range(len(m)), m)
this gives me minutes on the x-axis (just because I have measurements in minutes and range(len(m)) gives me integers). How do I quickl... | matplotlib: change axes | I have an array of measurements m, taken every minute. I plot these measurements against time by simply saying
import pylab as pl
pl.plot(range(len(m)), m)
this gives me minutes on the x-axis (just because I have measurements in minutes and range(len(m)) gives me integers). How do I quickly change the labeling of the ... | [
"Sorry rather than xlabels you need to create an axis and us ax.set_xticklabels:\nfrom matplotlib.pyplot import figure\nfig = figure()\nax = fig.add_subplot(111)\n\n\ndef mk_labels(vals):\n labels = []\n for i in vals:\n if i % 60 == 0:\n labels.append(\"Some new special label\")\n el... | [
3,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007205826_matplotlib_python.txt |
Q:
Replacing %20 with underscores in a URL using Python and web2py
Inside this code I have an 'args' value which is 'title.title', this value displays in my URL.
How do I make the url read like this: "index.html/something_something" instead how how it displays now, which is: "index.html/something%20something".
def l... | Replacing %20 with underscores in a URL using Python and web2py | Inside this code I have an 'args' value which is 'title.title', this value displays in my URL.
How do I make the url read like this: "index.html/something_something" instead how how it displays now, which is: "index.html/something%20something".
def livesearch():
'''Auto completes the search query'''
partialstr... | [
"The %20 is a replacement for a single white space, so you should replace spaces with underscores before passing them to URL:\ntitle.title.replace(' ', '_')\n\n",
"Elaborating on FB's answer: URL() invokes url lib.quote on the args portion of your URL, which does the %-escaping of spaces and other special charact... | [
2,
1
] | [] | [] | [
"python",
"url",
"web2py"
] | stackoverflow_0007200411_python_url_web2py.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.