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: Python Twisted: restricting access by IP address What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example w...
Python Twisted: restricting access by IP address
What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example where someone patched twcgi.py to set environment varia...
[ "When a connection is established, a factory's buildProtocol is called to create a new protocol instance to handle that connection. buildProtocol is passed the address of the peer which established the connection and buildProtocol may return None to have the connection closed immediately.\nSo, for example, you can...
[ 5, 2, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0001273297_python_twisted.txt
Q: Simulate multiple IP addresses for testing I need to simulate multiple embedded server devices that are typically used for motor control. In real life, there can be multiple servers on the network and our desktop software acts as a client to all the motor servers simultaneously. We have a half-dozen of these mot...
Simulate multiple IP addresses for testing
I need to simulate multiple embedded server devices that are typically used for motor control. In real life, there can be multiple servers on the network and our desktop software acts as a client to all the motor servers simultaneously. We have a half-dozen of these motor control servers on hand for basic testing, bu...
[ "You should set up a virtual network adapter. They are called TAP/TUN devices. If you are using windows, you can easily setup some dummy addresses with somthing like this:\nhttp://www.ntkernel.com/w&p.php?id=32\nGood luck!\n", "A. consider using Bonjour (zeroconf) for service discovery\nB. You can assign 1 or mor...
[ 6, 5, 2 ]
[]
[]
[ ".net", "networking", "python", "sockets" ]
stackoverflow_0001308879_.net_networking_python_sockets.txt
Q: Running function 5 seconds after pygtk widget is shown How to run function 5 seconds after pygtk widget is shown? A: You can use glib.timeout_add(interval, callback, ...) to periodically call a function. If the function returns True then it will be called again after the interval; if the function return False th...
Running function 5 seconds after pygtk widget is shown
How to run function 5 seconds after pygtk widget is shown?
[ "You can use glib.timeout_add(interval, callback, ...) to periodically call a function.\nIf the function returns True then it will be called again after the interval; if the function return False then it will not be called again.\nHere is a short example of adding a timeout after a widget's show event:\nimport pygt...
[ 15, 9 ]
[]
[]
[ "function", "pygtk", "python", "time" ]
stackoverflow_0001309006_function_pygtk_python_time.txt
Q: In GTK, is there an easy way to scale all widgets by an arbitrary amount? I want my widget to look exactly like it does now, except to be smaller. It includes buttons, labels, text, images, etc. Is there any way to just say "scale this to be half the size", and have GTK do all the image processing, widget resizing...
In GTK, is there an easy way to scale all widgets by an arbitrary amount?
I want my widget to look exactly like it does now, except to be smaller. It includes buttons, labels, text, images, etc. Is there any way to just say "scale this to be half the size", and have GTK do all the image processing, widget resizing, etc., necessary? If not, what's the easiest way to accomplish this?
[ "Change the theme from the user interface is not something that I recommend, but you can do it if you require it, using a custom gtkrc may help you to change the font and the way the buttons are drawed, mostly because of the xthickness and ythickness.\n import gtk\n file = \"/path/to/the/gtkrc\"\n gtk.rc_parse(file...
[ 2, 2, 1, 1 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0001269268_gtk_pygtk_python_user_interface.txt
Q: Does a UDP service have to respond from the connected IP address? Pyzor uses UDP/IP as the communication protocol. We recently switched the public server to a new machine, and started getting reports of many timeouts. I discovered that I could fix the problem if I changed the IP that was queried from eth0:1 to e...
Does a UDP service have to respond from the connected IP address?
Pyzor uses UDP/IP as the communication protocol. We recently switched the public server to a new machine, and started getting reports of many timeouts. I discovered that I could fix the problem if I changed the IP that was queried from eth0:1 to eth0. I can reproduce this problem with a simple example: This is the se...
[ "I came across this with a TFTP server. My server had two IP addresses facing the same network. Because UDP is connectionless, there can be issues with IP addresses not being set as expected in that situation. The sequence I had was:\n\nClient sends the initial packet to the server at a particular IP address\nServe...
[ 3, 1 ]
[]
[]
[ "ip", "multihomed", "python", "sockets", "udp" ]
stackoverflow_0001309370_ip_multihomed_python_sockets_udp.txt
Q: Python String Formatting And String Multiplication Oddity Python is doing string multiplication where I would expect it to do numeric multiplication, and I don't know why. >>> print('%d' % 2 * 4) 2222 >>> print('%d' % (2 * 4)) 8 Even forcing the type to integer does nothing. (I realize this is redundant, but it's...
Python String Formatting And String Multiplication Oddity
Python is doing string multiplication where I would expect it to do numeric multiplication, and I don't know why. >>> print('%d' % 2 * 4) 2222 >>> print('%d' % (2 * 4)) 8 Even forcing the type to integer does nothing. (I realize this is redundant, but it's an idiot-check for me: >>> print('%d' % int(2) * int(4)) 222...
[ "You are experiencing operator precedence.\nIn python % has the same precedence as * so they group left to right.\nSo,\nprint('%d' % 2 * 4)\n\nis the same as,\nprint( ('%d' % 2) * 4)\n\nHere is the python operator precedence table.\nSince it is difficult to remember operator precedence rules, and the rules can be s...
[ 12, 2 ]
[]
[]
[ "formatting", "operator_precedence", "python", "string" ]
stackoverflow_0001309737_formatting_operator_precedence_python_string.txt
Q: Is it possible to peek at the data in a urllib2 response? I need to detect character encoding in HTTP responses. To do this I look at the headers, then if it's not set in the content-type header I have to peek at the response and look for a "<meta http-equiv='content-type'>" header. I'd like to be able to write ...
Is it possible to peek at the data in a urllib2 response?
I need to detect character encoding in HTTP responses. To do this I look at the headers, then if it's not set in the content-type header I have to peek at the response and look for a "<meta http-equiv='content-type'>" header. I'd like to be able to write a function that looks and works something like this: response =...
[ "def detectit(response):\n # try headers &c, then, worst case...:\n content = response.read()\n response.read = lambda: content\n # now detect based on content\n\nThe trick of course is ensuring that response.read() WILL return the same thing again if needed... that's why we assign that lambda to it if nece...
[ 4, 0 ]
[]
[]
[ "encoding", "html", "http", "python", "urllib2" ]
stackoverflow_0001308584_encoding_html_http_python_urllib2.txt
Q: How to set smtplib sending timeout in python 2.4? I'm having problems with smtplib tying up my program when email sending fails, because a timeout is never raised. The server I'm using does not and will never have python greater than 2.4, so I can't make use of the timeout argument to the SMTP constructor in later...
How to set smtplib sending timeout in python 2.4?
I'm having problems with smtplib tying up my program when email sending fails, because a timeout is never raised. The server I'm using does not and will never have python greater than 2.4, so I can't make use of the timeout argument to the SMTP constructor in later versions of python. Python 2.4's docs show that the SM...
[ "import socket\nsocket.setdefaulttimeout(120)\n\nwill make any socket time out after 2 minutes, unless the specific socket's timeout is changed (and I believe SMTP in Python 2.4 doesn't do the latter).\nEdit: apparently per OP's comment this breaks TLS, so, plan B...:\nWhat about grabbing 2.6's smtplib source file ...
[ 6 ]
[]
[]
[ "python", "python_2.4", "smtplib" ]
stackoverflow_0001309991_python_python_2.4_smtplib.txt
Q: How can i use TurboMail 3 together with TurboGears 2 Hy, I want to use TurboMail3 (website) together with a TurboGears 2(website) project. Which files to I have to modify to include TurboMail into my TurboGears project? Everything I find on the web is for TurboMail2 and TurboGears1. The TurboMail Documentation st...
How can i use TurboMail 3 together with TurboGears 2
Hy, I want to use TurboMail3 (website) together with a TurboGears 2(website) project. Which files to I have to modify to include TurboMail into my TurboGears project? Everything I find on the web is for TurboMail2 and TurboGears1. The TurboMail Documentation states that there actually is a TG2 integration but I never ...
[ "The integration is currently the same as for Pylons. There is a ticket for a TG2 specific integration which is currently in our bug tracker. If you really want answers for that topic, please ask in the turbomail google group: http://groups.google.com/group/turbomail-devel\n", "This might help you along: Getting ...
[ 1, 0 ]
[]
[]
[ "email", "python", "turbogears" ]
stackoverflow_0000598019_email_python_turbogears.txt
Q: oop instantiation pythonic practices I've got the code below, and I was planning on making several classes all within the same "import". I was hoping to instantiate each class and get a return value with the widgets I'm making. This isn't really a PyQt question at all, more of a "good practices" question, as I'll...
oop instantiation pythonic practices
I've got the code below, and I was planning on making several classes all within the same "import". I was hoping to instantiate each class and get a return value with the widgets I'm making. This isn't really a PyQt question at all, more of a "good practices" question, as I'll have a class for each widget. Should I ...
[ "The answer will be decided if the list of tabs can be changed at runtime. If this widget really only supports adding a set of tabs, but never changing or appending new ones, the list of tabs should come from the initializer. Otherwise you should also add a method to do the job. Consider the QLabel widget which can...
[ 4 ]
[]
[]
[ "oop", "pyqt", "python" ]
stackoverflow_0001310158_oop_pyqt_python.txt
Q: Refresh QTextEdit in PyQt Im writing a PyQt app that takes some input in one widget, and then processes some text files. What ive got at the moment is when the user clicks the "process" button a seperate window with a QTextEdit in it pops up, and ouputs some logging messages. On Mac OS X this window is refreshed a...
Refresh QTextEdit in PyQt
Im writing a PyQt app that takes some input in one widget, and then processes some text files. What ive got at the moment is when the user clicks the "process" button a seperate window with a QTextEdit in it pops up, and ouputs some logging messages. On Mac OS X this window is refreshed automatically and you cna see th...
[ "It looks like your are running an external program, capturing its output into a QTextEdit. I didn't see the code of Form.process, but I am guessing on windows your function waits for the external program to finish, then quickly dumps everything to the QTextEdit. \nIf your interface really is waiting for the other ...
[ 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0001310142_pyqt_python.txt
Q: What does "built-in method decode" mean in Python when profiling? I'm trying to make my program faster, so I'm profiling it. Right now the top reason is: 566 1.780 0.003 1.780 0.003 (built-in method decode) What is this exactly? I never call 'decode' anywhere in my code. It reads text files, but I don...
What does "built-in method decode" mean in Python when profiling?
I'm trying to make my program faster, so I'm profiling it. Right now the top reason is: 566 1.780 0.003 1.780 0.003 (built-in method decode) What is this exactly? I never call 'decode' anywhere in my code. It reads text files, but I don't believe they are unicode-encoded.
[ "Most likely, this is the decode method of string objects.\n", "Presumably this is str.decode ... search your source for \"decode\". If it's not in your code, look at Python library routines that show up in the profile results. It's highly unlikely to be to be anything to do with cPickle. Care to show us a few mo...
[ 2, 1, 1, 0 ]
[]
[]
[ "optimization", "performance", "pickle", "python", "string" ]
stackoverflow_0001310201_optimization_performance_pickle_python_string.txt
Q: What is the best way to create a Python object when you have the class implementaion stored in a string? What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string? For background, I am working in the Google Application Engine environment and I want...
What is the best way to create a Python object when you have the class implementaion stored in a string?
What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string? For background, I am working in the Google Application Engine environment and I want to be able to load classes dynamically from a string version of the class. problem = “1,2,3,4,5” solvertext...
[ "Alas, exec is your only choice, but at least do it right to avert disaster: pass an explicit dictionary (with an in clause, of course)! E.g.:\n>>> class X(object): pass\n... \n>>> x=X()\n>>> exec 'a=23' in vars(x)\n>>> x.a\n23\n\nthis way you KNOW the exec won't pollute general namespaces, and whatever classes ar...
[ 9, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001310254_python.txt
Q: Is it possible to filter on a related item in Django annotations? I have the following 2 models: class Job(models.Model): title = models.CharField(_('title'), max_length=50) description = models.TextField(_('description')) category = models.ForeignKey(JobCategory, related_name='jobs') created_date ...
Is it possible to filter on a related item in Django annotations?
I have the following 2 models: class Job(models.Model): title = models.CharField(_('title'), max_length=50) description = models.TextField(_('description')) category = models.ForeignKey(JobCategory, related_name='jobs') created_date = models.DateTimeField(auto_now_add=True) class JobCategory(models.Mod...
[ "Just a guess... but would this work?\ndef job_categories():\n thritydaysago = datetime.datetime.now() - datetime.timedelta(days=30)\n categories = JobCategory.objects.filter(job__created_date__gte=thritydaysago).annotate(num_postings=Count('jobs'))\n return {'categories': categories}\n\nSee\"lookups-that-...
[ 4, 1 ]
[]
[]
[ "annotations", "django", "django_queryset", "python" ]
stackoverflow_0001292081_annotations_django_django_queryset_python.txt
Q: HTML forms not working with python I've created a HTML page with forms, which takes a name and password and passes it to a Python Script which is supposed to print the persons name with a welcome message. However, after i POST the values, i'm just getting the Python code displayed in the browser and not the welcom...
HTML forms not working with python
I've created a HTML page with forms, which takes a name and password and passes it to a Python Script which is supposed to print the persons name with a welcome message. However, after i POST the values, i'm just getting the Python code displayed in the browser and not the welcome message. I have stored the html file a...
[ "This\n\ni'm just getting the Python code\n displayed in the browser\n\nsounds like CGI handling with Apache and Python is not configured correctly.\nYou can narrow the test case by passing UserName and PassWord as GET parameters:\nhttp://example.com/cgi-bin/my-script.py?UserName=Foo&PassWord=bar\n\nWhat happens i...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001310443_python.txt
Q: is there similar syntax to php's $$variable in python is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value. for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php'...
is there similar syntax to php's $$variable in python
is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value. for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php's $$variable will be much convenient. what I am after is so...
[ "def load_module_attr (path):\n modname, attr = path.rsplit ('.', 1)\n mod = __import__ (modname, {}, {}, [attr])\n return getattr (mod, attr)\n\ndef my_view (request):\n model_name = \"myapp.models.Song\" # Get from command line, user, wherever\n model = load_module_attr (model_name)\n print mode...
[ 3, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001309366_django_python.txt
Q: Getting rid of Python console in wxPython under Windows Possible Duplicate: How can I hide the console window in a PyQt app running on Windows? How to get rid of the console that shows up as standard output when running wxPython programs in Windows? A: Not familiar with wxPython, but if you invoke your script ...
Getting rid of Python console in wxPython under Windows
Possible Duplicate: How can I hide the console window in a PyQt app running on Windows? How to get rid of the console that shows up as standard output when running wxPython programs in Windows?
[ "Not familiar with wxPython, but if you invoke your script with pythonw.exe rather than python.exe, the console window shouldn't appear. I believe saving the script as script.pyw also works.\n", "Others have already suggested of renaming from py to pyw.\nIf you instead refer to Output redirection pass redirect=Tr...
[ 6, 6, 6, 3 ]
[]
[]
[ "console", "python", "windows", "windows_console", "wxpython" ]
stackoverflow_0001310972_console_python_windows_windows_console_wxpython.txt
Q: How nicely does Python 'flow' with HTML as compared to PHP? I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use <? and ?> to put PHP where I want, and am then fr...
How nicely does Python 'flow' with HTML as compared to PHP?
I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use <? and ?> to put PHP where I want, and am then free to arrange/organize my HTML however I want. Is it just as easy...
[ "You can't easily compare PHP and Python.\nPHP is a web processing framework that is designed specifically as an Apache plug-in. It includes HTTP protocol handling as well as a programming language.\nPython is \"just\" a programming language. There are many Python web frameworks to plug Python into Apache. There...
[ 26, 2, 2, 1, 0 ]
[]
[]
[ "html", "php", "python" ]
stackoverflow_0001311789_html_php_python.txt
Q: Problem while running python script in java code When i run a python script from the below java code, where an input file is given as an argument to the python script as well as an "-v" option, i get a IOException String pythonScriptPath="\"C:\\Program Files\\bin\\CsvFile.py\""; String Filepath="C:\\Documents and ...
Problem while running python script in java code
When i run a python script from the below java code, where an input file is given as an argument to the python script as well as an "-v" option, i get a IOException String pythonScriptPath="\"C:\\Program Files\\bin\\CsvFile.py\""; String Filepath="C:\\Documents and Settings\\user\\Desktop\\arbit.csv"; String[] cmd = ne...
[ "error=2 means the Win32 CreateProcess function is returning an error code of 2, or ERROR_FILE_NOT_FOUND. Either it can't find your script, or (more likely, IMO) it can't find python.exe. If it's the latter, make sure your Python installation (possibly C:\\Program Files\\Python\\bin, though I'm not sure) is in your...
[ 2, 0, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0001311513_java_python.txt
Q: Help with Python while loop behaviour I have a script that uses a simple while loop to display a progress bar but it doesn't seem to be working as I expected: count = 1 maxrecords = len(international) p = ProgressBar("Blue") t = time while count < maxrecords: print 'Processing %d of %d' % (count, maxrecords) ...
Help with Python while loop behaviour
I have a script that uses a simple while loop to display a progress bar but it doesn't seem to be working as I expected: count = 1 maxrecords = len(international) p = ProgressBar("Blue") t = time while count < maxrecords: print 'Processing %d of %d' % (count, maxrecords) percent = float(count) / float(maxrecord...
[ "I see you are using the ProgressBar implementation on my website. If you want to print a message you can use the message argument in render\np.render(percent, message='Processing %d of %d' % (count, maxrecords))\n\n", "That's not the way to write a loop in Python.\nmaxrecords = len(international)\np = ProgressBa...
[ 5, 3, 2, 1 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0001312421_python_while_loop.txt
Q: display a QMessageBox PyQT when a different combobox /list box item is selected I have a combo box cbLayer and a function do_stuff of the following form: def do_stuff(item_selected_from_cbLayer): new_list = [] # do stuff based on item_selected_from_combobox and put the items in new_list return new_list...
display a QMessageBox PyQT when a different combobox /list box item is selected
I have a combo box cbLayer and a function do_stuff of the following form: def do_stuff(item_selected_from_cbLayer): new_list = [] # do stuff based on item_selected_from_combobox and put the items in new_list return new_list How can I get a QMessageBox to pop up whenever a different item is selected in the ...
[ "Write a method or function that contains this code and attach it to the combo boxes signal currentIndexChanged:\ndef __init__(self):\n ...\n QObject.connect(self.cbLayer, SIGNAL(\"currentIndexChanged(int)\"), self.warn)\n\ndef warn(index):\n QMessageBox.warning(self, \"items: \", do_stuff(cbLayer.itemData...
[ 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0001312598_pyqt_python.txt
Q: Python - ambiguity with decorators receiving a single arg I am trying to write a decorator that gets a single arg, i.e @Printer(1) def f(): print 3 So, naively, I tried: class Printer: def __init__(self,num): self.__num=num def __call__(self,func): def wrapped(*args,**kargs): ...
Python - ambiguity with decorators receiving a single arg
I am trying to write a decorator that gets a single arg, i.e @Printer(1) def f(): print 3 So, naively, I tried: class Printer: def __init__(self,num): self.__num=num def __call__(self,func): def wrapped(*args,**kargs): print self.__num return func(*args,**kargs...
[ "Well, it's already effectively prevented, in the sense that calling a() doesn't work.\nBut to stop it as the function is defined, I suppose you'd have to change __init__ to check the type of num:\ndef __init__(self,num):\n if callable(num):\n raise TypeError('Printer decorator takes an argument')\n se...
[ 4, 1, 1, 1 ]
[]
[]
[ "arguments", "decorator", "python" ]
stackoverflow_0001312785_arguments_decorator_python.txt
Q: Inserting python tuple in a MySQL database I need to insert a python tuple (of floats) into a MySQL database. In principle I could pickle it and insert it as a string, but that would grant me the chance only to retrieve it through python. Alternative is to serialize the tuple to XML and store the XML string. What ...
Inserting python tuple in a MySQL database
I need to insert a python tuple (of floats) into a MySQL database. In principle I could pickle it and insert it as a string, but that would grant me the chance only to retrieve it through python. Alternative is to serialize the tuple to XML and store the XML string. What solutions do you think would be also possible, w...
[ "Make another table and do one-to-many. Don't try to cram a programming language feature into a database as-is if you can avoid it.\nIf you absolutely need to be able to store an object down the line, your options are a bit more limited. YAML is probably the best balance of human-readable and program-readable, an...
[ 3, 2, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001313000_mysql_python.txt
Q: Porting python app to mobile platforms I have a python app running fine on Windows, Linux and Mac which I would like to port to multiple mobile platforms such as Blackberry, Windows Mobile, Palm, Android and iPhone. I have couple of ideas: port app to platform supporting some kind of Python like Android and Windo...
Porting python app to mobile platforms
I have a python app running fine on Windows, Linux and Mac which I would like to port to multiple mobile platforms such as Blackberry, Windows Mobile, Palm, Android and iPhone. I have couple of ideas: port app to platform supporting some kind of Python like Android and Windows Mobile port app to Java to target most pl...
[ "Here's what we're doing ...\nMake the app a generic web application/website. Host it on your server and have your server detect the type of browser. If it is a mobile browser, show the small-screen version of your app.\nOnce you get that going, create individual apps for the particular phones/mobile hardware. T...
[ 4, 1 ]
[]
[]
[ "mobile", "porting", "python" ]
stackoverflow_0001313164_mobile_porting_python.txt
Q: Using list_filter with Intermediary Models We have three models, Artist: class Artist(models.Model): family_name = models.CharField(max_length=50) given_name = models.CharField(max_length=50) Group: class Group(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(...
Using list_filter with Intermediary Models
We have three models, Artist: class Artist(models.Model): family_name = models.CharField(max_length=50) given_name = models.CharField(max_length=50) Group: class Group(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(Artist, through='Membership') and Membership: c...
[ "If you define a m2m between artist and group using through=Membership, you can set up a filter directly on group without going through membership. Can't remember if the syntax is \nlist_filter = ['group']\n\nor\nlist_filter = ['group_set']\n\nor something similar.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0001309348_django_django_admin_python.txt
Q: Python: what kind of literal delimiter is "better" to use? What is the best literal delimiter in Python and why? Single ' or double "? And most important, why? I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the ...
Python: what kind of literal delimiter is "better" to use?
What is the best literal delimiter in Python and why? Single ' or double "? And most important, why? I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?
[ "' because it's one keystroke less than \". Save your wrists!\nThey're otherwise identical (except you have to escape whichever you choose to use, if they appear inside the string).\n", "Consider these strings:\n\"Don't do that.\"\n'I said, \"okay\".'\n\"\"\"She said, \"That won't work\".\"\"\"\n\nWhich quote is ...
[ 9, 9, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001312940_python_string.txt
Q: How can I scrape this frame? If you visit this link right now, you will probably get a VBScript error. On the other hand, if you visit this link first and then the above link (in the same session), the page comes through. The way this application is set up, the first page is meant to serve as a frame in the second...
How can I scrape this frame?
If you visit this link right now, you will probably get a VBScript error. On the other hand, if you visit this link first and then the above link (in the same session), the page comes through. The way this application is set up, the first page is meant to serve as a frame in the second (main) page. If you click around ...
[ "It always comes down to the request/response model. You just have to craft a series of http requests such that you get the desired responses. In this case, you also need the server to treat each request as part of the same session. To do that, you need to figure out how the server is tracking sessions. It could be...
[ 8, 1 ]
[]
[]
[ "mechanize", "python", "screen_scraping", "vbscript" ]
stackoverflow_0001314052_mechanize_python_screen_scraping_vbscript.txt
Q: Python test framework with support of non-fatal failures I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test whil...
Python test framework with support of non-fatal failures
I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test while not aborting the test at the first failure. Am I missing som...
[ "I was wanting something similar for functional testing that I'm doing using nose. I eventually came up with this:\ndef raw_print(str, *args):\n out_str = str % args\n sys.stdout.write(out_str)\n\nclass DeferredAsserter(object):\n def __init__(self):\n self.broken = False\n def assert_equal(self...
[ 2, 1, 1, 0 ]
[ "nose will only abort on the first failure if you pass the -x option at the command line.\ntest.py:\ndef test1():\n assert False\n\ndef test2():\n assert False\n\nwithout -x option:\n\nC:\\temp\\py>C:\\Python26\\Scripts\\nosetests.exe test.py\nFF\n==============================================================...
[ -1 ]
[ "assert", "nose", "python", "testing" ]
stackoverflow_0001307367_assert_nose_python_testing.txt
Q: How to get pyodbc.connect to prompt? In my C++ programs, I'm used to the connection process prompting for a missing password or letting you select your own connection. Whe I use pyodbc.connect(), an exception is generated instead. Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> c...
How to get pyodbc.connect to prompt?
In my C++ programs, I'm used to the connection process prompting for a missing password or letting you select your own connection. Whe I use pyodbc.connect(), an exception is generated instead. Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> c=pyodbc.connect('') Error: ('IM002', '[IM0...
[ "I'm not sure if you can, I just checked the source for this and it seems like it always sends SQL_DRIVER_NOPROMPT.\nSee line 88 in connection.cpp\n" ]
[ 2 ]
[]
[]
[ "pyodbc", "python" ]
stackoverflow_0001314445_pyodbc_python.txt
Q: Is there a LGPL/Apache/BSD Python library for rendering modern HTML and Flash with a transparent background on Windows,Mac,Linux? I'm looking for a Python library that's suitable, with DOM access too. I don't mind if the flash transparency doesn't carry over. PyQT's license isn't compatible with the project, and P...
Is there a LGPL/Apache/BSD Python library for rendering modern HTML and Flash with a transparent background on Windows,Mac,Linux?
I'm looking for a Python library that's suitable, with DOM access too. I don't mind if the flash transparency doesn't carry over. PyQT's license isn't compatible with the project, and PySide isn't compiled cross-platform yet. Any thoughts?
[ "Actually, the pyside project now provides LGPL 2.1 python bindings for Qt.\nThe first public release was on August 18th. It is being developed with support from Nokia.\nAccording to the release announcement the bindings are initially focused on Linux/X11 but expect to support all Qt supported platforms eventually...
[ 2 ]
[]
[]
[ "alphablending", "gecko", "python", "webkit", "widget" ]
stackoverflow_0001314596_alphablending_gecko_python_webkit_widget.txt
Q: cURL: https through a proxy I need to make a cURL request to a https URL, but I have to go through a proxy as well. Is there some problem with doing this? I have been having so much trouble doing this with curl and php, that I tried doing it with urllib2 in Python, only to find that urllib2 cannot POST to https ...
cURL: https through a proxy
I need to make a cURL request to a https URL, but I have to go through a proxy as well. Is there some problem with doing this? I have been having so much trouble doing this with curl and php, that I tried doing it with urllib2 in Python, only to find that urllib2 cannot POST to https when going through a proxy. I ha...
[ "I find testing with command-line curl a big help before moving to PHP/cURL.\nFor example, w/ command-line, unless you've configured certificates, you'll need -k switch. And to go through a proxy, it's the -x <proxyhost[:port]> switch.\nI believe the -k equivalent is\ncurl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALS...
[ 2, 0 ]
[]
[]
[ "curl", "https", "php", "python", "urllib2" ]
stackoverflow_0001308760_curl_https_php_python_urllib2.txt
Q: Cannot connect to server externally using Twisted library in Python I am trying to get a simple TCP server running on my server. I am using echoserv.py and echoclient.py on the Twisted examples page. When I run echoserv.py on the server, I can connect fine using the following in echoclient.py: reactor.connectTCP('...
Cannot connect to server externally using Twisted library in Python
I am trying to get a simple TCP server running on my server. I am using echoserv.py and echoclient.py on the Twisted examples page. When I run echoserv.py on the server, I can connect fine using the following in echoclient.py: reactor.connectTCP('localhost', 8000, factory) <- for a localhost connection reactor.connectT...
[ "When you program your router to port-forward outcoming connections to your inbound server, it actually works only if the clients (those who try to connect) are really outside your network, really coming from the cloud. You, from inside your network, can't use it, it won't work for you. You will have the feeling th...
[ 4, 1 ]
[]
[]
[ "port", "python", "tcp", "twisted" ]
stackoverflow_0001315087_port_python_tcp_twisted.txt
Q: Can I create a Python extension module in D (instead of C) I hear D is link-compatible with C. I'd like to use D to create an extension module for Python. Am I overlooking some reason why it's never going to work? A: Wait? Something like this http://www.dsource.org/projects/pyd (previously http://pyd.dsource.or...
Can I create a Python extension module in D (instead of C)
I hear D is link-compatible with C. I'd like to use D to create an extension module for Python. Am I overlooking some reason why it's never going to work?
[ "Wait? Something like this http://www.dsource.org/projects/pyd (previously http://pyd.dsource.org/)\n", "Sounds easy and people here who say it's just up to the C API don't know how difficult it is to integrate the Boehm GC used by D within Python. PyD looks like a typical concept proof where people haven't rea...
[ 15, 2 ]
[]
[]
[ "d", "module", "python" ]
stackoverflow_0001150093_d_module_python.txt
Q: Python, find a file in the same directory Let's say I have the files a.py and b.txt in the same directory. I can't garuntee where that directory is, but I know b.txt will be in the same directory as a.py. a.py needs to access b.txt, how would I go about finding the path to b.txt? Something like "./b.txt" won't ...
Python, find a file in the same directory
Let's say I have the files a.py and b.txt in the same directory. I can't garuntee where that directory is, but I know b.txt will be in the same directory as a.py. a.py needs to access b.txt, how would I go about finding the path to b.txt? Something like "./b.txt" won't work if the user runs the program from a direct...
[ "Use the __file__ variable:\nos.path.join(os.path.dirname(__file__), \"b.txt\")\n\n", "If you want the location of the main script, even from code that might be running in an imported module, you need to use sys.argv[0] rather than __file__. (sys.argv[0] is always the path to the main script; see http://docs.pyth...
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0001315390_python.txt
Q: Is there any way to get vim to auto wrap python strings at 79 chars? I found this answer about wrapping strings using parens extremely useful, but is there a way in Vim to make this happen automatically? I want to be within a string, typing away, and have Vim just put parens around my string and wrap it as necess...
Is there any way to get vim to auto wrap python strings at 79 chars?
I found this answer about wrapping strings using parens extremely useful, but is there a way in Vim to make this happen automatically? I want to be within a string, typing away, and have Vim just put parens around my string and wrap it as necessary. For me, this would be a gigantic time saver as I spend so much time ...
[ "More a direction than a solution.\nUse 'formatexpr' or 'formatprg'. When a line exceeds 'textwidth' and passes the criteria set by the 'formatoptions' these are used (if set) to break the line. The only real difference is that 'formatexpr' is a vimscript expression, while 'formatprg' filters the line through an ...
[ 12 ]
[]
[]
[ "python", "string", "vim", "word_wrap" ]
stackoverflow_0001314174_python_string_vim_word_wrap.txt
Q: How to migrate packages to a new Python installation? How can i quickly migrate/copy my python packages that i have installed over time to a new machine? This is my scenario; Am upgrading from an old laptop running python2.5 & Django1.0, to a new laptop which i intend to install python 2.6.2 & Django 1.1. In time ...
How to migrate packages to a new Python installation?
How can i quickly migrate/copy my python packages that i have installed over time to a new machine? This is my scenario; Am upgrading from an old laptop running python2.5 & Django1.0, to a new laptop which i intend to install python 2.6.2 & Django 1.1. In time i have downloaded and installed many python packages in my ...
[ "If they're pure Python, then in theory you could just copy them across from one Lib\\site-packages directory to the other. However, this will not work for any packages which include C extensions (as these need to be recompiled anew for every Python version). You also need to consider e.g. .pth files which have bee...
[ 3, 1, 0 ]
[]
[]
[ "migration", "package", "python" ]
stackoverflow_0001315511_migration_package_python.txt
Q: How can Django projects be deployed with minimal installation work? To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux): Install MySQLPython Install ModPython Install Django (using python setup.py install) Add some directives on httpd.conf file (or use .htaccess) But, when I ...
How can Django projects be deployed with minimal installation work?
To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux): Install MySQLPython Install ModPython Install Django (using python setup.py install) Add some directives on httpd.conf file (or use .htaccess) But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I...
[ "To enable easy Django deployement I would to the following:\nFisrt-time server configuration\n\nInstall mod_wsgi which allow you to run in embedded mode OR in daemon mode.\nInstall python and virtualenv\n\nIn your development environment\n\nUse virtualenv. Take a look at mod_wsgi and virtualenv configuration\nInst...
[ 4, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001313989_django_python.txt
Q: Pythonic way of iterating over 3D array I have a 3D array in Python and I need to iterate over all the cubes in the array. That is, for all (x,y,z) in the array's dimensions I need to access the cube: array[(x + 0, y + 0, z + 0)] array[(x + 1, y + 0, z + 0)] array[(x + 0, y + 1, z + 0)] array[(x + 1, y + 1, z + 0...
Pythonic way of iterating over 3D array
I have a 3D array in Python and I need to iterate over all the cubes in the array. That is, for all (x,y,z) in the array's dimensions I need to access the cube: array[(x + 0, y + 0, z + 0)] array[(x + 1, y + 0, z + 0)] array[(x + 0, y + 1, z + 0)] array[(x + 1, y + 1, z + 0)] array[(x + 0, y + 0, z + 1)] array[(x + 1,...
[ "Have a look at itertools, especially itertools.product. You can compress the three loops into one with \nimport itertools\n\nfor x, y, z in itertools.product(*map(xrange, (x_dim, y_dim, z_dim)):\n ...\n\nYou can also create the cube this way:\ncube = numpy.array(list(itertools.product((0,1), (0,1), (0,1))))\npr...
[ 19, 8 ]
[]
[]
[ "arrays", "loops", "python" ]
stackoverflow_0001316068_arrays_loops_python.txt
Q: Downloading compressed content over HTTP using Python How do I take advantage of HTTP 1.1's compression when downloading web pages using Python? I am currently using the built-in urllib module for downloading web content. Reading through the documentation I couldn't find any information that is indeed using compr...
Downloading compressed content over HTTP using Python
How do I take advantage of HTTP 1.1's compression when downloading web pages using Python? I am currently using the built-in urllib module for downloading web content. Reading through the documentation I couldn't find any information that is indeed using compression. Is it already built-in into urllib or is there anot...
[ "httplib2 supports 'deflate' and 'gzip' compression. \nExample\nimport httplib2\nh = httplib2.Http(\".cache\")\nresp, content = h.request(\"http://example.org/\", \"GET\")\n\nThe content is decompressed as necessary. \n" ]
[ 6 ]
[]
[]
[ "compression", "gzip", "http", "httplib2", "python" ]
stackoverflow_0001316517_compression_gzip_http_httplib2_python.txt
Q: Django URL.py and the index I want to know what is the best way to write in the URL.py. I am trying to get the index in this way: www.example.com with (r'',index). But when I try r'', all pages in the website are going to the home page. Part of my url.py: (r'^index',homepages), (r'',homepages), Thanks :) A: Lik...
Django URL.py and the index
I want to know what is the best way to write in the URL.py. I am trying to get the index in this way: www.example.com with (r'',index). But when I try r'', all pages in the website are going to the home page. Part of my url.py: (r'^index',homepages), (r'',homepages), Thanks :)
[ "Like this:\n #...\n (r'^$', index),\n #...\n\n", "Django URL matching is very powerful if not always as convenient as it could be. As Brian says, you need to use the pattern r'^$' to force your pattern to match the entire string. With r'', you are looking for an empty string anywhere in the URL, which is true ...
[ 31, 5 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0001316682_django_django_urls_python.txt
Q: dictionary of object I have a sorted dict { 1L: '<'New_Config (type: 'String') (id: 1L) (value: 4L) (name: 'account_receivable')'>', 2L: '<'New_Config (type: 'string') (id: 2L) (value: 5L) (name: 'account_payable')'>', 3L: '<'New_Config (type: 'String') (id: 3L) (value: 8L) (name: 'account_cogs ')'>', 4L: '<'Ne...
dictionary of object
I have a sorted dict { 1L: '<'New_Config (type: 'String') (id: 1L) (value: 4L) (name: 'account_receivable')'>', 2L: '<'New_Config (type: 'string') (id: 2L) (value: 5L) (name: 'account_payable')'>', 3L: '<'New_Config (type: 'String') (id: 3L) (value: 8L) (name: 'account_cogs ')'>', 4L: '<'New_Config (type: 'String') ...
[ "Python dictionaries are not sorted. If you have some custom class which implements some mapping methods (like a dictionary) but over-rides some of them to give the appearance of maintaining some (sorted) ordering then the implementation details of that might also explain why your example doesn't look like valid P...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0001315407_dictionary_python_sorting.txt
Q: Using PyUNO on Windows and CentOS Is there any way to use OpenOffice's PyUNO without using the version of Python that comes with OpenOffice? I mean, can I install a package (on Windows and CentOS) that uses the version of Python that's already on the server? I'm trying to use OpenOffice in headless mode so that I ...
Using PyUNO on Windows and CentOS
Is there any way to use OpenOffice's PyUNO without using the version of Python that comes with OpenOffice? I mean, can I install a package (on Windows and CentOS) that uses the version of Python that's already on the server? I'm trying to use OpenOffice in headless mode so that I can do document conversion with a scrip...
[ "You can't use PyUNO with just any version of Python. You need to use the specific one that's integrated into your OpenOffice installation. However, the very latest OO (3.1 I believe) comes (on all platforms) with the very latest Python (2.6.2 I believe), so if you can upgrade your OpenOffice to the very latest rel...
[ 2 ]
[]
[]
[ "openoffice.org", "python", "pyuno" ]
stackoverflow_0001314009_openoffice.org_python_pyuno.txt
Q: app-engine-patch with pyamf = No module named encoding I'm trying to use app-engine-patch with pyamf by following this: http://pyamf.org/wiki/GoogleAppEngine because I want to migrate my Django <-> pyamf application to app-engine-patch <-> pyamf. What I have now is that I created my gateway.py with only one line o...
app-engine-patch with pyamf = No module named encoding
I'm trying to use app-engine-patch with pyamf by following this: http://pyamf.org/wiki/GoogleAppEngine because I want to migrate my Django <-> pyamf application to app-engine-patch <-> pyamf. What I have now is that I created my gateway.py with only one line of code: import pyamf just to test can I use pyamf and I ge...
[ "Are you activating Django 1.0.2 in your app engine startup code? App Engine now comes with it, but also (for backwards compatibility) with 0.9.6, and (still for backwards compatibility) 0.9.6 is what it defaults to -- all it takes to fix this is, at startup, use:\nfrom google.appengine.dist import use_library\nuse...
[ 1 ]
[]
[]
[ "app_engine_patch", "google_app_engine", "pyamf", "python" ]
stackoverflow_0001315368_app_engine_patch_google_app_engine_pyamf_python.txt
Q: What do you make of this Python error? Here's the error. Traceback (most recent call last): File "_ctypes/callbacks.c", line 295, in 'calling callback function' File "USB2.py", line 454, in ff self.drv_locked = False SystemError: Objects/cellobject.c:24: bad argument to internal function Here's the Python...
What do you make of this Python error?
Here's the error. Traceback (most recent call last): File "_ctypes/callbacks.c", line 295, in 'calling callback function' File "USB2.py", line 454, in ff self.drv_locked = False SystemError: Objects/cellobject.c:24: bad argument to internal function Here's the Python code involved. def drv_send(self, data, siz...
[ "An internal error is clearly a bug in Python itself, and if you're interested in further exploring this and offering a fix for the Python core, then simplifying your code down to where it still triggers the bug would be the right strategy.\nIf you're more interested in having your code work, rather than in fixing ...
[ 6, 2 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0001315465_ctypes_python.txt
Q: use python to access mysql i am finally starting with python. i wanted to ask if i use the mysql db with python, how should i expect python to connect to the db? what i mean is, i have mysql installed in xampp and have my database created in mysql through php myadmin. now my python is in C:\python25\ and my *.py ...
use python to access mysql
i am finally starting with python. i wanted to ask if i use the mysql db with python, how should i expect python to connect to the db? what i mean is, i have mysql installed in xampp and have my database created in mysql through php myadmin. now my python is in C:\python25\ and my *.py files would be in the same folde...
[ "the basics is\nimport MySQLdb\n\nconn = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"nobodyknow\", db=\"amit\")\ncursor = conn.cursor()\n\nstmt = \"SELECT * FROM overflows\"\ncursor.execute(stmt)\n\n# Fetch and output\nresult = cursor.fetchall()\nprint result\n\n# get the number of rows\nnumrows = i...
[ 4, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001317103_mysql_python.txt
Q: Transforming nested list in Python Assuming I have a structure like this: a = [ ('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I']) ] How can I transform it into: a = [ ('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I'), ] Thanks for your time! A: Try: >>> a = [('A', ['D', 'E',...
Transforming nested list in Python
Assuming I have a structure like this: a = [ ('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I']) ] How can I transform it into: a = [ ('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I'), ] Thanks for your time!
[ "Try:\n>>> a = [('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I'])]\n>>> [(k,j) for k, more in a for j in more]\n[('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I')]\n\nThis handles only one level of nesting of course.\n", "Here's a simple solution:\ndata = [\n('A',\n ['D',\n 'E',\n 'F...
[ 10, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001316319_python.txt
Q: Should I use "from package import utils, settings" or "from . import utils, settings" I'm developing a Python application; it has all its code in one package and runs inside this of course. The application's Python package is of no interest from the interpreter to the user, it's simply a GUI application. The quest...
Should I use "from package import utils, settings" or "from . import utils, settings"
I'm developing a Python application; it has all its code in one package and runs inside this of course. The application's Python package is of no interest from the interpreter to the user, it's simply a GUI application. The question is, which style is preferred when importing modules inside the application package from...
[ "The Python Style Guide recommends explicitly against relative imports (the . style):\n\nRelative imports for intra-package imports are highly discouraged.\n Always use the absolute package path for all imports.\n Even now that PEP 328 [7] is fully implemented in Python 2.5,\n its style of explicit relative impo...
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0001317624_python.txt
Q: Amazon S3 Python Bulk File Transfer through Python I want to tranfer files in around 1000 directories to an Amazon S3 bucket using Pythons S3 package. How could I do it ? A: I like boto, http://code.google.com/p/boto/
Amazon S3 Python Bulk File Transfer through Python
I want to tranfer files in around 1000 directories to an Amazon S3 bucket using Pythons S3 package. How could I do it ?
[ "I like boto,\nhttp://code.google.com/p/boto/\n" ]
[ 3 ]
[]
[]
[ "amazon_s3", "python" ]
stackoverflow_0001315660_amazon_s3_python.txt
Q: How can I hide incompatible code from older Python versions? I'm writing unit tests for a function that takes both an *args and a **kwargs argument. A reasonable use-case for this function is using keyword arguments after the *args argment, i.e. of the form def f(a, *b, **c): print a, b, c f(1, *(2, 3, 4), ke...
How can I hide incompatible code from older Python versions?
I'm writing unit tests for a function that takes both an *args and a **kwargs argument. A reasonable use-case for this function is using keyword arguments after the *args argment, i.e. of the form def f(a, *b, **c): print a, b, c f(1, *(2, 3, 4), keyword=13) Now this only became legal in Python 2.6; in earlier ve...
[ "I don't think you should be testing whether Python works correctly; instead, focus on testing your own code. In doing so, it is perfectly possible to write the specific invocation in a way that works for all Python versions, namely:\nf(1, *(2,3,4), **{'keyword':13})\n\n", "One approach might be to use eval() or ...
[ 11, 2, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0001317946_python_unit_testing.txt
Q: Dealing with dynamic urls Let's say my main controller 'hotels' has a pattern for the url, such as: /hotels/colorado/aspen/hotel-name/ How should I program my controller ( keep in mind I'm still learning MVC ) to handle this variable? I know that I have to probably check if anything after /hotels/ is set, otherwis...
Dealing with dynamic urls
Let's say my main controller 'hotels' has a pattern for the url, such as: /hotels/colorado/aspen/hotel-name/ How should I program my controller ( keep in mind I'm still learning MVC ) to handle this variable? I know that I have to probably check if anything after /hotels/ is set, otherwise show the default hotels page....
[ "Usually this is solved with Object Dispatch. You can also create nested Controllers to handle this. An advantage is, that you can follow a major OOP principle, namely encapsulation, as you group all functionality that only concerns Hotels generally in the Hotel controller (for example adding a new one)\nAnother ad...
[ 1, 0 ]
[]
[]
[ "php", "python", "url_routing" ]
stackoverflow_0001317541_php_python_url_routing.txt
Q: Parallel Python: What is a callback? In Parallel Python it has something in the submit function called a callback (documentation) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would someone explain what a callback is and what it's u...
Parallel Python: What is a callback?
In Parallel Python it has something in the submit function called a callback (documentation) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would someone explain what a callback is and what it's used for?
[ "A callback is a function provided by the consumer of an API that the API can then turn around and invoke (calling you back). If I setup a Dr.'s appointment, I can give them my phone number, so they can call me the day before to confirm the appointment. A callback is like that, except instead of just being a phone ...
[ 254, 21, 4, 3, 2 ]
[]
[]
[ "callback", "parallel_python", "python" ]
stackoverflow_0001319074_callback_parallel_python_python.txt
Q: Starting an INDIVIDUAL instance of a subclass from asynchat So the situation I have is that I have loaded more than one class that I've made that subclasses from asynchat, but I only want one of them to run. Of course, this doesn't work out when I call asyncore.loop() as they all begin. Is there any way to make on...
Starting an INDIVIDUAL instance of a subclass from asynchat
So the situation I have is that I have loaded more than one class that I've made that subclasses from asynchat, but I only want one of them to run. Of course, this doesn't work out when I call asyncore.loop() as they all begin. Is there any way to make only one of them begin running? edit: I think it has something to d...
[ "For all who were curious, I figured it out. If you pass your instance's _map to loop() it seems to only start the single instance.\nExample:\nmy_asyncore_obj = SomeAsyncoreObj()\nasyncore.loop(map=my_asyncore_obj._map)\n\n" ]
[ 0 ]
[]
[]
[ "asyncore", "python" ]
stackoverflow_0001105814_asyncore_python.txt
Q: Python/GAE web request error handling I am developing an application on the Google App Engine using Python. I have a handler that can return a variety of outputs (html and json at the moment), I am testing for obvious errors in the system based on invalid parameters sent to the request handler. However what I am d...
Python/GAE web request error handling
I am developing an application on the Google App Engine using Python. I have a handler that can return a variety of outputs (html and json at the moment), I am testing for obvious errors in the system based on invalid parameters sent to the request handler. However what I am doing feels dirty (see below): class FeedHan...
[ "There's a couple of handy methods here. The first is self.error(code). By default this method simply sets the status code and clears the output buffer, but you can override it to output custom error pages depending on the error result.\nThe second method is self.handle__exception(exception, debug_mode). This metho...
[ 9, 0 ]
[]
[]
[ "design_patterns", "error_handling", "google_app_engine", "python" ]
stackoverflow_0001318960_design_patterns_error_handling_google_app_engine_python.txt
Q: Ctypes pro and con I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing. I hear of swig, but I see Ctypes more often than not. Any danger...
Ctypes pro and con
I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing. I hear of swig, but I see Ctypes more often than not. Any danger here? If so, what shoul...
[ "In terms of robustness, I still think swig is somewhat superior to ctypes, because it's possible to have a C compiler check things more thoroughly for you; however, this is pretty moot by now (while it loomed larger in earlier ctypes versons), thanks to the argtypes feature @Mark already mentioned. However, there ...
[ 13, 6, 4, 2 ]
[]
[]
[ "ctypes", "python", "winapi" ]
stackoverflow_0001318736_ctypes_python_winapi.txt
Q: Is this a good approach to avoid using SQLAlchemy/SQLObject? Rather than use an ORM, I am considering the following approach in Python and MySQL with no ORM (SQLObject/SQLAlchemy). I would like to get some feedback on whether this seems likely to have any negative long-term consequences since in the short-term vie...
Is this a good approach to avoid using SQLAlchemy/SQLObject?
Rather than use an ORM, I am considering the following approach in Python and MySQL with no ORM (SQLObject/SQLAlchemy). I would like to get some feedback on whether this seems likely to have any negative long-term consequences since in the short-term view it seems fine from what I can tell. Rather than translate a row ...
[ "That doesn't do away with the need for an ORM. That is an ORM. In which case, why reinvent the wheel?\nIs there a compelling reason you're trying to avoid using an established ORM?\n", "You will still be using SQLAlchemy. ResultProxy is actually a dictionary once you go for .fetchmany() or similar.\nUse SQLAlc...
[ 8, 2, 0 ]
[]
[]
[ "python", "sqlalchemy", "sqlobject" ]
stackoverflow_0001319585_python_sqlalchemy_sqlobject.txt
Q: what are the pros/cons of py2exe im looking for simple script that will compile to exe , and i found py2exe before i decide to work with it , what do you think are the pros and cons of the py2exe tool? A: Pros: Your app becomes standalone, can run on a PC without Python Cons: False sense of security, your ap...
what are the pros/cons of py2exe
im looking for simple script that will compile to exe , and i found py2exe before i decide to work with it , what do you think are the pros and cons of the py2exe tool?
[ "Pros:\n\nYour app becomes standalone, can run\non a PC without Python\n\nCons:\n\nFalse sense of security, your app is still interpreted, it's just that the script is no longer visible but the byte code is and AFAIK it can be easily converted back to the source.\nLarge application size, the simplest script package...
[ 10, 5, 2 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0001318311_py2exe_python.txt
Q: What's a more elegant rephrasing of this cropping algorithm? (in Python) I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree. I have already written some code that does exactly this, but somehow it lacks a ce...
What's a more elegant rephrasing of this cropping algorithm? (in Python)
I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree. I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to...
[ "I think this should do.\nsize = min(image.Size)\n\noriginX = image.Size[0] / 2 - size / 2\noriginY = image.Size[1] / 2 - size / 2\n\ncropBox = (originX, originY, originX + size, originY + size)\n\n", "The fit() function in the PIL ImageOps module does what you want:\nImageOps.fit(image, (min(*image.size),) * 2, ...
[ 9, 6, 1, 0 ]
[]
[]
[ "crop", "image", "python", "python_imaging_library" ]
stackoverflow_0000709388_crop_image_python_python_imaging_library.txt
Q: How to submit data of a flash form? [python] I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. How...
How to submit data of a flash form? [python]
I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. However, Ming is only to create .swf files and that's...
[ "You can set the url attribute (I think it's url, please correct me if I'm wrong) on a Flash form control to a Python script - then it will pass it through HTTP POST like any normal HTML form.\nYou've got nothing to be afraid of, it uses the same protocol to communicate, it's just a different submission process.\n"...
[ 1, 0 ]
[]
[]
[ "flash", "forms", "python" ]
stackoverflow_0001319895_flash_forms_python.txt
Q: microcrontroller output to python cgi script I bought this temperature sensor logger kit: http://quozl.netrek.org/ts/. It works great with the supplied C code, I like to use python because of its simplicity, so I wrote a script in python that displays the output from the microcontroller. I only have one temperatur...
microcrontroller output to python cgi script
I bought this temperature sensor logger kit: http://quozl.netrek.org/ts/. It works great with the supplied C code, I like to use python because of its simplicity, so I wrote a script in python that displays the output from the microcontroller. I only have one temperature sensor hooked up to the kit. I want the temperat...
[ "I'm guessing that the execution context under which your CGI is running is unable to complete the read() from the serial port.\nIncidentally the Python standard libraries have MUCH better ways for writing CGI scripts than what you're doing here; and even the basic string handling offers a better way to interpolate...
[ 2, 0, 0 ]
[]
[]
[ "cgi", "python", "serial_port" ]
stackoverflow_0001291624_cgi_python_serial_port.txt
Q: Shorter, more pythonic way of writing an if statement I have this bc = 'off' if c.page == 'blog': bc = 'on' print(bc) Is there a more pythonic (and/or shorter) way of writing this in Python? A: Shortest one should be: bc = 'on' if c.page=='blog' else 'off' Generally this might look a bit confusing, so yo...
Shorter, more pythonic way of writing an if statement
I have this bc = 'off' if c.page == 'blog': bc = 'on' print(bc) Is there a more pythonic (and/or shorter) way of writing this in Python?
[ "Shortest one should be:\nbc = 'on' if c.page=='blog' else 'off'\n\nGenerally this might look a bit confusing, so you should only use it when it is clear what it means. Don't use it for big boolean clauses, since it begins to look ugly fast.\n", "This is:\n\ndefinitely shorter\narguably Pythonic (pre-Python 2.5, ...
[ 103, 65, 32, 15, 4, 3 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0001319214_if_statement_python.txt
Q: GTK: Modify bg color of a CheckButton I tried the following, yet the button still has a white background: self.button = gtk.CheckButton() self.button.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,0,0)) self.button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,0,0)) self.button.modify_fg(gtk.STA...
GTK: Modify bg color of a CheckButton
I tried the following, yet the button still has a white background: self.button = gtk.CheckButton() self.button.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,0,0)) self.button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,0,0)) self.button.modify_fg(gtk.STATE_ACTIVE, gtk.gdk.Color(65535,0,0)) se...
[ "So you want the part with the check mark on it to be a different color?\nThen use this button.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse(\"red\")).\nalt text http://www.ubuntu-pics.de/bild/22793/screenshot_009_MCxjbu.png\n" ]
[ 3 ]
[]
[]
[ "colors", "events", "gtk", "pygtk", "python" ]
stackoverflow_0001240764_colors_events_gtk_pygtk_python.txt
Q: Good graph traversal algorithm Abstract problem : I have a graph of about 250,000 nodes and the average connectivity is around 10. Finding a node's connections is a long process (10 seconds lets say). Saving a node to the database also takes about 10 seconds. I can check if a node is already present in the db very...
Good graph traversal algorithm
Abstract problem : I have a graph of about 250,000 nodes and the average connectivity is around 10. Finding a node's connections is a long process (10 seconds lets say). Saving a node to the database also takes about 10 seconds. I can check if a node is already present in the db very quickly. Allowing concurrency, but ...
[ "To remember IDs of the users you've already visited, you need a map of a length of 250,000 integers. That's far from \"too much\". Just maintain such a map and only traverse through the edges that lead to the already undiscovered users, adding them to that map at the point of finding such edge.\nAs far I can see...
[ 7, 2, 2, 0 ]
[]
[]
[ "algorithm", "graph_traversal", "language_agnostic", "performance", "python" ]
stackoverflow_0001320688_algorithm_graph_traversal_language_agnostic_performance_python.txt
Q: Multiple versions of Python on OS X Leopard I currently have multiple versions of Python installed on my Mac, the one that came with it, a version I downloaded recently from python.org, an older version used to run Zope locally and another version that Appengine is using. It's kind of a mess. Any recommendations o...
Multiple versions of Python on OS X Leopard
I currently have multiple versions of Python installed on my Mac, the one that came with it, a version I downloaded recently from python.org, an older version used to run Zope locally and another version that Appengine is using. It's kind of a mess. Any recommendations of using one version of python to rule them all? H...
[ "There's nothing inherently wrong with having multiple versions of Python around. Sometimes it's a necessity when using applications with version dependencies. Probably the biggest issue is dealing with site-package dependencies which may vary from app to app. Tools like virtualenv can help there. One thing you s...
[ 20, 9, 2, 1 ]
[]
[]
[ "macos", "osx_leopard", "python", "zope" ]
stackoverflow_0001218891_macos_osx_leopard_python_zope.txt
Q: How to start a COM server implemented in python? I am using python for making a COM local server. In fact, the whole COM part is implemented in a dll and my python script is calling that dll thanks to ctypes. It works ok when I run the script manually. I would like to see my server automatically ran when a COM cli...
How to start a COM server implemented in python?
I am using python for making a COM local server. In fact, the whole COM part is implemented in a dll and my python script is calling that dll thanks to ctypes. It works ok when I run the script manually. I would like to see my server automatically ran when a COM client request it. I know that it is possible by giving t...
[ "The \"-embedding\" flag is added by COM automatically, the purpose of which is so that the server application can parse this flag to determine that it was run by COM.\n\nCOM appends the \"-Embedding\" flag to\n the string, so the application that\n uses flags will need to parse the\n whole string and check for ...
[ 0 ]
[]
[]
[ "com", "python", "windows" ]
stackoverflow_0001320954_com_python_windows.txt
Q: What is the most efficient way to add an element to a list only if isn't there yet? I have the following code in Python: def point_to_index(point): if point not in points: points.append(point) return points.index(point) This code is awfully inefficient, especially since I expect points to grow to ...
What is the most efficient way to add an element to a list only if isn't there yet?
I have the following code in Python: def point_to_index(point): if point not in points: points.append(point) return points.index(point) This code is awfully inefficient, especially since I expect points to grow to hold a few million elements. If the point isn't in the list, I traverse the list 3 times:...
[ "You want to use a set:\n>>> x = set()\n>>> x\nset([])\n>>> x.add(1)\n>>> x\nset([1])\n>>> x.add(1)\n>>> x\nset([1])\n\nA set contains only one instance of any item you add, and it will be a lot more efficient than iterating a list manually.\nThis wikibooks page looks like a good primer if you haven't used sets in ...
[ 13, 10, 5, 2, 1, 1 ]
[]
[]
[ "list", "optimization", "python" ]
stackoverflow_0001319254_list_optimization_python.txt
Q: Creating a single exe file from Python code Possible Duplicate: py2exe - generate single executable file A friend of mine managed to pack some a Ruby script he wrote in a single exe file. When I tried to do the same thing for a Python script, with py2exe, I also got several pyd files and a dll. Is it possible t...
Creating a single exe file from Python code
Possible Duplicate: py2exe - generate single executable file A friend of mine managed to pack some a Ruby script he wrote in a single exe file. When I tried to do the same thing for a Python script, with py2exe, I also got several pyd files and a dll. Is it possible to pack a Python script with all it's DLL's and p...
[ "According to py2exe.org:\n\nThe --bundle or -b command line switch will create less files because binary extensions, runtime dlls, and even the Python-dll itself is bundled into the executable itself, or inside the library-archive if you prefer that.\n...\nUsing a level of 1 includes the .pyd and .dll files into...
[ 0, 0 ]
[]
[]
[ "executable", "python", "winapi" ]
stackoverflow_0001321708_executable_python_winapi.txt
Q: Vim python's buffer.append(line) switch window's focus I am trying to fill Vim's buffer from separate thread by using this python code. python << PYTHON_CODE import vim import time buffer_number = -1 class AppendLineTest( Thread ): def run(self): buffer = vim.buffers[buffer_number - 1] for i in r...
Vim python's buffer.append(line) switch window's focus
I am trying to fill Vim's buffer from separate thread by using this python code. python << PYTHON_CODE import vim import time buffer_number = -1 class AppendLineTest( Thread ): def run(self): buffer = vim.buffers[buffer_number - 1] for i in range(10): buffer.append('Line number %s' % i) ...
[ "I don't think Vim is very tolerant of multiple threads without patching. There's a lot more detail in the discussion at this link, but I suspect that what you want is far from trivial.\n" ]
[ 2 ]
[]
[]
[ "plugins", "python", "vim" ]
stackoverflow_0001321936_plugins_python_vim.txt
Q: os.path.exists() for files in your Path? I commonly use os.path.exists() to check if a file is there before doing anything with it. I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath. Is there something that can be done t...
os.path.exists() for files in your Path?
I commonly use os.path.exists() to check if a file is there before doing anything with it. I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath. Is there something that can be done to check if the file exists before calling it? ...
[ "You could get the PATH environment variable, and try \"exists()\" for the .exe in each dir in the path. But that could perform horribly.\nexample for finding notepad.exe:\nimport os\nfor p in os.environ[\"PATH\"].split(os.pathsep):\n print os.path.exists(os.path.join(p, 'notepad.exe'))\n\nmore clever example:\n...
[ 17, 5, 3, 2, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0000775351_python_windows.txt
Q: to restrict parameter values strictly with in bounds I am trying to optimize a function using l_bfgs constraint optimization routine in scipy. But the optimization routine passes values to the function, which are not with in the Bounds. my full code looks like, def humpy(aParams): aParams = numpy.asarray(aParams)...
to restrict parameter values strictly with in bounds
I am trying to optimize a function using l_bfgs constraint optimization routine in scipy. But the optimization routine passes values to the function, which are not with in the Bounds. my full code looks like, def humpy(aParams): aParams = numpy.asarray(aParams) print aParams #### # connect to some other software fo...
[ "You are trying to do bitwise exclusive or (the ^ operator) on floats, which makes no sense, so I don't think your code is actually the code you have problems with. However, I changed the ^ to ** assuming that was what you meant, and had no problems. The code worked fine for me with that change. The parameters are ...
[ 1, 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0001322049_python_scipy.txt
Q: python time format check At python, I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result. How can I achieve this by using regular expression ? A: You can achieve this without regular expressions: import time def isTimeFormat(input): try: ...
python time format check
At python, I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result. How can I achieve this by using regular expression ?
[ "You can achieve this without regular expressions:\nimport time\n\ndef isTimeFormat(input):\n try:\n time.strptime(input, '%H:%M')\n return True\n except ValueError:\n return False\n\n>>>isTimeFormat('12:12')\nTrue\n\n>>>isTimeFormat('012:12')\nFalse\n\n", "import re\n\ntime_re = re.com...
[ 30, 5, 3, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001322464_python_regex.txt
Q: What numbers can you pass as verbosity in running Python Unit Test Suites? The Python unittest framework has a concept of verbosity that I can't seem to find defined anywhere. For instance, I'm running test cases like this (like in the documentation): suite = unittest.TestLoader().loadTestsFromTestCase(MyAwesomeTe...
What numbers can you pass as verbosity in running Python Unit Test Suites?
The Python unittest framework has a concept of verbosity that I can't seem to find defined anywhere. For instance, I'm running test cases like this (like in the documentation): suite = unittest.TestLoader().loadTestsFromTestCase(MyAwesomeTest) unittest.TextTestRunner(verbosity=2).run(suite) The only number I've ever s...
[ "You only have 3 different levels:\n\n0 (quiet): you just get the total numbers of tests executed and the global result\n1 (default): you get the same plus a dot for every successful test or a F for every failure\n2 (verbose): you get the help string of every test and the result\n\nYou can use command line args rat...
[ 101 ]
[]
[]
[ "python", "unit_testing", "verbosity" ]
stackoverflow_0001322575_python_unit_testing_verbosity.txt
Q: Ipython common problems I love iPython's so many features, magic functions. I recently upgraded to the latest 0.10 version. But I face following common problems: %hist one of the most frequently used magic functions, doesn't exist. dreload doesn't seems to work (works only for modules?). run -d for debugging does...
Ipython common problems
I love iPython's so many features, magic functions. I recently upgraded to the latest 0.10 version. But I face following common problems: %hist one of the most frequently used magic functions, doesn't exist. dreload doesn't seems to work (works only for modules?). run -d for debugging doesn't work At times, typed char...
[ "sounds like an issue with your particular setup. ? and ?? have always worked on my machine, hist is still a magic function, and dreload has always only worked for modules--what else would it do?\nas for the debug thing, it's a known issue with python 2.6: https://bugs.launchpad.net/ipython/+bug/381069\n" ]
[ 1 ]
[]
[]
[ "command_line", "django", "ipython", "python" ]
stackoverflow_0001322569_command_line_django_ipython_python.txt
Q: Multiprocessing with renewable queue I'm trying to figure out how to write a program in python that uses the multiprocessing queue. I have multiple servers and one of them will provide the queue remotely with this: from multiprocessing.managers import BaseManager import Queue import daemonme queue = Queue.Queue()...
Multiprocessing with renewable queue
I'm trying to figure out how to write a program in python that uses the multiprocessing queue. I have multiple servers and one of them will provide the queue remotely with this: from multiprocessing.managers import BaseManager import Queue import daemonme queue = Queue.Queue() class QueueManager(BaseManager): pas...
[ "Look to the doc how to retreive a queue from the manager (paragraph 17.6.2.7)\nthan with a pool (paragraph 17.6.2.9) of workers launch 7 jobs passing the queue to each one.\nin alternative you can think something like a producer/consumer problem:\nfrom multiprocessing.managers import BaseManager\nimport random\n\n...
[ 2, 0 ]
[]
[]
[ "multiprocessing", "python", "queue" ]
stackoverflow_0001323086_multiprocessing_python_queue.txt
Q: Finding "closest" strings in a Python list (alphabetically) I have a Python list of strings, e.g. initialized as follows: l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alpha...
Finding "closest" strings in a Python list (alphabetically)
I have a Python list of strings, e.g. initialized as follows: l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitively (i.e. no phonetics, just a<b etc...
[ "This is exactly what the bisect module is for. It will be much faster than just iterating through large lists. \nimport bisect\n\ndef closest(haystack, needle):\n if len(haystack) == 0: return None, None\n\n index = bisect.bisect_left(haystack, needle)\n if index == 0:\n return None, haystack[0]\n...
[ 16, 2, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001322934_python_string.txt
Q: Getting Wing IDE to stop catching the exceptions that wxPython catches I started using Wing IDE and it's great. I'm building a wxPython app, and I noticed that Wing IDE catches exceptions that are usually caught by wxPython and not really raised. This is usually useful, but I would like to disable this behavior oc...
Getting Wing IDE to stop catching the exceptions that wxPython catches
I started using Wing IDE and it's great. I'm building a wxPython app, and I noticed that Wing IDE catches exceptions that are usually caught by wxPython and not really raised. This is usually useful, but I would like to disable this behavior occasionally. How do I do that?
[ "There is a Ignore this exception location check box in the window where the exception is reported in wing, or you could explicitly silence that specific exception in you code with a try except block.\n" ]
[ 0 ]
[]
[]
[ "python", "wing_ide", "wxpython" ]
stackoverflow_0001323361_python_wing_ide_wxpython.txt
Q: Is it possible to use Panda3D inside a wxPython app? I'm developing a wxPython application. Will it be possible to embed a 3D animation controlled by Panda3D inside the gui? Bonus question: Do you think that Panda3D is the best choice? (My interest is physical simulations, and no, I don't need an engine that suppo...
Is it possible to use Panda3D inside a wxPython app?
I'm developing a wxPython application. Will it be possible to embed a 3D animation controlled by Panda3D inside the gui? Bonus question: Do you think that Panda3D is the best choice? (My interest is physical simulations, and no, I don't need an engine that supports Physics, my program is responsible for calculating the...
[ "Yes - the Panda3D wiki has a mention of using wxPython to handle GUI duties.\nThere's also some threads on the Panda3D forum (1, 2) which might help.\nAnother popular choice for simulation visualization in Python is VPython; it is also dockable in wx.\n" ]
[ 5 ]
[]
[]
[ "3d", "python", "wxpython" ]
stackoverflow_0001322041_3d_python_wxpython.txt
Q: Python - How to edit hexadecimal file byte by byte I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library ...
Python - How to edit hexadecimal file byte by byte
I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutoria...
[ "Python standard library has mmap module, which can be used to do exactly this. Take a look on the documentation for further information.\n", "Depending on what you want to do it might be enough to open the file in binary mode and read the data with the normal file functions:\n# load it\nwith open(\"somefile\", ...
[ 13, 11, 5, 1 ]
[]
[]
[ "byte", "filereader", "hex", "python" ]
stackoverflow_0001322508_byte_filereader_hex_python.txt
Q: How to extend and modify PyUnit I'm about to embark upon extending and modifying PyUnit. For instance, I will add warnings to it, in addition to failures. I'm interested in hearing words of advice on how to start, for instance, subclass every PyUnit class? What to avoid and misc caveats. Looking for input from th...
How to extend and modify PyUnit
I'm about to embark upon extending and modifying PyUnit. For instance, I will add warnings to it, in addition to failures. I'm interested in hearing words of advice on how to start, for instance, subclass every PyUnit class? What to avoid and misc caveats. Looking for input from those that have extended PyUnit already...
[ "I recommend studying the nose project, a popular and well designed extension of PyUnit. You can browse its sources online here or get a copy on your machine via Mercurial, aka hg, a nice distributed version control system in which nose keeps its sources on Google Code Hosting.\nYou may well disagree with some of n...
[ 3 ]
[]
[]
[ "python", "python_unittest" ]
stackoverflow_0001323188_python_python_unittest.txt
Q: Running Panda3D on Python 2.6 I just got Panda3D for the first time. I deleted the included Python version. In my Python dir, I put a file panda.pth that looks like this: C:\Panda3D-1.6.2 C:\Panda3D-1.6.2\bin But when I run import direct.directbase.DirectStart, I get: Traceback (most recent call last): File "<p...
Running Panda3D on Python 2.6
I just got Panda3D for the first time. I deleted the included Python version. In my Python dir, I put a file panda.pth that looks like this: C:\Panda3D-1.6.2 C:\Panda3D-1.6.2\bin But when I run import direct.directbase.DirectStart, I get: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> ...
[ "Python extensions aren't binary compatible across major releases. Your options are:\nA. Recompile panda3d for python 2.6.\nB. Use python 2.5.\nNo way around it.\n", "If you can wait for the upcoming 1.7.0 release, it will be compiled against Python 2.6 - see this thread.\n" ]
[ 3, 2 ]
[]
[]
[ "panda3d", "python" ]
stackoverflow_0001323887_panda3d_python.txt
Q: How to alphabetically sort the values in a many-to-many django-admin box? I have a simple model like this one: class Artist(models.Model): surname = models.CharField(max_length=200) name = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique=True) photo = models.ImageField(upload...
How to alphabetically sort the values in a many-to-many django-admin box?
I have a simple model like this one: class Artist(models.Model): surname = models.CharField(max_length=200) name = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique=True) photo = models.ImageField(upload_to='artists', blank=True) bio = models.TextField(blank=True) class Image...
[ "Set ordering on the Article's inner Meta class.\nclass Article(models.Model):\n ....\n\n class Meta:\n ordering = ['surname', 'name']\n\n" ]
[ 8 ]
[]
[]
[ "django", "django_admin", "many_to_many", "python", "sorting" ]
stackoverflow_0001324602_django_django_admin_many_to_many_python_sorting.txt
Q: What python modules are available to assist in daemonization in the standard library? I have a simple python program that I'd like to daemonize. Since the point of my doing this is not to demonstrate mastery over the spawn, fork, disconnect , etc, I'd like to find a module that would make it quick and simple for ...
What python modules are available to assist in daemonization in the standard library?
I have a simple python program that I'd like to daemonize. Since the point of my doing this is not to demonstrate mastery over the spawn, fork, disconnect , etc, I'd like to find a module that would make it quick and simple for me. I've been looking in the std lib, but can not seem to find anything. Is there?
[ "Here's a library for making well behaved unix daemons: http://pypi.python.org/pypi/python-daemon/\nAnd another one that appears more lightweight:\nhttp://code.activestate.com/recipes/278731/\n" ]
[ 4 ]
[ "subprocess\n\nis an (almost) platform-independent module to work with processes.\n" ]
[ -1 ]
[ "daemon", "python" ]
stackoverflow_0001324651_daemon_python.txt
Q: python time interval algorithm sum Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all c...
python time interval algorithm sum
Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(s...
[ "from datetime import datetime, timedelta\n\nSTART, END = xrange(2)\ndef tparse(timestring):\n return datetime.strptime(timestring, '%H:%M')\n\ndef sum_intervals(intervals):\n times = []\n for interval in intervals:\n times.append((tparse(interval[START]), START))\n times.append((tparse(inter...
[ 4, 0, 0, 0 ]
[]
[]
[ "intervals", "python", "time" ]
stackoverflow_0001324748_intervals_python_time.txt
Q: Generate unique ID for python object based on its attributes Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicH...
Generate unique ID for python object based on its attributes
Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) What I'm looking for is somethi...
[ "You mean something like this?\nUsing the special method __hash__\nclass test:\n def __init__(self, name):\n self.name = name\n def __hash__(self):\n return hash(self.name)\n\n>>> hash(test(10)) == hash(test(20))\nFalse\n>>> hash(test(10)) == hash(test(10))\nTrue\n\n", "To get a unique com...
[ 7, 3, 2, 2 ]
[]
[]
[ "attributes", "object", "python" ]
stackoverflow_0001325195_attributes_object_python.txt
Q: Mutate an integer array using ctypes Currently I'm in the process of moving a performance bottleneck in my python code to c, to investigate peformance effects. This code will run a simulation, and report back the results to python via ctypes. However, I'm having problems getting my types to match up correctly. Alt...
Mutate an integer array using ctypes
Currently I'm in the process of moving a performance bottleneck in my python code to c, to investigate peformance effects. This code will run a simulation, and report back the results to python via ctypes. However, I'm having problems getting my types to match up correctly. Although I'm looking to solve this particular...
[ "Looks like you want the cast function:\n\nThe cast function can be used to cast a ctypes instance into a pointer to a different ctypes data type. cast takes two parameters, a ctypes object that is or can be converted to a pointer of some kind, and a ctypes pointer type. It returns an instance of the second argumen...
[ 4 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0001325518_ctypes_python.txt
Q: What order does SQLAlchemy use for primary key columns? Let's say I create a table like this: table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() Is it guaranteed that the primary key will be (a,b) and not (b,a)? A: its guaran...
What order does SQLAlchemy use for primary key columns?
Let's say I create a table like this: table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() Is it guaranteed that the primary key will be (a,b) and not (b,a)?
[ "its guaranteed, yes, since Column objects in Table are ordered. or if you really want to be explicit, use PrimaryKeyContraint().\n", "Yes.\nIt will be a really bad thing if resulting DDL wasn't giving consistent results.\n", "USe echo=True and compare yours with a swapped version? That should give the answer...
[ 5, 0, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001325018_python_sqlalchemy.txt
Q: Entity Framwework-like ORM NOT for .NET What I really like about Entity framework is its drag and drop way of making up the whole model layer of your application. You select the tables, it joins them and you're done. If you update the database scheda, right click -> update and you're done again. This seems to me m...
Entity Framwework-like ORM NOT for .NET
What I really like about Entity framework is its drag and drop way of making up the whole model layer of your application. You select the tables, it joins them and you're done. If you update the database scheda, right click -> update and you're done again. This seems to me miles ahead the competiting ORMs, like the mes...
[ "SQLAlchemy database reflection gets you half way there. You'll still have to declare your classes and relations between them. Actually you could easily autogenerate the classes too, but you'll still need to name the relations somehow so you might as well declare the classes manually.\nThe code to setup your databa...
[ 2, 2, 0 ]
[]
[]
[ "entity_framework", "open_source", "php", "python" ]
stackoverflow_0001283646_entity_framework_open_source_php_python.txt
Q: Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development? I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for ...
Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development?
I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for 3.0, I get an error in the NetBeans console that says "SyntaxError: invalid syntax". If it matters,...
[ "Yep- it's actually very easy. The scripts in the plugin use 'print' as a keyword which has been changed in Python 3; you just have to convert all 'print' statements in the console.py and platform_ info.py files under the 'python1' folder in your NetBeans installation directory to use parenthesis. For instance, in ...
[ 5, 2, 0, 0, 0 ]
[]
[]
[ "ide", "netbeans", "python" ]
stackoverflow_0000693459_ide_netbeans_python.txt
Q: Importing a text file into SQL Server in Python I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a que...
Importing a text file into SQL Server in Python
I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a question about the best way to execute it. I will be loo...
[ "If I understand what you are doing, Python is not going to be a problem. Executing a statement inside a transaction does not create cumulative state in Python. It will do so only at the database server itself.\nWhen you commit you will need to make sure the commit occurred, since having a large batch commit may ...
[ 0, 0 ]
[]
[]
[ "bulkinsert", "commit", "database", "odbc", "python" ]
stackoverflow_0001325481_bulkinsert_commit_database_odbc_python.txt
Q: how to take file like object in a file in python filename = fileobject.read() i want to transfer/assign the whole data of a object within a file. A: You are almost doing it correctly already; the code should read filecontent = fileobject.read() read() with no arguments will read the whole data, i.e. the whole...
how to take file like object in a file in python
filename = fileobject.read() i want to transfer/assign the whole data of a object within a file.
[ "You are almost doing it correctly already; the code should read\nfilecontent = fileobject.read()\n\nread() with no arguments will read the whole data, i.e. the whole file content. The file name has nothing to do with that.\n" ]
[ 4 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0001326271_file_io_python.txt
Q: Help with MySQL LOAD DATA INFILE I want to load a CSV file that looks like this: Acct. No.,1-15 Days,16-30 Days,31-60 Days,61-90 Days,91-120 Days,Beyond 120 Days 2314134101,898.89,8372.16,5584.23,7744.41,9846.54,2896.25 2414134128,5457.61,7488.26,9594.02,6234.78,273.7,2356.13 2513918869,2059.59,7578.59,9395.51,715...
Help with MySQL LOAD DATA INFILE
I want to load a CSV file that looks like this: Acct. No.,1-15 Days,16-30 Days,31-60 Days,61-90 Days,91-120 Days,Beyond 120 Days 2314134101,898.89,8372.16,5584.23,7744.41,9846.54,2896.25 2414134128,5457.61,7488.26,9594.02,6234.78,273.7,2356.13 2513918869,2059.59,7578.59,9395.51,7159.15,5827.48,3041.62 1687950783,4846.8...
[ "You have basically 3 issues here. In reverse order\n\nAre you doing your Python inserts in individual statements? You probably want to surround them all with a begin transaction/commit. 20,000 commits could easily take hours. \nYour import statement defines 6 fields, but the CSV has 7 fields. That would explain ...
[ 2, 0 ]
[]
[]
[ "load", "load_data_infile", "mysql", "python" ]
stackoverflow_0001236971_load_load_data_infile_mysql_python.txt
Q: Help me understand this traceback from the twisted.words msn sample I'm running the twisted.words msn protocol example from the twisted documentation located here: http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py I am aware there is another question about this sample .py on stackoverfl...
Help me understand this traceback from the twisted.words msn sample
I'm running the twisted.words msn protocol example from the twisted documentation located here: http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py I am aware there is another question about this sample .py on stackoverflow, but this is an entirely different problem. When I run the example, it...
[ "It looks like it's a change to the way the MSN server operates, although it doesn't really count as a change to the protocol. What's happening is the MSN server is sending a message to the client immediately after the client connects and the Twisted words example isn't expecting that.\nAssuming you're running the ...
[ 1, 0 ]
[]
[]
[ "msn", "python", "traceback", "twisted" ]
stackoverflow_0001244733_msn_python_traceback_twisted.txt
Q: Problem with shelve module? Using the shelve module has given me some surprising behavior. keys(), iter(), and iteritems() don't return all the entries in the shelf! Here's the code: cache = shelve.open('my.cache') # ... cache[url] = (datetime.datetime.today(), value) later: cache = shelve.open('my.cache') urls =...
Problem with shelve module?
Using the shelve module has given me some surprising behavior. keys(), iter(), and iteritems() don't return all the entries in the shelf! Here's the code: cache = shelve.open('my.cache') # ... cache[url] = (datetime.datetime.today(), value) later: cache = shelve.open('my.cache') urls = ['accounts_with_transactions.xml...
[ "According to the python library reference:\n\n...The database is also (unfortunately) subject to the limitations of dbm, if it is used — this means that (the pickled representation of) the objects stored in the database should be fairly small...\n\nThis correctly reproduces the 'bug':\nimport shelve\n\na = 'trxns....
[ 3, 0 ]
[]
[]
[ "python", "shelve" ]
stackoverflow_0001326459_python_shelve.txt
Q: Using sphinx to auto-document a python class, module I have installed Sphinx in order to document some Python modules and class I'm working on. While the markup language looks very nice, I haven't managed to auto-document a Python code. Basically, I have the following Python module: SegLib.py And A class called S...
Using sphinx to auto-document a python class, module
I have installed Sphinx in order to document some Python modules and class I'm working on. While the markup language looks very nice, I haven't managed to auto-document a Python code. Basically, I have the following Python module: SegLib.py And A class called Seg in it. I would like to display the docstrings of the cl...
[ "Add to the beginning of the file:\n.. module:: SegLib\n\nTry using :autoclass: directive for class doc.\nBTW: module names should be lower_case.\nEDIT: I learned a lot from reading other source files.\n" ]
[ 18 ]
[]
[]
[ "autodoc", "python", "python_sphinx" ]
stackoverflow_0001326796_autodoc_python_python_sphinx.txt
Q: How to organize a Data Base Access layer? I am using SqlAlchemy, a python ORM library. And I used to access database directly from business layer directly by calling SqlAlchemy API. But then I found that would cause too much time to run all my test cases and now I think maybe I should create a DB access layer, so...
How to organize a Data Base Access layer?
I am using SqlAlchemy, a python ORM library. And I used to access database directly from business layer directly by calling SqlAlchemy API. But then I found that would cause too much time to run all my test cases and now I think maybe I should create a DB access layer, so I can use mock objects during test instead of ...
[ "That's a good question!\nThe problem is not trivial, and may require several approaches to tackle it.\nFor instance:\n\nOrganize the code, so that you can test most of the application logic without accessing the database. This means that each class will have methods for accessing data, and methods for processing i...
[ 6, 2, 2, 0 ]
[]
[]
[ "database", "mocking", "orm", "python", "testing" ]
stackoverflow_0001326243_database_mocking_orm_python_testing.txt
Q: How can I overload the assignment of a class member? I am writing a Player model class in Python with Django, and I've ran into a small problem with the password member. I'd like the password to be automatically hashed upon assignment, but I can't find anything about overloading the assignment operator or anything...
How can I overload the assignment of a class member?
I am writing a Player model class in Python with Django, and I've ran into a small problem with the password member. I'd like the password to be automatically hashed upon assignment, but I can't find anything about overloading the assignment operator or anything. Is there any way I can overload the assignment of passw...
[ "Can't you use properties and override setter for the field?\nCiting from django documentation:\nfrom django.db import models\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=30)\n last_name = models.CharField(max_length=30)\n\n def _get_full_name(self):\n return \"%s %s\" %...
[ 6, 0 ]
[]
[]
[ "class", "django", "python", "variable_assignment" ]
stackoverflow_0001326978_class_django_python_variable_assignment.txt
Q: Append a tuple to a list Given a tuple (specifically, a functions varargs), I want to prepend a list containing one or more items, then call another function with the result as a list. So far, the best I've come up with is: def fn(*args): l = ['foo', 'bar'] l.extend(args) fn2(l) Which, given Pythons u...
Append a tuple to a list
Given a tuple (specifically, a functions varargs), I want to prepend a list containing one or more items, then call another function with the result as a list. So far, the best I've come up with is: def fn(*args): l = ['foo', 'bar'] l.extend(args) fn2(l) Which, given Pythons usual terseness when it comes t...
[ "You can convert the tuple to a list, which will allow you to concatenate it to the other list. ie:\ndef fn(*args):\n fn2(['foo', 'bar'] + list(args))\n\n", "If your fn2 took varargs also, you wouldn't need to build the combined list:\ndef fn2(*l):\n print l\n\ndef fn(*args):\n fn2(1, 2, *args)\n\nfn(10...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001327204_python.txt
Q: python - problems with regular expression and unicode Hi I have a problem in python. I try to explain my problem with an example. I have this string: >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' >>> print string ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà and i want, for example, r...
python - problems with regular expression and unicode
Hi I have a problem in python. I try to explain my problem with an example. I have this string: >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' >>> print string ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà and i want, for example, replace charachters different from Ñ,Ã,ï with "" i have trie...
[ "You need to make sure that your strings are unicode strings, not plain strings (plain strings are like byte arrays).\nExample:\n>>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ'\n>>> type(string)\n<type 'str'>\n\n# do this instead:\n# (note the u in front of the ', this marks the character sequen...
[ 14 ]
[]
[]
[ "python", "regex", "unicode" ]
stackoverflow_0001327731_python_regex_unicode.txt
Q: Having instance-like behaviour in databases Sorry for the bad title, but I have no idea how to put this in short. The Problem is the following: I have a generic item that represents a group, lets call it Car. Now this Car has attributes, that range within certain limits, lets say for example speed is between 0 and...
Having instance-like behaviour in databases
Sorry for the bad title, but I have no idea how to put this in short. The Problem is the following: I have a generic item that represents a group, lets call it Car. Now this Car has attributes, that range within certain limits, lets say for example speed is between 0 and 180 for a usual Car. Imagine some more attribute...
[ "The easiest way to use inheritance in database models is to use an ORM tool. For Python there is SQLAlchemy, Django and others.\nNow you should wonder whether e.g. a Ford Mustang is a kind of Car, or an instance of Car. In the former case, you should create a ford_mustang table defining the ford_mustang attributes...
[ 1, 1, 1, 1 ]
[]
[]
[ "database", "database_design", "mysql", "python" ]
stackoverflow_0001327848_database_database_design_mysql_python.txt
Q: Should I forward arguments as *args & **kwargs? I have a class that handles command line arguments in my program using python's optparse module. It is also inherited by several classes to create subsets of parameters. To encapsulate the option parsing mechanism I want to reveal only a function add_option to inheri...
Should I forward arguments as *args & **kwargs?
I have a class that handles command line arguments in my program using python's optparse module. It is also inherited by several classes to create subsets of parameters. To encapsulate the option parsing mechanism I want to reveal only a function add_option to inheriting classes. What this function does is then call op...
[ "It seems that you want your subclasses to have awareness of the command line stuff, which is often not a good idea.\nYou want to encapsulate the whole config input portion of your program so that you can drive it with a command line, config file, other python program, whatever.\nSo, I would remove any call to add_...
[ 1, 0 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0001328248_optparse_python.txt
Q: Templating+scripting reverse proxy? Thinking through an idea, wanted to get feedback/suggestions: Having had great success with url rewriting and nginx, I'm now thinking of a more capable reverse proxy/router that would do the following: Map requests to handlers based on regex matching (ala Django) Certain reques...
Templating+scripting reverse proxy?
Thinking through an idea, wanted to get feedback/suggestions: Having had great success with url rewriting and nginx, I'm now thinking of a more capable reverse proxy/router that would do the following: Map requests to handlers based on regex matching (ala Django) Certain requests would simply be routed to backend serv...
[ "This already exist an is called Deliverance: http://deliverance.openplans.org/\n", "So instead of doing something an AJAXy call into an iframe or something, you're doing it on the server side.\nI think it's something I'd only do if the external site was totally under my control, purely for the security implicati...
[ 1, 0 ]
[]
[]
[ "proxy", "python", "reverse_proxy", "twisted" ]
stackoverflow_0001202430_proxy_python_reverse_proxy_twisted.txt