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:
Auto filling polymorphic table on save or on delete in django
Am working on an project in which I made an app "core" it will contain some of the reused models across my projects, most of those are polymorphic models (Generic content types) and will be linked to different models.
Example below am trying to create ... | Auto filling polymorphic table on save or on delete in django | Am working on an project in which I made an app "core" it will contain some of the reused models across my projects, most of those are polymorphic models (Generic content types) and will be linked to different models.
Example below am trying to create audit model and will be linked to several models which may require ... | [
"You can override the save() method of Poll model or you can use Django Signals\nto do it.\ntry something like: \ndef save(self, *args, **kwargs,request): \n super(ModelName, self).save(*args, **kwargs)\n ## followed by your code\n\nyou can save your model instance using \nmodelinstance.save(request)\n\n... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004530284_django_python.txt |
Q:
Python Twisted Client Connection Lost
I have this twisted client, which connects with a twisted server having an index. I ran this client from command-line. It worked fine. Now I modified it to run in loop (see main()) so that I can keep querying. But the client runs only once. Next time it simply says connection ... | Python Twisted Client Connection Lost | I have this twisted client, which connects with a twisted server having an index. I ran this client from command-line. It worked fine. Now I modified it to run in loop (see main()) so that I can keep querying. But the client runs only once. Next time it simply says connection lost \n Connection lost - goodbye!.
What a... | [
"You don't quite understand how the Twisted reactor works.\nreactor.run() is starting up the reactor's event-loop --- it's a blocking call that loops \"forever\".\nSee http://twistedmatrix.com/documents/10.2.0/core/howto/reactor-basics.html for various reactor-related topics.\n"
] | [
4
] | [] | [] | [
"python",
"twisted",
"twisted.client",
"twisted.internet",
"twisted.web"
] | stackoverflow_0004530845_python_twisted_twisted.client_twisted.internet_twisted.web.txt |
Q:
How to receive an email on server? Better using Python or Perl
I've checked so many articles, but can't find one for server to server email receiving. I want to write a program or some code just acts as an email receiver, not SMTP server or something else.
Let's suppose I have a domain named example.com, and a gma... | How to receive an email on server? Better using Python or Perl | I've checked so many articles, but can't find one for server to server email receiving. I want to write a program or some code just acts as an email receiver, not SMTP server or something else.
Let's suppose I have a domain named example.com, and a gmail user user@gmail.com sends me an email to admin@example.com, or a ... | [
"http://docs.python.org/library/smtpd.html\nhttp://www.doughellmann.com/PyMOTW/smtpd/\n",
"In Perl:\nNet::SMTP libraries (including Net::SMTP::Server).\nHere's an example of using it: http://wiki.nil.com/Simple_SMTP_server_in_PERL\n",
"\"reveive\" is not a word. I'm really not sure if you mean \"receive\" or \"... | [
2,
1,
1,
1
] | [] | [] | [
"email",
"perl",
"python"
] | stackoverflow_0004530323_email_perl_python.txt |
Q:
Shallow copy, why does the list not change
I am trying to understand the difference between shallow copy and deep copy in python. I read many posts here and they have been helpful. However, I still don't understand the difference well. Can someone please explain the reason for the result below. The result that I d... | Shallow copy, why does the list not change | I am trying to understand the difference between shallow copy and deep copy in python. I read many posts here and they have been helpful. However, I still don't understand the difference well. Can someone please explain the reason for the result below. The result that I do not understand is indicated in the comments.
... | [
"In Python, object's field keep reference to object. So when you assign the new list in your exemple, you're changing the object that is referenced by the field, not its content. Before the affectation, the listofvalues property of both object where referencing the same list, but after the affectation, they are ref... | [
7,
3
] | [] | [] | [
"copy",
"python"
] | stackoverflow_0004530978_copy_python.txt |
Q:
Get binary data from audio impulses
I have IR sensor which have TRS connector and I can record my remotes signals into audio.
Now I want to control my computer with TV remote, but I don't have any clue how to compare audio input with pre-recorded audio. But after I realized that these audio waves contains only som... | Get binary data from audio impulses | I have IR sensor which have TRS connector and I can record my remotes signals into audio.
Now I want to control my computer with TV remote, but I don't have any clue how to compare audio input with pre-recorded audio. But after I realized that these audio waves contains only some kind data (binary) I can turn these int... | [
"The this is quite easy if you can forgo the real time requirement: just save the data as a .wav file, and then read it in using Python's wave module.\nHere's an example of how to read a wav file in Python,\nimport wave\n\nw = wave.open(\"myfile.wav\", \"rb\")\nbinary_data = w.readframes(w.getnframes())\nw.close()\... | [
5
] | [] | [] | [
"audio",
"fft",
"python"
] | stackoverflow_0004526895_audio_fft_python.txt |
Q:
Python Interactive Shell - SyntaxError with print
I am new to Python.
I installed Python on my Windows 2003 Virtual Machine; Launched the Python Shell; Typed the following code -
print "Hello World"
And it spit right back at me the following
SyntaxError: invalid syntax
Here are some other following statements... | Python Interactive Shell - SyntaxError with print | I am new to Python.
I installed Python on my Windows 2003 Virtual Machine; Launched the Python Shell; Typed the following code -
print "Hello World"
And it spit right back at me the following
SyntaxError: invalid syntax
Here are some other following statements
>>> x = 10
>>> print x
SyntaxError: invalid syntax... | [
"Duh! My mistake. \nprint(x)\n\nis the command. \nSorry folks!\n"
] | [
4
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004531083_python_python_3.x.txt |
Q:
why does this python script wait till the timer thread is executed?
from threading import Timer
def startTimer():
t = Timer(10.0, foo, ['hello world', 'tell me more'] )
t.start()
print 'Timer function invoked'
print 'function exit'
def foo(msg, msg2):
print 'foo was executed'
print msg
print msg2
... | why does this python script wait till the timer thread is executed? | from threading import Timer
def startTimer():
t = Timer(10.0, foo, ['hello world', 'tell me more'] )
t.start()
print 'Timer function invoked'
print 'function exit'
def foo(msg, msg2):
print 'foo was executed'
print msg
print msg2
if __name__ == '__main__':
startTimer()
print 'end of program'
I'... | [
"Timer is just a thread and Python waits for all non-daemonic threads before stopping the interpreter.\n\nA thread can be flagged as a “daemon\n thread”. The significance of this flag\n is that the entire Python program\n exits when only daemon threads are\n left. The initial value is inherited\n from the crea... | [
20
] | [] | [] | [
"execution",
"python"
] | stackoverflow_0004531164_execution_python.txt |
Q:
Query by non-ascii characters
I am using Python, on Google App Engine platform.
Let's say I have in my Data Store the following code :
class names(db.Model):
name = db.StringProperty(multiline=True)
and there are names like :
name1 = Beyoncé
name2 = El Súper Clásico
with non-ascii charachters.
When I make a ... | Query by non-ascii characters | I am using Python, on Google App Engine platform.
Let's say I have in my Data Store the following code :
class names(db.Model):
name = db.StringProperty(multiline=True)
and there are names like :
name1 = Beyoncé
name2 = El Súper Clásico
with non-ascii charachters.
When I make a query like :
q_1 = names.all().fil... | [
"There should be no problems with exact matches when correctly decoding input strings (that you get from web request parameters) and correctly encoding output strings (that you save in GAE data storage) in Unicode.\nI've tried this snippet in the GAE SDK Interactive Console and it works:\nfrom google.appengine.ext ... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004530930_google_app_engine_python.txt |
Q:
Data from XML to Python list
Is it possible to store data from an XML file to a list in python. For example I have an XML file with the following content:
<brochure>
<onlinePath>http://EEE</onlinePath>
<downloadPath>http://YYY</downloadPath>
<Name>ABC</Name>
<AAA>
<P>JPG</P>
<Q>JPG</Q>
</AAA>
</broch... | Data from XML to Python list | Is it possible to store data from an XML file to a list in python. For example I have an XML file with the following content:
<brochure>
<onlinePath>http://EEE</onlinePath>
<downloadPath>http://YYY</downloadPath>
<Name>ABC</Name>
<AAA>
<P>JPG</P>
<Q>JPG</Q>
</AAA>
</brochure>
<brochure>
<onlinePath>http:/... | [
"import lxml\n\nxml = \"\"\"\n<brochures>\n <brochure>\n <onlinePath>http://EEE</onlinePath>\n <downloadPath>http://YYY</downloadPath>\n <Name>ABC</Name>\n <AAA>\n <P>JPG</P>\n <Q>JPG</Q>\n </AAA>\n </brochure>\n <brochure>\n <onlinePath>http:... | [
9,
4,
1,
0,
0,
0
] | [] | [] | [
"python",
"storage",
"xml"
] | stackoverflow_0004525735_python_storage_xml.txt |
Q:
Data integration problem - How to integrate similar entities
I have a database which has very similar rows within the same table. Those rows are similar because they have nearly equal column values. I need to integrate those corresponding rows into one single row.
For example, those two users (u1 and u2) should be... | Data integration problem - How to integrate similar entities | I have a database which has very similar rows within the same table. Those rows are similar because they have nearly equal column values. I need to integrate those corresponding rows into one single row.
For example, those two users (u1 and u2) should be integrated:
u1 = User(name = "William Henry Gates III",
... | [
"Considered something like Refine?\n"
] | [
3
] | [] | [] | [
"data_integration",
"edit_distance",
"java",
"python",
"stemming"
] | stackoverflow_0004531433_data_integration_edit_distance_java_python_stemming.txt |
Q:
BufferedReader in Python 2.x vs Python 3.x
I have a program that runs in Python 2 and Python 3, but there is a drastic difference in speed. I understand a number of internal changes were made in the switch, but the difference in io.BufferedReader are really high. In both versions, I use io.BufferedReader because t... | BufferedReader in Python 2.x vs Python 3.x | I have a program that runs in Python 2 and Python 3, but there is a drastic difference in speed. I understand a number of internal changes were made in the switch, but the difference in io.BufferedReader are really high. In both versions, I use io.BufferedReader because the main program loop only needs data one byte at... | [
"To give you a fuller answer, one would need to see your code (or, better, an executable precis of your code).\nHowever a partial answer can be gleaned from your profile output: io.py suggests that \"Python 2\" (for avoidance of doubt, give the actual version numbers) is implementing BufferedReader in Python, where... | [
6,
4
] | [] | [] | [
"bufferedreader",
"performance",
"python",
"python_3.x"
] | stackoverflow_0004531147_bufferedreader_performance_python_python_3.x.txt |
Q:
How to make Universal Feed Parser only parse feeds?
I'm trying to get content from external feeds on my Django web site with Universal Feed Parser. I want to have some user error handling, e.g. if the user supplies a URL that is not a feed. When I tried how feedparser responds to faulty input, I was surprised to s... | How to make Universal Feed Parser only parse feeds? | I'm trying to get content from external feeds on my Django web site with Universal Feed Parser. I want to have some user error handling, e.g. if the user supplies a URL that is not a feed. When I tried how feedparser responds to faulty input, I was surprised to see that feedparser does not throw any Exceptions at all. ... | [
"Acoording to feedparser documentation, in the Bozo Detection section:\n\nUniversal Feed Parser can parse feeds whether they are well-formed XML or not. However, since some applications may wish to reject or warn users about non-well-formed feeds, Universal Feed Parser sets the bozo bit when it detects that a feed ... | [
6
] | [] | [] | [
"feedparser",
"python"
] | stackoverflow_0004530685_feedparser_python.txt |
Q:
Send one-way message to all threads in Python
I need to send information to every thread that's running in my program, and every thread has to process that information.
I can't do it using a regular queue, because that way once one thread removes the data from the queue all the other threads won't be able to see i... | Send one-way message to all threads in Python | I need to send information to every thread that's running in my program, and every thread has to process that information.
I can't do it using a regular queue, because that way once one thread removes the data from the queue all the other threads won't be able to see it anymore.
What's the best way of achieving this?
| [
"One way is to have a queue for each thread, and the function that broadcasts the information is responsible for inserting the message into the queue of every thread.\nThis is similar to the way message queues work in Windows, for example. Each thread that does GUI operations has an associated message queue, indepe... | [
4
] | [] | [] | [
"events",
"multithreading",
"python",
"queue"
] | stackoverflow_0004531564_events_multithreading_python_queue.txt |
Q:
Automatically import all modules in the current directory into python interactive interpreter
Coming from a Matlab background, I wanted to write small functions in python, and test them individually in the interpreter. However, every time I start the interpreter, I have to import all the modules. In contrast, with... | Automatically import all modules in the current directory into python interactive interpreter | Coming from a Matlab background, I wanted to write small functions in python, and test them individually in the interpreter. However, every time I start the interpreter, I have to import all the modules. In contrast, with matlab all you do is give it the path to the directory and you can execute any matlab function thr... | [
"Try autoimp. Example from the webpage:\n>>> from autoimp import *\n>>> os.stat('.')\n>>> Image.open('test.bmp')\n>>> pylab.plot([1,2],[3,4])\n>>> scipy.linalg.eig([[1,2],[3,4]])\n\n",
"I also consider myself a MATLAB user who is converting to Python. \"ipython -pylab\" (from a unix shell or mac terminal shell) ... | [
7,
0
] | [] | [] | [
"import",
"matlab",
"module",
"python"
] | stackoverflow_0004530763_import_matlab_module_python.txt |
Q:
Exception handling while iterating over Python queues
I've got a bunch of queues stored in the global globqueue array. I now want to iterate over all these queues and get all the items inside of them.
I'm having a few problems with getting the items from the queue, though.
I'm using .get_nowait(), which will throw... | Exception handling while iterating over Python queues | I've got a bunch of queues stored in the global globqueue array. I now want to iterate over all these queues and get all the items inside of them.
I'm having a few problems with getting the items from the queue, though.
I'm using .get_nowait(), which will throw an "Empty" exception if there is nothing in the queue. I t... | [
"You are catching ValueError but the call raises Empty. Try changing your except handler to catch the Empty exception instead.\nfrom _queue import Empty\n\nif __name__ == '__main__':\n try:\n item = item.get_nowait()\n # do some work\n except Empty:\n pass # handle error\n\n"
] | [
5
] | [] | [] | [
"exception",
"python",
"queue"
] | stackoverflow_0004531728_exception_python_queue.txt |
Q:
Android Emulator Keyboard
I'm using the Android 2.2 SDK emulator to test out the Scripting Layer for Android and have one annoyance.
When you launch a Python interpreter and start to type code it appears that the parentheses key isn't mapped properly. When I hit the key on the PC keyboard I get ^[[20~ instead. Wh... | Android Emulator Keyboard | I'm using the Android 2.2 SDK emulator to test out the Scripting Layer for Android and have one annoyance.
When you launch a Python interpreter and start to type code it appears that the parentheses key isn't mapped properly. When I hit the key on the PC keyboard I get ^[[20~ instead. What am I missing?
| [
"Looks like the Control-K button actually toggles the left-ALT key on the PC to mimic the virtual keyboard left-ALT.\n"
] | [
0
] | [] | [] | [
"android",
"python",
"sl4a"
] | stackoverflow_0004369261_android_python_sl4a.txt |
Q:
How to use Python with different SOCKS 5 Proxies?
The following is what a hacker always does.
I have a list of SOCKS5 proxies and a list of username/password combos. I want to test the username/password list with different SOCKS5 proxies for a website www.example.com/login.html.
I am using Python 2.5 on CentOS 5.5... | How to use Python with different SOCKS 5 Proxies? | The following is what a hacker always does.
I have a list of SOCKS5 proxies and a list of username/password combos. I want to test the username/password list with different SOCKS5 proxies for a website www.example.com/login.html.
I am using Python 2.5 on CentOS 5.5.
How can I use socksipy or other modules?
Could you pl... | [
"you can trying using pycurl \nimport pycurl\nc = pycurl.Curl()\nc.setopt(pycurl.URL, 'www.example.com/login.php')\npycurlConnect.setopt(pycurl.POSTFIELDS, POST_DATA)\nc.setopt(pycurl.PROXY, 'yourproxy')\nc.setopt(pycurl.PROXYPORT, 8080)\nc.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)\nc.perform()\n\nThe POST_... | [
4
] | [] | [] | [
"command_line",
"linux",
"proxy",
"python"
] | stackoverflow_0004531648_command_line_linux_proxy_python.txt |
Q:
TypeError: unhashable type: 'dict', when dict used as a key for another dict
I have this piece of code:
for element in json[referenceElement].keys():
When I run that code, I get this error:
TypeError: unhashable type: 'dict'
What is the cause of that error and what can I do to fix it?
A:
From the error, I inf... | TypeError: unhashable type: 'dict', when dict used as a key for another dict | I have this piece of code:
for element in json[referenceElement].keys():
When I run that code, I get this error:
TypeError: unhashable type: 'dict'
What is the cause of that error and what can I do to fix it?
| [
"From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).\n>>> d1, d2 = {}, {}\n>>> d1[d2] = 1\nTraceback (most recent call last):\n File \"<input>\", line 1, in <module>\... | [
77,
1
] | [] | [] | [
"hash",
"json",
"python"
] | stackoverflow_0004531941_hash_json_python.txt |
Q:
What's the logical value of "string" in Python?
I erroneously wrote this code in Python:
name = input("what is your name?")
if name == "Kamran" or "Samaneh":
print("That is a nice name")
else:
print("You have a boring name ;)")
It always prints out "That is a nice name" even when the input is neither "Kam... | What's the logical value of "string" in Python? | I erroneously wrote this code in Python:
name = input("what is your name?")
if name == "Kamran" or "Samaneh":
print("That is a nice name")
else:
print("You have a boring name ;)")
It always prints out "That is a nice name" even when the input is neither "Kamran" nor "Samaneh".
Am I correct in saying that it c... | [
"Any non empty string in Python (and most other languages) is true as are all non-zero numbers and non-empty lists, dictionaries, sets and tuples.1\nA nicer way to do what you want is:\nname = input(\"what is your name?\")\nif name in (\"Kamran\", \"Samaneh\"):\n print(\"That is a nice name\")\nelse:\n print(... | [
13,
7,
2,
2,
0
] | [
"Evidently, it must be:\nname = raw_input(\"what is your name?\")\n\nnot\nname = input(\"what is your name?\")\n\n.\nWhat you wrote is like:\nif (name == \"Kamran\" or \"Samaneh\")\n\nAnother good expression is:\nif name == (\"Kamran\" or \"Samaneh\")\n\nBut I also prefer if name in (\"Kamran\" or \"Samaneh\") as a... | [
-2
] | [
"boolean",
"casting",
"python",
"string"
] | stackoverflow_0004531794_boolean_casting_python_string.txt |
Q:
How do you make an identifier out of concatenated strings in Python 3
Basically I want to turn a string in to an identifier for an object like so:
count = 0
for i in range(50):
count += 1
functionToMakeIdentifier("foo" + str(count)) = Object(init_variable)
I want to make a series of objects with names like ... | How do you make an identifier out of concatenated strings in Python 3 | Basically I want to turn a string in to an identifier for an object like so:
count = 0
for i in range(50):
count += 1
functionToMakeIdentifier("foo" + str(count)) = Object(init_variable)
I want to make a series of objects with names like foo1, foo2, foo3, foo4, foo5, etc... But I don't know how to turn those str... | [
"Do this instead:\nfoos = [Object(init_variable) for _ in range(50)]\nprint(foos[0]) # first item\n\nYou now have a list of 50 Object items.\nMaybe, if you really want to use these foo1 strings you could do\nfoo_dict = {'foo%d'.format(i) : Object(init_variable) for i in range(1,51)]\nprint(foo_dict['foo1'])\n\n",
... | [
3,
3,
2,
1,
0
] | [] | [] | [
"identifier",
"python",
"python_3.x"
] | stackoverflow_0004531906_identifier_python_python_3.x.txt |
Q:
Applescript Bundle and Python
Basically i want to launch a Python script from within an applescript bundle
So i have bundled the file (Controller.py) within the bundle
The script i need to run is
do shell script "PYTHONPATH=/Applications/gtk/inst/lib/python2.6/site-packages python /path/to/Controller.py
I want to... | Applescript Bundle and Python | Basically i want to launch a Python script from within an applescript bundle
So i have bundled the file (Controller.py) within the bundle
The script i need to run is
do shell script "PYTHONPATH=/Applications/gtk/inst/lib/python2.6/site-packages python /path/to/Controller.py
I want to access Controller.py from within t... | [
"Use path to me to get the location of the AppleScript bindle, then find your script relative to it:\nset controller_script to (path to me as string) & \"Contents:Resources:Controller.py\"\ndo shell script \"PYTHONPATH=/Applications/gtk/inst/lib/python2.6/site-packages python \" & (quoted form of POSIX path of cont... | [
5
] | [] | [] | [
"applescript",
"bash",
"osx_snow_leopard",
"python",
"shell"
] | stackoverflow_0004531662_applescript_bash_osx_snow_leopard_python_shell.txt |
Q:
Inherit from a built-in class
I would like to add some methods to the datetime.datetime object. It seems that we can only do that by inheriting from it and adding this new method. The problem is that this method need to update the day/month/year values of the base class and that i can't call the base init method w... | Inherit from a built-in class | I would like to add some methods to the datetime.datetime object. It seems that we can only do that by inheriting from it and adding this new method. The problem is that this method need to update the day/month/year values of the base class and that i can't call the base init method with the new parameters.
How can I d... | [
"You can call the base class __init__ method.\nclass Foo(datetime.datetime):\n def __init__(self, argument):\n datetime.datetime.__init__(self, argument)\n\nThe key point here is that you need to call the __init__ method explicitly and you need to manually supply the first self argument that Python norma... | [
2
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0004532027_inheritance_python.txt |
Q:
any simple way to OCR an image?
It basically only uses the font Times New Roman and is a small rectangle (220x86). Text is uniform, same size, no strange characters, AZaz09, eight different colors (one per line).
is there any easy way to do this?
A:
The best Open Source OCR is Tesseract. It is trainable, so y... | any simple way to OCR an image? | It basically only uses the font Times New Roman and is a small rectangle (220x86). Text is uniform, same size, no strange characters, AZaz09, eight different colors (one per line).
is there any easy way to do this?
| [
"The best Open Source OCR is Tesseract. It is trainable, so you can target times new roman, although it already comes with training for similar text. You can use it with python by using os.popen()\n"
] | [
1
] | [] | [] | [
"ocr",
"php",
"python"
] | stackoverflow_0004532047_ocr_php_python.txt |
Q:
Meaning of >> in print statement
I was wondering what does print >> dbfile, key mean in python. What is the >> supposed to do?
A:
It should be noted that the >> syntax is specific to Python 2.x. In Python 3.x, that syntax goes away and code needs to be changed as follows:
print >>f, "Hello world" # Py... | Meaning of >> in print statement | I was wondering what does print >> dbfile, key mean in python. What is the >> supposed to do?
| [
"It should be noted that the >> syntax is specific to Python 2.x. In Python 3.x, that syntax goes away and code needs to be changed as follows:\nprint >>f, \"Hello world\" # Python 2.x\n\nprint(\"Hello world\", file=f) # Python 3.x\n\n",
"This redirects print to a file (in this case, dbfile).\nthe... | [
16,
9,
1
] | [] | [] | [
"python",
"python_2.x",
"syntax"
] | stackoverflow_0004532147_python_python_2.x_syntax.txt |
Q:
How to start a Python ipython shell, automatically run inside it a few commands, and leave it open?
I tried
echo "print 'hello'" | ipython
Which runs the command but ipython immediately exits afterwards.
Any ideas? Thanks!
Edit:
I actually need to pass the command into the interactive Django shell, e.g.:
echo "pr... | How to start a Python ipython shell, automatically run inside it a few commands, and leave it open? | I tried
echo "print 'hello'" | ipython
Which runs the command but ipython immediately exits afterwards.
Any ideas? Thanks!
Edit:
I actually need to pass the command into the interactive Django shell, e.g.:
echo "print 'hello'" | python manage.py shell
so the -i switch gimel suggested doesn't seem to work (the shell s... | [
"Use the same flag used by the standard interpreter, -i.\n\n-i\nWhen a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file is not read.\n\nA Linux example, using th... | [
5,
2,
0,
0
] | [] | [] | [
"bash",
"ipython",
"python",
"shell"
] | stackoverflow_0003035006_bash_ipython_python_shell.txt |
Q:
No connection could be made because the target machine actively refused it
I've tried to connect to my local machine every time I try and run my program.
I am a nub, so it's probably a simple mistake somewhere.
def connect(self):
self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.conn.conne... | No connection could be made because the target machine actively refused it | I've tried to connect to my local machine every time I try and run my program.
I am a nub, so it's probably a simple mistake somewhere.
def connect(self):
self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.conn.connect((self.host,self.port))
That is the code causing the error.
The host and port... | [
"It's because you haven't opened the port you are trying to connect to, nothing is listening there. If you're trying to connect to a web or ftp server, start it first. If you're trying to connect to another port, you need to write a server application too.\n"
] | [
4
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0004532335_python_sockets.txt |
Q:
Awkward python class behaviour?
I have the following simple code:
class Node:
pass
def make_node(value):
n = Node
n.value = value
return n
if __name__ == '__main__':
list = range(100)
random.shuffle(list)
nodes = []
for i in range(len(list)):
nodes.append(make_node(list[i]... | Awkward python class behaviour? | I have the following simple code:
class Node:
pass
def make_node(value):
n = Node
n.value = value
return n
if __name__ == '__main__':
list = range(100)
random.shuffle(list)
nodes = []
for i in range(len(list)):
nodes.append(make_node(list[i]))
for n in nodes:
print... | [
"I think you want to call the Node constructor:\n n = Node()\n\nOtherwise, the assignment to n.value is the same as assigning to Node.value, which sets an attribute of the class, not the object you wanted to create. By returning the Node class object itself, your nodes list contains a bunch of references to the ... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004532577_python.txt |
Q:
Get wrong PATH_INFO after rewriting in lighttpd
In my lighttpd config file, I have a rewrite rule like this:
$HTTP["host"] == "sub.example.com" {
url.rewrite = (
"^/(.*)" => "/sub/$1"
)
}
So when a user visits http://sub.example.com, she's actually visiting http://example.com/sub.
The problem is that the... | Get wrong PATH_INFO after rewriting in lighttpd | In my lighttpd config file, I have a rewrite rule like this:
$HTTP["host"] == "sub.example.com" {
url.rewrite = (
"^/(.*)" => "/sub/$1"
)
}
So when a user visits http://sub.example.com, she's actually visiting http://example.com/sub.
The problem is that the PATH_INFO seems wrong,
URL: http://sub.example.c... | [
"If you want pre-rewritten URI try REQUEST_URI. Generally if you have rewrite rules it is the rewritten path you actually want otherwise there is no purpose to the rewriting.\n"
] | [
2
] | [] | [] | [
"lighttpd",
"pathinfo",
"python"
] | stackoverflow_0004532546_lighttpd_pathinfo_python.txt |
Q:
What is the benefit(s) of having 'else clause' for the while loop in python?
Any code after while loop will execute when the condition in the while loop becomes False. It is the same for the code in the 'else clause' section of while loop in python. So What's the advantage of having 'else' in the while loop?
A:
... | What is the benefit(s) of having 'else clause' for the while loop in python? | Any code after while loop will execute when the condition in the while loop becomes False. It is the same for the code in the 'else clause' section of while loop in python. So What's the advantage of having 'else' in the while loop?
| [
"else will not execute if there is a break statement in the loop. From the docs:\n\nThe while statement is used for\n repeated execution as long as an\n expression is true:\nwhile_stmt ::= \"while\" expression \":\" suite\n [\"else\" \":\" suite]\n\nThis repeatedly tests the expression\n and, if ... | [
7,
1,
0,
0
] | [] | [] | [
"controls",
"python"
] | stackoverflow_0004532770_controls_python.txt |
Q:
Cannot programmatically move mouse cursor in VirtualBox
I'm trying to use this Python code:
import math
import win32api
for i in xrange(500):
x = 500 + math.sin(math.pi * i / 100) * 500
y = 500 + math.cos(i) * 100
x, y = int(x), int(y)
win32api.SetCursorPos((x, y))
time.sleep(.01)
taken from h... | Cannot programmatically move mouse cursor in VirtualBox | I'm trying to use this Python code:
import math
import win32api
for i in xrange(500):
x = 500 + math.sin(math.pi * i / 100) * 500
y = 500 + math.cos(i) * 100
x, y = int(x), int(y)
win32api.SetCursorPos((x, y))
time.sleep(.01)
taken from here to move the mouse cursor in an XP VirtualBox. The mouse i... | [
"It looks like you forgot to import the win32api.\n"
] | [
0
] | [] | [] | [
"python",
"virtualbox",
"winapi"
] | stackoverflow_0004533117_python_virtualbox_winapi.txt |
Q:
Windows application using Python
I am used to Windows application development using C# .Net. Now that I got interested in Python I need to know the best way to create a Windows application that has stuffs like minimizing to System tray, nice ide like visual studio that has GUI way of developing apps. Any suggestio... | Windows application using Python | I am used to Windows application development using C# .Net. Now that I got interested in Python I need to know the best way to create a Windows application that has stuffs like minimizing to System tray, nice ide like visual studio that has GUI way of developing apps. Any suggestions pls?
| [
"Check out this list on GUI programming with Python.\nScroll down to GUI Design Tools and IDEs. Take your pick, there are lots of choices.\nWhich one is the best? That depends on what you want to do. But for the purposes you mentioned, all should suffice. \n",
"For C# programmer is IronPython good choice. \n",
... | [
5,
4,
0
] | [] | [] | [
"ide",
"python",
"windows_applications"
] | stackoverflow_0004533229_ide_python_windows_applications.txt |
Q:
Is Pyramid ready/recommended for prime time?
I was wandering around testing various options for my new personal project, ranging from PHP, to node.js, to Haskell. I feel most comfortable with Python, though, so I thought I'd go back to it in the end.
I've taken a second look at frameworks like Django, but given I ... | Is Pyramid ready/recommended for prime time? | I was wandering around testing various options for my new personal project, ranging from PHP, to node.js, to Haskell. I feel most comfortable with Python, though, so I thought I'd go back to it in the end.
I've taken a second look at frameworks like Django, but given I mostly enjoy SQL and I don't want an ORM, I though... | [
"BFG, which is the precursor has been used in \"primetime\" for a while now. There are in Pyramid some additions to BFG to make it more \"Pylonic\", and these may not be ready, but I would say that they will be soon.\nSo if you are worried, you can use BFG for now. The migration to Pyramid should be simple once you... | [
24,
13
] | [
"I asked this question before: Should I use Pylons or Pyramid?\nPylons will continue and version 2 of it will be released. Pyramid is like Pylons distribution migrated with other components.\n"
] | [
-2
] | [
"pylons",
"pyramid",
"python"
] | stackoverflow_0004482879_pylons_pyramid_python.txt |
Q:
trying to teach myself python, stuck during one chapter of this book, very simple question
from sys import argv
script, user_name=argv
that's part of the program i'm trying to run and I don't think any more is necessary. I try and run it by typing into terminal:
python exl.py script user_name
That should work, ... | trying to teach myself python, stuck during one chapter of this book, very simple question | from sys import argv
script, user_name=argv
that's part of the program i'm trying to run and I don't think any more is necessary. I try and run it by typing into terminal:
python exl.py script user_name
That should work, right? I know this is pretty simple, but I am really stuck. Also I don't completely understand w... | [
"sys.argv[0] is the name of your script (in this case exl.py). You don't pass the literal \"script\".\nYou can easily try this with a test program:\nimport sys\nprint sys.argv\n\n",
"sys.argv is a list containing the name of the script and each of the command line parameters. In the case of running python exl.p... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004533198_python.txt |
Q:
Python unittest (using SQLAlchemy) does not write/update database?
I am puzzled at why my Python unittest runs perfectly fine without actually updating the database.
I can even see the SQL statements from SQLAlchemy and step through the newly created user object's email --
...INFO sqlalchemy.engine.base.Engine.0x.... | Python unittest (using SQLAlchemy) does not write/update database? | I am puzzled at why my Python unittest runs perfectly fine without actually updating the database.
I can even see the SQL statements from SQLAlchemy and step through the newly created user object's email --
...INFO sqlalchemy.engine.base.Engine.0x...954c INSERT INTO users (user_id, user_name, email, ...) VALUES (%(user... | [
"Not knowing SQLAlchemy, but that sounds like the test is being run in a transaction and that this transaction is never committed. Either explicitly rolled back, or automatically rolled back when the connection closes.\n"
] | [
7
] | [] | [] | [
"postgresql",
"pyramid",
"python",
"sqlalchemy",
"unit_testing"
] | stackoverflow_0004533245_postgresql_pyramid_python_sqlalchemy_unit_testing.txt |
Q:
Python URLRetrieve Limit Rate and Resume Partial Download
I'm using the code from this thread to limit my download rate.
How do I incorporate partial downloads resuming with the rate limiting code? The examples I've found use urlopen instead of urlretrieve, and the RateLimit class depends on urlretrieve.
I'd li... | Python URLRetrieve Limit Rate and Resume Partial Download | I'm using the code from this thread to limit my download rate.
How do I incorporate partial downloads resuming with the rate limiting code? The examples I've found use urlopen instead of urlretrieve, and the RateLimit class depends on urlretrieve.
I'd like to have an external function that controls the partial downl... | [
"May be able to use PyCurl instead:\ndef curl_progress(total, existing, upload_t, upload_d):\n try:\n frac = float(existing)/float(total)\n except:\n frac = 0\n print \"Downloaded %d/%d (%0.2f%%)\" % (existing, total, frac)\n\ndef curl_limit_rate(url, filename, rate_limit):\n \"\"\"Rate li... | [
4
] | [] | [] | [
"limit",
"python",
"rate",
"resume_download"
] | stackoverflow_0004533304_limit_python_rate_resume_download.txt |
Q:
What tool do you use to minify your javascript?
I'm using Django. Is there a Django plugin that does this?
A:
Here are some of these tools: http://djangopackages.com/grids/g/asset-managers/
A:
You could use jscompress but this is only for JavaScript files a simple search on django compressor brought up this h... | What tool do you use to minify your javascript? | I'm using Django. Is there a Django plugin that does this?
| [
"Here are some of these tools: http://djangopackages.com/grids/g/asset-managers/\n",
"You could use jscompress but this is only for JavaScript files a simple search on django compressor brought up this https://github.com/mintchaos/django_compressor\n"
] | [
1,
0
] | [] | [] | [
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0004533412_django_javascript_jquery_python.txt |
Q:
Python hangs in futex calls
I have a Python daemon running in production. It employs between 7 and 120 threads. Recently the smallest instance (7 threads) started to show hangs while all other instances never showed this kind of problem. Attaching strace to the python process shows that all threads are calling fut... | Python hangs in futex calls | I have a Python daemon running in production. It employs between 7 and 120 threads. Recently the smallest instance (7 threads) started to show hangs while all other instances never showed this kind of problem. Attaching strace to the python process shows that all threads are calling futex FUTEX_WAIT_PRIVATE, so they ar... | [
"The observation was slightly incorrect. One thread wasn't calling futex, but instead swapping while holding the gil. Since the machine in question is low hardware this swapping took very long and seemed to be a deadlock. The underlying problem is a memory leak. :-(\n",
"Dear Helmut, I've the same problem with on... | [
4,
2
] | [] | [] | [
"deadlock",
"debugging",
"futex",
"multithreading",
"python"
] | stackoverflow_0003905883_deadlock_debugging_futex_multithreading_python.txt |
Q:
Python with PIL and Libjpeg on Leopard
I'm having trouble getting pictures supported with PIL - it throws me this:
IOError: decoder jpeg not available
I installed PIL from binary, not realizing I needed libjpeg.
I installed libjpeg and freetype2 through fink.
I tried to reinstall PIL using instructions from http... | Python with PIL and Libjpeg on Leopard | I'm having trouble getting pictures supported with PIL - it throws me this:
IOError: decoder jpeg not available
I installed PIL from binary, not realizing I needed libjpeg.
I installed libjpeg and freetype2 through fink.
I tried to reinstall PIL using instructions from http://timhatch.com/ (bottom of the page)
Downl... | [
"I had the similar 'jpeg decoder problem' recently when deploying a django project on a product RHEL box that required PIL. I downloaded PIL, and ran 'python setup.py install' instantly, and was happy that everything was working, until I bumped into the problem. Solution: libjpeg was already installed on the system... | [
1,
1,
0,
0,
0
] | [] | [] | [
"libjpeg",
"python",
"python_imaging_library",
"python_install"
] | stackoverflow_0000249388_libjpeg_python_python_imaging_library_python_install.txt |
Q:
Is there an alternative python function does as PHP include() function?
My python project path /project and these are its files :
/project/test.py
/project/templates/
/project/includes/
/project/includes/config.py
# config.py
import os
template_path = os.path.join(os.path.dirname(__file__), "templates")
when I u... | Is there an alternative python function does as PHP include() function? | My python project path /project and these are its files :
/project/test.py
/project/templates/
/project/includes/
/project/includes/config.py
# config.py
import os
template_path = os.path.join(os.path.dirname(__file__), "templates")
when I used execute() function to include config.py from test.py , the /project/incl... | [
"Create a (empty) file __init__.py in includes.\nIn test.py, call config.py by doing an import.\nfrom includes import config \nSo if there is a function say foo in config, you will call it like:\nconfig.foo()\nRefer to the documentation (as pointed out by The MYYN)\n",
"In Python you don't include, you import, al... | [
3,
3,
2
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0004533953_import_module_python.txt |
Q:
Is using readlines in Python bad code?
I got downvoted for an answer using file.readlines. The critic said that using readlines is crap code (along with other very rude statements).
Is it so bad?
A:
I assume that the problem was the fact that readlines() loads the whole file into memory, which - theoretically - ... | Is using readlines in Python bad code? | I got downvoted for an answer using file.readlines. The critic said that using readlines is crap code (along with other very rude statements).
Is it so bad?
| [
"I assume that the problem was the fact that readlines() loads the whole file into memory, which - theoretically - can be a lot.\nA lazy approach (iterating over the file and reading progressively as needed) is indeed better in terms of memory usage. Not sure about efficiency, though.\n",
"No, readlines is fine. ... | [
9,
6,
6
] | [
"No, it is not. On the other hand, you can use xreadlines to have faster code.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0004533884_python.txt |
Q:
Cached re.compile failed to match problem on GAE
Today I tried to cache re.compile to speed up my testing. Something got weird:
I used three cached re.compile:
re_cache1=re.compile(regexp_string1)
re_cache2=re.compile(regexp_string2)
re_cache3=re.compile(regexp_string3)
def mytest():
m = re_cache1.split(data)
... | Cached re.compile failed to match problem on GAE | Today I tried to cache re.compile to speed up my testing. Something got weird:
I used three cached re.compile:
re_cache1=re.compile(regexp_string1)
re_cache2=re.compile(regexp_string2)
re_cache3=re.compile(regexp_string3)
def mytest():
m = re_cache1.split(data)
if m:
for item in m:
m2 = re_cache2.search... | [
"Keep in mind: the re module caches internally anyway. The difference between:\nre_cache1 = re.compile(regexp_string1)\n...\nre_cache1.search(data)\n\nand\nre.search(regexp_string1, data)\n\nis one dictionary lookup. It's usually not worth the extra bookkeeping to cache your own compiled regexes.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004533998_google_app_engine_python.txt |
Q:
Handling reCaptcha forms?
I'm trying to write a simple program that logs on to a site, does something and logs out. The problem is that the login form has three inputs: username, password and a recaptcha. I input all of them manually. The problem is I don't know how to display the captcha image or how to send the ... | Handling reCaptcha forms? | I'm trying to write a simple program that logs on to a site, does something and logs out. The problem is that the login form has three inputs: username, password and a recaptcha. I input all of them manually. The problem is I don't know how to display the captcha image or how to send the text.
Can someone explain how t... | [
"It is unreasonable to except that someone will post a complete solution for your problem.\nHere are the steps, just start by trying to complete them, post questions if you get stuck.\nvery generally speaking:\n\nGet the content of the site (use the urllib2 to fetch the page)\nParse the recaptcha image link and dow... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004533879_python.txt |
Q:
Or statements problem in python
Or statements in python do not seem to work as in other languages since:
-1 < 0 | 0<0
returns False (should return true since -1<0 is True)
What is the problem?
A:
There are two problems: First, the precedence of the operators is not what you expect. You can always add parens to... | Or statements problem in python | Or statements in python do not seem to work as in other languages since:
-1 < 0 | 0<0
returns False (should return true since -1<0 is True)
What is the problem?
| [
"There are two problems: First, the precedence of the operators is not what you expect. You can always add parens to make it explicit:\n>>> (-1 < 0) | (0 < 0)\nTrue\n\nAlso, single-pipe is a logical or that evaluates both of its arguments all the time. The equivalent of other languages's pipe-pipe is or:\n>>> -1 ... | [
9,
1
] | [] | [] | [
"boolean_logic",
"python"
] | stackoverflow_0004534151_boolean_logic_python.txt |
Q:
Reason for unintuitive UnboundLocalError behaviour 2
Following up on Reason for unintuitive UnboundLocalError behaviour (I will assume you've read it).
Consider the following Python script:
def f():
# a+=1 # 1
aa=a
aa+=1
# b+='b' # 2
bb=b
bb+='b'
c[0]+='c' # 3
... | Reason for unintuitive UnboundLocalError behaviour 2 | Following up on Reason for unintuitive UnboundLocalError behaviour (I will assume you've read it).
Consider the following Python script:
def f():
# a+=1 # 1
aa=a
aa+=1
# b+='b' # 2
bb=b
bb+='b'
c[0]+='c' # 3
c.append('c')
cc=c
cc.append('c')
d['d']=5... | [
"Unlike strings and integers, lists in Python are mutable objects. This means they are designed to be changed. The line\nc[0] += 'c'\n\nis identical to saying\nc.__setitem__(0, c.__getitem__(0) + 'c')\n\nwhich doesn't make any change to what the name c is bound to. Before and after this call, c is the same list – i... | [
3,
2
] | [] | [] | [
"global_variables",
"list",
"python",
"scope"
] | stackoverflow_0004534134_global_variables_list_python_scope.txt |
Q:
finding the greatest Fibonacci number within limited time in python
I need a code that calculates nth fibonacci number as well as giving me the time used to calculate it, in python.
def fib(n):
if n==0 or n==1: return 1
else: return fib(n-1)+fib(n-2)
The calculation of the number step must use a such meth... | finding the greatest Fibonacci number within limited time in python | I need a code that calculates nth fibonacci number as well as giving me the time used to calculate it, in python.
def fib(n):
if n==0 or n==1: return 1
else: return fib(n-1)+fib(n-2)
The calculation of the number step must use a such method.
| [
"This is a classic dynamic programming/recursion with memoization problem. Notice that in your code, you recursively call fib(x-1) a lot. This is a huge waste of effort: once you calculate it once, you should store it for later use so that you don't have to calculate it again. In Python 3 you can do this with the g... | [
7,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004534486_python.txt |
Q:
How to Make Efficient Google-App-Engine Schema with Lots of BooleanPropertys
I'm building a GAE app that has objects with a lot of boolean properties. I want to be able to search through those properties making a query like (in psuedo-sql) "get items where X1=True, X2=False, X3=False and let X4 through X7 be eithe... | How to Make Efficient Google-App-Engine Schema with Lots of BooleanPropertys | I'm building a GAE app that has objects with a lot of boolean properties. I want to be able to search through those properties making a query like (in psuedo-sql) "get items where X1=True, X2=False, X3=False and let X4 through X7 be either true or false".
I have a model similar to the one shown below:
class JobModel(Ba... | [
"This may be a good opportunity for a StringListProperty.\nSet membership is a strength of the ListProperty.\nYou would need to provide a way to update and marshal the list but it could be efficient for your needs.\ndb.StringListProperty\nhas = ['401k:T', 'health_in:F', 'has_childcare:T']\n\nGQL Where Clause\n\"WHE... | [
4
] | [] | [] | [
"database_design",
"google_app_engine",
"python",
"schema"
] | stackoverflow_0004534376_database_design_google_app_engine_python_schema.txt |
Q:
Extracting tuple indices
I recently got hold of kinect. I'm using the python wrapper to play around. Now there are 2 functions which give the depth and the RGB values of a particular frame. I wish to extract all the rgb values which have a depth value of say greater than 'd'
(depth,_) = sync_get_depth()
(rgb,_) = ... | Extracting tuple indices | I recently got hold of kinect. I'm using the python wrapper to play around. Now there are 2 functions which give the depth and the RGB values of a particular frame. I wish to extract all the rgb values which have a depth value of say greater than 'd'
(depth,_) = sync_get_depth()
(rgb,_) = sync_get_video()
I iterate ... | [
"I don't know the Python kinect wrapper, so I can't tell you which library functions to use. But you should look at the zip function:\ndepths = [0, 1, 2, 3, 4]\ncolors = ['a', 'b', 'c', 'd', 'e']\n\n# Colors with an even depth\n[color for depth, color in zip(depths, colors) if depth % 2]\n\nGiven a some iterables, ... | [
1
] | [] | [] | [
"kinect",
"python"
] | stackoverflow_0004534674_kinect_python.txt |
Q:
Python module that implements ftps
I was wondering if anybody could point me towards a free ftps module for python.
I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.
thanks,
David.
A:
I believe you could use Twisted to ... | Python module that implements ftps | I was wondering if anybody could point me towards a free ftps module for python.
I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.
thanks,
David.
| [
"I believe you could use Twisted to implement FTPS by simply using its FTP implementation, but changing the FTPClient.connectFactory attribute to be a function that does something with connectSSL rather than connectTCP.\nAre you sure you want FTPS though? SFTP is a different, better, and much more popular protocol... | [
9,
7,
4,
3,
2,
0,
0
] | [] | [] | [
"ftps",
"python"
] | stackoverflow_0000207939_ftps_python.txt |
Q:
How to test python code on command line
While writing and testing a python method, I am currently using the following approach:
import foo as f
bar = f.bar()
bar.runMyMethodAndSeeIfItWorks()
If I change something in my method, and I need to retest it, I have to execute the following:
f = reload(foo)
bar = f.bar(... | How to test python code on command line | While writing and testing a python method, I am currently using the following approach:
import foo as f
bar = f.bar()
bar.runMyMethodAndSeeIfItWorks()
If I change something in my method, and I need to retest it, I have to execute the following:
f = reload(foo)
bar = f.bar()
bar.runMyMethodAndSeeIfItWorks()
I was wo... | [
"Write a real unit test, and run it from the command line. I find this is one of the most compelling reasons for adopting unit testing: you're going to need to try out your methods as you write them anyway, you might as well do it in a form that will be runnable for evermore after that.\n",
"You must be referrin... | [
8,
2,
0
] | [] | [] | [
"class",
"command_line",
"module",
"python",
"reload"
] | stackoverflow_0004534058_class_command_line_module_python_reload.txt |
Q:
Colon difference in Matlab and Python
What is the equivalent to someArray(:,1,1) in python from Matlab?
In python someArray[:][0][0] produces a different value
A:
someArray[:,0,0] is the Python NumPy equivalent of MATLAB's someArray(:,1,1). I've never figured out how to do it in pure Python, the colon slice op... | Colon difference in Matlab and Python | What is the equivalent to someArray(:,1,1) in python from Matlab?
In python someArray[:][0][0] produces a different value
| [
"someArray[:,0,0] is the Python NumPy equivalent of MATLAB's someArray(:,1,1). I've never figured out how to do it in pure Python, the colon slice operation is a total mystery to me with lists-of-lists.\n"
] | [
5
] | [] | [] | [
"arrays",
"matlab",
"python",
"syntax"
] | stackoverflow_0004535359_arrays_matlab_python_syntax.txt |
Q:
Excecuting methods within a Django project context? - Django
I need to execute e few methods within my Django project's context, in order to work with Models.
I know commands exists, but I would like to import these methods and execute them within Python code.
Any ideas?
A:
You only need to set your PYTHONPATH ... | Excecuting methods within a Django project context? - Django | I need to execute e few methods within my Django project's context, in order to work with Models.
I know commands exists, but I would like to import these methods and execute them within Python code.
Any ideas?
| [
"You only need to set your PYTHONPATH and DJANGO_SETTINGS_MODULE environment variables prior to calling the python interpreter. From then on you can import your models, call their methods, etc...\nexport PYTHONPATH=\"...include your site's apps path...\"\nexport DJANGO_SETTINGS_MODULE=\"mysite.settings\"\npython\n>... | [
2,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004534993_django_django_models_python.txt |
Q:
How do I get user email using Facebook Graph API in GAE Python?
I'm using Facebook Graph API on Google App Engine. I was able to fetch all the basic info from an user. However when I tried to fetch any user info that requires permission, email for exemple, it always appears as None. I've followed the whole tutoria... | How do I get user email using Facebook Graph API in GAE Python? | I'm using Facebook Graph API on Google App Engine. I was able to fetch all the basic info from an user. However when I tried to fetch any user info that requires permission, email for exemple, it always appears as None. I've followed the whole tutorial available at the developers blog.
Here's my code:
class User(db.Mod... | [
"Email is written on User creation. Maybe you are trying to access users that were created when you didn't have email permission, therefore the written email was None. Does the problem appear also for new User object?\n",
"Just gave up using facebook.py and facebookoauth.py and made my own OAuth 2 client using ur... | [
1,
1,
0
] | [] | [] | [
"authentication",
"facebook",
"facebook_graph_api",
"google_app_engine",
"python"
] | stackoverflow_0004005963_authentication_facebook_facebook_graph_api_google_app_engine_python.txt |
Q:
Django admin: What is the best way to add a custom list view?
I want to provide a custom view in the admin very similar to changelist_view(), but without the links to the edit form view. Users will be able to select the items in the list and apply actions just like in the change list form but they won't have acces... | Django admin: What is the best way to add a custom list view? | I want to provide a custom view in the admin very similar to changelist_view(), but without the links to the edit form view. Users will be able to select the items in the list and apply actions just like in the change list form but they won't have access to the edit form.
I think the structure in the ModelAdmin class ... | [
"The following custom ModelAdmin is the best solution I could come up with so far:\nclass UserModelAdmin(ModelAdmin):\n def get_urls(self):\n urls = super(UserModelAdmin, self).get_urls()\n info = self.model._meta.app_label, self.model._meta.module_name\n select_list_url = patterns('',\n ... | [
5,
3
] | [] | [] | [
"custom_view",
"django",
"django_admin",
"python"
] | stackoverflow_0004534268_custom_view_django_django_admin_python.txt |
Q:
PUT parameters not working in python / google app engine
i'm working on a simple RESTful webservice with python with the webapp framework on the google app engine.
Basically i'm sending all request via AJAX/jquery - for POST it works like a charm, but when I'm sending data with PUT, the parameters are empty / not... | PUT parameters not working in python / google app engine | i'm working on a simple RESTful webservice with python with the webapp framework on the google app engine.
Basically i'm sending all request via AJAX/jquery - for POST it works like a charm, but when I'm sending data with PUT, the parameters are empty / not processed.
this is my PUT:
$.ajax({
type: "PUT",
... | [
"The put method in your code is correctly invoked because as you can see, test is printed;\nwhat is not working is the parameter parsing, this problem is an open issue in the webob class.\nYou could try to parse the request.body to extract the query string.\ndef put(self):\n print \"test\"\n name = parse_body... | [
4
] | [] | [] | [
"google_app_engine",
"http",
"put",
"python",
"web_applications"
] | stackoverflow_0004535056_google_app_engine_http_put_python_web_applications.txt |
Q:
Instantiating classes in python - setting attributes
Coming from a Java background, I want a class to have certain attributes and set them in the constructor.
Currently I use the global keyword
eg.
def class A():
global attribute1
global attribute2
__init__():
attribute1 = 1
attribute2 = 2
Is there a b... | Instantiating classes in python - setting attributes | Coming from a Java background, I want a class to have certain attributes and set them in the constructor.
Currently I use the global keyword
eg.
def class A():
global attribute1
global attribute2
__init__():
attribute1 = 1
attribute2 = 2
Is there a better way of doing this? Reason I am asking is because I a... | [
"The right way to do this is to add the attributes to the constructor and add them on your instance.\n>>> class A(object):\n... def __init__(self, attribute1, attribute2):\n... self.attribute1 = attribute1\n... self.attribute2 = attribute2\n...\n\n>>> a = A(1, 2)\n>>> a.attribute1\n1\n>>> a.attribu... | [
4
] | [] | [] | [
"attributes",
"constructor",
"global",
"java",
"python"
] | stackoverflow_0004535741_attributes_constructor_global_java_python.txt |
Q:
Getting the identifier name of an instance in python
I haven't found anything. I want to do this without passing the name inside the constructor.
class foo:
pass
something = foo()
I want each instance of foo to be aware of its initial identifier name. In this case the instance of foo() I created should be awar... | Getting the identifier name of an instance in python | I haven't found anything. I want to do this without passing the name inside the constructor.
class foo:
pass
something = foo()
I want each instance of foo to be aware of its initial identifier name. In this case the instance of foo() I created should be aware that its identifier is the string "something"
I am worki... | [
"Even if you could do this—which you can't—it would be an abuse of the language. For the sanity of whoever reads your code, please avoid hidden \"magic\" behavior. Python programmers would not expect their local variable names to be meaningful and actually be exposed to outside code.\n",
"You can't. Creation of a... | [
4,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0004535698_python.txt |
Q:
OpenGL Shadow Mapping using GLSL
I am trying to get shadow mapping working using GLSL. Unfortunately my depth render results are unusable even I have a pretty decent depth buffer precision. It is rendering like wireframe, following image may be a better description.
I am also including a test case(single file incl... | OpenGL Shadow Mapping using GLSL | I am trying to get shadow mapping working using GLSL. Unfortunately my depth render results are unusable even I have a pretty decent depth buffer precision. It is rendering like wireframe, following image may be a better description.
I am also including a test case(single file including shader), only dependency is pyop... | [
"solved it, it is the binding issue, in shadow pass fragment shader I simply checked a boolean value to disable reading the texture, but that was not enough. I should have unbind the texture before shadow pass, that is mentioned in documentation as: \nQuote from OpenGL Refence:\nSpecial precautions need to be taken... | [
3
] | [
"// shadowCoord.z -= 0.0003;\n\nYour commented out shadow bias is the solution to your z-fighting problem. Change it to some value e.g. += 0.0005 and you should be good to go.\n"
] | [
-2
] | [
"glsl",
"opengl",
"pyopengl",
"python",
"shader"
] | stackoverflow_0004484605_glsl_opengl_pyopengl_python_shader.txt |
Q:
Using map() on a _set in a template?
I have two models like this:
class KPI(models.Model):
"""KPI model to hold the basic info on a Key Performance Indicator"""
title = models.CharField(blank=False, max_length=100)
description = models.TextField(blank=True)
target = models.FloatField(blank=False, n... | Using map() on a _set in a template? | I have two models like this:
class KPI(models.Model):
"""KPI model to hold the basic info on a Key Performance Indicator"""
title = models.CharField(blank=False, max_length=100)
description = models.TextField(blank=True)
target = models.FloatField(blank=False, null=False)
group = models.ForeignKey(K... | [
"You should probably be doing the logic to decide which instances should be shown in a particular request in the view function, rather than in the template. \n"
] | [
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004535858_django_django_templates_python.txt |
Q:
Connect to mysql
Possible Duplicate:
How do I connect to a MySQL Database in Python?
There is a way to connect python with a mysql db?
I found something, but seems to is only for windows and I'm working with linux.
A:
Use MySQL-Python.
I also strongly advise having a look at SQLAlchemy, an ORM that allows you ... | Connect to mysql |
Possible Duplicate:
How do I connect to a MySQL Database in Python?
There is a way to connect python with a mysql db?
I found something, but seems to is only for windows and I'm working with linux.
| [
"Use MySQL-Python.\nI also strongly advise having a look at SQLAlchemy, an ORM that allows you to write once for all major sql's including MySQL. It's a bit more complex, but the flexibility is a serious advantage.\n",
"You can use the MySQL-Python package. Search your disto's package database first before instal... | [
4,
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004535529_mysql_python.txt |
Q:
Converting code from the Tornado python web framework to work independently
I need to use a library which depends on the Tornado Python Web Framework, but I cannot have it dependent on Tornado.
Does anyone have any advice when converting code over from this framework?
Has anything similar been attempted before (... | Converting code from the Tornado python web framework to work independently | I need to use a library which depends on the Tornado Python Web Framework, but I cannot have it dependent on Tornado.
Does anyone have any advice when converting code over from this framework?
Has anything similar been attempted before (and the result published)?
| [
"The normal way to create web-server-independent Python web apps is to code it to WSGI, optionally using a web framework. This way it can be used with any WSGI container.\n"
] | [
3
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0004535261_python_tornado.txt |
Q:
Python Gui: Which framework would be the best to display arrays
I was wondering which gui library would be appropriate to display a maze (a NxN array) and being able to fill each cell with a colour to represent states of that cell. I will also be generating a path from one part of the maze to another, and would li... | Python Gui: Which framework would be the best to display arrays | I was wondering which gui library would be appropriate to display a maze (a NxN array) and being able to fill each cell with a colour to represent states of that cell. I will also be generating a path from one part of the maze to another, and would like to display such path.
I need to choose a Gui framework for this. ... | [
"pygame is a nice library for making games but could also be useful here. You can start simple by just drawing squares. Later you can change the code to use sprites if you want to make it more visually appealing.\nCheck out some of the examples of maze games written using pygame.\n"
] | [
3
] | [] | [] | [
"arrays",
"maze",
"python",
"user_interface"
] | stackoverflow_0004536030_arrays_maze_python_user_interface.txt |
Q:
Python: Best practice for including a version number in an app?
I have a PyQt application that reads and writes data files. I am including a 'version number' in each file written. This is a simple number similar to: 1.2 or something (major and minor versions).
I am doing this so that I can change the format of t... | Python: Best practice for including a version number in an app? | I have a PyQt application that reads and writes data files. I am including a 'version number' in each file written. This is a simple number similar to: 1.2 or something (major and minor versions).
I am doing this so that I can change the format of these data files in future versions and then still correctly parse the... | [
"Many open source projects (e.g. numpy, fabric) have a module called \"version\", which contains version information in top-level variables. See e.g. fabric's version file.\n",
"First, version the data format separately from the app, if not already doing so. Second, have separate classes for newer versions of the... | [
4,
4,
1
] | [] | [] | [
"global_variables",
"python",
"version"
] | stackoverflow_0004535895_global_variables_python_version.txt |
Q:
String concatenation in Python and commas
I'm having a hard time figuring out how the native data types interact in Python. Here, I am trying to concatenate different parts of the lyrics into one long string which will be returned as output.
The error I receive upon trying run the script is:
TypeError: cannot con... | String concatenation in Python and commas | I'm having a hard time figuring out how the native data types interact in Python. Here, I am trying to concatenate different parts of the lyrics into one long string which will be returned as output.
The error I receive upon trying run the script is:
TypeError: cannot concatenate 'str' and 'tuple' objects.
I put ever... | [
"Don't use string concatenation for this. Put the strings in a list and join the list at the end. I'd also suggest using str.format.\nverse = \"{0} bottles of beer on the wall, {0} bottles of beer.\\n\" \\\n \"Take one down and pass it around, {1} bottles of beer on the wall.\\n\"\n\ndef bottles_of_beer_lyri... | [
6,
4,
3,
2,
0
] | [] | [] | [
"python",
"string",
"tuples"
] | stackoverflow_0004535944_python_string_tuples.txt |
Q:
Choosing MooTools over Google closure?
I am in a process to select javascript library for our new web application. This app is not very UI heavy but has forms, reports, search, calendars, tabs and target multiple countries like most web apps.
We are a tiny team. Biggest concern is maintainability and readability ... | Choosing MooTools over Google closure? | I am in a process to select javascript library for our new web application. This app is not very UI heavy but has forms, reports, search, calendars, tabs and target multiple countries like most web apps.
We are a tiny team. Biggest concern is maintainability and readability of the code.
We are Python programmers. Aft... | [
"This shouldn't be the accepted answer, but it may help a little. I've had to make a similar choice recently -- but for me it was between YUI3 and JQuery. My main priority was agility and modularity, which tipped me toward YUI3. Though a few things make me think a little every day about my choice:\n\nCode Assist... | [
5,
1
] | [] | [] | [
"google_closure",
"javascript",
"mootools",
"python"
] | stackoverflow_0004526906_google_closure_javascript_mootools_python.txt |
Q:
Linear Interpolation. How to implement this algorithm in C ? (Python version is given)
There exists one very good linear interpolation method. It performs linear interpolation requiring at most one multiply per output sample. I found its description in a third edition of Understanding DSP by Lyons. This method inv... | Linear Interpolation. How to implement this algorithm in C ? (Python version is given) | There exists one very good linear interpolation method. It performs linear interpolation requiring at most one multiply per output sample. I found its description in a third edition of Understanding DSP by Lyons. This method involves a special hold buffer. Given a number of samples to be inserted between any two input ... | [
"Interpolation in the sense of \"signal sample rate increase\"\n... or i call it, \"upsampling\" (wrong term, probably. disclaimer: i have not read Lyons'). I just had to understand what the code does and then re-write it for readability. As given it has couple of problems: \na) it is inefficient - two loops is ok ... | [
9,
2,
1,
0,
0
] | [] | [] | [
"algorithm",
"c",
"math",
"python",
"signal_processing"
] | stackoverflow_0004459930_algorithm_c_math_python_signal_processing.txt |
Q:
Structured python docstrings, IDE-friendly
In PHP I was used to PHPdoc syntax:
/** Do something useful
@param first Primary data
@return int
@throws BadException
*/
function($first){ ...
— kinda short useful reference: very handy when all you need is just to recall 'what's that??', especially for 3rd-party lib... | Structured python docstrings, IDE-friendly | In PHP I was used to PHPdoc syntax:
/** Do something useful
@param first Primary data
@return int
@throws BadException
*/
function($first){ ...
— kinda short useful reference: very handy when all you need is just to recall 'what's that??', especially for 3rd-party libraries. Also, all IDEs can display this in popup... | [
"I use epydoc. It supports comments in reStructured Text, and it generates HTML documentation from those comments (akin to javadoc).\n",
"The numpydoc standard is well-defined, based around reStructuredText (which is standard within the python ecosystem), and has Sphinx integration. It should be relatively strai... | [
2,
1
] | [] | [] | [
"docstring",
"python",
"python_2.x"
] | stackoverflow_0004536437_docstring_python_python_2.x.txt |
Q:
Cant get the child dir in django hosting (alwaysdata.com)
this is my file :
mysite
templates
homepage.html
accounts
a.html
login_view.html
i can get the homepage.html and accounts\a.html on 127.0.0.1:8000
but in http://zjm1126.alwaysdata.net , i can only get the homepage... | Cant get the child dir in django hosting (alwaysdata.com) | this is my file :
mysite
templates
homepage.html
accounts
a.html
login_view.html
i can get the homepage.html and accounts\a.html on 127.0.0.1:8000
but in http://zjm1126.alwaysdata.net , i can only get the homepage.html ,and cant get
the accounts\a.html ,
this is my code :
r... | [
"Did you mean accounts/a.html?\n"
] | [
0
] | [] | [] | [
"django",
"hosting",
"python",
"templates"
] | stackoverflow_0004536834_django_hosting_python_templates.txt |
Q:
How can I query a numpy array to find the minimum multiplication of the first two columns?
For example: test_array = numpy.array([[10, 1], [2, 12], [3, 5]]) and I'd like to do something along the lines of test_array.where( min(test_array[0] * test_array[1]) ) and have it return that same structure that numpy.where... | How can I query a numpy array to find the minimum multiplication of the first two columns? | For example: test_array = numpy.array([[10, 1], [2, 12], [3, 5]]) and I'd like to do something along the lines of test_array.where( min(test_array[0] * test_array[1]) ) and have it return that same structure that numpy.where returns pointing to [10, 1].
| [
"Unless I'm misunderstanding something, you just want numpy.argmin...\nE.g.\nimport numpy as np\nx = np.array([[10, 1], [2, 12], [3, 5]])\nmulti_cols = x[:,0] * x[:,1]\nprint x[multi_cols.argmin()]\n\n"
] | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004536815_numpy_python.txt |
Q:
i want to read the data from website the website contains downloadable files and then i want to send it to the oracle using python script how?
I want to read the data from website the website contains down-loadable files and then i want to send it to the oracle using python script how??
the website is WWW.EODDATA... | i want to read the data from website the website contains downloadable files and then i want to send it to the oracle using python script how? | I want to read the data from website the website contains down-loadable files and then i want to send it to the oracle using python script how??
the website is WWW.EODDATA.COM
| [
"Look into urllib and some sort of xml parser like xml.dom.minidom. I've never messed with oracle so I don't know a good library but it looks like oracle provides a python library: http://wiki.oracle.com/page/Python\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004536962_python.txt |
Q:
Creating a Better Tabbed Interface in Django
I've been trying to create a tabbed interface using Django. The current effort (which works fine) is having each template have the header hard-coded in, with the selected tab given the "selected" CSS attribute. Of course, this is a massive violation of DRY and I'm looki... | Creating a Better Tabbed Interface in Django | I've been trying to create a tabbed interface using Django. The current effort (which works fine) is having each template have the header hard-coded in, with the selected tab given the "selected" CSS attribute. Of course, this is a massive violation of DRY and I'm looking to remedy it.
My current idea is adding a jQuer... | [
"I usually just pass in the selected tab in the context in each view that utilizes the tabs, and select the tab in a common header based on that value. \n",
"Update: The below link is broken now, however Django now has in built feature for comparing URLs now. Check this bug for more details.\nYou can create a te... | [
0,
0
] | [] | [] | [
"css",
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0004536346_css_django_javascript_jquery_python.txt |
Q:
ctypes import not working on python 2.5
I am trying to import ctypes, and I am using Python 2.5.5 installed using macports (on Mac OS X 10.6).
I get an error saying "ImportError: No module named _ctypes" (see details below). As I understand it ctypes is supposed to come preinstalled for python 2.5. Any suggestion... | ctypes import not working on python 2.5 | I am trying to import ctypes, and I am using Python 2.5.5 installed using macports (on Mac OS X 10.6).
I get an error saying "ImportError: No module named _ctypes" (see details below). As I understand it ctypes is supposed to come preinstalled for python 2.5. Any suggestions?
thanks,
Saurabh
Error details:
$ python
Py... | [
"The latest Mac OS X ships with Python 2.6. Try using that instead of macports. Importing ctypes works already on my system.\nPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import c... | [
1,
1,
0
] | [] | [] | [
"ctypes",
"macos",
"python",
"python_2.5"
] | stackoverflow_0004535725_ctypes_macos_python_python_2.5.txt |
Q:
python - how to pipe the output using popen?
I want to pipe output of my file using popen, how can I do that?
test.py:
while True:
print"hello"
a.py :
import os
os.popen('python test.py')
I want to pipe the output using os.popen.
how can i do the same?
A:
First of all, os.popen() is deprecated, use the su... | python - how to pipe the output using popen? | I want to pipe output of my file using popen, how can I do that?
test.py:
while True:
print"hello"
a.py :
import os
os.popen('python test.py')
I want to pipe the output using os.popen.
how can i do the same?
| [
"First of all, os.popen() is deprecated, use the subprocess module instead.\nYou can use it like this:\nfrom subprocess import Popen, PIPE\n\noutput = Popen(['command-to-run', 'some-argument'], stdout=PIPE)\nprint output.stdout.read()\n\n",
"Use the subprocess module, here is an example:\nfrom subprocess import P... | [
17,
12,
4
] | [] | [] | [
"popen",
"python"
] | stackoverflow_0004537259_popen_python.txt |
Q:
how to communicate with ror program in python
i have a application which use rails to do the CRUD operation,it's handy
now i want to write a crawler use python,after that i want to save the data to db,
so my question is how to python communicate with ror program?
A:
I don't have any idea about python or rails (o... | how to communicate with ror program in python | i have a application which use rails to do the CRUD operation,it's handy
now i want to write a crawler use python,after that i want to save the data to db,
so my question is how to python communicate with ror program?
| [
"I don't have any idea about python or rails (only grails :) but the easiest solution (if you don't want the python script to touch the DB) would be to implement a controller action for the REST PUT method in your rails application and call it from your python crawler with the crawled data.\nNow, all the rails cont... | [
1,
0
] | [] | [] | [
"python",
"rest",
"ruby_on_rails_3",
"web_services"
] | stackoverflow_0004537434_python_rest_ruby_on_rails_3_web_services.txt |
Q:
Problem accessing static variables from another thread
I've got a class
class KeyConstants:
VK_CTLR = 37
VK_SHIFT = 50
VK_ALT = 65
and some code using the class
class EventListener(threading.Thread)
... snip ...
def is_modkey(self, event):
return event.detail == KeyConstants.VK_CTRL
And... | Problem accessing static variables from another thread | I've got a class
class KeyConstants:
VK_CTLR = 37
VK_SHIFT = 50
VK_ALT = 65
and some code using the class
class EventListener(threading.Thread)
... snip ...
def is_modkey(self, event):
return event.detail == KeyConstants.VK_CTRL
And then I get AttributeError, KeyConstants does not have attri... | [
"I noticed that the attribute is defined as VK_CTLR but used as VK_CTRL (with R and L swapped)... Maybe it is just a typing error...\n",
"If you can access KeyConstants, you should be able to access it's attributes. The error is likely somewhere else.\n"
] | [
2,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004537355_multithreading_python.txt |
Q:
A good way to store this browser versions - Django/Postgresql
I have this data:
Firefox 3.6
There are 3 items
name
max version
min version
I am storing it this way:
class MyModel(models.Model):
browser_name = models.CharField(...)
browser_max_version = models.IntegerField(...)
browser_min_version ... | A good way to store this browser versions - Django/Postgresql | I have this data:
Firefox 3.6
There are 3 items
name
max version
min version
I am storing it this way:
class MyModel(models.Model):
browser_name = models.CharField(...)
browser_max_version = models.IntegerField(...)
browser_min_version = models.IntegerField(...)
or alternative
class Browser(models.Mo... | [
"You could make it parseable, but probably not indexable. For example, you could concatenate the values together separated by semicolons (or some other character), then simply split the string to get the values back. \"Firefox 3.6\" would become \"Firefox;3;6\". While this is somewhat easier to parse, it doesn't pr... | [
3,
0
] | [] | [] | [
"django",
"postgresql",
"python",
"sql"
] | stackoverflow_0004536276_django_postgresql_python_sql.txt |
Q:
Hide app from taskbar
I'm trying to get my application hidden to systray and the systray thing works fine, except my app won't disspaear from the taskbar. The icon seem to dissapear, but another icon pops up and when I click to show that window I get a windowframe but the contents aren't drawn.
def hideEvent(self,... | Hide app from taskbar | I'm trying to get my application hidden to systray and the systray thing works fine, except my app won't disspaear from the taskbar. The icon seem to dissapear, but another icon pops up and when I click to show that window I get a windowframe but the contents aren't drawn.
def hideEvent(self, event):
self.trayIcon.... | [
"You could try also calling the super-class' version of the method you override. Try something like\ndef hideEvent(self, event):\n self.trayIcon.show()\n return super(MyClass, self).hideEvent(event)\n\nwhere MyClass is the name of the class where you override the hideEvent meth\n",
"Your GUI event loop is s... | [
0,
0
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0003828807_pyqt4_python.txt |
Q:
Good examples of open source Google App Engine Django projects
I am looking for a good example of a Django / python based Google App Engine app to use a learning tool.
I have seen some of the other posts and they are mainly Java based and not really what I am looking for.
Any advice?
Thank you in advance,
Kent... | Good examples of open source Google App Engine Django projects | I am looking for a good example of a Django / python based Google App Engine app to use a learning tool.
I have seen some of the other posts and they are mainly Java based and not really what I am looking for.
Any advice?
Thank you in advance,
Kent
| [
"i didnt find an open source project but i think i found a good tutorial for you\nhttp://www.joeyb.org/blog/2009/05/28/django-based-blog-on-google-app-engine-tutorial-part-1\ni'll keep this post updated when i find more\n",
"Here you have an example of the google prediction api in python that uses appengine and D... | [
1,
1,
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004522570_django_google_app_engine_python.txt |
Q:
What's the difference between 'class A:' and 'class A(object):' in Python?
What's the difference between
class A:
pass
and
class B(object):
pass
? For some reason, in methods I can't use super(A, self) but super(B, self) works great. I guess there's no such peculiarity in Py3k :)
A:
In 2.x, the latter ... | What's the difference between 'class A:' and 'class A(object):' in Python? | What's the difference between
class A:
pass
and
class B(object):
pass
? For some reason, in methods I can't use super(A, self) but super(B, self) works great. I guess there's no such peculiarity in Py3k :)
| [
"In 2.x, the latter creates a new-style class. In 3.x, both have the same effect since old-style classes have been removed.\n",
"The first is an old style class. The second is a new-style class. See http://docs.python.org/tutorial/classes.html#multiple-inheritance for a good discussion of the difference. super() ... | [
6,
6,
1,
1
] | [] | [] | [
"class",
"inheritance",
"python",
"python_3.x"
] | stackoverflow_0004535966_class_inheritance_python_python_3.x.txt |
Q:
Optimized way of fetching parents with only latest child using django ORM
We want to fetch parent child in such a way that it gives me latest 10 parents with each having only one latest child record.
For example:
Category
- id
- name
- created_date
Item
- id
- name
- category
- created_date
Using above specifie... | Optimized way of fetching parents with only latest child using django ORM | We want to fetch parent child in such a way that it gives me latest 10 parents with each having only one latest child record.
For example:
Category
- id
- name
- created_date
Item
- id
- name
- category
- created_date
Using above specified model structure, I would like to fetch latest 10 categories along with latest... | [
"You can resort to raw SQL, and your query looks fine (just lacks an \"order by c.created_date desc\" before the limit in the end.\nThe subquery in the raw SQL solution is not much better than having a method returning the 10 last entries in the Category model, something like this (untested) sample:\nclass Category... | [
3,
0
] | [] | [] | [
"django",
"django_models",
"mysql",
"python",
"sqlite"
] | stackoverflow_0004529678_django_django_models_mysql_python_sqlite.txt |
Q:
Python, a function in a method
I have a method (__init__) in a class, and I want to use a function from the class in this method.
But when I want to run my program. I get: NameError: global name 'myfunction' is not defined
Someone, who knows what I have to do? :)
Thank you. But I have still a problem, because def... | Python, a function in a method | I have a method (__init__) in a class, and I want to use a function from the class in this method.
But when I want to run my program. I get: NameError: global name 'myfunction' is not defined
Someone, who knows what I have to do? :)
Thank you. But I have still a problem, because def myFunc(self, a): is a method and I ... | [
"class Myclass(object):\n def __init__(self, a):\n self.a = self.myFunc(a)\n\n def myFunc(self, a):\n return a+1\n\n",
"Then you don't have a function call in the method, but you have a method call in it.\nWhen creating a class you must specify the object when calling its methods:\n>>> class A... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004532595_python.txt |
Q:
Python NetworkX Increase circular graph size
Is it possible to increase the size of graphs generated with networkx? Currently, it always outputs 800x600.
How can I output a graph with a larger radius. Does it depend on my display size?
A:
Example page from NetworkX show that case:
http://networkx.lanl.gov/exampl... | Python NetworkX Increase circular graph size | Is it possible to increase the size of graphs generated with networkx? Currently, it always outputs 800x600.
How can I output a graph with a larger radius. Does it depend on my display size?
| [
"Example page from NetworkX show that case:\nhttp://networkx.lanl.gov/examples/drawing/circular_tree.html\nThese lines do square image 800x800px:\nplt.figure(figsize=(8,8))\nplt.axis('equal')\nplt.savefig('circular_tree.png')\n\n"
] | [
7
] | [] | [] | [
"graph",
"networkx",
"python"
] | stackoverflow_0004538241_graph_networkx_python.txt |
Q:
Concatenate values in a list (XML,Python)
i have trouble with my XML. What i have to do is concatenate values from a list that is extracted from an XML Example
<?xml version="1.0" encoding="UTF-8"?>
<locales>
<api-url>url</api-url>
<locale>
<market>AE</market>
<languages>
<language>ar</language>
... | Concatenate values in a list (XML,Python) | i have trouble with my XML. What i have to do is concatenate values from a list that is extracted from an XML Example
<?xml version="1.0" encoding="UTF-8"?>
<locales>
<api-url>url</api-url>
<locale>
<market>AE</market>
<languages>
<language>ar</language>
</languages>
</locale>
<locale>
<market>A... | [
"import lxml.etree as ET\nimport io\n\ncontent='''\\\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<locales>\n<api-url>url</api-url>\n<locale>\n <market>AE</market>\n <languages>\n <language>ar</language>\n </languages>\n</locale>\n<locale>\n <market>AM</market>\n <languages>\n <language... | [
5
] | [] | [] | [
"concatenation",
"python",
"xml"
] | stackoverflow_0004538589_concatenation_python_xml.txt |
Q:
IconView with one scrollbar
Good day!
I need an IconView widget with vertical (only) scrollbar. I put my IconView into ScrolledWindow and turned off the horizontal scrollbar. This way:
liststore = gtk.ListStore(gtk.gdk.Pixbuf)
for item in gtk.stock_list_ids():
liststore.append([self.render_icon(item, gtk.ICON_... | IconView with one scrollbar | Good day!
I need an IconView widget with vertical (only) scrollbar. I put my IconView into ScrolledWindow and turned off the horizontal scrollbar. This way:
liststore = gtk.ListStore(gtk.gdk.Pixbuf)
for item in gtk.stock_list_ids():
liststore.append([self.render_icon(item, gtk.ICON_SIZE_DIALOG)])
iconview = gtk.Ico... | [
"Should use\nscrolledwindow.add(iconview)\n\ninstead of 'add_with_viewport'\n"
] | [
2
] | [] | [] | [
"pygtk",
"python",
"scrollbar"
] | stackoverflow_0004538962_pygtk_python_scrollbar.txt |
Q:
mouseMoveEvent not working in QGraphicsScene
I am trying to implement a paint program in PyQt4. In the QGraphicsScene, I use the mouseMoveEvent to draw lines connecting the consecutive mouse co-ordinates.
The code is as follows:
def mouseMoveEvent(self, event):
x1 = event.pos().x()
... | mouseMoveEvent not working in QGraphicsScene | I am trying to implement a paint program in PyQt4. In the QGraphicsScene, I use the mouseMoveEvent to draw lines connecting the consecutive mouse co-ordinates.
The code is as follows:
def mouseMoveEvent(self, event):
x1 = event.pos().x()
y1 = event.pos().y()
self.addLine(self.... | [
"I figured out the problem. The above code is fine, except that event.pos() does not work in QGraphicsScene. Inorder to capture the mouseEvent's co-ordinates in QGraphicsScene, we must use event.scenePos()\n"
] | [
0
] | [] | [] | [
"drawing",
"pyqt",
"python"
] | stackoverflow_0004104260_drawing_pyqt_python.txt |
Q:
wxPython: Change a buttons text in a wx.FileDialog
I have a wx.FileDialog (with the wx.FD_OPEN flag) & I would like to know if I can (& how) I could change the button in the bottom right of the FileDialog from "Open" to "Create" or "Delete", etc.
What I am doing is I have a button with the text "Delete Portfolio",... | wxPython: Change a buttons text in a wx.FileDialog | I have a wx.FileDialog (with the wx.FD_OPEN flag) & I would like to know if I can (& how) I could change the button in the bottom right of the FileDialog from "Open" to "Create" or "Delete", etc.
What I am doing is I have a button with the text "Delete Portfolio", when pressed it opens a FileDialog & allows the user to... | [
"Yeah, I agree with Arafangion. wxPython uses the native widgets and can only manipulate them in whatever way that native widgets allow. You would need to create a custom dialog to do this.\n",
"If you are using the native controls, which wx tends to use, then you probably can't.\n"
] | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004529991_python_wxpython.txt |
Q:
Can I do a reduce on a list comprehension into two lists, based on two values?
I've got the following code.
sum_review = reduce(add,[book['rw'] for book in books])
sum_rating = reduce(add,[book['rg'] for book in books])
items = len(books)
avg_review = sum_review/items
avg_rating = sum_rating/items
What I'd like i... | Can I do a reduce on a list comprehension into two lists, based on two values? | I've got the following code.
sum_review = reduce(add,[book['rw'] for book in books])
sum_rating = reduce(add,[book['rg'] for book in books])
items = len(books)
avg_review = sum_review/items
avg_rating = sum_rating/items
What I'd like is this.
sum_review,sum_rating = reduce(add,([book['rw'],[book['rg']) for book in boo... | [
"I'd avoid using reduce here. For something so simple use sum:\nsum_review = sum(book['rw'] for book in books)\nsum_rating = sum(book['rg'] for book in books)\n\nIn my opinion this simpler version doesn't need refactoring to remove redundancy. With just two items (rw and rg) I think it's best to just leave it as it... | [
9,
3,
2,
2,
1
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0004539704_python_python_2.5.txt |
Q:
add a python module with out root permission
I meet a problem when I try to install module omniORB&omniORBpy to a system, I don't have the root permission so I use --prefix to installed them to my user dir.
my question is : how can I make python load this module? I try add my user path to sys.path, but it still do... | add a python module with out root permission | I meet a problem when I try to install module omniORB&omniORBpy to a system, I don't have the root permission so I use --prefix to installed them to my user dir.
my question is : how can I make python load this module? I try add my user path to sys.path, but it still doesn't work.
Br,
J.K.
| [
"You can add it to the search path by adding the directory to the environment variable PYTHONPATH or by adding it to sys.path in your Python script. Both work; if they don't, then you're using the wrong path.\n",
"I usually use the --user option instead of --prefix, since it installs it in ${HOME}/.local/lib/pyth... | [
4,
1
] | [] | [] | [
"module",
"python"
] | stackoverflow_0004537975_module_python.txt |
Q:
How to get alert for shutdown of python process/abrupt termination?
How we can hook up a code inside a python process so that it should send an alert in case of shutdown of process/abrupt termination ?
A:
Use Supervisor Daemon
A:
It's not clear what exactly you mean. Shutdown/abort of the process itself? Or ... | How to get alert for shutdown of python process/abrupt termination? | How we can hook up a code inside a python process so that it should send an alert in case of shutdown of process/abrupt termination ?
| [
"Use Supervisor Daemon\n",
"It's not clear what exactly you mean. Shutdown/abort of the process itself? Or of a child process?\n\nShutdown/abort of a process itself: Have a look at Pythons atexit module; here you can register a callback for when your program cleanly exits. But there is absolutely no way for y... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004538695_python.txt |
Q:
Django - How to use URLconfs with an apps folder?
I'm following the tutorial on the Django website but I'm trying to expand upon it. I like the organizational scheme of putting all of your apps in an "apps" folder. I'm trying to figure out the proper way to include urls.py in order to get everything to link toge... | Django - How to use URLconfs with an apps folder? | I'm following the tutorial on the Django website but I'm trying to expand upon it. I like the organizational scheme of putting all of your apps in an "apps" folder. I'm trying to figure out the proper way to include urls.py in order to get everything to link together.
Here's my root urls.py:
from django.conf.urls.d... | [
"The way you currently have it set up... the URLs for polls would be:\nhttp://your.url.here/polls/polls/235/results/\n\nThis is probably not what you want. The include function in the urlpatterns in the root urls.py file specifies \"polls/\" as a prefix to all urlpatterns in the polls app. Therefore, in the polls... | [
2,
0,
0
] | [] | [] | [
"django",
"python",
"urlconf"
] | stackoverflow_0004540013_django_python_urlconf.txt |
Q:
WSGI server that processes request despite client disconnecting? - Python
I need to find a stable wsgi server that won't stop processing requests when client disconnect.
I'm not sure if uWSGI or gunicorn would fit this criteria.
Forgot to add this:
I am also trying to return a response before the request gets pro... | WSGI server that processes request despite client disconnecting? - Python | I need to find a stable wsgi server that won't stop processing requests when client disconnect.
I'm not sure if uWSGI or gunicorn would fit this criteria.
Forgot to add this:
I am also trying to return a response before the request gets processed.
Any ideas?
| [
"almost all wsgi servers do that. I'm not sure what you mean.\n\ngunicorn\npaste\ncherrypy\ntwisted.web\napache with mod_wsgi \nwerkzeug\n...\n\n"
] | [
1
] | [] | [] | [
"django",
"gevent",
"python",
"uwsgi",
"wsgi"
] | stackoverflow_0004540089_django_gevent_python_uwsgi_wsgi.txt |
Q:
"Unknown object" error when trying to capture artwork from a pict file and embed it into a track
I'm trying to capture artwork from a pict file and embed it into a track on iTunes using python appscript.
I did something like this:
imFile = open('/Users/kartikaiyer/temp.pict','r')
data = imFile.read()
it = app('iTu... | "Unknown object" error when trying to capture artwork from a pict file and embed it into a track | I'm trying to capture artwork from a pict file and embed it into a track on iTunes using python appscript.
I did something like this:
imFile = open('/Users/kartikaiyer/temp.pict','r')
data = imFile.read()
it = app('iTunes')
sel = it.current_track.get()
sel.artworks[0].data_.set(data[513:])
I get an error OSERROR: -17... | [
"This is an older question, but since I was having trouble doing this same thing now, I thought I'd post my solution in case someone else might benefit.\nselected = appscript.app('iTunes').selection.get()\n\nfor t in selected:\n myArt = open(/path/to/image.jpg,'r')\n data = myArt.read()\n t.artworks[1].dat... | [
3,
0,
0
] | [] | [] | [
"python",
"sourceforge_appscript"
] | stackoverflow_0001640558_python_sourceforge_appscript.txt |
Q:
python interactive mode module import issue
I believe I have what would be called a scope issue, perhaps name space. Not too sure I'm new to python.
I'm trying to make a module that will search through a list using regular expressions. I'm sure there is a better way of doing it but this error that I'm getting is... | python interactive mode module import issue | I believe I have what would be called a scope issue, perhaps name space. Not too sure I'm new to python.
I'm trying to make a module that will search through a list using regular expressions. I'm sure there is a better way of doing it but this error that I'm getting is bugging me and I want to understand why.
here's ... | [
"Move the \"import re\" out of the bottom \"if...\" to the top of the file:\nimport re\n\nclass ....\n\nYou're only importing the re module when run as a program, not imported as a module.\n(Also, Python style prefers upper-case class names.)\n",
"Python does not run anything \"ahead of time\"; it runs code when ... | [
2,
1
] | [] | [] | [
"namespaces",
"python",
"scope"
] | stackoverflow_0004540624_namespaces_python_scope.txt |
Q:
Generating all possible 3-connected graphs
There is a conjecture by Tutte and Thomassen (Planarity and duality of finite and infinite graphs, 1979) saying this
A 3-connected graph can be obtained
from a wheel by succestively adding an
edge and splitting a vertex into two
adjacent vertices of degree at least... | Generating all possible 3-connected graphs | There is a conjecture by Tutte and Thomassen (Planarity and duality of finite and infinite graphs, 1979) saying this
A 3-connected graph can be obtained
from a wheel by succestively adding an
edge and splitting a vertex into two
adjacent vertices of degree at least
three such that the edge joining them
is no... | [
"Your splitting operation should be a bit more involved. You need to modify all the edges that used to connect to v to connect to x or y instead.\ndef splitVertex(g,v):\n numver = g.vcount()\n g.add_vertices(2)\n x = numver\n y = numver+1\n g.add_edges([(x,y)])\n\n neighbors = g.neighbors(v)\n g.delete_vert... | [
1,
0
] | [] | [] | [
"algorithm",
"graph",
"graph_theory",
"igraph",
"python"
] | stackoverflow_0004532406_algorithm_graph_graph_theory_igraph_python.txt |
Q:
How to query on ReferenceProperties?
Assume:
class Pet (db.model):
owner = db.ReferenceProperty(User)
vet = db.ReferenceProperty(Vet)
name = db.StringProperty()
How do I query for Pets that have user Owner A and Vet B? I assume the references in the Pet class are keys. Please post a reference if you know ... | How to query on ReferenceProperties? | Assume:
class Pet (db.model):
owner = db.ReferenceProperty(User)
vet = db.ReferenceProperty(Vet)
name = db.StringProperty()
How do I query for Pets that have user Owner A and Vet B? I assume the references in the Pet class are keys. Please post a reference if you know a good one - I could not find a good examp... | [
"They are keys. \nAnd you can get them from a model instance or you can generate them from scratch.\nFilter on a key: Question GQL ReferenceProperty filter\ndb.GqlQuery(\"SELECT * FROM Pet WHERE owner = :1 and vet = :2\", owner.key(), vet.key())\n\nPet.all().filter(\"owner =\", owner.key()).filter(\"vet =\", vet.k... | [
2,
0,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004540947_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I create a class in Python that behaves like Django's abstract base class?
I'm using an existing Django library and I'm creating a class that I'd like to be abstract.
Let's say the class in question is BaseFoo.
Currently, the implementation has a base class BaseFoo.
Each time a class extending BaseFoo is cr... | How do I create a class in Python that behaves like Django's abstract base class? | I'm using an existing Django library and I'm creating a class that I'd like to be abstract.
Let's say the class in question is BaseFoo.
Currently, the implementation has a base class BaseFoo.
Each time a class extending BaseFoo is created, a metaclass adds it to a list of classes. It explicitly doesn't add BaseFoo by d... | [
"There is no need to set abstract to False in concrete classes - it's sufficient to have this setting in the abstract classes only:\nclass_list = []\nclass CollectSubclasses(type):\n def __new__(cls, name, bases, attrs):\n abstract = False\n if attrs.get('abstract', False):\n abstract = ... | [
3
] | [] | [] | [
"abstract",
"django",
"metaclass",
"python"
] | stackoverflow_0004541486_abstract_django_metaclass_python.txt |
Q:
Python client/server project code layout
Suppose you have a client/server application, say a webserver component and a qt gui. How do you layout your python code?
Packages foo.server and foo.client?
Packages fooserver and fooclient, with both importing from foocommon?
Everything together with no clear distinction... | Python client/server project code layout | Suppose you have a client/server application, say a webserver component and a qt gui. How do you layout your python code?
Packages foo.server and foo.client?
Packages fooserver and fooclient, with both importing from foocommon?
Everything together with no clear distinction?
Having subpackages for server and client co... | [
"buildbot has opted to create separate packages (for the master and the slave). In source control, they have three folders: common, master, and slave (plus documentation).\n",
"I like namespaces, so yes. foo.client and foo.server and foo.common and foo.anythingelsethatcanbeusedseparately. But it's all a matter of... | [
0,
0,
0,
-1
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0004541603_distutils_python.txt |
Q:
Override form data when editing an object
I want to override the fields when editing an object in Django.
When I try to edit an existing category for example, the fields name and description are loaded from the database. What I want to do is displaying another data in the fields rather that the data stored in the ... | Override form data when editing an object | I want to override the fields when editing an object in Django.
When I try to edit an existing category for example, the fields name and description are loaded from the database. What I want to do is displaying another data in the fields rather that the data stored in the database. There is any way to do that ?
The que... | [
"I didn't test this but I have done it before. Create a custom ModelForm for your model, set it on the ModelAdmin class and implement the form class like this:\nclass MyForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(MyForm, self).__init__(*args, **kwargs)\n if kwargs.get('ins... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004528667_django_django_forms_django_models_python.txt |
Q:
pyopengl display blocked when acting as a socket server at the same time
I am actually using a pyopengl program to act as a socket server. At the same time
the server receives commands from clients and interprets these commands and does corresponding drawing at the same time.
In case that the main thread got block... | pyopengl display blocked when acting as a socket server at the same time | I am actually using a pyopengl program to act as a socket server. At the same time
the server receives commands from clients and interprets these commands and does corresponding drawing at the same time.
In case that the main thread got blocked when doing socket things I actually started a thread to do the socket serve... | [
"In getClientContent, the line self.clientbuffer.readline(); is doing a blocking call on the socket, and that is almost certainly what is causing your trouble.\nWhat you need to do instead is have your run method do the readlines and stick the data into a queue, which the graphical display thread then reads from.\... | [
0
] | [] | [] | [
"multithreading",
"opengl",
"pyopengl",
"python"
] | stackoverflow_0004487608_multithreading_opengl_pyopengl_python.txt |
Q:
Updated Python from disk image, want to make it available in terminal
I have Python 2.6.1 which came on the Mac I have, but I'd recently downloaded and installed the disk image of 3.1.3 and I'd like to have it available in Terminal, how can I do this? For instance when I do $ python -V in Terminal I get 2.6.1.
Th... | Updated Python from disk image, want to make it available in terminal | I have Python 2.6.1 which came on the Mac I have, but I'd recently downloaded and installed the disk image of 3.1.3 and I'd like to have it available in Terminal, how can I do this? For instance when I do $ python -V in Terminal I get 2.6.1.
Thanks for any help.
| [
"By default, Python 3 versions are installed with the symlink name python3. Try:\n$ python3 -V\n\n",
"The default Python version in Mac OS X needs to stay the default Python version, or things will break. You want to install it alongside with Python 2. This is most likely exactly what happened, but you start Pyt... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004542014_python.txt |
Q:
Installing MySQL on Mac for use with Python
I simply want to install MySQL on my Mac (running Mac OS X 10.6.5 (Snow Leopard)) for use with Python.
So far I have:
Downloaded and installed [mysql-5.5.8-osx10.6-x86_64.dmg]. (I have also accidentally downloaded and installed [mysql-5.1.54-osx10.6-x86_64.dmg])
Downloa... | Installing MySQL on Mac for use with Python | I simply want to install MySQL on my Mac (running Mac OS X 10.6.5 (Snow Leopard)) for use with Python.
So far I have:
Downloaded and installed [mysql-5.5.8-osx10.6-x86_64.dmg]. (I have also accidentally downloaded and installed [mysql-5.1.54-osx10.6-x86_64.dmg])
Downloaded and installed [mySQL-python-1.2.3]
Added the ... | [
"It is certainly possible to make it all work by yourself. But there are a lot of pieces and, especially on OS X 10.6 and its preference for running in 64-bit, it can be difficult to get everything right. We could debug each step along the way; to do that you are going to need to supply more information. Or you ... | [
1,
0,
0
] | [] | [] | [
"importerror",
"macos",
"mysql",
"python"
] | stackoverflow_0004514682_importerror_macos_mysql_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.