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: SPARQL Query gives unexpected result I hope someone can help me on this probably totally easy-to-solve problem: I want to run a SPARQL query against the following RDF (noted in N3, the RDF/XMl sits here). This is the desription of a journal article and descriptions of the journal, author and publisher: @prefix bi...
SPARQL Query gives unexpected result
I hope someone can help me on this probably totally easy-to-solve problem: I want to run a SPARQL query against the following RDF (noted in N3, the RDF/XMl sits here). This is the desription of a journal article and descriptions of the journal, author and publisher: @prefix bibo: <http://purl.org/ontology/bibo/> . @p...
[ "I don't think that you can use a QName in an XML attribute value; e.g. the value of rdf:about. So consider this line from your RDF/XML file:\n <bibo:Journal rdf:about=\"ex:bibdienst\">\n\nI think that this is actually saying that the subject URI is \"ex:bibdienst\". That is a syntactically valid URI, but it is n...
[ 7, 6 ]
[]
[]
[ "python", "rdf", "rdflib", "sparql" ]
stackoverflow_0001594518_python_rdf_rdflib_sparql.txt
Q: Sending a file with OBEX push in Python How to send a file using OBEX push to a device, which has an open OBEX port in Python? In my case it is a Bluetooth device. A: There is an "OBEX data server" DEBIAN package with DBus interface which could help you. Accessing DBus through Python is fairly easy. A: Try htt...
Sending a file with OBEX push in Python
How to send a file using OBEX push to a device, which has an open OBEX port in Python? In my case it is a Bluetooth device.
[ "There is an \"OBEX data server\" DEBIAN package with DBus interface which could help you. Accessing DBus through Python is fairly easy.\n", "Try http://lightblue.sourceforge.net/\nThe documentation for the OBEX client is here: http://lightblue.sourceforge.net/doc/lightblue.obex-OBEXClient.html\n" ]
[ 0, 0 ]
[]
[]
[ "bluetooth", "obex", "python" ]
stackoverflow_0001563488_bluetooth_obex_python.txt
Q: Implement a listbox I need to implement a listbox for a mobile. The only relevant controls are up and down arrow keys. The listbox should display as many rows of items from a list as will fit on the screen (screen_rows), one row should be highighted (sel_row) and the display should wrap if the user hits up arrow...
Implement a listbox
I need to implement a listbox for a mobile. The only relevant controls are up and down arrow keys. The listbox should display as many rows of items from a list as will fit on the screen (screen_rows), one row should be highighted (sel_row) and the display should wrap if the user hits up arrow when the first item is h...
[ "Few Python programs implement listboxes from scratch -- they're normally just taken from existing toolkits. That may explain why there's no real cross-toolkit \"standard\"!-)\nComing to your code, I imagine set_pos is meant to be called right after either up_key or down_key are finished (you don't make this entir...
[ 1 ]
[]
[]
[ "listbox", "pseudocode", "python" ]
stackoverflow_0001594589_listbox_pseudocode_python.txt
Q: Adding and subtracting dates without Standard Library I am working in a limited environment developing a python script. My issue is I must be able to accomplish datetime addition and subtractions. For example I get the following string: "09/10/20,09:59:47-16" Which is formatted as year/month/day,hour:minute:seco...
Adding and subtracting dates without Standard Library
I am working in a limited environment developing a python script. My issue is I must be able to accomplish datetime addition and subtractions. For example I get the following string: "09/10/20,09:59:47-16" Which is formatted as year/month/day,hour:minute:second-ms. How would I go about adding 30 seconds to this numbe...
[ "You are doing math in different bases. You need to parse the string and come up with a list of values, for example (year, month, day, hour, minute, second), and then do other-base math to add and subtract. For example, hours are base-24, so you need to use modulus to perform the calculations. This sounds suspiciou...
[ 2, 2, 2, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001595704_datetime_python.txt
Q: Convert to UTC Timestamp # parses some string into that format. datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S") # gets the seconds from the above date. timestamp1 = time.mktime(datetime1.timetuple()) # adds milliseconds to the above seconds. timeInMillis = int(timestamp1) * 1000 How do I (at any ...
Convert to UTC Timestamp
# parses some string into that format. datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S") # gets the seconds from the above date. timestamp1 = time.mktime(datetime1.timetuple()) # adds milliseconds to the above seconds. timeInMillis = int(timestamp1) * 1000 How do I (at any point in that code) turn the d...
[ "datetime.utcfromtimestamp is probably what you're looking for:\n>>> timestamp1 = time.mktime(datetime.now().timetuple())\n>>> timestamp1\n1256049553.0\n>>> datetime.utcfromtimestamp(timestamp1)\ndatetime.datetime(2009, 10, 20, 14, 39, 13)\n\n", "I think you can use the utcoffset() method:\nutc_time = datetime1 -...
[ 19, 6, 5, 5 ]
[]
[]
[ "datetime", "python", "utc" ]
stackoverflow_0001595047_datetime_python_utc.txt
Q: Can I execute an SQL Server DTS package from a Python script? I currently have a number of Python scripts that help prep a staging area for testing. One thing that the scripts do not handle is executing DTS packages on MS SQL Server. Is there a way to execute these packages using Python? A: Is calling the DTS ru...
Can I execute an SQL Server DTS package from a Python script?
I currently have a number of Python scripts that help prep a staging area for testing. One thing that the scripts do not handle is executing DTS packages on MS SQL Server. Is there a way to execute these packages using Python?
[ "Is calling the DTS run from the command line an option. If so here is an example for that.\nhttp://www.mssqltips.com/tip.asp?tip=1007\n", "The answer is yes. As mentioned by lansinwd, you'd want to use the command line tool DTSRun. SQL Server tools will need to be installed on the machine executing the Python s...
[ 1, 1 ]
[]
[]
[ "python", "sql_server" ]
stackoverflow_0001596270_python_sql_server.txt
Q: Preserving extent from the old image I am using PIL 1.1.6, Python 2.5 on the Windows platform. In my program, I am performing a point operation (changing the pixel values) and then saving the new image. When I am loading the new and old image, they are not in the same extent. How to impose the extent of old image ...
Preserving extent from the old image
I am using PIL 1.1.6, Python 2.5 on the Windows platform. In my program, I am performing a point operation (changing the pixel values) and then saving the new image. When I am loading the new and old image, they are not in the same extent. How to impose the extent of old image to the new image? My code is: img = Image....
[ "Assuming by \"extent\" you mean \"size\" (pixels wide by pixels high), then there are several options depending on what you have as a \"new\" image.\nIf \"new\" is an existing image (and you want to stretch/shrink/grow the new):\nfrom PIL import Image\n>>> im1 = Image.open('img1.jpg')\n>>> im2 = Image.open('img2.j...
[ 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0001594223_image_python_python_imaging_library.txt
Q: How should I optimize this filesystem I/O bound program? I have a python program that does something like this: Read a row from a csv file. Do some transformations on it. Break it up into the actual rows as they would be written to the database. Write those rows to individual csv files. Go back to step 1 unless t...
How should I optimize this filesystem I/O bound program?
I have a python program that does something like this: Read a row from a csv file. Do some transformations on it. Break it up into the actual rows as they would be written to the database. Write those rows to individual csv files. Go back to step 1 unless the file has been totally read. Run SQL*Loader and load those f...
[ "Poor man's map-reduce:\nUse split to break the file up into as many pieces as you have CPUs.\nUse batch to run your muncher in parallel.\nUse cat to concatenate the results.\n", "If you are I/O bound, the best way I have found to optimize is to read or write the entire file into/out of memory at once, then opera...
[ 5, 3, 3, 2, 1, 1 ]
[ "The first thing is to be certain of what you should optimize. You seem to not know precisely where your time is going. Before spending more time wondering, use a performance profiler to see exactly where the time is going.\nhttp://docs.python.org/library/profile.html\nWhen you know exactly where the time is going...
[ -2 ]
[ "file_io", "optimization", "performance", "python" ]
stackoverflow_0001594604_file_io_optimization_performance_python.txt
Q: Multithreaded Downloading Through Proxies In Python What would be the best library for multithreaded harvesting/downloading with multiple proxy support? I've looked at Tkinter, it looks good but there are so many, does anyone have a specific recommendation? Many thanks! A: Twisted A: Is this something you can'...
Multithreaded Downloading Through Proxies In Python
What would be the best library for multithreaded harvesting/downloading with multiple proxy support? I've looked at Tkinter, it looks good but there are so many, does anyone have a specific recommendation? Many thanks!
[ "Twisted\n", "Is this something you can't just do by passing a URL to newly spawned threads and calling urllib2.urlopen in each one, or is there a more specific requirement?\n", "Also take a look at http://scrapy.org/, which is a scraping framework built on top of twisted. \n" ]
[ 1, 0, 0 ]
[]
[]
[ "download", "harvest", "multithreading", "proxy", "python" ]
stackoverflow_0001597093_download_harvest_multithreading_proxy_python.txt
Q: Fix permissions for rpm/setuptools packaging I have a project that requires post-install hooks for deployment. My method is to use setuptools to generate the skeleton rpm spec file and tar the source files. The problem is that I don't know how to control permissions with this method. The spec file looks like: %i...
Fix permissions for rpm/setuptools packaging
I have a project that requires post-install hooks for deployment. My method is to use setuptools to generate the skeleton rpm spec file and tar the source files. The problem is that I don't know how to control permissions with this method. The spec file looks like: %install python setup.py install --single-version-ex...
[ "\n%defattr(755,%{user},%{user})\n\nThat line sets the default permissions, user, and group ownership on all files. You can override the default with something like:\n%attr(644, <username>, <username>) </path/to/file>\n\nIf you want the default to be owned by a user other than root, then you probably need to defin...
[ 3 ]
[]
[]
[ "packaging", "python", "rpm", "setuptools" ]
stackoverflow_0001402224_packaging_python_rpm_setuptools.txt
Q: How to store dynamically generated HTML form elements from Javascript in Python? I have an HTML form that a user can add an arbitrary amount of input fields to through jQuery. The user is also able to remove any input field from any position. My current implementation is that each new input box has an id of "field...
How to store dynamically generated HTML form elements from Javascript in Python?
I have an HTML form that a user can add an arbitrary amount of input fields to through jQuery. The user is also able to remove any input field from any position. My current implementation is that each new input box has an id of "field[i]" so when the form is posted it is processed in Python as field1, field2 field3, .....
[ "You could serialize the data with javascript and pass it in as json. Then you would just have a dictionary to work with in python. You would need something like simplejson, of course\n" ]
[ 1 ]
[]
[]
[ "dhtml", "google_app_engine", "javascript", "jquery", "python" ]
stackoverflow_0001597766_dhtml_google_app_engine_javascript_jquery_python.txt
Q: Python callback with SWIG wrapped type I'm trying to add a python callback to a C++ library as illustrated: template<typename T> void doCallback(shared_ptr<T> data) { PyObject* pyfunc; //I have this already PyObject* args = Py_BuildValue("(O)", data); PyEval_CallObject(pyfunc,args); } This fails because ...
Python callback with SWIG wrapped type
I'm trying to add a python callback to a C++ library as illustrated: template<typename T> void doCallback(shared_ptr<T> data) { PyObject* pyfunc; //I have this already PyObject* args = Py_BuildValue("(O)", data); PyEval_CallObject(pyfunc,args); } This fails because data hasn't gone through swig, and isn't a P...
[ "shared_ptr<T> for unknown T isn't a type, so SWIG can't hope to wrap it. What you need to do is provide a SWIG wrapping for each instance of shared_ptr that you intend to use. So if for example you want to be able to doCallback() with both shared_ptr<Foo> and shared_ptr<Bar>, you will need:\n\nA wrapper for Foo\...
[ 0, 0 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0001575802_c++_python_swig.txt
Q: Where do I start with a web bot? I simply want to create an automatic script that can run (preferably) on a web-server, and simply 'clicks' on an object of a web page. I am new to Python or whatever language this would be used for so I thought I would go here to ask where to start! This may seem like I want the sc...
Where do I start with a web bot?
I simply want to create an automatic script that can run (preferably) on a web-server, and simply 'clicks' on an object of a web page. I am new to Python or whatever language this would be used for so I thought I would go here to ask where to start! This may seem like I want the script to scam advertisements or do some...
[ "It doesn't have to be Python, I've seen it done in PHP and Perl, and you can probably do it in many other languages.\nThe general approach is:\n1) You give your app a URL and it makes an HTTP request to that URL. I think I have seen this done with php/wget. Probably many other ways to do it.\n2) Scan the HTTP resp...
[ 6, 4, 2, 1 ]
[]
[]
[ "bots", "python" ]
stackoverflow_0001597833_bots_python.txt
Q: Is there a better, pythonic way to do this? This is my first python program - Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds. Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more...
Is there a better, pythonic way to do this?
This is my first python program - Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds. Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way? CODE : import csv adDict = {} r...
[ "Congratulations, your code is very nice.\nThere are a few little tricks you could use to make it shorter/simpler.\nThere is a nifty object type called defaultdict which is provided by the collections module. Instead of having to check if adDict has an adId key, you can set up a defaultdict which acts like a regul...
[ 18, 10, 7, 3, 3, 3, 1, 1 ]
[]
[]
[ "dictionary", "python", "set" ]
stackoverflow_0001597764_dictionary_python_set.txt
Q: Adding row to numpy recarray Is there an easy way to add a record/row to a numpy recarray without creating a new recarray? Let's say I have a recarray that takes 1Gb in memory, I want to be able to add a row to it without having python take up 2Gb of memory temporarily. A: You can call yourrecarray.resize with a...
Adding row to numpy recarray
Is there an easy way to add a record/row to a numpy recarray without creating a new recarray? Let's say I have a recarray that takes 1Gb in memory, I want to be able to add a row to it without having python take up 2Gb of memory temporarily.
[ "You can call yourrecarray.resize with a shape which has one more row, then assign to that new row. Of course. numpy might still have to allocate completely new memory if it just doesn't have room to grow the array in-place, but at least you stand a chance!-)\nSince an example was requested, here comes, modified o...
[ 10 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001598251_numpy_python.txt
Q: Printing basenames by Python How can you print the basenames of files by Python in the main folder and subfolders? My attempt #!/usr/bin/python import os import sys def dir_basename (dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): for fname in filenames:...
Printing basenames by Python
How can you print the basenames of files by Python in the main folder and subfolders? My attempt #!/usr/bin/python import os import sys def dir_basename (dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): for fname in filenames: print os....
[ "Let me explain the debugging methodology a little bit.\nAs you've encountered the situation in which len(sys.argv) != 1, you should ask youself: \"What is the actual value of len(sys.argv)? Why it is so?\". The answers are:\n>>> len(sys.argv)\n2\n>>> sys.argv\n['/tmp/basename.py', '/path/to/home/Desktop/pgCodes/']...
[ 8, 3, 2, 1, 1 ]
[]
[]
[ "path", "python" ]
stackoverflow_0001598013_path_python.txt
Q: Python graceful fail on int() call? I have to make a rudimentary FSM in a class, and am writing it in Python. The assignment requires we read the transitions for the machine from a text file. So for example, a FSM with 3 states, each of which have 2 possible transitions, with possible inputs 'a' and 'b', wolud h...
Python graceful fail on int() call?
I have to make a rudimentary FSM in a class, and am writing it in Python. The assignment requires we read the transitions for the machine from a text file. So for example, a FSM with 3 states, each of which have 2 possible transitions, with possible inputs 'a' and 'b', wolud have a text file that looks like this: 2 ...
[ "You should really only be trying to parse the tokens that you expect to be integers\nfor line in f:\n tokens = line.split(\" \")\n current_state, input_val, next_state = int(tokens[0]), tokens[1], int(tokens[2])\n\nArguably more-readable:\nfor line in f:\n current_state, input_val, next_state = parseline(...
[ 12, 4, 1, 0 ]
[]
[]
[ "fsm", "python" ]
stackoverflow_0001597114_fsm_python.txt
Q: How to read continous HTTP streaming data in Python? How to read binary streams from a HTTP streamer server in python. I did a search and someone said urllib2 can do the job but had blocking issues. Someone suggested Twisted framework. My questions are: If it's just a streaming client reads data on background, ca...
How to read continous HTTP streaming data in Python?
How to read binary streams from a HTTP streamer server in python. I did a search and someone said urllib2 can do the job but had blocking issues. Someone suggested Twisted framework. My questions are: If it's just a streaming client reads data on background, can I ignore the blocking issues caused by urllib2? What wil...
[ "To defeat urllib2's intrinsic buffering, you could do:\nimport socket\nsocket._fileobject.default_bufsize = 0\n\nbecause it's actualy socket._fileobject that buffers underneath. No data will be lost anyway, but with the default buffering (8192 bytes at a time) data may end up overly chunked for real-time streamin...
[ 6 ]
[]
[]
[ "client", "python", "stream", "streaming" ]
stackoverflow_0001598331_client_python_stream_streaming.txt
Q: cElementTree invalid encoding problem I'm encoding challenged, so this is probably simple, but I'm stuck. I'm trying to parse an XML file emailed to the App Engine's new receive mail functionality. First, I just pasted the XML into the body of the message, and it parsed fine with CElementTree. Then I changed to us...
cElementTree invalid encoding problem
I'm encoding challenged, so this is probably simple, but I'm stuck. I'm trying to parse an XML file emailed to the App Engine's new receive mail functionality. First, I just pasted the XML into the body of the message, and it parsed fine with CElementTree. Then I changed to using an attachment, and parsing it with CEle...
[ "Ah, nevermind. There's a bug in App Engine that is calling lower() on all attachments when you decode them. This made the CDATA string invalid. \nHere's a link to the bug report: http://code.google.com/p/googleappengine/issues/detail?id=2289#c2\n" ]
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001597604_python_xml.txt
Q: Encoding of arguments to subprocess.Popen I have a Python extension to the Nautilus file browser (AFAIK this runs exclusively on GNU/Linux/Unix/etc environments). I decided to split out an expensive computation and run it as a subprocess, pickle the result and send it back over a pipe. My question concerns the arg...
Encoding of arguments to subprocess.Popen
I have a Python extension to the Nautilus file browser (AFAIK this runs exclusively on GNU/Linux/Unix/etc environments). I decided to split out an expensive computation and run it as a subprocess, pickle the result and send it back over a pipe. My question concerns the arguments to the script. Since the computation req...
[ "It does not matter: as long as your script knows to expect a utf-8 encoding for the argument, it can decode it properly. utf-8 is the correct choice because it will let you encode ANY Unicode string -- not just those for some languages but not others, as choices such as Latin-1 would entail!\n", "Use sys.getfil...
[ 4, 2 ]
[]
[]
[ "localization", "python", "subprocess" ]
stackoverflow_0001598334_localization_python_subprocess.txt
Q: Specific use case for Django admin I have a couple special use cases for Django admin, and I'm curious about other peoples' opinions: I'd like to use a customized version the admin to allow users to edit certain objects on the site (customized to look more like the rest of the site). At this point users can only ...
Specific use case for Django admin
I have a couple special use cases for Django admin, and I'm curious about other peoples' opinions: I'd like to use a customized version the admin to allow users to edit certain objects on the site (customized to look more like the rest of the site). At this point users can only edit objects they own, but I'll eventual...
[ "You are free to do whatever you want. If you want to customize the Django admin, go for it, but you will likely not be as well supported by the mailing list and IRC once you deviate from the typical admin modifications path.\nWhile customizing the admin might seem like the easy solution right now, more than likel...
[ 4, 2, 1 ]
[]
[]
[ "django", "django_admin", "django_views", "python" ]
stackoverflow_0001598248_django_django_admin_django_views_python.txt
Q: Configuring Python's default exception handling For an uncaught exception, Python by default prints a stack trace, the exception itself, and terminates. Is anybody aware of a way to tailor this behaviour on the program level (other than establishing my own global, catch-all exception handler), so that the stack tr...
Configuring Python's default exception handling
For an uncaught exception, Python by default prints a stack trace, the exception itself, and terminates. Is anybody aware of a way to tailor this behaviour on the program level (other than establishing my own global, catch-all exception handler), so that the stack trace is omitted? I would like to toggle in my app whet...
[ "You are looking for sys.excepthook:\nsys.excepthook(type, value, traceback) \nThis function prints out a given traceback and exception to sys.stderr.\nWhen an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object...
[ 27 ]
[]
[]
[ "python" ]
stackoverflow_0001599962_python.txt
Q: How to read a csv file with python I'm trying to read a csv file but it doesn't work. I can read my csv file but when I see what I read, there where white space between values. Here is my code # -*- coding: iso-8859-1 -*- import sql_db, tmpl_macros, os import security, form, common import csv class windows_dial...
How to read a csv file with python
I'm trying to read a csv file but it doesn't work. I can read my csv file but when I see what I read, there where white space between values. Here is my code # -*- coding: iso-8859-1 -*- import sql_db, tmpl_macros, os import security, form, common import csv class windows_dialect(csv.Dialect): """Describe the us...
[ "I prefer to use numpy's genfromtxt rather than the standard csv library, because it generates numpy's recarray, which are clean data structures to store data in a table-like object.\n>>> from numpy import genfromtxt\n>>> data = genfromtxt(csvfile, delimiter=',', dtype=None)\n# data is a table-like structure (a num...
[ 7, 2, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0001593318_csv_python.txt
Q: setTrace() in Python Is there a way to use the setTrace() function in a script that has no method definitions? i.e. for i in range(1, 100): print i def traceit(frame, event, arg): if event == "line": lineno = frame.f_lineno print "line", lineno return traceit sys.settrace(traceit) so id...
setTrace() in Python
Is there a way to use the setTrace() function in a script that has no method definitions? i.e. for i in range(1, 100): print i def traceit(frame, event, arg): if event == "line": lineno = frame.f_lineno print "line", lineno return traceit sys.settrace(traceit) so ideally I would want the tra...
[ "settrace() is really only intended for implementing debuggers. If you are using it to debug this program, you may be better off using PDB\nAccording to the documentation, settrace() will not do what you want.\nIf you really want to do this line by line tracing, have a look at the compiler package which allows you ...
[ 2, 2 ]
[]
[]
[ "python", "trace" ]
stackoverflow_0001600726_python_trace.txt
Q: setTrace() in Python (redux) Apologies for reposting but I had to edit this question when I got to work and realized I needed to have an account to do so. So here it goes again (with a little more context). I'm trying to time how long a script takes to execute, and I am thinking of doing that by checking the elaps...
setTrace() in Python (redux)
Apologies for reposting but I had to edit this question when I got to work and realized I needed to have an account to do so. So here it goes again (with a little more context). I'm trying to time how long a script takes to execute, and I am thinking of doing that by checking the elapsed time after every line of code i...
[ "No, as the docs say, \"The trace function is invoked (with event set to 'call') whenever a new local scope is entered\" -- if you never enter a local scope (and only execute in global scope), the trace function will never be called. Note that settrace is too invasive anyway for the purpose of timing \"how long a ...
[ 2 ]
[]
[]
[ "python", "trace" ]
stackoverflow_0001601217_python_trace.txt
Q: Is there a way to tell whether a function is getting executed in a unittest? I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory ...
Is there a way to tell whether a function is getting executed in a unittest?
I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory sqlite database instead. Is there a way to tell at that point whether I'm inside ...
[ "Inject your database dependency into your class using IoC. This should be done by handing it a repository object in the constructor of your class. Note that you don't necessarily need an IoC container to do this. You just need a repository interface and two implementations of your repository.\nNote: In Python ...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python", "sqlite", "unit_testing" ]
stackoverflow_0001601308_python_sqlite_unit_testing.txt
Q: How can I closely achieve ?: from C++/C# in Python? In C# I could easily write the following: string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString; Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement? A: In Python 2.5, there is A if C els...
How can I closely achieve ?: from C++/C# in Python?
In C# I could easily write the following: string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString; Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?
[ "In Python 2.5, there is\nA if C else B\n\nwhich behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:\nstringValue = otherString or defaultString\n\n", "@Dan\n\nif otherString:\n ...
[ 24, 5, 1, 1, 0, 0, 0 ]
[ "You can take advantage of the fact that logical expressions return their value, and not just true or false status. For example, you can always use:\nresult = question and firstanswer or secondanswer\n\nWith the caveat that it doesn't work like the ternary operator if firstanswer is false. This is because questio...
[ -1, -1 ]
[ "python", "syntax", "syntax_rules", "ternary_operator" ]
stackoverflow_0000135303_python_syntax_syntax_rules_ternary_operator.txt
Q: Cherrypy server unavailable from anything but localhost I am having an issue with cherrypy that looks solved, but doesn't work. I can only bind on localhost or 127.0.0.1. Windows XP Home and Mac OS X (linux untested), cherrypy 3.1.2, python 2.5.4. This is the end of my app: global_conf = { 'global': { '...
Cherrypy server unavailable from anything but localhost
I am having an issue with cherrypy that looks solved, but doesn't work. I can only bind on localhost or 127.0.0.1. Windows XP Home and Mac OS X (linux untested), cherrypy 3.1.2, python 2.5.4. This is the end of my app: global_conf = { 'global': { 'server.environment= "production"' 'engi...
[ "huh, you're doing something wrong with your dict:\n>>> global_conf = {\n... 'global': { 'server.environment= \"production\"'\n... 'engine.autoreload_on : True'\n... 'engine.autoreload_frequency = 5 '\n... 'server.socket_host': '0.0.0.0',\n...
[ 7, 3 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0001555319_cherrypy_python.txt
Q: How to make a completely unshared copy of a complicated list? (Deep copy is not enough) Have a look at this Python code: a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] Notice how mo...
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
Have a look at this Python code: a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] Notice how modifying one element of c modifies that everywhere. That is, if 99 is appended to c[0][0], it ...
[ "When you want a copy, you explicitly make a copy - the cryptical [:] \"slice it all\" form is idiomatic, but my favorite is the much-more-readable approach of explicitly calling list.\nIf c is constructed in the wrong way (with references instead of shallow copies to lists you want to be able to modify independent...
[ 8, 8, 5, 5, 1 ]
[]
[]
[ "copy", "list", "python" ]
stackoverflow_0001601269_copy_list_python.txt
Q: Recursion - Python, return value question I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off: A recursive function as so: def fac(n): if n == 0: return 1 else: return n * fac(n - 1) Why is it that when the funct...
Recursion - Python, return value question
I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off: A recursive function as so: def fac(n): if n == 0: return 1 else: return n * fac(n - 1) Why is it that when the function reaches n == 0 that it does not return 1 bu...
[ "Think about like this, for fac(5) for example:\nreturn 5 * fac(4)\n return 4 * fac(3)\n return 3 * fac(2)\n return 2 * fac(1)\n return 1 * fac(0)\n 1\n\nSo...
[ 12, 1, 0, 0, 0 ]
[]
[]
[ "python", "recursion", "stack" ]
stackoverflow_0001601757_python_recursion_stack.txt
Q: Asynchronous Stream Processing in Python Let's start with a simple example. A HTTP data stream comes in the following format: MESSAGE_LENGTH, 2 bytes MESSAGE_BODY, REPEAT... Currently, I use urllib2 to retrieve and process streaming data as below: length = response.read(2) while True: data = response.read(le...
Asynchronous Stream Processing in Python
Let's start with a simple example. A HTTP data stream comes in the following format: MESSAGE_LENGTH, 2 bytes MESSAGE_BODY, REPEAT... Currently, I use urllib2 to retrieve and process streaming data as below: length = response.read(2) while True: data = response.read(length) DO DATA PROCESSING It works, but si...
[ "Yes, can be done and is not that hard, if your format is essentially fixed.\nI used it with httplib in Python 2.2.3 and found it had some abysmal performance in the way we hacked it together (basically monkey patching a select() based socket layer into httplib).\nThe trick is to get the socket and do the buffering...
[ 1, 0 ]
[]
[]
[ "python", "stream", "streaming" ]
stackoverflow_0001599540_python_stream_streaming.txt
Q: What's the difference between casting and coercion in Python? In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced". A: Cast is explicit. Coerce is implicit. The examples in Python would be: cast(2, POINTER(c_float)) #cast 1.0 + 2 #coerce 1.0 + float(2...
What's the difference between casting and coercion in Python?
In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced".
[ "Cast is explicit. Coerce is implicit.\nThe examples in Python would be:\ncast(2, POINTER(c_float)) #cast\n1.0 + 2 #coerce \n1.0 + float(2) #conversion\n\nCast really only comes up in the C FFI. What is typically called casting in C or Java is referred to as conversion in python, though it often gets referred to ...
[ 43, 32 ]
[]
[]
[ "casting", "coercion", "python", "types" ]
stackoverflow_0001602122_casting_coercion_python_types.txt
Q: Foreign key needs a value from the key's table to match a column in another table Pardon the excessive amount of code, but I'm not sure if I can explain my question otherwise I have a Django project that I am working on which has the following: class Project(models.Model): name = models.CharField(max_length=10...
Foreign key needs a value from the key's table to match a column in another table
Pardon the excessive amount of code, but I'm not sure if I can explain my question otherwise I have a Django project that I am working on which has the following: class Project(models.Model): name = models.CharField(max_length=100, unique=True) dir = models.CharField(max_length=300, blank=True, unique=True ) ...
[ "You could use the pre_save signal and raise an error if they do no match... The effect would be similar to overridding save (it gets called before save)\nThe problem is creating/deleting/updating the many-to-many relation will not trigger save (or consequentially pre_save or post_save)\nUpdate\nTry using the throu...
[ 2, 1 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0001601586_database_django_python.txt
Q: Problems scripting Unison with Python I am trying to make a simple script to automate and log synchronization via Unison. I am also using subprocess.Popen rather than the usual os.system call as it's deprecated. I've spent the past 2 days looking at docs and such trying to figure out what I'm doing wrong, but for ...
Problems scripting Unison with Python
I am trying to make a simple script to automate and log synchronization via Unison. I am also using subprocess.Popen rather than the usual os.system call as it's deprecated. I've spent the past 2 days looking at docs and such trying to figure out what I'm doing wrong, but for some reason if I call unison from a termina...
[ "The most likely culprit is that unison is sending some output to stderr instead of just stdout. Popen takes an additional stderr argument so you can try capturing that instead of (or in addition to) stdout).\nFor a quick reference on standard streams see Wikipedia.\n", "Changed [\"unison\", \"sync\"] to simply ...
[ 1, 0 ]
[]
[]
[ "python", "unison" ]
stackoverflow_0001602529_python_unison.txt
Q: Python problem executing popen in cron I use popen to execute commands in a Python script, and I call it via cron. Cron calls out this script but the behavior isn't the same if I call it by hand. Source: from subprocess import Popen, PIPE pp = Popen('/usr/bin/which iptables', shell=True, stdout=PIPE) data = '' f...
Python problem executing popen in cron
I use popen to execute commands in a Python script, and I call it via cron. Cron calls out this script but the behavior isn't the same if I call it by hand. Source: from subprocess import Popen, PIPE pp = Popen('/usr/bin/which iptables', shell=True, stdout=PIPE) data = '' for ln in pp.stdout: data = data+ln if d...
[ "Normally when processes are run from cron, the PATH is set to a very restrictive value (the man page for my crontab says /usr/bin:/bin). You may need to add:\n\nPATH=/usr/bin:/bin:/sbin\n\nto the top of your crontab file.\n" ]
[ 20 ]
[]
[]
[ "console", "cron", "python" ]
stackoverflow_0001602830_console_cron_python.txt
Q: How do I wrangle python lookups: make.up.a.dot.separated.name.and.use.it.until.destroyed = 777 I'm a Python newbie with a very particular itch to experiment with Python's dot-name-lookup process. How do I code either a class or function in "make.py" so that these assignment statements work succesfully? import mak...
How do I wrangle python lookups: make.up.a.dot.separated.name.and.use.it.until.destroyed = 777
I'm a Python newbie with a very particular itch to experiment with Python's dot-name-lookup process. How do I code either a class or function in "make.py" so that these assignment statements work succesfully? import make make.a.dot.separated.name = 666 make.something.else.up = 123 make.anything.i.want = 777
[ "#!/usr/bin/env python\n\nclass Make:\n def __getattr__(self, name):\n self.__dict__[name] = Make()\n return self.__dict__[name]\n\nmake = Make()\n\nmake.a.dot.separated.name = 666\nmake.anything.i.want = 777\n\nprint make.a.dot.separated.name\nprint make.anything.i.want\n\nThe special __getattr__ ...
[ 19 ]
[]
[]
[ "lookup", "namespaces", "python" ]
stackoverflow_0001602745_lookup_namespaces_python.txt
Q: Django raw id field lookup has the wrong link I have a django app, and on the backend I've got a many to many field that I've set in the 'raw_id_fields' property in the ModelAdmin class. When running it locally, everything is fine, but when I test on the live site, the link to the lookup popout window doesnt work...
Django raw id field lookup has the wrong link
I have a django app, and on the backend I've got a many to many field that I've set in the 'raw_id_fields' property in the ModelAdmin class. When running it locally, everything is fine, but when I test on the live site, the link to the lookup popout window doesnt work. The django app resides at example.com/djangoapp/ ...
[ "This sounds like a bug in Django, I've seen a few of this kind. I'm pretty sure it has to do with the fact that you placed your admin at example.com/djangoapp/admin/ instead of example.com/admin/ which is the default. I have a hunch that if you change the admin url, it will work.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0001602607_django_django_admin_python.txt
Q: Exit a process while threads are sleeping In a python script, I started a bunch of threads, each of which pulls some resource at an interval using time.sleep(interval). I have another thread running, which uses the cmd module to monitor user inputs. When the user enters 'q', I call sys.exit(0) However, when the s...
Exit a process while threads are sleeping
In a python script, I started a bunch of threads, each of which pulls some resource at an interval using time.sleep(interval). I have another thread running, which uses the cmd module to monitor user inputs. When the user enters 'q', I call sys.exit(0) However, when the script is running and I enter 'q', the thread us...
[ "sys.exit will only stop the thread it executes from. If you have other non-daemon thread in your program they will continue to execute. Section 17.2.1 of the Python library docs contains:\n\nA thread can be flagged as a “daemon\n thread”. The significance of this flag\n is that the entire Python program\n exits...
[ 5 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001602743_multithreading_python.txt
Q: I want to create a "CGI script" in python that stays resident in memory and services multiple requests I have a website that right now, runs by creating static html pages from a cron job that runs nightly. I'd like to add some search and filtering features using a CGI type script, but my script will have enough o...
I want to create a "CGI script" in python that stays resident in memory and services multiple requests
I have a website that right now, runs by creating static html pages from a cron job that runs nightly. I'd like to add some search and filtering features using a CGI type script, but my script will have enough of a startup time (maybe a few seconds?) that I'd like it to stay resident and serve multiple requests. This ...
[ "That's exactly what WSGI is for ;)\nI don't know off hand what the simplest way to turn a CGI script into a WSGI application is, though (I've always had that managed by a framework). It shouldn't be too tricky, though.\nThat said, An Introduction to the Python Web Server Gateway Interface (WSGI) seems to be a reas...
[ 4 ]
[ "maybe you should direct your search towards inter process commmunication and make a search process that returns the results to the web server. This search process will be running all the time assuming you have your own server.\n" ]
[ -1 ]
[ "cgi", "frameworks", "pylons", "python" ]
stackoverflow_0001602516_cgi_frameworks_pylons_python.txt
Q: Setting value for a node in XML document in Python I have a XML document "abc.xml": I need to write a function replace(name, newvalue) which can replace the value node with tag 'name' with the new value and write it back to the disk. Is this possible in python? How should I do this? A: Sure it is possible. The...
Setting value for a node in XML document in Python
I have a XML document "abc.xml": I need to write a function replace(name, newvalue) which can replace the value node with tag 'name' with the new value and write it back to the disk. Is this possible in python? How should I do this?
[ "Sure it is possible. \nThe xml.etree.ElementTree module will help you with parsing XML, finding tags and replacing values.\nIf you know a little bit more about the XML file you want to change, you can probably make the task a bit easier than if you need to write a generic function that will handle any XML file.\nI...
[ 2, 2 ]
[]
[]
[ "python", "python_3.x", "xml" ]
stackoverflow_0001602919_python_python_3.x_xml.txt
Q: mysqldb on python 2.6+ (win32) I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6? A: There are versions of mysqldb for...
mysqldb on python 2.6+ (win32)
I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6?
[ "There are versions of mysqldb for python 2.6, they're just not available on the official site. It took me a while (and unfortunately I lost the link) but you can search google and find people who have compiled and released 2.6 versions of mysqldb for windows x64 and x32.\nEDIT:\nhttp://sourceforge.net/forum/forum....
[ 11, 7 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000685869_mysql_python.txt
Q: Why can I not import the Python module 'signal' using Jython, in Linux? I can't find any reference to the 'signal' class being left out in Jython. Using Jython 2.1. Thanks A: I would imagine Unix-style signals are difficult to do on the JVM, since the JVM has no notion of signals, and it is likely some JNI magic...
Why can I not import the Python module 'signal' using Jython, in Linux?
I can't find any reference to the 'signal' class being left out in Jython. Using Jython 2.1. Thanks
[ "I would imagine Unix-style signals are difficult to do on the JVM, since the JVM has no notion of signals, and it is likely some JNI magic would be required to get this to work.\nIn Jython 2.5, the module exists, but seems to throw NotImplementedError for most functions.\n" ]
[ 2 ]
[]
[]
[ "jython", "python", "signals" ]
stackoverflow_0001603189_jython_python_signals.txt
Q: Python idiom for 'Try until no exception is raised' I want my code to automatically try multiple ways to create a database connection. As soon as one works, the code needs to move on (i.e. it shouldn't try to other ways anymore). If they all fail well, then the script can just blow up. So in - what I thought was, ...
Python idiom for 'Try until no exception is raised'
I want my code to automatically try multiple ways to create a database connection. As soon as one works, the code needs to move on (i.e. it shouldn't try to other ways anymore). If they all fail well, then the script can just blow up. So in - what I thought was, but most likely isn't - a stroke of genius I tried this: ...
[ "Approximately:\nattempts = [\n { 'database'='postgres', 'user'='pgsql', ...},\n { 'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=getpass()},\n ...\n]\nconn = None\nfor attempt in attempts:\n try:\n conn = psycopg2.connect(**attempt)\n break\n except psycopg2.O...
[ 14 ]
[ "You're close. Probably the best thing to do in this case is nesting the second and subsequent attempts in the except block. Thus the critical part of your code would look like:\nif not CURSOR:\n # try to connect and get a cursor\n try:\n # first try the bog standard way: db postgres, user postgres a...
[ -1 ]
[ "python" ]
stackoverflow_0001603578_python.txt
Q: Why is this simple python class not working? I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here's what I have so far class getlist: def newlist(self,*number): lst=[] ...
Why is this simple python class not working?
I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here's what I have so far class getlist: def newlist(self,*number): lst=[] self.number=number lst.append(number) ...
[ "In Python, when you are writing methods inside an object, you need to prefix all references to variables belonging to that object with self. - like so:\nclass getlist: \n def newlist(self,*number):\n self.lst=[]\n self.lst += number #I changed this to add all args to the list\n\n def printlis...
[ 7, 3 ]
[]
[]
[ "class", "list", "python" ]
stackoverflow_0001603696_class_list_python.txt
Q: CherryPy, load image from matplotlib, or in general I am not sure what I am doing wrong, It would be great if you could point me toward what to read. I have taken the first CherryPy tutorial "hello world" added a little matplotlib plot. Question 1: how do I know where the file will be saved? It happens to be where...
CherryPy, load image from matplotlib, or in general
I am not sure what I am doing wrong, It would be great if you could point me toward what to read. I have taken the first CherryPy tutorial "hello world" added a little matplotlib plot. Question 1: how do I know where the file will be saved? It happens to be where I am running the file. Question 2: I don't seem to be ge...
[ "Below are some things that have worked for me, but before you proceed further I recommend that you read this page about how to configure directories which contain static content.\nQuestion 1: How do I know where the file will be saved?\nIf you dictate where the file should be saved, the process of finding it shou...
[ 5 ]
[]
[]
[ "cherrypy", "matplotlib", "python" ]
stackoverflow_0001603669_cherrypy_matplotlib_python.txt
Q: What is the right way to design an adventure game with PyGame? I have started development on a small 2d adventure side view game together with a couple of people. The game will consist of the regular elements: A room, a main character, an inventory, npcs, items and puzzles. We've chosen PyGame since we all are fam...
What is the right way to design an adventure game with PyGame?
I have started development on a small 2d adventure side view game together with a couple of people. The game will consist of the regular elements: A room, a main character, an inventory, npcs, items and puzzles. We've chosen PyGame since we all are familiar with python from before. My question is quite theoretical, but...
[ "Python Adventure Writing System - http://home.fuse.net/wolfonenet/PAWS.htm - might be useful\nhttp://proquestcombo.safaribooksonline.com/1592000770 may also be useful\n" ]
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0001603928_pygame_python.txt
Q: Deploying a web service to my Google App Engine application We made a simple application and using GoogleAppEngineLauncher (GAEL) ran that locally. Then we deployed, using GAEL again, to our appid. It works fine. Now, we made a web service. We ran that locally using GAEL and a very thin local python client. It wo...
Deploying a web service to my Google App Engine application
We made a simple application and using GoogleAppEngineLauncher (GAEL) ran that locally. Then we deployed, using GAEL again, to our appid. It works fine. Now, we made a web service. We ran that locally using GAEL and a very thin local python client. It works fine. We deployed that, and we get this message when we try t...
[ "Looks like you're not setting the Content-Type header correctly in your service (assuming you ARE actually trying to send XML -- e.g. SOAP, XML-RPC, &c). What code are you using to set that header? Without some indication about what protocol you're implementing and via what framework, it's impossible to help in d...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "iphone", "python", "web_services" ]
stackoverflow_0001513038_google_app_engine_iphone_python_web_services.txt
Q: Parallel SSH in Python I wonder what is the best way to handle parallel SSH connections in python. I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way. Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SS...
Parallel SSH in Python
I wonder what is the best way to handle parallel SSH connections in python. I need to open several SSH connections to keep in background and to feed commands in interactive or timed batch way. Is this possible to do it with the paramiko libraries? It would be nice not to spawn a different SSH process for each connectio...
[ "It might be worth checking out what options are available in Twisted. For example, the Twisted.Conch page reports:\n\nhttp://twistedmatrix.com/users/z3p/files/conch-talk.html\nUnlike OpenSSH, the Conch server does not fork a process for each incoming connection. Instead, it uses the Twisted reactor to multiplex t...
[ 3, 3, 1, 1, 1 ]
[ "This might not be relevant to your question. But there are tools like pssh, clusterssh etc. that can parallely spawn connections. You can couple Expect with pssh to control them too.\n" ]
[ -1 ]
[ "parallel_processing", "python", "ssh" ]
stackoverflow_0001185855_parallel_processing_python_ssh.txt
Q: Do dictionaries in Python have a single repr value? In this question, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case? PS. the most elegant solution to the ori...
Do dictionaries in Python have a single repr value?
In this question, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case? PS. the most elegant solution to the original problem was actually using frozenset
[ "No, the order that keys are added to a dictionary can affect the internal data structure. When two items have the same hash value and end up in the same bucket then the order they are added to the dictionary matters.\n>>> (1).__hash__()\n1\n>>> (1 << 32).__hash__()\n1\n>>> repr({1: 'one', 1 << 32: 'not one'})\n\"{...
[ 7, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001604281_python.txt
Q: How to use JQuery and Django (ajax + HttpResponse)? Suppose I have an AJAX function: function callpage{ $.ajax({ method:"get", url:"/abc/", data:"x="+3 beforeSend:function() {}, success:function(html){ IF HTTPRESPONSE = "1" , ALERT SUCCESS! } }); return false; } } When my "V...
How to use JQuery and Django (ajax + HttpResponse)?
Suppose I have an AJAX function: function callpage{ $.ajax({ method:"get", url:"/abc/", data:"x="+3 beforeSend:function() {}, success:function(html){ IF HTTPRESPONSE = "1" , ALERT SUCCESS! } }); return false; } } When my "View" executes in Django, I want to return HttpResponse('1...
[ "The typical workflow is to have the server return a JSON object as text, and then interpret that object in the javascript. In your case you could return the text {\"httpresponse\":1} from the server, or use the python json libary to generate that for you. \nJQuery has a nice json-reader (I just read the docs, so t...
[ 16, 2 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0001527641_django_jquery_python.txt
Q: Object oriented design? I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great ...
Object oriented design?
I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in so...
[ "You don't have to throw out structured programming to do object-oriented programming. The code is still structured, it just belongs to the objects rather than being separate from them.\nIn classical programming, code is the driving force that operates on data, leading to a dichotomy (and the possibility that code ...
[ 7, 5, 3, 1 ]
[ "Rather than using dicts to represent your transactions, a better container would be a namedtuple from the collections module. A namedtuple is a subclass of tuple which allows you to reference it's items by name as well as index number.\nSince you may possibly have thousands of transactions in your journal lists, ...
[ -1 ]
[ "oop", "python" ]
stackoverflow_0001604391_oop_python.txt
Q: How to get output? I am using the Python/C API with my app and am wondering how you can get console output with a gui app. When there is a script error, it is displayed via printf but this obviously has no effect with a gui app. I want to be able to obtain the output without creating a console. Can this be done? E...
How to get output?
I am using the Python/C API with my app and am wondering how you can get console output with a gui app. When there is a script error, it is displayed via printf but this obviously has no effect with a gui app. I want to be able to obtain the output without creating a console. Can this be done? Edit - Im using Windows, ...
[ "Use the logging package instead of printf. You can use something similar if you need to log output from a C function.\n", "If by printf you mean exactly thqt call from C code, you need to redirect (and un-buffer) your standard output (file descriptor 0) to somewhere you can pick up the data from -- far from tri...
[ 1, 1 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0001604811_python_user_interface.txt
Q: Parsing a text file with Python? I have to do an assignment where i have a .txt file that contains something like this p There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain... h1 this is another example of what this text file looks like i am suppose to writ...
Parsing a text file with Python?
I have to do an assignment where i have a .txt file that contains something like this p There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain... h1 this is another example of what this text file looks like i am suppose to write a python code that parses this text ...
[ "You say you're very new to Python, so I'll start at the very low-level. You can iterate over the lines in a file very simply in Python\nfyle = open(\"contents.txt\")\nfor lyne in fyle :\n # Do string processing here\nfyle.close()\n\nNow how to parse it. If each formatting directive (e.g. p, h1), is on a separ...
[ 10, 1 ]
[]
[]
[ "parsing", "python", "string", "text_files" ]
stackoverflow_0001604074_parsing_python_string_text_files.txt
Q: How can I work out the class hierarchy given an object instance in Python? Is there anyway to discover the base class of a class in Python? For given the following class definitions: class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" If I received an instance of an...
How can I work out the class hierarchy given an object instance in Python?
Is there anyway to discover the base class of a class in Python? For given the following class definitions: class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" If I received an instance of an object I can easily work out that it is a B by doing the following: instance = ...
[ "The inspect module is really powerful also:\n>>> import inspect\n\n>>> inst = B()\n>>> inspect.getmro(inst.__class__)\n(<class __main__.B at 0x012B42A0>, <class __main__.A at 0x012B4210>)\n\n", "b = B()\nb.__class__\nb.__class__.__base__\nb.__class__.__bases__\nb.__class__.__base__.__subclasses__()\n\nI strongly...
[ 6, 5, 4, 0 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0001603964_inheritance_oop_python.txt
Q: Emulate processing with python? I'm looking for a basic programmatic animation framework similar to processing except in python. That is, something that allows pixel manipulation, has basic drawing/color primitives, and is geared towards animation. Is pygame pretty much the best bet or are there other options? A:...
Emulate processing with python?
I'm looking for a basic programmatic animation framework similar to processing except in python. That is, something that allows pixel manipulation, has basic drawing/color primitives, and is geared towards animation. Is pygame pretty much the best bet or are there other options?
[ "\"Similar to processing except in python\" screams \"NodeBox\" to me. NodeBox is OSX-only, and i don't know if it allows pixel-level manipulation, but much of its command set was derived directly from processing. You can find it at the NodeBox site.\n", "Well, this is as close as it gets: http://code.google.com...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "processing", "pygame", "python" ]
stackoverflow_0001150897_processing_pygame_python.txt
Q: Pure python solution to convert XHTML to PDF I am after a pure Python solution (for the GAE) to convert webpages to pdf. I had a look at reportlab but the documentation focuses on generating pdfs from scratch, rather than converting from HTML. What do you recommend? - pisa? Edit: My use case is I have a HTML repor...
Pure python solution to convert XHTML to PDF
I am after a pure Python solution (for the GAE) to convert webpages to pdf. I had a look at reportlab but the documentation focuses on generating pdfs from scratch, rather than converting from HTML. What do you recommend? - pisa? Edit: My use case is I have a HTML report that I want to make available in PDF too. I will...
[ "Pisa claims to support what I want to do:\n\npisa is a html2pdf converter using the\n ReportLab Toolkit, the HTML5lib and\n pyPdf. It supports HTML 5 and CSS 2.1\n (and some of CSS 3). It is completely\n written in pure Python so it is\n platform independent. The main benefit\n of this tool that a user with ...
[ 8, 4, 4 ]
[]
[]
[ "google_app_engine", "pdf", "python" ]
stackoverflow_0001598715_google_app_engine_pdf_python.txt
Q: What files do I need to include with my Python app? I have an app that uses the python/c api and I was wondering what files I need to distribute with it? The app runs on Windows and links with libpython31.a Are there any other files? I tried the app on a seperate Win2k system and it said that python31.dll was need...
What files do I need to include with my Python app?
I have an app that uses the python/c api and I was wondering what files I need to distribute with it? The app runs on Windows and links with libpython31.a Are there any other files? I tried the app on a seperate Win2k system and it said that python31.dll was needed so theres at least one. Edit - My app is written in C+...
[ "The best way to tell is to try it on 'clean' installations of windows and see what it complains about. Virtual machines are a good way to do that.\n", "You'll need at least Python's own DLL (release-specific) and the wincrt DLL version it requires, also Python version depended (if you want to run on releases of ...
[ 2, 1 ]
[]
[]
[ "file", "python", "runtime" ]
stackoverflow_0001605022_file_python_runtime.txt
Q: Python - Using the Multiply Operator to Create Copies of Objects in Lists In Python, if I multiply of list of objects by an integer, I get a list of references to that object, e.g.: >>> a = [[]] * 3 >>> a [[], [], []] >>> a[0].append(1) >>> a [[1], [1], [1]] If my desired behavior is to create a list of copies of...
Python - Using the Multiply Operator to Create Copies of Objects in Lists
In Python, if I multiply of list of objects by an integer, I get a list of references to that object, e.g.: >>> a = [[]] * 3 >>> a [[], [], []] >>> a[0].append(1) >>> a [[1], [1], [1]] If my desired behavior is to create a list of copies of the original object (e.g. copies created by the "copy.copy()" method or someth...
[ "This is a good usage of list comprehension - its also the most readable way to do it IMO.\nSo the [[] for x in range(0,3)] you suggest isn't the multiplication operator, but gets the result you want.\n", "The multiplication operator on a sequence means repetition of the item(s) -- NOT creation of copies (shallow...
[ 17, 4, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001605024_list_python.txt
Q: python fileinput changes permission In my python code, I use the fileinput module for inplace replacing: import fileinput for line in fileinput.FileInput("permission.txt",inplace=1): line = line.strip() if not 'def' in line: print line else: line=line.replace(line,'zzz') print ...
python fileinput changes permission
In my python code, I use the fileinput module for inplace replacing: import fileinput for line in fileinput.FileInput("permission.txt",inplace=1): line = line.strip() if not 'def' in line: print line else: line=line.replace(line,'zzz') print line fileinput.close() However, once i...
[ "If you can help it, don't run your script as root.\nEDIT\nWell, the answer has been accepted, but it's not really much of an answer. In case you must run the script as root (or indeed as any other user), you can use os.stat() to determine the user id and group id of the file's owner before processing the file, and...
[ 2 ]
[]
[]
[ "file_io", "file_permissions", "python" ]
stackoverflow_0001605288_file_io_file_permissions_python.txt
Q: How to launch and run external script in background? I tried these two methods: os.system("python test.py") subprocess.Popen("python test.py", shell=True) Both approaches need to wait until test.py finishes which blocks main process. I know "nohup" can do the job. Is there a Python way to launch test.py or any o...
How to launch and run external script in background?
I tried these two methods: os.system("python test.py") subprocess.Popen("python test.py", shell=True) Both approaches need to wait until test.py finishes which blocks main process. I know "nohup" can do the job. Is there a Python way to launch test.py or any other shell scripts and leave it running in background? Sup...
[ "subprocess.Popen([\"python\", \"test.py\"]) should work.\nNote that the job might still die when your main script exits. In this case, try subprocess.Popen([\"nohup\", \"python\", \"test.py\"])\n", "os.spawnlp(os.P_NOWAIT, \"path_to_test.py\", \"test.py\")\n\n" ]
[ 39, 1 ]
[]
[]
[ "background_process", "external_process", "python" ]
stackoverflow_0001605520_background_process_external_process_python.txt
Q: how to put in transaction I have a class: class AccountTransaction(db.Model): account = db.ReferenceProperty(reference_class=Account) tran_date = db.DateProperty() debit_credit = db.IntegerProperty() ## -1, 1 amount = db.FloatProperty() comment = db.StringProperty() pair = db.SelfReferenceP...
how to put in transaction
I have a class: class AccountTransaction(db.Model): account = db.ReferenceProperty(reference_class=Account) tran_date = db.DateProperty() debit_credit = db.IntegerProperty() ## -1, 1 amount = db.FloatProperty() comment = db.StringProperty() pair = db.SelfReferenceProperty() so, what I want is t...
[ "Because your Account entities can't all be in the same entity group, you can't perform an update in a single transaction. There are techniques to do this, particularly in the 'money transfer' case you've encountered - I wrote a blog post about this exact subject, in fact.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001604021_google_app_engine_python.txt
Q: Pythonic way to print a table I'm using this simple function: def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 and I'm supposing nicks are no longer than 15 characters. I'd like to keep e...
Pythonic way to print a table
I'm using this simple function: def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 and I'm supposing nicks are no longer than 15 characters. I'd like to keep each "column" aligned, is there a so...
[ "To left-align instead of right-align, use %-15s instead of %15s.\n", "Slightly off topic, but you can avoid performing explicit addition on tot using enumerate:\nfor tot, p in enumerate(players, start=1):\n print '...'\n\n", "Or if your using python 2.6 you can use the format method of the string:\nThis def...
[ 4, 4, 3, 2 ]
[]
[]
[ "printing", "python", "string_formatting" ]
stackoverflow_0001605861_printing_python_string_formatting.txt
Q: Wait for an event, but don't take it off the queue Is there any way to make the program sleep until an event occurs, but to not take it off the queue? Similarly to http://www.pygame.org/docs/ref/event.html#pygame.event.wait Or will I need to use pygame.event.wait, and then put that event back onto the queue? Just ...
Wait for an event, but don't take it off the queue
Is there any way to make the program sleep until an event occurs, but to not take it off the queue? Similarly to http://www.pygame.org/docs/ref/event.html#pygame.event.wait Or will I need to use pygame.event.wait, and then put that event back onto the queue? Just to clarify, I do not need to know what that event is whe...
[ "You will need to do what you suggest and post it back onto the queue. If the ordering is important (which it often is), then just keep your own queue of already retrieved events, and whenever you want to start processing events normally, just handle your own list first before draining pygame's queue.\nI'm at a los...
[ 1 ]
[]
[]
[ "event_handling", "pygame", "python" ]
stackoverflow_0001603537_event_handling_pygame_python.txt
Q: Using multiple databases with Elixir I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardcoded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice? The only thing I thought of is to: from s...
Using multiple databases with Elixir
I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardcoded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice? The only thing I thought of is to: from sys import argv metadata.bind = argv[1] C...
[ "I have some code that does this in a slightly nicer fashion than just using argv\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-u\", \"--user\", dest=\"user\",\n help=\"Database username\")\nparser.add_option(\"-p\", \"--password\", dest=\"password\",\n ...
[ 1, 0 ]
[]
[]
[ "python", "python_elixir" ]
stackoverflow_0001606341_python_python_elixir.txt
Q: Programmatically fetching contacts from Yahoo! Address Book Is there a way to programmatically log into Yahoo!, providing email id and password as inputs, and fetch the user's contacts? I've achieved the same thing with Gmail, thanks to the its ClientLogin interface. Yahoo Address book API provides BBAuth, which...
Programmatically fetching contacts from Yahoo! Address Book
Is there a way to programmatically log into Yahoo!, providing email id and password as inputs, and fetch the user's contacts? I've achieved the same thing with Gmail, thanks to the its ClientLogin interface. Yahoo Address book API provides BBAuth, which requires the user to be redirected to Yahoo login page. But I'm ...
[ "You may want to look into the Contacts API provided by Yahoo!\n", "I just found a python script that solves my problem \nhttp://pypi.python.org/pypi/ContactGrabber/0.1\nIt's not complete though, fetches only a portion of the address book.\n", "you can try this\nhttp://developer.yahoo.com/social/contacts/\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python", "yahoo" ]
stackoverflow_0000909508_python_yahoo.txt
Q: What is the best way to store integers mapped to strings so that the keys can be ranges in python? What would be the best way to store (non-mutable) data that is of format: doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } I have a relativel...
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
What would be the best way to store (non-mutable) data that is of format: doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } I have a relatively large amount of these type of data sets, so something that I can define the way of dictionaries (or cl...
[ "I'd split the range into a tuple and then inside your class, keep the items in an ordered list. You can use the bisect module to make inserts O(n) and lookup O(logn).\nIf you are converting a dict to your new class, you can build an unordered list and sort it at the end\ndoodahs = [\n (0, 256, \"FOO\"),\n (2...
[ 5, 2, 1, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0001606150_python_types.txt
Q: Timer in Python I am writing a python app using Tkinter for buttons and graphics and having trouble getting a timer working, what I need is a sample app that has three buttons and a label. [start timer] [stop timer] [quit] When I press the start button a function allows the label to count up from zero every 5 sec...
Timer in Python
I am writing a python app using Tkinter for buttons and graphics and having trouble getting a timer working, what I need is a sample app that has three buttons and a label. [start timer] [stop timer] [quit] When I press the start button a function allows the label to count up from zero every 5 seconds, the stop button...
[ "Check the .after method of your Tk() object. This allows you to use Tk's timer to fire events within the gui's own loop by giving it a length of time and a callback method.\n" ]
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0001606700_python_tkinter.txt
Q: Function parameters hint Eclipse with PyDev Seems like newbie's question, but I just can't find the answer. Can I somehow see function parameters hint like in Visual Studio by pressing Ctrl+Shift+Space when cursor is in function call like this: someObj.doSomething("Test", "hello, wold", 4|) where | is my cursor p...
Function parameters hint Eclipse with PyDev
Seems like newbie's question, but I just can't find the answer. Can I somehow see function parameters hint like in Visual Studio by pressing Ctrl+Shift+Space when cursor is in function call like this: someObj.doSomething("Test", "hello, wold", 4|) where | is my cursor position. Ctrl+Spase shows me that information whe...
[ "Try \"CTRL+space\" after a ',', not after a parameter.\nThe function parameters are displayed just after the '(' or after a ',' + \"CTRL+space\".\n", "Parameters will show up just after a '(', which is how I re-displayed mine for ages. I recently discovered that 'CTRL + Shift + Space' will show the parameters an...
[ 11, 3 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0000969466_eclipse_pydev_python.txt
Q: How to get all unique IDs from the list of dicts? Say you have a list of dicts like this {'id': 1, 'other_value':5} So maybe; items = [{'id': 1, 'other_value':5}, {'id': 1, 'other_value2':6}, {'id': 2, 'other_value':4}, {'id': 2, 'other_value2':3}] Now, you can assume this is a small subset of the data. There are...
How to get all unique IDs from the list of dicts?
Say you have a list of dicts like this {'id': 1, 'other_value':5} So maybe; items = [{'id': 1, 'other_value':5}, {'id': 1, 'other_value2':6}, {'id': 2, 'other_value':4}, {'id': 2, 'other_value2':3}] Now, you can assume this is a small subset of the data. There are maybe thousands. Also the structure isn't specified by...
[ "if you want unique id's you can use a set:\nset(i['id'] for i in items)\n\n", "set(i['id'] for i in items)\n\nbut you might consider another data structure altogether, for example dict of lists:\nitems = {1: [5, 6], 2: [2, 4]}\n\n" ]
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001606915_python.txt
Q: Best method to determine which of a set of keys exist in the datastore I have a few hundred keys, all of the same Model, which I have pre-computed: candidate_keys = [db.Key(...), db.Key(...), db.Key(...), ...] Some of these keys refer to actual entities in the datastore, and some do not. I wish to determine which...
Best method to determine which of a set of keys exist in the datastore
I have a few hundred keys, all of the same Model, which I have pre-computed: candidate_keys = [db.Key(...), db.Key(...), db.Key(...), ...] Some of these keys refer to actual entities in the datastore, and some do not. I wish to determine which keys do correspond to entities. It is not necessary to know the data within...
[ "IN filters are not supported directly by the App Engine datastore; they're a convenience that's implemented in the client library. An IN query with 30 values is translated into 30 equality queries on one value each, resulting in 30 regular queries!\nDue to round-trip times and the expense of even keys-only queries...
[ 3, 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001607126_google_app_engine_google_cloud_datastore_python.txt
Q: PyQt custom widget in c++ Can I write custom Qt widget in pure C++, compile it and use in PyQt? I'm trying to use the ctypes-opencv with qt and I have performance problems with python's code for displaying opencv's image in Qt form. A: You will have to write a Python wrapper for the widget, using the sip library...
PyQt custom widget in c++
Can I write custom Qt widget in pure C++, compile it and use in PyQt? I'm trying to use the ctypes-opencv with qt and I have performance problems with python's code for displaying opencv's image in Qt form.
[ "You will have to write a Python wrapper for the widget, using the sip library (which is used by PyQt). There is a simple example for a Qt/C++ widget in the documentation.\n" ]
[ 5 ]
[]
[]
[ "c++", "pyqt", "python", "python_sip", "qt" ]
stackoverflow_0001607515_c++_pyqt_python_python_sip_qt.txt
Q: How to create a file one directory up? How can I create a file in python one directory up, without using the full path? I would like a way that worked both for windows and linux. Thanks. A: Use os.pardir (which is probably always "..") import os fobj = open(os.path.join(os.pardir, "filename"), "w") A: People d...
How to create a file one directory up?
How can I create a file in python one directory up, without using the full path? I would like a way that worked both for windows and linux. Thanks.
[ "Use os.pardir (which is probably always \"..\")\nimport os\nfobj = open(os.path.join(os.pardir, \"filename\"), \"w\")\n\n", "People don't seem to realize this, but Python is happy to accept forward slash even on Windows. This works fine on all platforms:\nfobj = open(\"../filename\", \"w\")\n\n", "Depends whe...
[ 33, 19, 2 ]
[]
[]
[ "io", "python" ]
stackoverflow_0001607751_io_python.txt
Q: os.walk and some tests I'm not sure if i understand properly how os.walk store its results. Im trying to do the following: I'm checking a root folder for subsequent folders. There are several hundreds of em, and they are nested in somewaht uniform way. I'm trying to check each subfolder, and if it ends with a four...
os.walk and some tests
I'm not sure if i understand properly how os.walk store its results. Im trying to do the following: I'm checking a root folder for subsequent folders. There are several hundreds of em, and they are nested in somewaht uniform way. I'm trying to check each subfolder, and if it ends with a four digit number, store it in a...
[ "\nusing \"$[0-9]{4}\" but it returns me\n nothing. Any ideas why?\n\n$ means end-of-(line or string) in a regex pattern, so I wonder how you expected \"end of string then four digits\" to ever possibly match anything...? By definition of \"end\" it won't be followed by 4 digits! r'(^|\\D)\\d{4}$' should work bet...
[ 3, 0, 0 ]
[]
[]
[ "directory", "python", "regex" ]
stackoverflow_0001608090_directory_python_regex.txt
Q: How to check which part of app is consuming CPU? I have a wxPython app which has many worker threads, idle event cycles, and many other such event handling code which can consume CPU, for now when app is not being interacted with consumes about 8-10% CPU. Question: Is there a tool which can tell which part/threads...
How to check which part of app is consuming CPU?
I have a wxPython app which has many worker threads, idle event cycles, and many other such event handling code which can consume CPU, for now when app is not being interacted with consumes about 8-10% CPU. Question: Is there a tool which can tell which part/threads of my app is consuming most CPU? If there are no such...
[ "If all your threads have unique start methods you could use the profiler that comes with Python.\nIf you're on a Mac you should check out the Instruments app. You could also use dtrace for Linux.\n", "This isn't very practical at a language-agnostic level. Take away the language and all you have left is a load o...
[ 1, 0, 0, 0 ]
[]
[]
[ "cpu_usage", "python", "wxpython" ]
stackoverflow_0001470453_cpu_usage_python_wxpython.txt
Q: XML-RPC server with better error reporting Standard libraries (xmlrpclib+SimpleXMLRPCServer in Python 2 and xmlrpc.server in Python 3) report all errors (including usage errors) as python exceptions which is not suitable for public services: exception strings are often not easy understandable without python knowle...
XML-RPC server with better error reporting
Standard libraries (xmlrpclib+SimpleXMLRPCServer in Python 2 and xmlrpc.server in Python 3) report all errors (including usage errors) as python exceptions which is not suitable for public services: exception strings are often not easy understandable without python knowledge and might expose some sensitive information....
[ "I don't think you have a library specific problem. When using any library or framework you typically want to trap all errors, log them somewhere, and throw up \"Oops, we're having problems. You may want to contact us at x@x.com with error number 100 and tell us what you did.\" So wrap your failable entry points...
[ 1, 1 ]
[]
[]
[ "python", "xml_rpc" ]
stackoverflow_0001571598_python_xml_rpc.txt
Q: Whats new in Python 3.x? http://docs.python.org/3.0/whatsnew/3.0.html says it lists whats new, but in my opinion, it only lists differences, so has does anybody know of any completely new Python features, introduced in release 3.x? To Avoid Confusion, I will define a completely new feature as something that has ne...
Whats new in Python 3.x?
http://docs.python.org/3.0/whatsnew/3.0.html says it lists whats new, but in my opinion, it only lists differences, so has does anybody know of any completely new Python features, introduced in release 3.x? To Avoid Confusion, I will define a completely new feature as something that has never been used in any other cod...
[ "Many of the completely new features introduced in 3.0 were also backported to 2.6, a deliberate choice. However, this was not practical in all cases, so some of the new features remained Python 3 - only.\nHow metaclasses work, is probably the biggest single new feature. The syntax is clearly better than 2.*'s __m...
[ 9, 4 ]
[]
[]
[ "python" ]
stackoverflow_0001608731_python.txt
Q: How to use PIL to resize and apply rotation EXIF information to the file? I am trying to use Python to resize picture. With my camera, files are all written is landscape way. The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this i...
How to use PIL to resize and apply rotation EXIF information to the file?
I am trying to use Python to resize picture. With my camera, files are all written is landscape way. The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information and keeping ...
[ "I finally used pyexiv2, but it is a bit tricky to install on other platforms than GNU.\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Copyright (C) 2008-2009 Rémy HUBSCHER <natim@users.sf.net> - http://www.trunat.fr/portfolio/python.html\n\n# This program is free software; you can redistribute it and/or modify\n# ...
[ 15, 6, 2 ]
[]
[]
[ "exif", "jpeg", "python", "python_imaging_library", "rotation" ]
stackoverflow_0001606587_exif_jpeg_python_python_imaging_library_rotation.txt
Q: Load different modules without changing the logic file Suppose I've got 2 different modules which have the uniform(same) interfaces. The files list like this: root/ logic.py sns_api/ __init__.py facebook/ pyfacebook.py __init__.py myspace/ pymyspace.py ...
Load different modules without changing the logic file
Suppose I've got 2 different modules which have the uniform(same) interfaces. The files list like this: root/ logic.py sns_api/ __init__.py facebook/ pyfacebook.py __init__.py myspace/ pymyspace.py __init__.py And pyfacebook.py and pymyspace.py have the s...
[ "With just two i'd do\nif platform == 'facebook':\n from pyfacebook import FaceBook as Platform\nelif platform == 'myspace':\n from pymyspace import Myspace as Platform\nelse:\n raise RuntimeError, \"not a valid platform\"\n\nand use Platform in the rest of the code. It's done like this in the library, see...
[ 6, 0, 0 ]
[]
[]
[ "dynamic_import", "interface", "python" ]
stackoverflow_0001606960_dynamic_import_interface_python.txt
Q: Types that define `__eq__` are unhashable? I had a strange bug when porting a feature to the Python 3.1 fork of my program. I narrowed it down to the following hypothesis: In contrast to Python 2.x, in Python 3.x if an object has an __eq__ method it is automatically unhashable. Is this true? Here's what happens in...
Types that define `__eq__` are unhashable?
I had a strange bug when porting a feature to the Python 3.1 fork of my program. I narrowed it down to the following hypothesis: In contrast to Python 2.x, in Python 3.x if an object has an __eq__ method it is automatically unhashable. Is this true? Here's what happens in Python 3.1: >>> class O(object): ... def __...
[ "Yes, if you define __eq__, the default __hash__ (namely, hashing the address of the object in memory) goes away. This is important because hashing needs to be consistent with equality: equal objects need to hash the same.\nThe solution is simple: just define __hash__ along with defining __eq__.\n", "This paragra...
[ 96, 33, 6, 1 ]
[]
[]
[ "hash", "python", "python_3.x" ]
stackoverflow_0001608842_hash_python_python_3.x.txt
Q: Abstract base class inheritance in Django with foreignkey I am attempting model inheritance on my Django powered site in order to adhere to DRY. My goal is to use an abstract base class called BasicCompany to supply the common info for three child classes: Butcher, Baker, CandlestickMaker (they are located in thei...
Abstract base class inheritance in Django with foreignkey
I am attempting model inheritance on my Django powered site in order to adhere to DRY. My goal is to use an abstract base class called BasicCompany to supply the common info for three child classes: Butcher, Baker, CandlestickMaker (they are located in their own apps under their respective names). Each of the child cla...
[ "I suspect you'll be better off with generic relations for the links, rather than trying to tie everything to a base class. Generic relations allow you to link a model such as EmailAddress to any other class, which would seem to be a good fit with your use case.\n" ]
[ 6 ]
[]
[]
[ "abstract_class", "django", "django_models", "inheritance", "python" ]
stackoverflow_0001608975_abstract_class_django_django_models_inheritance_python.txt
Q: Site wide caching with Django - problems with password protected pages on logout I've recently implemented sitewide caching using memcached on my Django application, I've set the TTL to about 500 seconds, and implement per view caches on other parts of the web application. The problem I have is that when a user lo...
Site wide caching with Django - problems with password protected pages on logout
I've recently implemented sitewide caching using memcached on my Django application, I've set the TTL to about 500 seconds, and implement per view caches on other parts of the web application. The problem I have is that when a user logs out, because it's a form post the site behaves as expected, however if they then go...
[ "I ran into similar issues. The standard Django way is to disable cache for authenticated users. \n#settings.py\nCACHE_MIDDLEWARE_ANONYMOUS_ONLY=True\n\nIt works fine if different users see different pages (example: their user name on them) and you can't have one version for them.\nBut if there are only 2 versions ...
[ 7, 1 ]
[]
[]
[ "django", "memcached", "python" ]
stackoverflow_0001608521_django_memcached_python.txt
Q: I need __closure__ I just checked out this very interesting mindmap: http://www.mindmeister.com/10510492/python-underscore And I was wondering what some of the new ones mean, like __code__ and __closure__. I googled around but nothing concrete. Does anyone know? A: From What's New in Python 3.0 The function attr...
I need __closure__
I just checked out this very interesting mindmap: http://www.mindmeister.com/10510492/python-underscore And I was wondering what some of the new ones mean, like __code__ and __closure__. I googled around but nothing concrete. Does anyone know?
[ "From What's New in Python 3.0\nThe function attributes named func_X have been renamed to use the __X__ form, freeing up these names in the function attribute namespace for user-defined attributes. To wit, func_closure, func_code, func_defaults, func_dict, func_doc, func_globals, func_name were renamed to __closure...
[ 7, 6, 4, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001609716_python_python_3.x.txt
Q: Unable to get WAF to run I am trying to build the Monotooth library on Ubuntu and there is a native component which needs to be compiled. The distro from github has a wscript file and requires WAF to build. However, whenever I try to execute waf configure I get: Checking for program gcc : ok /usr...
Unable to get WAF to run
I am trying to build the Monotooth library on Ubuntu and there is a native component which needs to be compiled. The distro from github has a wscript file and requires WAF to build. However, whenever I try to execute waf configure I get: Checking for program gcc : ok /usr/bin/gcc Checking for program ...
[ "I found that I needed to use a version of waf from http://waf.googlecode.com/files/waf-1.3.2.tar.bz2\nI had version 1.5.9 which must have deprecated the create_library_configurator method.\n" ]
[ 2 ]
[]
[]
[ "python", "waf", "wsh" ]
stackoverflow_0001608646_python_waf_wsh.txt
Q: sqlite3 Operation Error when doing many commits rapidly I get sqlite3.OperationalError: SQL logic error or missing database when I run an application I've been working on. What follows is a narrowed-down but complete sample that exhibits the problem for me. This sample uses two tables; one to store users and on...
sqlite3 Operation Error when doing many commits rapidly
I get sqlite3.OperationalError: SQL logic error or missing database when I run an application I've been working on. What follows is a narrowed-down but complete sample that exhibits the problem for me. This sample uses two tables; one to store users and one to record whether user information is up-to-date in an exte...
[ "As the \"lite\" part of the name implies, sqlite3 is meant for light-weight database use, not massive scalable concurrency like some of the Big Boys. Seems to me that what's happening here is that sqlite hasn't finished writing the last change you requested when you make another request\nSo, some options I see for...
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0001610154_python_sqlite.txt
Q: Run time of a subprocess.Popen instance Is there an easy way to find out the current (real or cpu) run time of a subprocess.Popen instance? A: No, but you can simply subclass and extend the Popen class to store the time it was created. A: Not in a platform-independent manner. On Linux, you can read /proc/<pid>...
Run time of a subprocess.Popen instance
Is there an easy way to find out the current (real or cpu) run time of a subprocess.Popen instance?
[ "No, but you can simply subclass and extend the Popen class to store the time it was created.\n", "Not in a platform-independent manner. On Linux, you can read /proc/<pid>/stat, in particular the columns utime, stime, and starttime (as described in proc(5)).\n", "On a Windows machine, you can use win32 APIs alo...
[ 1, 0, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001608724_python_subprocess.txt
Q: C# equivalence of python maketrans and translate Where could I find code of a C# equivalence of Python maketrans and translate? Thanks! A: This should take you most of the way there: public class MakeTrans { private readonly Dictionary<char, char> d; public MakeTrans(string intab, string outab) { ...
C# equivalence of python maketrans and translate
Where could I find code of a C# equivalence of Python maketrans and translate? Thanks!
[ "This should take you most of the way there:\npublic class MakeTrans\n{\n private readonly Dictionary<char, char> d;\n public MakeTrans(string intab, string outab)\n {\n d = Enumerable.Range(0, intab.Length).ToDictionary(i => intab[i], i => outab[i]);\n //d = new Dictionary<char, char>();\n ...
[ 3 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0001610217_c#_python.txt
Q: How does __iter__ work? Despite reading up on it, I still dont quite understand how __iter__ works. What would be a simple explaination? I've seen def__iter__(self): return self. I don't see how this works or the steps on how this works. A: As simply as I can put it: __iter__ defines a method on a class whi...
How does __iter__ work?
Despite reading up on it, I still dont quite understand how __iter__ works. What would be a simple explaination? I've seen def__iter__(self): return self. I don't see how this works or the steps on how this works.
[ "As simply as I can put it:\n__iter__ defines a method on a class which will return an iterator (an object that successively yields the next item contained by your object).\nThe iterator object that __iter__() returns can be pretty much any object, as long as it defines a next() method.\nThe next method will be cal...
[ 28, 9, 6, 3, 3 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0001610371_iterator_python.txt
Q: How to impose a time limit on a whole script in Python The user is entering a python script in a Java GUI python-editor and can run it from the editor. Is there a way to take the user's script and impose a time limit on the total script? I'm familiar with how to this with functions / signal.alarm(but I'm on windo...
How to impose a time limit on a whole script in Python
The user is entering a python script in a Java GUI python-editor and can run it from the editor. Is there a way to take the user's script and impose a time limit on the total script? I'm familiar with how to this with functions / signal.alarm(but I'm on windows & unix Jython) but the only solution I have come up with ...
[ "Use a threading.Timer to run a function in a separate thread after a specified delay (the max duration you want for your program), and in that function use thread.interrupt_main (note it's in module thread, not in module threading!) to raise a KeyboardInterrupt exception in the main thread.\nA more solid approach ...
[ 4, 0 ]
[]
[]
[ "limit", "python", "scripting", "time" ]
stackoverflow_0001609869_limit_python_scripting_time.txt
Q: when to use an alternative Python distribution? I have been programming in Python for a few years now and have always used CPython without thinking about it. The books and documentation I have read always refer to CPython too. When does it make sense to use an alternative distribution (PyPy, Stackless, etc)? Thank...
when to use an alternative Python distribution?
I have been programming in Python for a few years now and have always used CPython without thinking about it. The books and documentation I have read always refer to CPython too. When does it make sense to use an alternative distribution (PyPy, Stackless, etc)? Thanks!
[ "If you need native interfacing with the JVM, use Jython.\nWhen you need native interfacing with the .Net platform, or want to use Winforms, use IronPython.\nIf you need the latest version, cross-OS support, make use of existing C-based modules existing only for CPython, the use it.\nIf you are thinking into propos...
[ 8, 0 ]
[]
[]
[ "cpython", "distribution", "pypy", "python" ]
stackoverflow_0001610822_cpython_distribution_pypy_python.txt
Q: CherryPy variables in html I have a cherryPy program that returns a page that has an image (plot) in a table. I would also like to have variables in the table that describe the plot. I am not using any templating just trying to keep it really simple. In the example below I have the variable numberofapplicants wher...
CherryPy variables in html
I have a cherryPy program that returns a page that has an image (plot) in a table. I would also like to have variables in the table that describe the plot. I am not using any templating just trying to keep it really simple. In the example below I have the variable numberofapplicants where I want it but it does not outp...
[ "Assuming you're using Python 2.x, just use regular string formatting.\nreturn '''\n <html>\n <body>\n <table width=\"400\" border=\"1\">\n <tr>\n <td>%(numberofapplicants)s</td>\n </tr>\n <tr>\n <td width=\"400\" height=\"400\"><img src=\"img/atest.png\" width=\"400\" height=\"400\" /></td>...
[ 3, 2 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0001610995_cherrypy_python.txt
Q: AppEngine: Will the items stored in a StringListProperty always remain in the same order? After looking through the docs on App Engine and the StringListProperty or the ListProperty I can't seem to find whether there is a guarantee on the order of the items in the list. That is, I'd like to be certain that the lis...
AppEngine: Will the items stored in a StringListProperty always remain in the same order?
After looking through the docs on App Engine and the StringListProperty or the ListProperty I can't seem to find whether there is a guarantee on the order of the items in the list. That is, I'd like to be certain that the list order stays the same despite putting and getting from the DataStore: instance = MyModel() ins...
[ "Yep, per the docs, \n\nOrder is preserved, so when entities\n are returned by queries and get(),\n list properties will have values in\n the same order as when they were\n stored.\n\nIt's the last sentence of the first paragraph at the URL I gave.\n", "I can't find it explicitly said in the documentation, bu...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001610687_google_app_engine_python.txt
Q: Determine if a script is running in pythonw? I would like to redirect stderr and stdout to files when run inside of pythonw. How can I determine whether a script is running in pythonw or in python? A: sys.executable -- "A string giving the name of the executable binary for the Python interpreter, on systems wher...
Determine if a script is running in pythonw?
I would like to redirect stderr and stdout to files when run inside of pythonw. How can I determine whether a script is running in pythonw or in python?
[ "sys.executable -- \"A string giving the name of the executable binary for the Python interpreter, on systems where this makes sense.\"\n" ]
[ 5 ]
[]
[]
[ "python", "pythonw" ]
stackoverflow_0001611543_python_pythonw.txt
Q: Why does Psyco use a lot of memory? Psyco is a specialising compiler for Python. The documentation states Psyco can and will use large amounts of memory. What are the main reasons for this memory usage? Is substantial memory overhead a feature of JIT compilers in general? Edit: Thanks for the answers so far. The...
Why does Psyco use a lot of memory?
Psyco is a specialising compiler for Python. The documentation states Psyco can and will use large amounts of memory. What are the main reasons for this memory usage? Is substantial memory overhead a feature of JIT compilers in general? Edit: Thanks for the answers so far. There are three likely contenders. Writing ...
[ "From psyco website \"The difference with the traditional approach to JIT compilers is that Psyco writes several version of the same blocks (a block is a bit of a function), which are optimized by being specialized to some kinds of variables (a \"kind\" can mean a type, but it is more general)\"\n", "\n\"Psyco us...
[ 10, 5, 2, 2 ]
[]
[]
[ "compiler_construction", "jit", "memory", "psyco", "python" ]
stackoverflow_0001438220_compiler_construction_jit_memory_psyco_python.txt
Q: Automatically restart program when error occur The program is like this: HEADER CODE urllib2.initialization() try: while True: urllib2.read(somebytes) urllib2.read(somebytes) urllib2.read(somebytes) ... except Exception, e: print e FOOTER CODE My question is when error occu...
Automatically restart program when error occur
The program is like this: HEADER CODE urllib2.initialization() try: while True: urllib2.read(somebytes) urllib2.read(somebytes) urllib2.read(somebytes) ... except Exception, e: print e FOOTER CODE My question is when error occurs (timeout, connection reset by peer, etc), how to ...
[ "You could wrap your code in a \"while not done\" loop:\n#!/usr/bin/env python\n\nHEADER CODE\ndone=False\nwhile not done:\n try:\n urllib2.initialization()\n while True:\n # I assume you have code to break out of this loop\n urllib2.read(somebytes)\n urllib2.read(s...
[ 5, 4, 2 ]
[]
[]
[ "python", "restart" ]
stackoverflow_0001611256_python_restart.txt
Q: How can I make HTML safe for web browser with python? How can I make HTML from email safe to display in web browser with python? Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet. Other than spam emails should be...
How can I make HTML safe for web browser with python?
How can I make HTML from email safe to display in web browser with python? Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet. Other than spam emails should be displayed as closely as possible like intended by the writ...
[ "html5lib contains an HTML+CSS sanitizer. It allows too much currently, but it shouldn't be too hard to modify it to match the use case.\nFound it from here.\n", "I'm not quite clear with what exactly you mean with \"safe\". It's a pretty big topic... but, for what it's worth:\nIn my opinion, the stripping parser...
[ 1, 1, 0 ]
[]
[]
[ "browser", "email", "html", "html_sanitizing", "python" ]
stackoverflow_0001606201_browser_email_html_html_sanitizing_python.txt
Q: Getting a list of child entities in App Engine using get_by_key_name (Python) My adventures with entity groups continue after a slightly embarrassing beginning (see Under some circumstances an App Engine get_by_key_name call using an existing key_name returns None). I now see that I can't do a normal get_by_key_na...
Getting a list of child entities in App Engine using get_by_key_name (Python)
My adventures with entity groups continue after a slightly embarrassing beginning (see Under some circumstances an App Engine get_by_key_name call using an existing key_name returns None). I now see that I can't do a normal get_by_key_name call over a list of entities for child entities that have more than one parent e...
[ "Just create a key list and do a get on it.\nentities = Model.get_by_key_name(key_names)\ncontent_keys = [db.Key.from_path('Model', name, 'ContentModel', name) \n for name in key_names]\ncontent_entities = ContentModel.get(content_keys)\n\nNote that I assume the key_name for each ContentModel entity ...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "model", "performance", "python" ]
stackoverflow_0001611148_google_app_engine_model_performance_python.txt
Q: Pamie and python-win32 question pamie3 not working currently im making some web scraping script. and i was choice PAMIE to use my script. actually im new to python and programming. so i have no idea ,if i use PAMIE,it really helpful to make script to relate with win32-python. ok my problem is , while im making scr...
Pamie and python-win32 question pamie3 not working
currently im making some web scraping script. and i was choice PAMIE to use my script. actually im new to python and programming. so i have no idea ,if i use PAMIE,it really helpful to make script to relate with win32-python. ok my problem is , while im making script,i was encounter two probelm. first , i want to let w...
[ "PAMIE might be getting a bit dated. You could take a look at Selenium which will also automate a web browser, but is more current. \nhttp://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "pamie", "python", "winapi" ]
stackoverflow_0001611852_beautifulsoup_pamie_python_winapi.txt
Q: Performance of Python worth the cost? I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries. I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~...
Performance of Python worth the cost?
I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries. I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM). The main concern is that re...
[ "In general, you shouldn't obsess over performance until you've actually seen it become a problem. Since we don't know the details of your app, we can't say how it'd perform if implemented in Python. And since you haven't implemented it yet, neither can you.\nImplement the version you're most comfortable with, and ...
[ 35, 12, 5, 1, 0, 0 ]
[]
[]
[ "c", "embedded", "fuzzy_logic", "python" ]
stackoverflow_0001498155_c_embedded_fuzzy_logic_python.txt
Q: What profiling tools exist for Python on Linux beyond the ones included in the standard library? I've been using Python's built-in cProfile tool with some pretty good success. But I'd like to be able to access more information such as how long I'm waiting for I/O (and what kind of I/O I'm waiting on) or how many ...
What profiling tools exist for Python on Linux beyond the ones included in the standard library?
I've been using Python's built-in cProfile tool with some pretty good success. But I'd like to be able to access more information such as how long I'm waiting for I/O (and what kind of I/O I'm waiting on) or how many cache misses I have. Are there any Linux tools to help with this beyond your basic time command?
[ "I'm not sure if python will provide the low level information you are looking for. You might want to look at oprofile and latencytop though.\n", "If you want to know exactly what you are waiting for, and approximately what percentage of the time, this will tell you. It won't tell you other things though, like c...
[ 2, 1 ]
[]
[]
[ "linux", "profiling", "python" ]
stackoverflow_0001607641_linux_profiling_python.txt
Q: Rolling my own __repr__ I want to write my own __repr__ for some class that I define. I want it to be similar to the default <__main__.O object at 0x00D229D0>, except have a few other details in there. How do I reproduce that <__main__.O object at 0x00D229D0> thing? A: See http://docs.python.org/reference/datamo...
Rolling my own __repr__
I want to write my own __repr__ for some class that I define. I want it to be similar to the default <__main__.O object at 0x00D229D0>, except have a few other details in there. How do I reproduce that <__main__.O object at 0x00D229D0> thing?
[ "See http://docs.python.org/reference/datamodel.html#object.repr\n#!/usr/bin/env python\nclass O(object):\n def __repr__(self):\n return '<%s.%s object at 0x%x>'%(self.__module__,self.__class__.__name__,id(self))\no=O()\nprint(repr(o))\n\n# <__main__.O object at 0xb7e7d0cc>\n\n", "You can write your own...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001613037_python.txt