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:
How to use backends in google app engine without wasting cpu resources?
While processing data in datastore using backends, app engine is using my cpu resources completely.
How do i process my data without wasting CPU resources?
Can i have the entire app on a backend without wasting cpu resources?
am i missing som... | How to use backends in google app engine without wasting cpu resources? | While processing data in datastore using backends, app engine is using my cpu resources completely.
How do i process my data without wasting CPU resources?
Can i have the entire app on a backend without wasting cpu resources?
am i missing something..
if the question is too vague, ask me to clarify.. thanks
| [
"The general advice for optimizing CPU usage is to minimize RPCs, understand how to use the datastore efficiently and use appstats to find your bottlenecks. For specific optimization advice, we would need to see some code.\nWhile backends can be configured to handle public requests, they aren't intended to replace ... | [
1
] | [] | [] | [
"backend",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006096806_backend_google_app_engine_google_cloud_datastore_python.txt |
Q:
Creating a function object from a string
Question: Is there a way to make a function object in python using strings?
Info: I'm working on a project which I store data in a sqlite3 server backend. nothing to crazy about that. a DAL class is very commonly done through code generation because the code is so incredib... | Creating a function object from a string | Question: Is there a way to make a function object in python using strings?
Info: I'm working on a project which I store data in a sqlite3 server backend. nothing to crazy about that. a DAL class is very commonly done through code generation because the code is so incredibly mundane. But that gave me an idea. In pytho... | [
"The following puts the symbols that you define in your string in the dictionary d:\nd = {}\nexec \"def f(x): return x\" in d\n\nNow d['f'] is a function object. If you want to use variables from your program in the code in your string, you can send this via d:\nd = {'a':7}\nexec \"def f(x): return x + a\" in d\n\n... | [
26,
2,
0
] | [] | [] | [
"code_generation",
"function_object",
"python",
"python_2.x"
] | stackoverflow_0006098073_code_generation_function_object_python_python_2.x.txt |
Q:
Rewrite a python script, injecting a method in each of the script's classes
Say I have a python module foo.py which contains:
class Foo(object):
def __init__(self):
pass
I next want to parse this script and inject a method in each of it's classes, re-writing it to something like this:
class Foo(object... | Rewrite a python script, injecting a method in each of the script's classes | Say I have a python module foo.py which contains:
class Foo(object):
def __init__(self):
pass
I next want to parse this script and inject a method in each of it's classes, re-writing it to something like this:
class Foo(object):
def __init__(self):
pass
def my_method(self):
pass # d... | [
"I understand what you are trying to do, but if your source code is reasonably simple, perhaps you could skip the whole parsing and writing back altogether and just run a regexp?\nSomething like:\nre.sub('^class\\s+(\\w+):\\s*\\n', 'class \\\\1:\\n%s' % method_source, file_source, flags=re.M)\n\nJust get the indent... | [
2,
1,
0
] | [] | [] | [
"code_generation",
"python"
] | stackoverflow_0006093566_code_generation_python.txt |
Q:
Efficient data structure of objects in python for lookup based on any object member variable
I need to store objects that have a number (>2) of integer member variables and do quick look-ups using any member variables as a search key.
For easier illustration let's say the objects are tuples of 3 integers and I nee... | Efficient data structure of objects in python for lookup based on any object member variable | I need to store objects that have a number (>2) of integer member variables and do quick look-ups using any member variables as a search key.
For easier illustration let's say the objects are tuples of 3 integers and I need to do quick look-ups using any element of a tuple as a key in a list of such tuples:
collection ... | [
"This is a simple solution. You could easily put this in a class and provide a neater interface. \n>>> from collections import defaultdict\n>>> collection = [(1, 200, 9),\n... (2, 300, 8),\n... (3, 400, 7)]\n>>> keyed_dict = defaultdict(list)\n>>> for tup in collection:\n... for i, e... | [
11,
6,
-1
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0006091549_data_structures_python.txt |
Q:
How do I get rid of this TypeError, and why is it occurring given that I am simply reassigning a value in a list?
Code:
http://pastie.org/1961455
Trackback:
Traceback (most recent call last):
File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 149, in <module>
main ()
File "C:\Users\COMPAQ\Desktop\Noug... | How do I get rid of this TypeError, and why is it occurring given that I am simply reassigning a value in a list? | Code:
http://pastie.org/1961455
Trackback:
Traceback (most recent call last):
File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 149, in <module>
main ()
File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 144, in main
move = computer_move(computer, board, human)
File "C:\Users\COMPAQ\Desktop\Noug... | [
"The problem is here:\ndef computer_move (computer, board, human):\n best = (4,0,8,2,6,1,3,5,7)\n board = board [:]\n for i in legal_moves(board):\n board[i] = computer\n if winner(board) == computer:\n return i\n board = EMPTY\n\nAt the end of the function, you assign EMPTY... | [
5,
4,
1
] | [] | [] | [
"debugging",
"python",
"tic_tac_toe",
"typeerror"
] | stackoverflow_0006099215_debugging_python_tic_tac_toe_typeerror.txt |
Q:
Django - template context processors - breaking my app
I was trying to set up a template context processor like this article mentions so that I could provide information to every template.
I wrote this function in views.py:
def items_in_cart(request):
"""Used by settings.TEMPLATE_CONTEXT_PROCESSORS to provide ... | Django - template context processors - breaking my app | I was trying to set up a template context processor like this article mentions so that I could provide information to every template.
I wrote this function in views.py:
def items_in_cart(request):
"""Used by settings.TEMPLATE_CONTEXT_PROCESSORS to provide an item count
to every template"""
cart, lines = get... | [
"Django has a default set of TEMPLATE_CONTEXT_PROCESSORS, which you need to manually add when adding your own. http://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors\nDepending on your Django version these are different, however if using Django 1.3 you might have something as follows\nTEMPLA... | [
21
] | [] | [] | [
"django",
"django_settings",
"django_templates",
"python"
] | stackoverflow_0006099330_django_django_settings_django_templates_python.txt |
Q:
Having trouble with multiplying a variable with a number
I'm trying to shorten my code and have more functionality but its not working right.
Heres my code(basically)
def times4():
number = droid.dialogGetInput('Input', 'Enter a number between 1 and 10').result
number4 = number * 4
if number == '... | Having trouble with multiplying a variable with a number | I'm trying to shorten my code and have more functionality but its not working right.
Heres my code(basically)
def times4():
number = droid.dialogGetInput('Input', 'Enter a number between 1 and 10').result
number4 = number * 4
if number == '1':
droid.dialogCreateAlert(number,number + ' * 4 ='... | [
"You want:\nnumber = int(number)\n\nAt the moment, 'number' is a string (i.e. '1' rather than 1) so multiplying it by four naturally just gives you '1111'. Using int() will give you an integer representation of the string.\n",
"Your variable number is a string and not an int. So it does a \"string multiplication\... | [
6,
3,
2,
2,
0,
0,
0
] | [] | [] | [
"multiplication",
"python",
"sl4a",
"variables"
] | stackoverflow_0005981981_multiplication_python_sl4a_variables.txt |
Q:
Reprioritizing priority queue (efficient manner)
I'm looking for a more efficient way to reprioritize items in a priority queue. I have a (quite naive) priority queue implementation based on heapq. The relevant parts are like:
from heapq import heapify, heappop
class pq(object):
def __init__(self, init= None)... | Reprioritizing priority queue (efficient manner) | I'm looking for a more efficient way to reprioritize items in a priority queue. I have a (quite naive) priority queue implementation based on heapq. The relevant parts are like:
from heapq import heapify, heappop
class pq(object):
def __init__(self, init= None):
self.inner, self.item_f= [], {}
if n... | [
"Since the new prioritization function may have no relationship to the previous one, you have to pay the cost to get the new ordering (and it's at minimum O(n) just to find the minimum element in the new ordering). If you have a small, fixed number of prioritization functions and switch frequently between them, th... | [
4
] | [] | [] | [
"data_structures",
"performance",
"python"
] | stackoverflow_0006099344_data_structures_performance_python.txt |
Q:
XML-RPC - cannot marshal recursive dictionaries
I have a simple example to send a dictionary through xml-rpc:
class CTest(object):
def __init__(self):
self.node1 = {'data':'zek', 'parent':{}, 'children':[]}
self.node2 = {'data':'bill', 'parent':{}, 'children':[]}
self.node1['children'... | XML-RPC - cannot marshal recursive dictionaries | I have a simple example to send a dictionary through xml-rpc:
class CTest(object):
def __init__(self):
self.node1 = {'data':'zek', 'parent':{}, 'children':[]}
self.node2 = {'data':'bill', 'parent':{}, 'children':[]}
self.node1['children'].append(self.node2)
self.node2['parent'] = s... | [
"Serialize and deserialize 'test' yourself by using the 'pickle' module of Python.\ncPickle.dumps(test)\n\nis working. On the other side of the wire you use\ncPickle.loads(received_test_pickle)\n\nIt might be necessary to base-64 encode/decode the pickle before/after the XMLRPC call.\nBut also look into PyRo\nhttp:... | [
5
] | [] | [] | [
"dictionary",
"marshalling",
"python",
"recursion",
"xml_rpc"
] | stackoverflow_0006099947_dictionary_marshalling_python_recursion_xml_rpc.txt |
Q:
Django/JQuery Question Regarding Multiple Part Form
I am developing a website which needs to contain functionality in which the user has to enter multiple pieces of data that end up being one large document. Imagine that I am designing a system for resume generation, where a resume is like 5+ pages long. The user ... | Django/JQuery Question Regarding Multiple Part Form | I am developing a website which needs to contain functionality in which the user has to enter multiple pieces of data that end up being one large document. Imagine that I am designing a system for resume generation, where a resume is like 5+ pages long. The user logs into the site and then has to enter in all the infor... | [
"If you already use jquery then I would recommend to have only one form with all fields and use a plugin to split it into multiple sub-forms. I use stepy for that. Or you can implement the similar functionality yourself.\nHaving only one form you can use a regular POST request to send the data to the server and get... | [
1
] | [] | [] | [
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0006097523_django_javascript_jquery_python.txt |
Q:
Is it possible to embed PyPy into a .NET application?
I would like to embed a Python interpreter into my .NET application. I'm aware of IronPython, of course, but I'm specifically interested in PyPy, because of its stackless support and microthreads.
However, while PyPy can be built against the CLI, it looks like ... | Is it possible to embed PyPy into a .NET application? | I would like to embed a Python interpreter into my .NET application. I'm aware of IronPython, of course, but I'm specifically interested in PyPy, because of its stackless support and microthreads.
However, while PyPy can be built against the CLI, it looks like that just gives you a standalone Python interpreter a la py... | [
"PyPy's CLI backend is not as mature as C backend and also does not integrate as well with .NET libraries. While normal PyPy compiled to C is production ready, I wouldn't call the .NET version production ready. It's also missing the JIT (although some work has been done in this area) and microthreads. Unless someon... | [
5,
3
] | [] | [] | [
".net",
"pypy",
"python",
"python_embedding",
"python_stackless"
] | stackoverflow_0006084697_.net_pypy_python_python_embedding_python_stackless.txt |
Q:
Authenticated HTTP POST with XML payload using Python urllib2
I'm trying to send a POST message with a purely XML payload (I think) using urllib2 in IronPython. However, everytime I send it, it returns Error code 400 (Bad Request).
I'm actually trying to mimick a Boxee remove queue item call for which the actual ... | Authenticated HTTP POST with XML payload using Python urllib2 | I'm trying to send a POST message with a purely XML payload (I think) using urllib2 in IronPython. However, everytime I send it, it returns Error code 400 (Bad Request).
I'm actually trying to mimick a Boxee remove queue item call for which the actual data packets looks like this (from WireShark):
POST /action/add HTT... | [
"This worked fine for me:\ncurl -v -A 'curl/7.16.3 (Windows build 7600; en-US; beta) boxee/0.9.21.11487' \\\n -H 'Content-Type: text/xml' -u \"USER:PASS\" \\\n --data '<message type=\"dequeue\" referral=\"12573293\"></message>' \\\n 'http://app.boxee.tv/action/add'\n\nBut I get 400 Bad Request if I try to remove a... | [
0
] | [] | [] | [
"http",
"ironpython",
"post",
"python",
"urllib2"
] | stackoverflow_0003164977_http_ironpython_post_python_urllib2.txt |
Q:
Python: Can't continually catch keyboardinterrupt in Windows?
In Python, I wrote the following code to see if I could get my program to not terminate upon Control+C like all those fancy terminal apps such as Vim or Dwarf Fortress.
def getinput():
x = input('enter something: ')
while True:
try:
... | Python: Can't continually catch keyboardinterrupt in Windows? | In Python, I wrote the following code to see if I could get my program to not terminate upon Control+C like all those fancy terminal apps such as Vim or Dwarf Fortress.
def getinput():
x = input('enter something: ')
while True:
try:
getinput()
except KeyboardInterrupt:
pass
Unfortun... | [
"In order to not terminate on Control-C you need to set a signal handler.\nFrom the Python doc here\n\nPython installs a small number of\n signal handlers by default: SIGPIPE is\n ignored (so write errors on pipes and\n sockets can be reported as ordinary\n Python exceptions) and SIGINT is\n translated into a ... | [
2
] | [] | [] | [
"python",
"terminal",
"windows"
] | stackoverflow_0006099931_python_terminal_windows.txt |
Q:
Creating a back-up list in python
I want to create a back-up list of another list in python. Here is an example of the code.
x = [1,2,3]
y = x
x.pop(0)
print y
This however yields the result y = [2,3] when I want it to yield [1,2,3]. How would I go about making the y list independent of the x list?
A:
... | Creating a back-up list in python | I want to create a back-up list of another list in python. Here is an example of the code.
x = [1,2,3]
y = x
x.pop(0)
print y
This however yields the result y = [2,3] when I want it to yield [1,2,3]. How would I go about making the y list independent of the x list?
| [
"A common idiom for this is y = x[:]. This makes a shallow copy of x and stores it in y.\nNote that if x contains references to objects, y will also contain references to the same objects. This may or may not be what you want. If it isn't, take a look at copy.deepcopy().\n",
"Here is one way to do it:\nimport cop... | [
17,
4,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006100719_list_python.txt |
Q:
invalid syntax in python while trying to plot
After my blunder with the infinity factorial sum XD I redid the code, but I keep getting syntax error :\
from scitools.std import *
from math import factorial, cos, e
from scipy import *
import numpy as np
def f1(t):
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n... | invalid syntax in python while trying to plot | After my blunder with the infinity factorial sum XD I redid the code, but I keep getting syntax error :\
from scitools.std import *
from math import factorial, cos, e
from scipy import *
import numpy as np
def f1(t):
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in range(0,100)... | [
"The parentheses in return 0.5*(1 + sum(... are not balanced.\nAs a matter of style, I would recommend avoiding from <module> import *-style imports. In your specific example you end up with a single-letter variable name (e) imported into the global namespace, which you then proceed to use. This could lead to confu... | [
4
] | [] | [] | [
"plot",
"python",
"syntax"
] | stackoverflow_0006100820_plot_python_syntax.txt |
Q:
How to print to HTML using python as server side script?
I have the following html button
<td><form id="form2" name="form2" method="post" onclick="../cgi-bin/py/GuestBookEntry.py">
<input type="submit" name="gBookSrib" id="gBookSrib" value="Sribble" />
</form></td>
My python script is
#!/usr/bin/python
print "Con... | How to print to HTML using python as server side script? | I have the following html button
<td><form id="form2" name="form2" method="post" onclick="../cgi-bin/py/GuestBookEntry.py">
<input type="submit" name="gBookSrib" id="gBookSrib" value="Sribble" />
</form></td>
My python script is
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html><body>Hello World!</bod... | [
"You need a webserver that serves Python code.\nThere are several different possibilities out there.\n\nTwisted Web is a webserver written in Python, allowing you to serve content from python with minimal overhead.\nApache / ngnix + Django offers a more complete stack to develop a full web application\n\n",
"Whic... | [
3,
2
] | [] | [] | [
"html",
"python"
] | stackoverflow_0006100882_html_python.txt |
Q:
Are python's file write() and urlopen() methods asynchronous?
As asked in the title, are open('...','w').write('...') and urllib.urlopen('..') asynchronous calls?
A:
No. If you need them to be asynchronous then consider looking at event frameworks such as Twisted, glib, or Qt.
| Are python's file write() and urlopen() methods asynchronous? | As asked in the title, are open('...','w').write('...') and urllib.urlopen('..') asynchronous calls?
| [
"No. If you need them to be asynchronous then consider looking at event frameworks such as Twisted, glib, or Qt.\n"
] | [
7
] | [] | [] | [
"file_io",
"python",
"urllib"
] | stackoverflow_0006100934_file_io_python_urllib.txt |
Q:
appengine: parse a csv data in uploaded file
Are there any modules or packages which help parsing csv content from a uploaded csv file in appengine. tried using the csv package in python. but it could parse only files in file system but could not data..
http://docs.python.org/library/csv.html
A:
but it could par... | appengine: parse a csv data in uploaded file | Are there any modules or packages which help parsing csv content from a uploaded csv file in appengine. tried using the csv package in python. but it could parse only files in file system but could not data..
http://docs.python.org/library/csv.html
| [
"\nbut it could parse only files in file\n system but could not data\n\nNo, csv.reader accepts any object that supports line-by-line iteration. Assuming cgi.FieldStorage supports it, and assuming you've posted a file named \"file\", you should be able to do this:\nimport csv\nfor row in csv.reader(self.request.POS... | [
3,
0
] | [] | [] | [
"csv",
"google_app_engine",
"python"
] | stackoverflow_0006100986_csv_google_app_engine_python.txt |
Q:
Python: Alternating functions every x minutes
Say if I have four functions as below:
def foo():
subprocess.Popen('start /B someprogramA.exe', shell=True)
def bar():
subprocess.Popen('start /B someprogramB.exe', shell=True)
def foo_kill():
subprocess.Popen('taskkill /IM someprogramA.exe')
def bar_kil... | Python: Alternating functions every x minutes | Say if I have four functions as below:
def foo():
subprocess.Popen('start /B someprogramA.exe', shell=True)
def bar():
subprocess.Popen('start /B someprogramB.exe', shell=True)
def foo_kill():
subprocess.Popen('taskkill /IM someprogramA.exe')
def bar_kill():
subprocess.Popen('taskkill /IM someprogram... | [
"Remember that functions are first-class objects in Python. That means you can store them in variables and containers! One way to do it would be:\nfuncs = [(foo, foo_kill), (bar, bar_kill)]\n\ndef run(self):\n counter = self.runTime\n for sec in range(self.runTime):\n runner, killer = funcs[counter % 2... | [
10,
6,
2,
1
] | [] | [] | [
"alternate",
"function",
"multithreading",
"python",
"timer"
] | stackoverflow_0006100441_alternate_function_multithreading_python_timer.txt |
Q:
How to make python regex which matches multiple patterns to same index
Is it possible to get all overlapping matches, which starts from the same index, but are from different matching group?
e.g. when I look for pattern "(A)|(AB)" from "ABC" regex should return following matches:
(0,"A") and (0,"AB")
A:
For on... | How to make python regex which matches multiple patterns to same index | Is it possible to get all overlapping matches, which starts from the same index, but are from different matching group?
e.g. when I look for pattern "(A)|(AB)" from "ABC" regex should return following matches:
(0,"A") and (0,"AB")
| [
"For one possibility see the answer of Evpok. The second interpretation of your question can be that you want to match all patterns at the same time from the same position. You can use a lookahead expression in this case. E.g. the regular expression\n(?=(A))(?=(AB))\n\nwill give you the desired result (i.e. all pla... | [
6,
3
] | [] | [] | [
"match",
"overlapping",
"python",
"regex"
] | stackoverflow_0006100817_match_overlapping_python_regex.txt |
Q:
Python serial communication
I'm working on an Arduino project, and I am interfacing it with a Python script due to memory limitations. On the Python side I have a 2 dimensional matrix containing respective x, y values for coordinates, and in this list is 26000 coordinate pairs. So, in interest of clarifying the da... | Python serial communication | I'm working on an Arduino project, and I am interfacing it with a Python script due to memory limitations. On the Python side I have a 2 dimensional matrix containing respective x, y values for coordinates, and in this list is 26000 coordinate pairs. So, in interest of clarifying the data structure for all of you, path... | [
"You should wait a bit for the serial data to arrive.\nThe Arduino code should be:\nif (Serial.available()){\n delay(100); // Wait for all data.\n while (Serial.available()) {\n char d = Serial.read();\n str.concat(d);\n }\n}\n\nAlso you have to clear your string before re-using it.\n[Edit]\n... | [
5,
5
] | [] | [] | [
"arduino",
"pyserial",
"python",
"serial_port"
] | stackoverflow_0006048270_arduino_pyserial_python_serial_port.txt |
Q:
PyQt - how can element exist without pointer?
This program shows window and 3 buttons.
Buttons are generated by iteration for i in range(3):.
I don't understand this:
If button in the end only contains last button, where are all other buttons?
Why they are not deleted, when button starts referring to other element... | PyQt - how can element exist without pointer? | This program shows window and 3 buttons.
Buttons are generated by iteration for i in range(3):.
I don't understand this:
If button in the end only contains last button, where are all other buttons?
Why they are not deleted, when button starts referring to other element?
import sys
from PyQt4.QtGui import *
class MainW... | [
"A reference to the button is held in the 'vbox' object.\n",
"By calling addWidget you \"attach\" the button to the view and this view stores some reference to its children. If you want to access them from your script, I would suggest you safe them as a local (or instance) variable.\nSomething like:\nclass MainWi... | [
3,
2,
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0006101016_pyqt_python.txt |
Q:
PyGTK blocking non-GUI threads
I want to play with the thread-bugs with PyGTK. I have this code so far:
#!/usr/bin/python
import pygtk
pygtk.require('2.0')
import gtk
import threading
from time import sleep
class SomeNonGUIThread(threading.Thread):
def __init__(self, tid):
super(SomeNonGUIThread, sel... | PyGTK blocking non-GUI threads | I want to play with the thread-bugs with PyGTK. I have this code so far:
#!/usr/bin/python
import pygtk
pygtk.require('2.0')
import gtk
import threading
from time import sleep
class SomeNonGUIThread(threading.Thread):
def __init__(self, tid):
super(SomeNonGUIThread, self).__init__()
self.tid = tid... | [
"You have to call gobject.threads_init() before you do anything Gtk related.\nMore info in PyGtk's FAQ\n"
] | [
5
] | [] | [] | [
"multithreading",
"pygtk",
"python"
] | stackoverflow_0006101415_multithreading_pygtk_python.txt |
Q:
PyOpenSSL: Force SSL negotiations without sending/receiving?
Is it possible to force PyOpenSSL into performing the SSL negotiation (and, specifically, retrieving the peer's certificate) without trying to send/receive data?
Currently, with this code:
ssl_soc = SSL.Connection(self._mk_ctx(), plain_soc)
ssl_s... | PyOpenSSL: Force SSL negotiations without sending/receiving? | Is it possible to force PyOpenSSL into performing the SSL negotiation (and, specifically, retrieving the peer's certificate) without trying to send/receive data?
Currently, with this code:
ssl_soc = SSL.Connection(self._mk_ctx(), plain_soc)
ssl_soc.set_connect_state()
cert = ssl_soc.get_peer_certificate()
... | [
"Err, clearly I need to RTFM a little harder. I was looking for the do_handshake method: http://packages.python.org/pyOpenSSL/openssl-connection.html\n"
] | [
3
] | [] | [] | [
"pyopenssl",
"python"
] | stackoverflow_0006101587_pyopenssl_python.txt |
Q:
What happens behind the scenes when python adds small ints?
I was fiddling around with id recently and realized that (c?)Python does something quite sensible: it ensures that small ints always have the same id.
>>> a, b, c, d, e = 1, 2, 3, 4, 5
>>> f, g, h, i, j = 1, 2, 3, 4, 5
>>> [id(x) == id(y) for x, y in zip... | What happens behind the scenes when python adds small ints? | I was fiddling around with id recently and realized that (c?)Python does something quite sensible: it ensures that small ints always have the same id.
>>> a, b, c, d, e = 1, 2, 3, 4, 5
>>> f, g, h, i, j = 1, 2, 3, 4, 5
>>> [id(x) == id(y) for x, y in zip([a, b, c, d, e], [f, g, h, i, j])]
[True, True, True, True, True... | [
"You've fallen into a not uncommon trap:\nid(2 * x + y) == id(300 + x)\n\nThe two expressions 2 * x + y and 300 + x don't have overlapping lifetimes. That means that Python can calculate the left hand side, take its id, and then free the integer before it calculates the right hand side. When CPython frees an intege... | [
20,
17,
2
] | [] | [] | [
"cpython",
"integer",
"python"
] | stackoverflow_0006101379_cpython_integer_python.txt |
Q:
How can I implement matlabs ``ismember()`` command in Python?
here is my problem: I would like to create a boolean matrix B that contains True everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:
import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, ... | How can I implement matlabs ``ismember()`` command in Python? | here is my problem: I would like to create a boolean matrix B that contains True everywhere that matrix A has a value contained in vector v. One inconvenient solution would be:
import numpy as np
>>> A = np.array([[0,1,2], [1,2,3], [2,3,4]])
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
>>> v = [1,2]
>>> B = (... | [
"I don't know much numpy, be here's a raw python one:\n>>> A = [[0,1,2], [1,2,3], [2,3,4]]\n>>> v = [1,2]\n>>> B = [map(lambda val: val in v, a) for a in A]\n>>>\n>>> B\n[[False, True, True], [True, True, False], [True, False, False]]\n\nEdit: As Brooks Moses notes and some simple timing seems to show, this one is ... | [
4,
3,
3,
2,
1,
1
] | [] | [] | [
"arrays",
"matrix",
"python"
] | stackoverflow_0001273041_arrays_matrix_python.txt |
Q:
Communication between parent child processes
Im trying to create a Python 3 program that has one or more child processes.
The Parent process spawns the child processes and then goes on with its own buisiness, now and then I want to send a message to a specific child process that catches it and takes action.
Also t... | Communication between parent child processes | Im trying to create a Python 3 program that has one or more child processes.
The Parent process spawns the child processes and then goes on with its own buisiness, now and then I want to send a message to a specific child process that catches it and takes action.
Also the child process need to be non locked while waiti... | [
"See Doug Hellmann's (multiprocessing) \"Communication Between Processes\". Part of his Python Module of the Week series. It is fairly simple to use a dictionary or list to communicate with a process.\nimport time\nfrom multiprocessing import Process, Manager\n\ndef test_f(test_d):\n \"\"\" frist process to run\... | [
5,
2
] | [] | [] | [
"multithreading",
"python",
"python_3.x"
] | stackoverflow_0006099981_multithreading_python_python_3.x.txt |
Q:
Django python help needed
I am trying to sync my DB but at time of sync it shows error to migrate my models.py containing folder on migrating it shows no fixtures found.
I have pasted the messages which it shows:
C:\election\trunk\election-server\geodjango>manage.py syncdb
Syncing...
No fixtures found.
Synced:
... | Django python help needed | I am trying to sync my DB but at time of sync it shows error to migrate my models.py containing folder on migrating it shows no fixtures found.
I have pasted the messages which it shows:
C:\election\trunk\election-server\geodjango>manage.py syncdb
Syncing...
No fixtures found.
Synced:
> django.contrib.auth
> django... | [
"Your first paragraph is a little confusing to me. If I understand your question correctly, it sounds like something I ran into.\nInitial data for a database is stored in the file initial_data.json by default. The migration messages you are getting indicate that you're using the django migration tool South. IF y... | [
3
] | [] | [] | [
"django",
"django_south",
"manage.py",
"python"
] | stackoverflow_0006102114_django_django_south_manage.py_python.txt |
Q:
TypeError in python while trying to plot a sum
Since I got the advice to make another question here it goes... I want to plot the sum, and I have a code:
from scitools.std import *
from math import factorial, cos, e, sqrt
from scipy import *
import numpy as np
def f1(t):
return 0.5*(1 + sum( (a**(2*n)*cos(2*s... | TypeError in python while trying to plot a sum | Since I got the advice to make another question here it goes... I want to plot the sum, and I have a code:
from scitools.std import *
from math import factorial, cos, e, sqrt
from scipy import *
import numpy as np
def f1(t):
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in rang... | [
"You can't divide a numpy.ndarray by a numpy.float64. This is the problematic code:\nreturn 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n))\n\n",
"I don't understand what that generator expression is doing at the end of the return statement in f1, but this:\na=4\nt = linspace(0, 35, 1000)\ny1... | [
1,
1
] | [] | [] | [
"plot",
"python",
"sum"
] | stackoverflow_0006101902_plot_python_sum.txt |
Q:
Creating Frame inside a Canvas
I am trying to make a frame scrollable, and the only way I found to do this is making a scrollable canvas and adding a frame to it. This would work fine, if it worked for me.
I am able to create a scrollable canvas that works fine, but I can't seem to properly add a frame inside of ... | Creating Frame inside a Canvas | I am trying to make a frame scrollable, and the only way I found to do this is making a scrollable canvas and adding a frame to it. This would work fine, if it worked for me.
I am able to create a scrollable canvas that works fine, but I can't seem to properly add a frame inside of it:
self.title = Label(root, tex... | [
"By default, when you add a window to a canvas, the center of the window will be at the coordinates you give. Thus, the center of your frame will be at 0,0 which is the upper-left corner of the canvas. You can't see the widgets because they are outside the borders of the canvas.\nThe solution is to include anchor=... | [
7,
4
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006100748_python_tkinter.txt |
Q:
Encoding binary data in a PNG?
I'm looking for information on how to encode a small amount of binary data (say, around 200 bytes) into a PNG through colors; essentially what Hid.im does for .torrent files. Any information or springboard for a best practice would be stellar.
Thanks!
A:
The very basics of hiding a... | Encoding binary data in a PNG? | I'm looking for information on how to encode a small amount of binary data (say, around 200 bytes) into a PNG through colors; essentially what Hid.im does for .torrent files. Any information or springboard for a best practice would be stellar.
Thanks!
| [
"The very basics of hiding a data in an lossless-compressed image is modifying the lower bits of every pixel, so that altogether those bits mean something. \nFor example in R.G.B., you can modify the last bit in Red color value (technically human eye is less sensitive to red that to green or blue). \nFor example, l... | [
5
] | [] | [] | [
"encoding",
"png",
"python",
"python_imaging_library",
"steganography"
] | stackoverflow_0006102349_encoding_png_python_python_imaging_library_steganography.txt |
Q:
Buttons have their own coordinate system according to the "grid_location" method?
I'm trying to use the grid_location method, from the Grid Geometry Manager, in Tkinter, but it seems that I'm doing something wrong.
Here's my code:
from tkinter import *
root = Tk()
b=Button(root, text="00")
b.grid(row=0, column... | Buttons have their own coordinate system according to the "grid_location" method? | I'm trying to use the grid_location method, from the Grid Geometry Manager, in Tkinter, but it seems that I'm doing something wrong.
Here's my code:
from tkinter import *
root = Tk()
b=Button(root, text="00")
b.grid(row=0, column=0)
b2=Button(root, text="11")
b2.grid(row=1, column=1)
b3=Button(root, text="22")
b3.... | [
"You are correct that each button \"has it's own coordinate system\". More accurately, though, the event.x and event.y values are relative to the widget associated with the event rather than the widget's parent or the root window. \nIf you really do need the row and column that the widget is in you can use grid_inf... | [
7
] | [] | [] | [
"grid",
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0006101709_grid_python_python_3.x_tkinter.txt |
Q:
Django .save() Reverts
I have an InteferField set in models called the status. I have a method that is two switch the value of two rows statuses.
Row one -> status = 1
Row two -> status = 2
Now, I figure, if I switch row one's status to some unattainable reach (99) I could use that as the middle man to switch ro... | Django .save() Reverts | I have an InteferField set in models called the status. I have a method that is two switch the value of two rows statuses.
Row one -> status = 1
Row two -> status = 2
Now, I figure, if I switch row one's status to some unattainable reach (99) I could use that as the middle man to switch row two and then switch row on... | [
"Hmmm... Shouldn't the following:\noriginalCase = Case.objects.get(queue_num = swap)\n\nBe this:\noriginalCase = Case.objects.get(queue_num = 99)\n\nIf you copy and pasted that code as is, that's your problem. You're essentially fetching the one you just changed and changing it back.\nUPDATE:\nSimplifying your code... | [
0,
0
] | [] | [] | [
"django",
"mysql",
"python",
"save"
] | stackoverflow_0006102864_django_mysql_python_save.txt |
Q:
import python file
Possible Duplicate:
Python package structure
Hello,
I'm looking to import a python file that I have in a sub-directory that is below the root of my main file. e.g.
import ../library/utils.py
When I put that into my code and run it I get a compile error.
Is there a way to include files from be... | import python file |
Possible Duplicate:
Python package structure
Hello,
I'm looking to import a python file that I have in a sub-directory that is below the root of my main file. e.g.
import ../library/utils.py
When I put that into my code and run it I get a compile error.
Is there a way to include files from below the main file root ... | [
"You don't import files, you import modules. Modify sys.path accordingly, and do import utils, e.g.\nimport sys\nsys.path.append('../library')\nimport utils\n\n",
"import sys, os\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'library')))\n\nimport utils\n\nThis will modify the sys... | [
9,
3
] | [] | [] | [
"python",
"python_2.7",
"python_import"
] | stackoverflow_0006103067_python_python_2.7_python_import.txt |
Q:
Cherrypy unable to create socket on WinXP
Python 2.7, Cherrypy 3.2.0, Windows XP SP3.
Cherrypy app works fine using quickstart when binding to 127.0.0.1 port 8080, however any attempt to bind to actual IP results in
File "C:\Python27\lib\site-packages\cherrypy\wsgiserver__init__.py", line 175
3, in start
rais... | Cherrypy unable to create socket on WinXP | Python 2.7, Cherrypy 3.2.0, Windows XP SP3.
Cherrypy app works fine using quickstart when binding to 127.0.0.1 port 8080, however any attempt to bind to actual IP results in
File "C:\Python27\lib\site-packages\cherrypy\wsgiserver__init__.py", line 175
3, in start
raise socket.error(msg)
error: No socket could be c... | [
"Windows discovery #1: XP Service Pack 2 apparently ceased to allow binding to raw sockets as a \"hacker avoidance\" something-or-other. So, to successfully bind to a socket one must use python win32 utils and cherrypy to create a windows service, which turned out to be pretty much cake!\nAn excellent, work-on-the-... | [
0
] | [] | [] | [
"cherrypy",
"python",
"sockets"
] | stackoverflow_0006022846_cherrypy_python_sockets.txt |
Q:
Python's equivelant for php's getLoginUrl for Facebook Graph API
I have some experience working with facebook's php sdk. Now I need to use python to create a facebook app, but the python sdk is not as complete as the one for php
Is there a port of the php sdk to python?
One of the methods missing is the below
$se... | Python's equivelant for php's getLoginUrl for Facebook Graph API | I have some experience working with facebook's php sdk. Now I need to use python to create a facebook app, but the python sdk is not as complete as the one for php
Is there a port of the php sdk to python?
One of the methods missing is the below
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUr... | [
"As for as the python transformation (provided you use the app engine) is concerned , you have an already defined python script in the examples/OAuth directory of your python-sdk . Hack it up to add the value:pair scope='email,publish_stream,status_update,user_birthday,user_location,user_work_history' , (here scope... | [
0
] | [] | [] | [
"facebook_graph_api",
"python"
] | stackoverflow_0004605183_facebook_graph_api_python.txt |
Q:
Why does Django not generate CSRF or Session Cookies behind a Varnish Proxy?
Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF verification error upon submitting the... | Why does Django not generate CSRF or Session Cookies behind a Varnish Proxy? | Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF verification error upon submitting the login form. Has anyone come up against this and found a solution?
I AM able to ma... | [
"The problem was that I have a Varnish Proxy server in front of my site. Varnish was taking requests and stripping cookies from them. To fix this I had to have the company that is managing the Varnish Server add '/admin' to a list of exceptions so that cookies could be passed. Sorry I can't shed more light on how t... | [
3,
2,
0
] | [] | [] | [
"csrf",
"django",
"python",
"varnish"
] | stackoverflow_0006065503_csrf_django_python_varnish.txt |
Q:
Checking A PyObjects C Type
I am using Python 3.2 and C++.
I need to extract what kind of C type is currently being stored in a PyObject.
I have checked over the documentation and googled it as well and no one else seems to have needed to do this.
So I have a PyObject and am attempting to extract the C Value. I ha... | Checking A PyObjects C Type | I am using Python 3.2 and C++.
I need to extract what kind of C type is currently being stored in a PyObject.
I have checked over the documentation and googled it as well and no one else seems to have needed to do this.
So I have a PyObject and am attempting to extract the C Value. I have the list of functions need to ... | [
"Python objects don't have a C type, they have a Python type. For example, an integer can be an C long or a long integer. You can check for the type with PyInt_Check(obj), PyList_Check(obj), etc. If that returns true then you know you have an object of that type.\nNote that PyLong_FromLong and such go the other way... | [
5,
1
] | [] | [] | [
"c++",
"python",
"python_c_api"
] | stackoverflow_0006103847_c++_python_python_c_api.txt |
Q:
How do I create a dynamic job ticket for Xerox printers?
I am programmatically creating PDF files in Python and Reportlab Toolkit, each containing several thousand documents, each document with a variable amount of pages.
My problem is that I need to instruct the printer which media type each page should be printe... | How do I create a dynamic job ticket for Xerox printers? | I am programmatically creating PDF files in Python and Reportlab Toolkit, each containing several thousand documents, each document with a variable amount of pages.
My problem is that I need to instruct the printer which media type each page should be printed on (pre-printed letterhead for the first page of a document ... | [
"I've run into the same problem. Eventually, I found out that I was going about it the wrong way, caused by a misunderstanding of the PDF format. We think of PDF files as WYSIWYG for printers. This is not the case. In any kind of print flow, the PDF file gets converted to some intermediate format, PostScript, TIFF ... | [
6,
2,
1
] | [] | [] | [
"jdf",
"pdf",
"printing",
"python",
"reportlab"
] | stackoverflow_0006051536_jdf_pdf_printing_python_reportlab.txt |
Q:
How can I render a bar code as an image through google app engine with python?
After a day's reading, I'm no closer to finding a good way to render a bar code through Google app engine on python. The closest I've found is PyPNG as a pure python image library but it looks as though that would require quite a bit of... | How can I render a bar code as an image through google app engine with python? | After a day's reading, I'm no closer to finding a good way to render a bar code through Google app engine on python. The closest I've found is PyPNG as a pure python image library but it looks as though that would require quite a bit of work to make it usable. Does anyone have any good suggestions on how to do it befor... | [
"You might want to look at a webservice to generate the barcode. I found the site below on google but there are many results if you search for: barcode webservice. Many of them are code for you to download and use but some appear to be live webservices.\nhttp://www.barcodesoft.com/barcode-generator-webservice.aspx\... | [
3
] | [] | [] | [
"google_app_engine",
"image",
"python"
] | stackoverflow_0006103376_google_app_engine_image_python.txt |
Q:
How to handle exceptions correctly?
I don't quite understand yet how to correctly use exceptions in Python. I want to process the data I can't completely trust (they are prone to change, and if they change, script may break). Let's say I process a webpage using BeautifulSoup. If author of the website make some cha... | How to handle exceptions correctly? | I don't quite understand yet how to correctly use exceptions in Python. I want to process the data I can't completely trust (they are prone to change, and if they change, script may break). Let's say I process a webpage using BeautifulSoup. If author of the website make some changes to his website, some statements may ... | [
"Firstly, if you don't mind the exception you can just let it pass:\ntry:\n something()\nexcept AttributeError:\n pass\n\nbut never do this as it is will let all errors pass:\ntry:\n something()\nexcept Exception:\n pass\n\nAs for your code sample, perhaps it could be tidied up with something like this:... | [
4,
1
] | [] | [] | [
"exception_handling",
"python",
"variables"
] | stackoverflow_0006104167_exception_handling_python_variables.txt |
Q:
What exactly does pygame.display.set_mode() do?
I've recently started to play around with the pygame python library and I just wanted to see if I was understanding something correctly:
The following is some code that sets up the window. In the line that says:
windowSurface = pygame.display.set_mode((WINDOWWIDTH, ... | What exactly does pygame.display.set_mode() do? | I've recently started to play around with the pygame python library and I just wanted to see if I was understanding something correctly:
The following is some code that sets up the window. In the line that says:
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
, does display refer to a modu... | [
"display is a module, and set_mode is a function inside that module. It actually creates an instance of the pygame.Surface class, and returns that. See the docs.\nIn Python, the standard is that classes have capitalised names, and modules and functions are all lower case. Not everything follows that, but a lot of t... | [
6,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0006104207_pygame_python.txt |
Q:
Using a tuples of values in sqlalchemy mapped collection
In a many-to-many relationship, I have some extra data on the association table to describe the relationship (a quantity and a boolean value). I'd like to use a mapped collection to avoid working directly with the association objects, but I can't figure out ... | Using a tuples of values in sqlalchemy mapped collection | In a many-to-many relationship, I have some extra data on the association table to describe the relationship (a quantity and a boolean value). I'd like to use a mapped collection to avoid working directly with the association objects, but I can't figure out how to use a tuple for the values in the mapping. As far as I ... | [
"the linked answer has all the components. attribute_mapped_collection and association_proxy can do lots together. First here is the dictionary of string->tuple(int, boolean) (updated for m2m):\nfrom sqlalchemy import Integer, Boolean, String, Column, create_engine, \\\n ForeignKey\nfrom sqlalchemy.orm impor... | [
7
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006104059_python_sqlalchemy.txt |
Q:
How can I communicate between two python scripts?
I have a 3d party python script which takes input from the command line. The relevant code from this script (input.py) looks like the following:
import sys
def chooseinput():
valid_inputs = ('a', 'b')
inp = raw_input('Enter choice (%s): ' % "/".join(valid... | How can I communicate between two python scripts? | I have a 3d party python script which takes input from the command line. The relevant code from this script (input.py) looks like the following:
import sys
def chooseinput():
valid_inputs = ('a', 'b')
inp = raw_input('Enter choice (%s): ' % "/".join(valid_inputs))
if inp not in valid_inputs:
sys.s... | [
"Try:\np.stdin.write('a\\n')\np.stdin.write('b\\n')\n\n",
"linuts answer works well in your simple example, but for the benefit of future readers, I would strongly recommend against using this methodology for communicating between Python scripts.\nThis method is a throwback to when few other options were availabl... | [
6,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0006104289_python.txt |
Q:
Printing a square dot board
I need to make a program in python to print a square board consisting of dots. The size is input by the user (between 2x2 and 9x9 squares) eg 4x4 =
. . . .
. . . .
. . . .
. . . .
The program asks the user for the int value between 2-9 and prints the board.
eg board_size? 4
A:
I'm ... | Printing a square dot board | I need to make a program in python to print a square board consisting of dots. The size is input by the user (between 2x2 and 9x9 squares) eg 4x4 =
. . . .
. . . .
. . . .
. . . .
The program asks the user for the int value between 2-9 and prints the board.
eg board_size? 4
| [
"I'm telling your teacher where you got this from:\n(w, h) = [int(i) for i in raw_input().split('x')]\nprint (\". \"*w + \"\\n\") * h\n\n",
"Here's your answer using generator expressions. It's basically the same as using a list comprehension in this case except that it does double the work while still being sem... | [
1,
0,
0
] | [
"Here is your homework (being s the size of the square):\nprint \"\\n\".join ( [\" \".join ( [\".\" for i in range (s) ] ) for j in range (s) ] )\n\nJust scan the size s from stdin or wherever the user inputs it.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0006103345_python.txt |
Q:
Mutually dependent PyGtk SpinButtons
I have three PyGTK SpinButtons that are mutually dependent on each other: call them A, B, and C. There is another button D that toggles between two reciprocal definitions of C, such that the value of C is defined as A/B unless D has been pressed an odd number of times.
I want ... | Mutually dependent PyGtk SpinButtons | I have three PyGTK SpinButtons that are mutually dependent on each other: call them A, B, and C. There is another button D that toggles between two reciprocal definitions of C, such that the value of C is defined as A/B unless D has been pressed an odd number of times.
I want to be able, for example, to change A and h... | [
"You can disable the signal handler for a given spinner before calling set_value on it. This ensures that the signal is only fired in reaction to mouse and keyboard events, not programmatic changes. Here is a quick example:\nimport pygtk, gtk\nwin = gtk.Window(gtk.WINDOW_TOPLEVEL)\nwin.connect('destroy', lambda w:... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0006104098_gtk_pygtk_python_user_interface.txt |
Q:
Is Dive Into Python outdated?
I am learning Python, and I saw Dive Into Python and it looks cool and all, but it was released in 2004. So, what I am wondering is if Python 2.x has changed enough since 2004 that Dive Into Python has become so obsolete. And are there any more recent online textbooks like that for ... | Is Dive Into Python outdated? | I am learning Python, and I saw Dive Into Python and it looks cool and all, but it was released in 2004. So, what I am wondering is if Python 2.x has changed enough since 2004 that Dive Into Python has become so obsolete. And are there any more recent online textbooks like that for Python that can get me to become an... | [
"Well, there is Dive Into Python 3...\n\nDive Into Python 3 covers Python 3 and its differences from Python 2. Compared to Dive Into Python, it’s about 20% revised and 80% new material. \n\n",
"There's a new version of Dive into Python that focuses on 3.x.\n",
"No, it is not obsolete. It is still a good resourc... | [
23,
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006104865_python.txt |
Q:
PyQt4 character encoding: 'ascii' codec can't encode character
Trying to use this following script to load a page so that I can access the page with javascript executed. I would like to log in and look at the resultant page (https://www.thomsononeim.com/v-hom.asp), also with Javascript executed. In Python 2.7, I g... | PyQt4 character encoding: 'ascii' codec can't encode character | Trying to use this following script to load a page so that I can access the page with javascript executed. I would like to log in and look at the resultant page (https://www.thomsononeim.com/v-hom.asp), also with Javascript executed. In Python 2.7, I get this error:
Traceback (most recent call last):
File "C:/Pytho... | [
"This should work:\nprint(html.toUtf8())\n\n"
] | [
4
] | [] | [] | [
"character_encoding",
"pyqt4",
"python"
] | stackoverflow_0006104874_character_encoding_pyqt4_python.txt |
Q:
Foreign key constraints in SQLAlchemy
I'm using the ORM side of SQLAlchemy, and I've defined one of my columns to have a foreign key relation to another model, using:
Base = declarative_base()
class Model1(Base):
__tablename__ = 'm1'
Name = Column(String, primary_key = True)
info = Column(String)
clas... | Foreign key constraints in SQLAlchemy | I'm using the ORM side of SQLAlchemy, and I've defined one of my columns to have a foreign key relation to another model, using:
Base = declarative_base()
class Model1(Base):
__tablename__ = 'm1'
Name = Column(String, primary_key = True)
info = Column(String)
class Model2(Base):
__tablename__ = 'm2'
... | [
"It looks like the answer was in the database I was using (SQLite), not SQLAlchemy. SQLite versions <3.6.1 (AFAIK) do not support foreign key constraints.\nThe answer is therefore very similar to this answer on foreign keys and SQLAlchemy.\nAs I'm using Windows, I was able to go to the pysqlite2 page, the packaged ... | [
4
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006093499_python_sqlalchemy.txt |
Q:
Centering wx.TextCtrl?
I'm having difficulties centering the text within a wx.TextCtrl (as shown in the photoshopped illustration below). -- For some reason, it always prints LEFT aligned, instead of CENTERED.
Could someone please point me to the proper "styles" OR tell me what I'm doing wrong?
import wx
class S... | Centering wx.TextCtrl? | I'm having difficulties centering the text within a wx.TextCtrl (as shown in the photoshopped illustration below). -- For some reason, it always prints LEFT aligned, instead of CENTERED.
Could someone please point me to the proper "styles" OR tell me what I'm doing wrong?
import wx
class SimplePanel(wx.Panel):
d... | [
"This seems to work fine on Windows but I was using both OSX and Windows for development and wx.TE_CENTRE does not appear to work on OSX. This was defect was reported many years ago (http://trac.wxwidgets.org/ticket/10010).\n",
"(Edited after clarification)\nThere was a bug once in wxPython which broke TE_CENTRE... | [
2,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005568894_python_wxpython.txt |
Q:
Problems building node.js on Cygwin, please help
I'm trying to get node.js running on Windows 7. I have no experience with Linux so I've just been blindly following instructions from tutorials I've found, but I'm still unable to build node.js.
What I did:
Install Cygwin - the entirety
Attempt to build node.js
T... | Problems building node.js on Cygwin, please help | I'm trying to get node.js running on Windows 7. I have no experience with Linux so I've just been blindly following instructions from tutorials I've found, but I'm still unable to build node.js.
What I did:
Install Cygwin - the entirety
Attempt to build node.js
This is the error I first got:
I then followed the com... | [
"Add -e '/\\/sys-root\\/mingw\\/bin/d' at line 110 in /bin/rebaseall file.\nThen re-run rebaseall -v and you shouldn't get the error anymore.\n",
"First of all, why did you check out such an old release v0.2.5? When I did it a few weeks ago I just took the latest and ended up with 0.5.0pre, but it would also be r... | [
2,
1,
1,
0,
0
] | [] | [] | [
"cygwin",
"node.js",
"path",
"python",
"windows_7"
] | stackoverflow_0005399947_cygwin_node.js_path_python_windows_7.txt |
Q:
Nameclash when importing packages that has the word 'django' in the name?
I have a somewhat odd problem. I decided to rename an entire branch of my package from
foo.bar.somemodule
to
foo.django.bar.somemodule
The problem is after this is done, I get the following error:
Traceback (most recent call last):
File ... | Nameclash when importing packages that has the word 'django' in the name? | I have a somewhat odd problem. I decided to rename an entire branch of my package from
foo.bar.somemodule
to
foo.django.bar.somemodule
The problem is after this is done, I get the following error:
Traceback (most recent call last):
File "/home/workspace/eclipse/foo/src/foo/manage.py", line 2, in <module>
from d... | [
"You're running into a situation where you want to perform an absolute import, but your Python version doesn't do them by default. Add from __future__ import absolute_import at the top of the afflicted file to tell the Python VM to activate it.\n"
] | [
1
] | [] | [] | [
"django",
"import",
"name_clash",
"package",
"python"
] | stackoverflow_0006104921_django_import_name_clash_package_python.txt |
Q:
Fully parsable dictionary/thesaurus
I'm in the early stages of designing a series of simple word games which I hope will help me learn new words. A crucial part of the ideas that I have is a fully parsable dictionary; I want to be able to use regular expressions to search the dictionary for given words and extract... | Fully parsable dictionary/thesaurus | I'm in the early stages of designing a series of simple word games which I hope will help me learn new words. A crucial part of the ideas that I have is a fully parsable dictionary; I want to be able to use regular expressions to search the dictionary for given words and extract certain other bits of information (e.g. ... | [
"The nltk wordnet corpus provides a programmatic interface to a \"large lexical database of English words\". You can navigate the word graph based on a variety of relationships. It meets the requirements for showing \"definition, part-of-speech, synonyms, antonyms, quotes\", and \"from a dictionary which is ideall... | [
7,
4,
2
] | [] | [] | [
"dictionary",
"macos",
"parsing",
"python",
"words"
] | stackoverflow_0006103907_dictionary_macos_parsing_python_words.txt |
Q:
How to display a volume with non-cubic voxels correctly in mayavi
I'm using mayavi (3.3.2) to display volume isosurfaces.
Generally, my volumes do not have cubic voxels; for example, the sampling grid might be 1mm x 1mm in X and Y, but 1.4mm in the Z direction.
How can I get such volumes to display with the correc... | How to display a volume with non-cubic voxels correctly in mayavi | I'm using mayavi (3.3.2) to display volume isosurfaces.
Generally, my volumes do not have cubic voxels; for example, the sampling grid might be 1mm x 1mm in X and Y, but 1.4mm in the Z direction.
How can I get such volumes to display with the correct spatial proportions using mayavi's mlab.contour3d or mlab.pipeline.is... | [
"For this, it's easiest to explicitly create a scalar_field object from the input data. \nI actually do this quite frequently, as we like to put things in depth (where positive is downwards) in geology. That means that you need a negative increment in the z-direction. It would be nice if it was just an argument t... | [
7
] | [] | [] | [
"mayavi",
"python",
"scipy",
"volume"
] | stackoverflow_0006076827_mayavi_python_scipy_volume.txt |
Q:
Can i use python OS /system modules inside django
I want to know that if i build a website in django then inside any django script can i use something like
os.listdir(path)
and get contents there or do i need to do something else to make that work?
A:
This should work fine. Why don't you try it?
| Can i use python OS /system modules inside django | I want to know that if i build a website in django then inside any django script can i use something like
os.listdir(path)
and get contents there or do i need to do something else to make that work?
| [
"This should work fine. Why don't you try it?\n"
] | [
2
] | [] | [] | [
"django",
"linux",
"python"
] | stackoverflow_0006105683_django_linux_python.txt |
Q:
How to filter two model objects by time?
models.py:
class Post(models.Model):
msg=models.TextField("Shout it out!:")
college=models.ForeignKey('College')
time=models.DateTimeField(auto_now_add=True)
class Feed(models.Model):
gender = models.CharField(max_length=5, choices=GENDER_CHOICES, default='girl')
... | How to filter two model objects by time? | models.py:
class Post(models.Model):
msg=models.TextField("Shout it out!:")
college=models.ForeignKey('College')
time=models.DateTimeField(auto_now_add=True)
class Feed(models.Model):
gender = models.CharField(max_length=5, choices=GENDER_CHOICES, default='girl')
location=models.CharField(max_length=25, choi... | [
"You might consider creating a base class containing the common fields. Then, you could do a query similar to BaseFeed.objects.all().order_by('time') and iterate through it in your template, but you could treat each result item as the type that it really is. \nclass BaseFeed(models.Model):\n ....\n msg = mo... | [
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0006104768_django_django_models_django_templates_django_views_python.txt |
Q:
Trying to learn F#...sort list of integers
I've been using Python the past couple of months and now am trying to give F# a whirl. Only...I don't really get it. I've been reading documentation for the past few days and still don't completely understand how to accomplish basic tasks.
I've been following the tuto... | Trying to learn F#...sort list of integers | I've been using Python the past couple of months and now am trying to give F# a whirl. Only...I don't really get it. I've been reading documentation for the past few days and still don't completely understand how to accomplish basic tasks.
I've been following the tutorials on tryfsharp.org and fsharp.net.
For ins... | [
"When porting code from an imperative language to a functional language, you should try to convert the algorithm that is used in the code, rather than the code itself IMHO.\nThe code is doing a selection sort so you want to ask yourself, what does the selection sort do?\n\nfind the minimum\nput it in the front of t... | [
5,
4,
2
] | [] | [] | [
"f#",
"python",
"sorting"
] | stackoverflow_0006105880_f#_python_sorting.txt |
Q:
Finding a small list of strings in a large list of strings (Python)
Hi I'm new to Python, so this may come across as a simple problem but I've been searching through Google many times and I can't seem to find a way to overcome it.
Basically I have a list of strings, taken from a CSV file. And I have another list o... | Finding a small list of strings in a large list of strings (Python) | Hi I'm new to Python, so this may come across as a simple problem but I've been searching through Google many times and I can't seem to find a way to overcome it.
Basically I have a list of strings, taken from a CSV file. And I have another list of strings in a text file. My job is to see if the words from my text file... | [
"import csv\n\ndef read_input(filename):\n f = open(filename)\n return csv.DictReader(f, delimiter = ',')\n\ndef search_filter(src, term):\n term = term.lower()\n for s in src:\n if term in map(str.lower, s.values()):\n yield s\n\ndef query(src, terms):\n terms = terms.split()\n ... | [
3
] | [] | [] | [
"csv",
"python",
"search"
] | stackoverflow_0006106131_csv_python_search.txt |
Q:
Specific IDE, for specific things
I need an IDE that can do the following:
Run on an oldish laptop (2GB Ram, 1.9 ghz intel celeron M)
Run well on an oldish laptop (with a browswer open)
Be able to run on windows
Be able to run smoothly on windows
Is able to do Java (or, if you really can't find anything, C# will ... | Specific IDE, for specific things | I need an IDE that can do the following:
Run on an oldish laptop (2GB Ram, 1.9 ghz intel celeron M)
Run well on an oldish laptop (with a browswer open)
Be able to run on windows
Be able to run smoothly on windows
Is able to do Java (or, if you really can't find anything, C# will be okay)
An extension or something for ... | [
"notepad++ has an ftp plugin that works very nicely and runs on very little resource. Will syntax highlight most languages and has some compiler support.\n",
"Eclipse with PyDev plugin gives you Java, Python and Django. Not sure about SFTP/FTP editing.\n",
"E Text Editor looks promising.\n",
"I think IntelliJ... | [
5,
3,
1,
1,
1,
0
] | [] | [] | [
"editor",
"ide",
"java",
"python"
] | stackoverflow_0006105273_editor_ide_java_python.txt |
Q:
Dynamic use of templates in Jinja2
I have to following scenario:
a python list of python dictionaries l = [a,b,c,...,n]
each element of the list is a python dictionary that looks something like this:
d = {}
d['type'] = 5
d['content'] = 'somestring'
Now i want all dictionaries as a list in in a main template. Howe... | Dynamic use of templates in Jinja2 | I have to following scenario:
a python list of python dictionaries l = [a,b,c,...,n]
each element of the list is a python dictionary that looks something like this:
d = {}
d['type'] = 5
d['content'] = 'somestring'
Now i want all dictionaries as a list in in a main template. However each dictionary's content should be ... | [
"If anyone needs it:\n{% for d in dicts %}\n {% set template = d.type + '.html' %} {% include template %}\n{% endfor %}\n\nthen in the template you can access the content like so:\n{{ d.content }}\n\nThanks to donri from the #pocoo channel on freenode !\n"
] | [
53
] | [] | [] | [
"flask",
"jinja2",
"python",
"templates"
] | stackoverflow_0006101864_flask_jinja2_python_templates.txt |
Q:
arranging a set of names such that two names are printed as one solution
How can arrange a set of names so that each solution has two names.for example
["bob", "sally", "jane"]
the outcome should be like;
bob & sally,
sally & jane etc, using python
Thanks in advance.
A:
>>> import itertools
>>> li = ["bob", "sal... | arranging a set of names such that two names are printed as one solution | How can arrange a set of names so that each solution has two names.for example
["bob", "sally", "jane"]
the outcome should be like;
bob & sally,
sally & jane etc, using python
Thanks in advance.
| [
">>> import itertools\n>>> li = [\"bob\", \"sally\", \"jane\"]\n>>> for i in itertools.combinations(li, 2):\n print i\n\nAnd you get:\n('bob', 'sally')\n('bob', 'jane')\n('sally', 'jane')\n\nCheck out the docs for itertools, especially on combinations and permutations. There are good code examples there showing ... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006106828_python.txt |
Q:
Django static files once again not working
I know this question appeared like a milion times, also I'm not a newbie django coder still recently I'm having terrible problems gotting static files work in django projects. Last time I worked around this by using 1.3 but now I'm working on 1.2.5 version and none of the... | Django static files once again not working | I know this question appeared like a milion times, also I'm not a newbie django coder still recently I'm having terrible problems gotting static files work in django projects. Last time I worked around this by using 1.3 but now I'm working on 1.2.5 version and none of the solutions works.
So basically I have statics wo... | [
"I guess it`s because of this:\n (r'^(?P<reqPath>[\\w\\-,.]+)/', views.globals_views),\n\nIt will intercept all request to static, and will call that view, which will cause TemplateDoesNotExist error.\nPut a static url before this or change this( and in urls that it refers to) regex.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"static",
"static_files"
] | stackoverflow_0006104526_django_python_static_static_files.txt |
Q:
How to rename a file and preserve creation date in Python
I know that the creation date isn't stored in the filesystem itself, but I'm encountering the problem that when I use os.rename, it's updating the creation date of the files I'm working with.
Is it possible to rename a file without changing its original cre... | How to rename a file and preserve creation date in Python | I know that the creation date isn't stored in the filesystem itself, but I'm encountering the problem that when I use os.rename, it's updating the creation date of the files I'm working with.
Is it possible to rename a file without changing its original creation date?
| [
"As said by Tudor you can use os.stat() and os.utime().\nstat = os.stat(myfile)\n# your code - rename access and modify your file\nos.utime(my_new_file, (stat.st_atime, stat.st_mtime))\n\n",
"You can read the timestamp before modifying it with os.stat(), keep it in som variable, rename the file, then change newfi... | [
12,
1
] | [] | [] | [
"filesystems",
"python"
] | stackoverflow_0006106303_filesystems_python.txt |
Q:
python pdf to text convert
I want to convert pdf into text. I tried this code in python command prompt but it is not showing any output. Maybe I'm wrong. Can you please tell me where im wrong. Thanks in advance.
import pyPdf
def getPDFContent(path):
content = ""
# Load PDF into pyPDF
pdf = pyPdf.PdfFi... | python pdf to text convert | I want to convert pdf into text. I tried this code in python command prompt but it is not showing any output. Maybe I'm wrong. Can you please tell me where im wrong. Thanks in advance.
import pyPdf
def getPDFContent(path):
content = ""
# Load PDF into pyPDF
pdf = pyPdf.PdfFileReader(file(path, "rb"))
#... | [
"If your PDF contains only images (e.g. from a scanned page) then you won't be able to extract any text.\n"
] | [
2
] | [] | [] | [
"pypdf",
"python"
] | stackoverflow_0006107195_pypdf_python.txt |
Q:
Printing a name only if it is longer than the one before it
Suppose you have a namelist ["sam", "janet", "bob","samantha"].
How would you write a program in Python such that it prints the name only if it is longer than the one before it.
A:
Using the pairwise recipe from itertools with a list comprehension strik... | Printing a name only if it is longer than the one before it | Suppose you have a namelist ["sam", "janet", "bob","samantha"].
How would you write a program in Python such that it prints the name only if it is longer than the one before it.
| [
"Using the pairwise recipe from itertools with a list comprehension strikes me as the most pythonic way:\n>>> from itertools import izip, tee\n>>> def pairwise(iterable):\n... \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n... a, b = tee(iterable)\n... next(b, None)\n... return izip(a, b)\n...\n>>> namel... | [
5,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006107086_python.txt |
Q:
Is it possible to filter choices on a foreign key in Django Admin panel?
Here is my situation:
I have three models : Grade, Course and Program.
Grade has a foreign key to Course and Course has a foreign key to Program.
Here is my problem:
When I need to add some grades in my admin panel, I have a listbox full of C... | Is it possible to filter choices on a foreign key in Django Admin panel? | Here is my situation:
I have three models : Grade, Course and Program.
Grade has a foreign key to Course and Course has a foreign key to Program.
Here is my problem:
When I need to add some grades in my admin panel, I have a listbox full of Course. First problem : same course name can be found in two different program ... | [
"I had a similar problem, here is the solution I came to:\nDefine a InlineModelAdmin for Grade in the ModelAdmin of Course.\nclass CourseAdmin(admin.ModelAdmin):\n class GradeInline(admin.StackedInline):\n model = Grade\n fk_name = 'course'\n extra = 2\n and so on\n\nThen you can add ... | [
0,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0006103132_django_django_admin_python.txt |
Q:
How would I play audio in Python 2.6.6 while displaying text?
I am trying to make a program with Python 2.6.6 that displays text while having audio playing in the background. I have only completed some of the text.
print "Well here we are again"
print "It’s always such a pleasure"
print "Remember when you tried to... | How would I play audio in Python 2.6.6 while displaying text? | I am trying to make a program with Python 2.6.6 that displays text while having audio playing in the background. I have only completed some of the text.
print "Well here we are again"
print "It’s always such a pleasure"
print "Remember when you tried to kill me twice?"
print "Oh, how we laughed and laughed"
print "Exce... | [
"I did a similar thing recently and used the audiere module \nimport audiere\nds = audiere.open_device()\nos = ds.open_array(input, fs)\nos.play()\n\nThis will open the first available audio device, since you're on windows it's probably DirectSound. input is just a numpy array, fs is the sampling frequency (since ... | [
4,
1,
1
] | [] | [] | [
"audio",
"python",
"python_2.6",
"wav"
] | stackoverflow_0006103657_audio_python_python_2.6_wav.txt |
Q:
Best way to match a large list against strings in python
I have a python list that contains about 700 terms that I would like to use as metadata for some database entries in Django. I would like to match the terms in the list against the entry descriptions to see if any of the terms match but there are a couple of... | Best way to match a large list against strings in python | I have a python list that contains about 700 terms that I would like to use as metadata for some database entries in Django. I would like to match the terms in the list against the entry descriptions to see if any of the terms match but there are a couple of issues. My first issue is that there are some multiword terms... | [
"If you need more flexibility to match entry descriptions, you can combine nltk and re\nfrom nltk.stem import PorterStemmer\nimport re\n\nlet's say you have different descriptions of the same event ie. a rewrite of the system. You can use nltk.stem to capture rewrite, rewriting, rewrites, singular and plural forms ... | [
2,
0
] | [] | [] | [
"list",
"pattern_matching",
"python"
] | stackoverflow_0006104576_list_pattern_matching_python.txt |
Q:
Randomizing a dictionary in python
I know you might say that dictionaries are not in any order naturally, but I have a large dictionary keys are numbers and some string as their values. The keys start from 0. for example: x={0:'a',1:'b',2:'c'}. I am using .iteritems() to go over my dictionary in a loop. however, t... | Randomizing a dictionary in python | I know you might say that dictionaries are not in any order naturally, but I have a large dictionary keys are numbers and some string as their values. The keys start from 0. for example: x={0:'a',1:'b',2:'c'}. I am using .iteritems() to go over my dictionary in a loop. however, this is done in the exact order of the ke... | [
"Use random.shuffle. Also, the key iteration order of a dictionary is not guaranteed by any means - you just happened to get (0, 1, 2).\nimport random\nkeys = my_dict.keys()\nrandom.shuffle(keys)\nfor key in keys:\n print key, my_dict[key]\n\n"
] | [
10
] | [] | [] | [
"dictionary",
"python",
"random"
] | stackoverflow_0006107861_dictionary_python_random.txt |
Q:
Designing callbacks with method "overloading" in Python
I design a validation API where call-backs are used to check values. There a two variants of callback signatures:
def check(self, value):
pass
def check(self, value, domain_object):
pass
Example for calling the callback implementations:
fo... | Designing callbacks with method "overloading" in Python | I design a validation API where call-backs are used to check values. There a two variants of callback signatures:
def check(self, value):
pass
def check(self, value, domain_object):
pass
Example for calling the callback implementations:
for constraint in constraints:
constraint.check(value)
... | [
"The most idiomatic way would be to first try with two arguments, and if it fails, try with one:\ntry:\n callback(value_param, domain_object_param)\nexcept TypeError:\n callback(value_param)\n\n",
"I like @Space_C0wb0y's answer, it is similar to code Raymond Hettinger sent to me to address a similar situati... | [
2,
2,
0
] | [] | [] | [
"callback",
"oop",
"overloading",
"python"
] | stackoverflow_0006069290_callback_oop_overloading_python.txt |
Q:
Problem with mod_wsgi: Getting a permission denied
Hello I seem to be getting an error when restarting my httpd.conf file for apache. I have tried to reinstall python, but that has not made any difference.
Recently, I had to do a clean installation on my server so I'm pretty much reinstalling and configuring every... | Problem with mod_wsgi: Getting a permission denied | Hello I seem to be getting an error when restarting my httpd.conf file for apache. I have tried to reinstall python, but that has not made any difference.
Recently, I had to do a clean installation on my server so I'm pretty much reinstalling and configuring everything.
`Starting httpd: httpd: Syntax error on line 200 ... | [
"This is covered in the mod_wsgi documentation at:\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues#Secure_Variants_Of_UNIX\n"
] | [
2
] | [] | [] | [
"apache2",
"django",
"httpd.conf",
"mod_wsgi",
"python"
] | stackoverflow_0006108301_apache2_django_httpd.conf_mod_wsgi_python.txt |
Q:
Recursively matching filenames with glob argument
I have been trying to get a list of files matching a glob pattern in a command line argument (sys.argv[1]) recursively using glob.glob and os.walk. The problem is, bash (and many other shells it seems) auto-expand glob patterns into filenames.
How do standard unix... | Recursively matching filenames with glob argument | I have been trying to get a list of files matching a glob pattern in a command line argument (sys.argv[1]) recursively using glob.glob and os.walk. The problem is, bash (and many other shells it seems) auto-expand glob patterns into filenames.
How do standard unix programs (e.g. grep -R) do this then? I realize they'r... | [
"The shell performs glob expansion before it even thinks of invoking the command. Programs such as grep don't do anything to prevent globbing: they can't. You, as the caller of these programs, must tell the shell that you want to pass the special characters such as * and ? to the program, and not let the shell inte... | [
6,
1,
1
] | [] | [] | [
"argv",
"bash",
"glob",
"python"
] | stackoverflow_0006103730_argv_bash_glob_python.txt |
Q:
Change the python version after installing django
I am trying to install mod_wsgi and django. When i "make" mod_wsgi then i get error if i use python2.7 but it went ok with default python.
i already wasted much time to figure that but could not solve it.
I just wanted to know that if continue with default python a... | Change the python version after installing django | I am trying to install mod_wsgi and django. When i "make" mod_wsgi then i get error if i use python2.7 but it went ok with default python.
i already wasted much time to figure that but could not solve it.
I just wanted to know that if continue with default python and install Django then can i change the python to 2.7 l... | [
"\nI just wanted to know that if continue with default python and install Django then can i change the python to 2.7 later\n\nYes. Upgrades are permitted. AFAIK, there's no law that says you are not permitted to upgrade. Indeed, why ask if an upgrade is possible? Have you been told that you're not permitted to ... | [
1
] | [] | [] | [
"django",
"mod_wsgi",
"python"
] | stackoverflow_0006108474_django_mod_wsgi_python.txt |
Q:
Can a Tkinter dialog be tied to a parent who is a completely different application
I am new to both python and gui programming.
I am working on a python script which would pop-up a Tkinter dialog which needs to sit on top of another application (say Outlook for example) and should not allow me to do anything in Ou... | Can a Tkinter dialog be tied to a parent who is a completely different application | I am new to both python and gui programming.
I am working on a python script which would pop-up a Tkinter dialog which needs to sit on top of another application (say Outlook for example) and should not allow me to do anything in Outlook until I click the cancel button on the tkinter dialog or until the dialog is withd... | [
"It's possible, but you have to be very, very careful. If you make a programming mistake you can effectively disable your computer. \nWhat you want to do is called a \"global grab\". That is, you grab all events. You do this with the tkinter command grab_set_global. You should test your application by adding a time... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006105571_python_tkinter.txt |
Q:
How to save data to database from browser in database - call python function
How to save data to database from browser, I have function which saves to database ( in python - cherrypy and I can collect easy data from form) and it works, but how to call this function on click event ?
A:
I didn't completely unders... | How to save data to database from browser in database - call python function | How to save data to database from browser, I have function which saves to database ( in python - cherrypy and I can collect easy data from form) and it works, but how to call this function on click event ?
| [
"I didn't completely understand the question.\nBut considering you have something like a checkbox in some CherryPy app,\nyou can pass the selected value forward as,\n<input type=\"checkbox\" name=\"cpu\" value=\"host1\" /> host1<br>\n\n.....\nclass Root(object):\n @cherrypy.expose\n\n def default(self, **... | [
0
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0006107816_cherrypy_python.txt |
Q:
Compare Dictionary Values for each key in the same Dictionary in Python
Update:
Hello again. My question is, how can I compare values of an dictionary for equality. More Informationen about my Dictionary:
keys are session numbers
values of each key are nested lists -> f.e.
[[1,0],[2,0],[3,1]]
the length of value... | Compare Dictionary Values for each key in the same Dictionary in Python | Update:
Hello again. My question is, how can I compare values of an dictionary for equality. More Informationen about my Dictionary:
keys are session numbers
values of each key are nested lists -> f.e.
[[1,0],[2,0],[3,1]]
the length of values for each key arent the same, so it could be that session number 1 have more... | [
"If your dictionary is long, you'd want to use sets, for better performance (looking up already-encountered values in lists is going to be quite slow):\ndef get_repeated_values(sessions):\n known = set()\n already_repeated = set()\n for lst in sessions.itervalues():\n session_set = set(tuple(x) for ... | [
2,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006108999_dictionary_python.txt |
Q:
Python modules importing
I have folder with such structure:
parent/
---__init__.py
---SomeClass.py
---Worker.py
First file (__init__.py) is empty.
Second file (SomeClass.py) content is following code:
class Test:
pass
Third file (Worker.py):
import SomeClass
Test()
ImportError: No module named SomeC... | Python modules importing | I have folder with such structure:
parent/
---__init__.py
---SomeClass.py
---Worker.py
First file (__init__.py) is empty.
Second file (SomeClass.py) content is following code:
class Test:
pass
Third file (Worker.py):
import SomeClass
Test()
ImportError: No module named SomeClass
What I do wrong?
| [
"Try\nfrom . import SomeClass\n\nbut remember you'll have to\nSomeClass.Text()\n\ninstead of just Test()\n"
] | [
1
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0006109455_import_module_python.txt |
Q:
Automatic DrawingArea scaling on resize with (Py)GTK
How can i scale the gtk.DrawingArea on window resize? I'm writing a code that will draw some colors in DrawingArea that will be added to an gtk.Table cell. I just need, that the image will be stretched in all of space of the cell.
sorry for my english.
thx
A:
... | Automatic DrawingArea scaling on resize with (Py)GTK | How can i scale the gtk.DrawingArea on window resize? I'm writing a code that will draw some colors in DrawingArea that will be added to an gtk.Table cell. I just need, that the image will be stretched in all of space of the cell.
sorry for my english.
thx
| [
"First create the table with homogeneous turned off:\ntable = gtk.Table(rows=1, columns=1, homogeneous=False)\n\nIf homogeneous is not turned off, every table cell will be as wide and tall as your DrawingArea.\nTo attach the DrawingArea to the table:\n table.attach(child, left_attach, right_attach, top_attach, bot... | [
1
] | [] | [] | [
"drawing",
"pygtk",
"python",
"scaling"
] | stackoverflow_0006109714_drawing_pygtk_python_scaling.txt |
Q:
Python/Pylons - Session Handling - User Session not active anymore
I use Pylons for the Session Handling on my Project. If an user session is not active anymore, the user get a 500 Server Error on FireBug. Now i want inform the user that this session is inactive and that he had to login again.
I can't find where t... | Python/Pylons - Session Handling - User Session not active anymore | I use Pylons for the Session Handling on my Project. If an user session is not active anymore, the user get a 500 Server Error on FireBug. Now i want inform the user that this session is inactive and that he had to login again.
I can't find where the Session is checked and the 500 Error is generated. Has someone an ide... | [
"If you are using pylons you wrote your own auth code (or at least modify it if you use something like repoze who&what). so you should check your code where did you put that chunk of code that returns 500 Error.\nbtw i saw that you posted a link from pylonsproject. pylonsproject != pylons.\nso if you are using pyra... | [
0
] | [] | [] | [
"exception",
"pylons",
"python",
"session"
] | stackoverflow_0006056657_exception_pylons_python_session.txt |
Q:
Writing XML files with Python
I have created an XML document with the following contents.
<books>
<book id="1">
<title>Title01</title>
<authors/>
<pages>
<page>Page01</page>
<page>Page02</page>
<page>Page03</page>
<page>Page04</page>
<page>Page05</page>
</pages>
</... | Writing XML files with Python | I have created an XML document with the following contents.
<books>
<book id="1">
<title>Title01</title>
<authors/>
<pages>
<page>Page01</page>
<page>Page02</page>
<page>Page03</page>
<page>Page04</page>
<page>Page05</page>
</pages>
</book>
<book id="2">
<title>Ti... | [
"Why don't you write the xml declaration to each book file before you write the book entry?\n",
"Encode your files in UTF-8 instead of some legacy encoding like ISO-8859-1. Then you don't need an XML declaration.\n",
"You should look into the xml.etree.ElementTree module. The link is for Python 3, but it was in... | [
0,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0006109469_python_xml.txt |
Q:
How do I get the modified date/time of a file in Python?
How do I get the modified date/time of a file in Python?
A:
os.path.getmtime(filepath)
or
os.stat(filepath).st_mtime
A:
Formated:
import time
print time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(fname)))
| How do I get the modified date/time of a file in Python? | How do I get the modified date/time of a file in Python?
| [
"os.path.getmtime(filepath)\n\nor\nos.stat(filepath).st_mtime\n\n",
"Formated:\nimport time\nprint time.strftime(\"%m/%d/%Y %I:%M:%S %p\",time.localtime(os.path.getmtime(fname)))\n\n"
] | [
39,
19
] | [] | [] | [
"file",
"python"
] | stackoverflow_0000121025_file_python.txt |
Q:
Multi-domain authentication options for google app engine
I am looking for some suggestions to implement authentication (and authorization) in our GAE app. Assuming that our app is called someapp, our requirement is as follows:
someapp is primarily for google apps users of the domain its installed for but can als... | Multi-domain authentication options for google app engine | I am looking for some suggestions to implement authentication (and authorization) in our GAE app. Assuming that our app is called someapp, our requirement is as follows:
someapp is primarily for google apps users of the domain its installed for but can also authenticate users from other google apps domains.
For exam... | [
"Authentication does not imply authorisation. All that the federated ID system does for your application is give you a username/userid that you can trust. So you can setup your user accounts tied to this infomation and rely on the fact that whenever you see that userid you are talking to the same user. Or in the ca... | [
0
] | [] | [] | [
"authentication",
"google_app_engine",
"python"
] | stackoverflow_0006107318_authentication_google_app_engine_python.txt |
Q:
Twisted Python + spawnProcess. Getting output from a command
I'm working to wrap the Minecraft server application with a Twisted Python server that has a RESTful API for getting the list of currently connected players. The Twisted app starts the minecraft server via reactor.spawnProcess(), then communicates via a ... | Twisted Python + spawnProcess. Getting output from a command | I'm working to wrap the Minecraft server application with a Twisted Python server that has a RESTful API for getting the list of currently connected players. The Twisted app starts the minecraft server via reactor.spawnProcess(), then communicates via a ProcessTransport, which writes to stdin. Reading stdout and stdin ... | [
"First, do not call writeSomeData ever. Call write. Second, having a global protocol instance is probably a bad idea, for all the usual reasons globals are generally a bad idea.\nThird, add a method to the ProcessProtocol subclass for getting the information you want. The protocol's job is knowing how to turn ab... | [
3
] | [] | [] | [
"minecraft",
"python",
"twisted"
] | stackoverflow_0006105760_minecraft_python_twisted.txt |
Q:
Zope 3 + windows + MySQL - How to install ZMySQLDA on windows?
I'm looking for instructions 'how to install ZMySQLDA on windows'
I have installed python 2.4, Zope 3, and I have downloaded The Zope MySQL Database Adapter (ZMySQLDA), available from http://www.zope.org/Members/adustman/Products/ZMySQLDA
I unpacked... | Zope 3 + windows + MySQL - How to install ZMySQLDA on windows? | I'm looking for instructions 'how to install ZMySQLDA on windows'
I have installed python 2.4, Zope 3, and I have downloaded The Zope MySQL Database Adapter (ZMySQLDA), available from http://www.zope.org/Members/adustman/Products/ZMySQLDA
I unpacked and copied library to zope/lip/python/Products directory and I rest... | [
"ZMySQLDA is a Zope2 Product; in Zope 3 I'd use SQLAlchemy integrated with zope.sqlalchemy (and optionally z3c.saconfig) to access MySQL data in your application.\nNote that your biggest problem is most likely one of being able to find the python MySQL drivers. See Integrating MySQL with Python in Windows for help ... | [
1,
0
] | [] | [] | [
"mysql",
"python",
"python_db_api",
"windows",
"zope"
] | stackoverflow_0006110016_mysql_python_python_db_api_windows_zope.txt |
Q:
SyntaxError: invalid syntax while building a dict from a list using Python 2.6
I created a Python script with Python2.7 and it works fine. However, when I run the same script with Python2.6, I got a "SyntaxError: invalid syntax" error.
After investigating, the problem seems to be related to a for loop.
l1 = [["a1... | SyntaxError: invalid syntax while building a dict from a list using Python 2.6 | I created a Python script with Python2.7 and it works fine. However, when I run the same script with Python2.6, I got a "SyntaxError: invalid syntax" error.
After investigating, the problem seems to be related to a for loop.
l1 = [["a1", "a2"], ["b1", "b2"]]
print {item[0]:item[1] for item in l1}
When I run the above... | [
"Try this:\nprint dict(item for item in l1)\n\nEdit about your comment: If you want to explicitly select items, wrap them in a tuple:\nprint dict((item[1], item[4]) for item in l1)\n\n",
"Dictionary comprehensions aren't available in Python 2.6. See Space_C0wb0y's answer for how to get around that in code.\n",
... | [
4,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0006110970_python.txt |
Q:
How to write container/wrapper class that adapts to member class interface?
I'm writing a class that wraps around an object of another class. The intend is to change some of its method behaviors while able to extend all of its other interfaces. I'm not using inheritance because the inner class object can die and o... | How to write container/wrapper class that adapts to member class interface? | I'm writing a class that wraps around an object of another class. The intend is to change some of its method behaviors while able to extend all of its other interfaces. I'm not using inheritance because the inner class object can die and outer class needs to be able to replace it with a live one without destroying itse... | [
"Something like the code below does what you want, but: 1) it is ugly; 2) it is not thread safe; 3) it falls into a loop until some method from Inner raises an exception (this is not due to the implementation but due to the initial idea posted); 4) some more reasons to avoid using it :)\nclass Inner:\n def foo(sel... | [
3,
0
] | [] | [] | [
"containers",
"python",
"wrapper"
] | stackoverflow_0006110799_containers_python_wrapper.txt |
Q:
Windows fails to pass the args to a python script
in py_script.py:
import os
import sys
l = len(sys.argv)
if l == 1:
print 'no args'
else:
if l > 1:
print 'first arg is %s'%sys.argv[1]
if l > 2:
print 'second arg is %s'%sys.argv[2]
now going command-line, on my winXP platform:
d:\p... | Windows fails to pass the args to a python script | in py_script.py:
import os
import sys
l = len(sys.argv)
if l == 1:
print 'no args'
else:
if l > 1:
print 'first arg is %s'%sys.argv[1]
if l > 2:
print 'second arg is %s'%sys.argv[2]
now going command-line, on my winXP platform:
d:\path\py_script.py 1 2
yields
first arg is 1
second arg ... | [
"I'm using 2.7.1 on Win 7.\nIf you want to invoke Python programs by file extension alone, you should check the file type associations and command line parameters. I have experienced issues when installing/reinstalling multiple versions of Python on Windows.\nC:\\dv>assoc .py\n.py=Python.File\n\nC:\\dv>ftype Python... | [
5,
1,
0
] | [] | [] | [
"command_line",
"python",
"windows",
"windows_7"
] | stackoverflow_0006109582_command_line_python_windows_windows_7.txt |
Q:
BlobReferenceProperty and ReferenceProperty model design
I have a design question is BlobReferenceProperty basically ReferenceProperty? Should I do prefetch (suggested by Nick http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine) like for ReferenceProperty?
Currently I have this design:
class... | BlobReferenceProperty and ReferenceProperty model design | I have a design question is BlobReferenceProperty basically ReferenceProperty? Should I do prefetch (suggested by Nick http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine) like for ReferenceProperty?
Currently I have this design:
class Entry(db.Model):
creator = db.ReferenceProperty(User, r... | [
"Blobreference property is similar to db.ReferenceProperty, except for the fact that the entity actually lies in the blobstore. So prefetching ReferenceProperty applies to BlobReferenceProperty as well. blobstore.py also includes get_value_for_datastore using which you can prefetch blob entities.\nComing to your se... | [
1,
0
] | [] | [] | [
"blobstore",
"google_app_engine",
"google_cloud_datastore",
"python",
"referenceproperty"
] | stackoverflow_0006109399_blobstore_google_app_engine_google_cloud_datastore_python_referenceproperty.txt |
Q:
How can I get contact name with his/her number
I'm trying to develop a simple app using Android Scripting and Python.
Now, I have a phone number, and I want to find out which contact has that number. I can do a contactsGet() and search for numbers, but so many programs uses that feature that, I think there is an ... | How can I get contact name with his/her number | I'm trying to develop a simple app using Android Scripting and Python.
Now, I have a phone number, and I want to find out which contact has that number. I can do a contactsGet() and search for numbers, but so many programs uses that feature that, I think there is an easier way for that.
There is a question with same p... | [
"package com.slk.example.CursorActivity;\nimport android.app.ListActivity;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.provider.Contacts.Phones;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport an... | [
1,
1,
0,
0
] | [] | [] | [
"android",
"android_scripting",
"python"
] | stackoverflow_0006009852_android_android_scripting_python.txt |
Q:
Unbound Local error in Python I can't shake!
http://pastie.org/1966237
I keep getting an unbound local error. I don't understand why it occurs, if the program is running right, it should go straight into the second assignment of the print_et_list function within the main function, looping itself without actually l... | Unbound Local error in Python I can't shake! | http://pastie.org/1966237
I keep getting an unbound local error. I don't understand why it occurs, if the program is running right, it should go straight into the second assignment of the print_et_list function within the main function, looping itself without actually looping. The program only quits using sys.exit() in... | [
"UnboundLocalError happens when you read the value of a local variable before you set it. Why is score a local variable rather than a global variable? Because you set it in the function. Consider these two functions:\ndef foo():\n print a\n\nvs\ndef bar():\n a = 1\n print a\n\nIn foo(), a is global, beca... | [
3,
0,
0,
0
] | [] | [] | [
"debugging",
"local",
"python"
] | stackoverflow_0006111544_debugging_local_python.txt |
Q:
Saving a file on desktop from a given url with a proxy server
My problem is that I want to save a file given by an url.
say the url is something like 'http://www.somesitename.com/Something/filename.fileextension"
for example
some_url = 'http://www.fordantitrust.com/files/python.pdf'
filename = myfile.pdf
I want ... | Saving a file on desktop from a given url with a proxy server | My problem is that I want to save a file given by an url.
say the url is something like 'http://www.somesitename.com/Something/filename.fileextension"
for example
some_url = 'http://www.fordantitrust.com/files/python.pdf'
filename = myfile.pdf
I want to download this file.
I know I can do it easily with urllib.urlret... | [
"Urllib is deprecated since Python 2.6, use urllib2 instead. Genereally, proxy is handled by urllib2 transparently if a global proxy is set. If not, try use urllib2.proxyhandler to set your proxy. \nSample code from python docs :\nproxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})\nproxy... | [
2
] | [] | [] | [
"proxy",
"python",
"urllib"
] | stackoverflow_0006110588_proxy_python_urllib.txt |
Q:
Python development - Storing results in a for loop
I am new to python and i am writing an XML file parser app. I have a directory full of XML files which i need to iterate through. Each file has attributes set such as 'HeadLine'. I am parsing the files with the code below
def index(request):
dirlist = glob.glo... | Python development - Storing results in a for loop | I am new to python and i am writing an XML file parser app. I have a directory full of XML files which i need to iterate through. Each file has attributes set such as 'HeadLine'. I am parsing the files with the code below
def index(request):
dirlist = glob.glob("/home/somebody/vids/*.xml")
for item in dirlist:
... | [
"The usual way to do this in Python is by appending to a list.\nresults = []\nfor item in dirlist:\n newsML = ET.parse(item)\n NewsLines = newsML.getroot()\n HeadLine = NewsLines.getiterator(\"HeadLine\")\n results.append(HeadLine)\n\nIf you also want to extract all the elements out of the iterator as a list, t... | [
5,
1
] | [] | [] | [
"django",
"php",
"python"
] | stackoverflow_0006111669_django_php_python.txt |
Q:
Limitations of PyTuple_SetItem
I have a Python extension module which creates a tuple as an attribute of another object, and sets items in the tuple. Whenever I execute this module in Python, I keep getting the error SystemError: bad argument to internal function
After reading over the docs for PyTuple, and debug... | Limitations of PyTuple_SetItem | I have a Python extension module which creates a tuple as an attribute of another object, and sets items in the tuple. Whenever I execute this module in Python, I keep getting the error SystemError: bad argument to internal function
After reading over the docs for PyTuple, and debugging my program for a few hours, I s... | [
"I'm quite sure that you can get around the restrictions by using PyTuple_SET_ITEM instead of PyTuple_SetItem. PyTuple_SET_ITEM is a macro defined in tupleobject.h as follows:\n#define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject*)(op))->ob_item[i] = v\n\nSo, if you are absolutely, definitely and utterly sure that:\... | [
8,
2
] | [] | [] | [
"c",
"python",
"python_c_api",
"tuples"
] | stackoverflow_0006111843_c_python_python_c_api_tuples.txt |
Q:
Graphical User Interfaces for cracks, keygens, etc
Have you ever used those cracks and keygens with the really nice interfaces and 8-bit music playing in the bg with special effects when you clicked buttons and stuff? I'd like to create works like such (the GUI part), but I'm wondering which GUI toolkit has that k... | Graphical User Interfaces for cracks, keygens, etc | Have you ever used those cracks and keygens with the really nice interfaces and 8-bit music playing in the bg with special effects when you clicked buttons and stuff? I'd like to create works like such (the GUI part), but I'm wondering which GUI toolkit has that kind of flexibility.
Do all GUI toolkits have the ability... | [
"I'd wager most of those cracks are written in C or even assembly language, using the Windows API at a very low level. Very few, if any, are written in Python, and positively none are written using GTK. :) Crackers have different aesthetics than ordinary programmers, and they tend to idealize low-level programs wit... | [
2
] | [] | [] | [
"interface",
"python",
"user_interface"
] | stackoverflow_0006111171_interface_python_user_interface.txt |
Q:
SendKeys for Python 3.1 on Windows
The latest Python Sendkeys module is for Python 2.6. I can't upgrade it myself as it needs the C module to be recompiled.
Does anyone know of a fairly easy alternative way to send keys to a window?
Using win32ui.FindWindow() I can find the right window, then make it active with P... | SendKeys for Python 3.1 on Windows | The latest Python Sendkeys module is for Python 2.6. I can't upgrade it myself as it needs the C module to be recompiled.
Does anyone know of a fairly easy alternative way to send keys to a window?
Using win32ui.FindWindow() I can find the right window, then make it active with PyCWnd.SetActiveWindow(), so all that's n... | [
"Here is a working module that calls user32.SendInput().\nNot perfect, but usable.\nEdit: \nYesterday I did a version with a class, and am using it in a working tkinter app. Will put it here when i get time to clean it up.\nHave added this in the doc string below:\n[ It is OK if I work from a folder within my profi... | [
9,
5,
2,
0
] | [] | [] | [
"python",
"sendkeys"
] | stackoverflow_0001823762_python_sendkeys.txt |
Q:
Debugging Trivia game in Python
Creating function to print question, add choices to a list.
def print_et_list ():
answer_list = []
function = open ("modStory.txt","r")
#Question
question = function.readline()
print question
#Choices
one = answer_list.append (function.readline())
two... | Debugging Trivia game in Python | Creating function to print question, add choices to a list.
def print_et_list ():
answer_list = []
function = open ("modStory.txt","r")
#Question
question = function.readline()
print question
#Choices
one = answer_list.append (function.readline())
two = answer_list.append (function.readl... | [
"To correct the infinite loop, avoid to re-open the file on each call to print_et_list()\nTry this (I renamed function into file_handle to be a little more explicit while reading the code)\nimport sys\n\ndef print_et_list (file_handle):\n answer_list = []\n #Question\n question = file_handle.readline()\n ... | [
2,
0
] | [] | [] | [
"debugging",
"python",
"text_files"
] | stackoverflow_0006112162_debugging_python_text_files.txt |
Q:
UnicodeDecodeError while using cyryllic
I have a module which contains only (it's only example. Problem is in much bigger module):
# -*- coding: utf-8 -*-
"януари"
While execution I get:
File "C:\Program Files\JetBrains\PyCharm 107.130\helpers\pydev\pydevd.py", line 1184, in <module>
debugger.run(setup['file'... | UnicodeDecodeError while using cyryllic | I have a module which contains only (it's only example. Problem is in much bigger module):
# -*- coding: utf-8 -*-
"януари"
While execution I get:
File "C:\Program Files\JetBrains\PyCharm 107.130\helpers\pydev\pydevd.py", line 1184, in <module>
debugger.run(setup['file'], None, None)
File "C:\Program Files\JetBr... | [
"That module is not the problem, it seems to be a problem with PyCharm. It apparently reads your file, and assumes it's cp1250, even when it's specified to be utf-8. So that's a bug in PyCharm. \nIt should open the file as binary, read the first line to see if it has an encoding, in other case it should assume it t... | [
5,
0
] | [] | [] | [
"encoding",
"pycharm",
"python"
] | stackoverflow_0006109022_encoding_pycharm_python.txt |
Q:
Deploying to production with buildout and minimal downtime?
I've got a buildout with django + wsgi that's working nicely on dev and production. The only issue is that when I make a change or addition to the buildout.cfg and have to run bin/buildout, the website goes offline from the time buildout starts till the ... | Deploying to production with buildout and minimal downtime? | I've got a buildout with django + wsgi that's working nicely on dev and production. The only issue is that when I make a change or addition to the buildout.cfg and have to run bin/buildout, the website goes offline from the time buildout starts till the time it finishes. This can take upwards of 5 minutes.
Is there a ... | [
"Buildout will only update parts where the configuration has changed (or in case of a stupid recipe implementation). One option is to copy/checkout the buildout configuration into a new location re-run buildout and then stop the old instance and then restart the instance on the new installation. In some case we mai... | [
4
] | [] | [] | [
"buildout",
"deployment",
"django",
"python"
] | stackoverflow_0006112682_buildout_deployment_django_python.txt |
Q:
Script having trouble passing Unicode through a REST interface
I am having trouble getting my Python script to ass Unicode data over RESTful http call.
I have a script that reads data from web site X using a REST interface and then pushes it into web site Y using it's REST interface. Both system are open source a... | Script having trouble passing Unicode through a REST interface | I am having trouble getting my Python script to ass Unicode data over RESTful http call.
I have a script that reads data from web site X using a REST interface and then pushes it into web site Y using it's REST interface. Both system are open source and are run on our servers. Site X uses PHP, Apache and PostgreSQL. ... | [
"With regard to your test script, it is failing because you are passing unicode object to urllib.urlencode() (it is being called for you by urlopen()). It does not support unicode objects, so it implicitly encodes using the default charset, which is ascii. Obviously, it fails.\nThe simplest way to handle POSTing un... | [
2
] | [] | [] | [
"python",
"rest",
"unicode"
] | stackoverflow_0006112226_python_rest_unicode.txt |
Q:
Python global/package alias implementation class
I have that strange feeling this is an easy question.
I want to be able to "alias" a class type so i can swap out the implementation at a package level. I dont want to have X amount of import X as bah scattered throughout my code...
Aka. How can I do something like... | Python global/package alias implementation class | I have that strange feeling this is an easy question.
I want to be able to "alias" a class type so i can swap out the implementation at a package level. I dont want to have X amount of import X as bah scattered throughout my code...
Aka. How can I do something like the below:
class BaseClass(object):
def __init__(s... | [
"In any file (where this fits best is up to you, probably wherever Implementation was defined):\nBaseClassProxy = Implementation\n\nSince classes are first class objects in Python, you can pretty much bind them to any variable and use them the same way. In this case, you can make an alias for the class.\n",
"just... | [
5,
2
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006113142_python_python_2.7.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.